util.c 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887
  1. /* Copyright (c) 2003, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2010, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file util.c
  7. * \brief Common functions for strings, IO, network, data structures,
  8. * process control.
  9. **/
  10. /* This is required on rh7 to make strptime not complain.
  11. */
  12. #define _GNU_SOURCE
  13. #include "orconfig.h"
  14. #include "util.h"
  15. #include "torlog.h"
  16. #undef log
  17. #include "crypto.h"
  18. #include "torint.h"
  19. #include "container.h"
  20. #include "address.h"
  21. #ifdef MS_WINDOWS
  22. #include <io.h>
  23. #include <direct.h>
  24. #include <process.h>
  25. #include <tchar.h>
  26. #else
  27. #include <dirent.h>
  28. #include <pwd.h>
  29. #endif
  30. /* math.h needs this on Linux */
  31. #ifndef __USE_ISOC99
  32. #define __USE_ISOC99 1
  33. #endif
  34. #include <math.h>
  35. #include <stdlib.h>
  36. #include <stdio.h>
  37. #include <string.h>
  38. #include <assert.h>
  39. #ifdef HAVE_NETINET_IN_H
  40. #include <netinet/in.h>
  41. #endif
  42. #ifdef HAVE_ARPA_INET_H
  43. #include <arpa/inet.h>
  44. #endif
  45. #ifdef HAVE_ERRNO_H
  46. #include <errno.h>
  47. #endif
  48. #ifdef HAVE_SYS_SOCKET_H
  49. #include <sys/socket.h>
  50. #endif
  51. #ifdef HAVE_SYS_TIME_H
  52. #include <sys/time.h>
  53. #endif
  54. #ifdef HAVE_UNISTD_H
  55. #include <unistd.h>
  56. #endif
  57. #ifdef HAVE_SYS_STAT_H
  58. #include <sys/stat.h>
  59. #endif
  60. #ifdef HAVE_SYS_FCNTL_H
  61. #include <sys/fcntl.h>
  62. #endif
  63. #ifdef HAVE_FCNTL_H
  64. #include <fcntl.h>
  65. #endif
  66. #ifdef HAVE_TIME_H
  67. #include <time.h>
  68. #endif
  69. #ifdef HAVE_MALLOC_MALLOC_H
  70. #include <malloc/malloc.h>
  71. #endif
  72. #ifdef HAVE_MALLOC_H
  73. #ifndef OPENBSD
  74. /* OpenBSD has a malloc.h, but for our purposes, it only exists in order to
  75. * scold us for being so stupid as to autodetect its presence. To be fair,
  76. * they've done this since 1996, when autoconf was only 5 years old. */
  77. #include <malloc.h>
  78. #endif
  79. #endif
  80. #ifdef HAVE_MALLOC_NP_H
  81. #include <malloc_np.h>
  82. #endif
  83. /* =====
  84. * Memory management
  85. * ===== */
  86. #ifdef USE_DMALLOC
  87. #undef strndup
  88. #include <dmalloc.h>
  89. /* Macro to pass the extra dmalloc args to another function. */
  90. #define DMALLOC_FN_ARGS , file, line
  91. #if defined(HAVE_DMALLOC_STRDUP)
  92. /* the dmalloc_strdup should be fine as defined */
  93. #elif defined(HAVE_DMALLOC_STRNDUP)
  94. #define dmalloc_strdup(file, line, string, xalloc_b) \
  95. dmalloc_strndup(file, line, (string), -1, xalloc_b)
  96. #else
  97. #error "No dmalloc_strdup or equivalent"
  98. #endif
  99. #else /* not using dmalloc */
  100. #define DMALLOC_FN_ARGS
  101. #endif
  102. /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
  103. * result. On error, log and terminate the process. (Same as malloc(size),
  104. * but never returns NULL.)
  105. *
  106. * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
  107. * ignored otherwise.
  108. */
  109. void *
  110. _tor_malloc(size_t size DMALLOC_PARAMS)
  111. {
  112. void *result;
  113. tor_assert(size < SIZE_T_CEILING);
  114. #ifndef MALLOC_ZERO_WORKS
  115. /* Some libc mallocs don't work when size==0. Override them. */
  116. if (size==0) {
  117. size=1;
  118. }
  119. #endif
  120. #ifdef USE_DMALLOC
  121. result = dmalloc_malloc(file, line, size, DMALLOC_FUNC_MALLOC, 0, 0);
  122. #else
  123. result = malloc(size);
  124. #endif
  125. if (PREDICT_UNLIKELY(result == NULL)) {
  126. log_err(LD_MM,"Out of memory on malloc(). Dying.");
  127. /* If these functions die within a worker process, they won't call
  128. * spawn_exit, but that's ok, since the parent will run out of memory soon
  129. * anyway. */
  130. exit(1);
  131. }
  132. return result;
  133. }
  134. /** Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
  135. * zero bytes, and return a pointer to the result. Log and terminate
  136. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  137. */
  138. void *
  139. _tor_malloc_zero(size_t size DMALLOC_PARAMS)
  140. {
  141. /* You may ask yourself, "wouldn't it be smart to use calloc instead of
  142. * malloc+memset? Perhaps libc's calloc knows some nifty optimization trick
  143. * we don't!" Indeed it does, but its optimizations are only a big win when
  144. * we're allocating something very big (it knows if it just got the memory
  145. * from the OS in a pre-zeroed state). We don't want to use tor_malloc_zero
  146. * for big stuff, so we don't bother with calloc. */
  147. void *result = _tor_malloc(size DMALLOC_FN_ARGS);
  148. memset(result, 0, size);
  149. return result;
  150. }
  151. /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
  152. * bytes long; return the new memory block. On error, log and
  153. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  154. */
  155. void *
  156. _tor_realloc(void *ptr, size_t size DMALLOC_PARAMS)
  157. {
  158. void *result;
  159. #ifdef USE_DMALLOC
  160. result = dmalloc_realloc(file, line, ptr, size, DMALLOC_FUNC_REALLOC, 0);
  161. #else
  162. result = realloc(ptr, size);
  163. #endif
  164. if (PREDICT_UNLIKELY(result == NULL)) {
  165. log_err(LD_MM,"Out of memory on realloc(). Dying.");
  166. exit(1);
  167. }
  168. return result;
  169. }
  170. /** Return a newly allocated copy of the NUL-terminated string s. On
  171. * error, log and terminate. (Like strdup(s), but never returns
  172. * NULL.)
  173. */
  174. char *
  175. _tor_strdup(const char *s DMALLOC_PARAMS)
  176. {
  177. char *dup;
  178. tor_assert(s);
  179. #ifdef USE_DMALLOC
  180. dup = dmalloc_strdup(file, line, s, 0);
  181. #else
  182. dup = strdup(s);
  183. #endif
  184. if (PREDICT_UNLIKELY(dup == NULL)) {
  185. log_err(LD_MM,"Out of memory on strdup(). Dying.");
  186. exit(1);
  187. }
  188. return dup;
  189. }
  190. /** Allocate and return a new string containing the first <b>n</b>
  191. * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
  192. * characters, only the first <b>n</b> are copied. The result is
  193. * always NUL-terminated. (Like strndup(s,n), but never returns
  194. * NULL.)
  195. */
  196. char *
  197. _tor_strndup(const char *s, size_t n DMALLOC_PARAMS)
  198. {
  199. char *dup;
  200. tor_assert(s);
  201. tor_assert(n < SIZE_T_CEILING);
  202. dup = _tor_malloc((n+1) DMALLOC_FN_ARGS);
  203. /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
  204. * this function gets called a whole lot, and platform strncpy is
  205. * much faster than strlcpy when strlen(s) is much longer than n.
  206. */
  207. strncpy(dup, s, n);
  208. dup[n]='\0';
  209. return dup;
  210. }
  211. /** Allocate a chunk of <b>len</b> bytes, with the same contents as the
  212. * <b>len</b> bytes starting at <b>mem</b>. */
  213. void *
  214. _tor_memdup(const void *mem, size_t len DMALLOC_PARAMS)
  215. {
  216. char *dup;
  217. tor_assert(len < SIZE_T_CEILING);
  218. tor_assert(mem);
  219. dup = _tor_malloc(len DMALLOC_FN_ARGS);
  220. memcpy(dup, mem, len);
  221. return dup;
  222. }
  223. /** Helper for places that need to take a function pointer to the right
  224. * spelling of "free()". */
  225. void
  226. _tor_free(void *mem)
  227. {
  228. tor_free(mem);
  229. }
  230. #if defined(HAVE_MALLOC_GOOD_SIZE) && !defined(HAVE_MALLOC_GOOD_SIZE_PROTOTYPE)
  231. /* Some version of Mac OSX have malloc_good_size in their libc, but not
  232. * actually defined in malloc/malloc.h. We detect this and work around it by
  233. * prototyping.
  234. */
  235. extern size_t malloc_good_size(size_t size);
  236. #endif
  237. /** Allocate and return a chunk of memory of size at least *<b>size</b>, using
  238. * the same resources we would use to malloc *<b>sizep</b>. Set *<b>sizep</b>
  239. * to the number of usable bytes in the chunk of memory. */
  240. void *
  241. _tor_malloc_roundup(size_t *sizep DMALLOC_PARAMS)
  242. {
  243. #ifdef HAVE_MALLOC_GOOD_SIZE
  244. tor_assert(*sizep < SIZE_T_CEILING);
  245. *sizep = malloc_good_size(*sizep);
  246. return _tor_malloc(*sizep DMALLOC_FN_ARGS);
  247. #elif 0 && defined(HAVE_MALLOC_USABLE_SIZE) && !defined(USE_DMALLOC)
  248. /* Never use malloc_usable_size(); it makes valgrind really unhappy,
  249. * and doesn't win much in terms of usable space where it exists. */
  250. void *result;
  251. tor_assert(*sizep < SIZE_T_CEILING);
  252. result = _tor_malloc(*sizep DMALLOC_FN_ARGS);
  253. *sizep = malloc_usable_size(result);
  254. return result;
  255. #else
  256. return _tor_malloc(*sizep DMALLOC_FN_ARGS);
  257. #endif
  258. }
  259. /** Call the platform malloc info function, and dump the results to the log at
  260. * level <b>severity</b>. If no such function exists, do nothing. */
  261. void
  262. tor_log_mallinfo(int severity)
  263. {
  264. #ifdef HAVE_MALLINFO
  265. struct mallinfo mi;
  266. memset(&mi, 0, sizeof(mi));
  267. mi = mallinfo();
  268. tor_log(severity, LD_MM,
  269. "mallinfo() said: arena=%d, ordblks=%d, smblks=%d, hblks=%d, "
  270. "hblkhd=%d, usmblks=%d, fsmblks=%d, uordblks=%d, fordblks=%d, "
  271. "keepcost=%d",
  272. mi.arena, mi.ordblks, mi.smblks, mi.hblks,
  273. mi.hblkhd, mi.usmblks, mi.fsmblks, mi.uordblks, mi.fordblks,
  274. mi.keepcost);
  275. #else
  276. (void)severity;
  277. #endif
  278. #ifdef USE_DMALLOC
  279. dmalloc_log_changed(0, /* Since the program started. */
  280. 1, /* Log info about non-freed pointers. */
  281. 0, /* Do not log info about freed pointers. */
  282. 0 /* Do not log individual pointers. */
  283. );
  284. #endif
  285. }
  286. /* =====
  287. * Math
  288. * ===== */
  289. /**
  290. * Returns the natural logarithm of d base 2. We define this wrapper here so
  291. * as to make it easier not to conflict with Tor's log() macro.
  292. */
  293. double
  294. tor_mathlog(double d)
  295. {
  296. return log(d);
  297. }
  298. /** Return the long integer closest to d. We define this wrapper here so
  299. * that not all users of math.h need to use the right incancations to get
  300. * the c99 functions. */
  301. long
  302. tor_lround(double d)
  303. {
  304. return lround(d);
  305. }
  306. /** Returns floor(log2(u64)). If u64 is 0, (incorrectly) returns 0. */
  307. int
  308. tor_log2(uint64_t u64)
  309. {
  310. int r = 0;
  311. if (u64 >= (U64_LITERAL(1)<<32)) {
  312. u64 >>= 32;
  313. r = 32;
  314. }
  315. if (u64 >= (U64_LITERAL(1)<<16)) {
  316. u64 >>= 16;
  317. r += 16;
  318. }
  319. if (u64 >= (U64_LITERAL(1)<<8)) {
  320. u64 >>= 8;
  321. r += 8;
  322. }
  323. if (u64 >= (U64_LITERAL(1)<<4)) {
  324. u64 >>= 4;
  325. r += 4;
  326. }
  327. if (u64 >= (U64_LITERAL(1)<<2)) {
  328. u64 >>= 2;
  329. r += 2;
  330. }
  331. if (u64 >= (U64_LITERAL(1)<<1)) {
  332. u64 >>= 1;
  333. r += 1;
  334. }
  335. return r;
  336. }
  337. /** Return the power of 2 closest to <b>u64</b>. */
  338. uint64_t
  339. round_to_power_of_2(uint64_t u64)
  340. {
  341. int lg2 = tor_log2(u64);
  342. uint64_t low = U64_LITERAL(1) << lg2, high = U64_LITERAL(1) << (lg2+1);
  343. if (high - u64 < u64 - low)
  344. return high;
  345. else
  346. return low;
  347. }
  348. /** Return the lowest x such that x is at least <b>number</b>, and x modulo
  349. * <b>divisor</b> == 0. */
  350. unsigned
  351. round_to_next_multiple_of(unsigned number, unsigned divisor)
  352. {
  353. number += divisor - 1;
  354. number -= number % divisor;
  355. return number;
  356. }
  357. /** Return the lowest x such that x is at least <b>number</b>, and x modulo
  358. * <b>divisor</b> == 0. */
  359. uint32_t
  360. round_uint32_to_next_multiple_of(uint32_t number, uint32_t divisor)
  361. {
  362. number += divisor - 1;
  363. number -= number % divisor;
  364. return number;
  365. }
  366. /** Return the lowest x such that x is at least <b>number</b>, and x modulo
  367. * <b>divisor</b> == 0. */
  368. uint64_t
  369. round_uint64_to_next_multiple_of(uint64_t number, uint64_t divisor)
  370. {
  371. number += divisor - 1;
  372. number -= number % divisor;
  373. return number;
  374. }
  375. /* =====
  376. * String manipulation
  377. * ===== */
  378. /** Remove from the string <b>s</b> every character which appears in
  379. * <b>strip</b>. */
  380. void
  381. tor_strstrip(char *s, const char *strip)
  382. {
  383. char *read = s;
  384. while (*read) {
  385. if (strchr(strip, *read)) {
  386. ++read;
  387. } else {
  388. *s++ = *read++;
  389. }
  390. }
  391. *s = '\0';
  392. }
  393. /** Return a pointer to a NUL-terminated hexadecimal string encoding
  394. * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
  395. * result does not need to be deallocated, but repeated calls to
  396. * hex_str will trash old results.
  397. */
  398. const char *
  399. hex_str(const char *from, size_t fromlen)
  400. {
  401. static char buf[65];
  402. if (fromlen>(sizeof(buf)-1)/2)
  403. fromlen = (sizeof(buf)-1)/2;
  404. base16_encode(buf,sizeof(buf),from,fromlen);
  405. return buf;
  406. }
  407. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  408. * lowercase. */
  409. void
  410. tor_strlower(char *s)
  411. {
  412. while (*s) {
  413. *s = TOR_TOLOWER(*s);
  414. ++s;
  415. }
  416. }
  417. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  418. * lowercase. */
  419. void
  420. tor_strupper(char *s)
  421. {
  422. while (*s) {
  423. *s = TOR_TOUPPER(*s);
  424. ++s;
  425. }
  426. }
  427. /** Return 1 if every character in <b>s</b> is printable, else return 0.
  428. */
  429. int
  430. tor_strisprint(const char *s)
  431. {
  432. while (*s) {
  433. if (!TOR_ISPRINT(*s))
  434. return 0;
  435. s++;
  436. }
  437. return 1;
  438. }
  439. /** Return 1 if no character in <b>s</b> is uppercase, else return 0.
  440. */
  441. int
  442. tor_strisnonupper(const char *s)
  443. {
  444. while (*s) {
  445. if (TOR_ISUPPER(*s))
  446. return 0;
  447. s++;
  448. }
  449. return 1;
  450. }
  451. /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
  452. * strcmp.
  453. */
  454. int
  455. strcmpstart(const char *s1, const char *s2)
  456. {
  457. size_t n = strlen(s2);
  458. return strncmp(s1, s2, n);
  459. }
  460. /** Compare the s1_len-byte string <b>s1</b> with <b>s2</b>,
  461. * without depending on a terminating nul in s1. Sorting order is first by
  462. * length, then lexically; return values are as for strcmp.
  463. */
  464. int
  465. strcmp_len(const char *s1, const char *s2, size_t s1_len)
  466. {
  467. size_t s2_len = strlen(s2);
  468. if (s1_len < s2_len)
  469. return -1;
  470. if (s1_len > s2_len)
  471. return 1;
  472. return memcmp(s1, s2, s2_len);
  473. }
  474. /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
  475. * strcasecmp.
  476. */
  477. int
  478. strcasecmpstart(const char *s1, const char *s2)
  479. {
  480. size_t n = strlen(s2);
  481. return strncasecmp(s1, s2, n);
  482. }
  483. /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
  484. * strcmp.
  485. */
  486. int
  487. strcmpend(const char *s1, const char *s2)
  488. {
  489. size_t n1 = strlen(s1), n2 = strlen(s2);
  490. if (n2>n1)
  491. return strcmp(s1,s2);
  492. else
  493. return strncmp(s1+(n1-n2), s2, n2);
  494. }
  495. /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
  496. * strcasecmp.
  497. */
  498. int
  499. strcasecmpend(const char *s1, const char *s2)
  500. {
  501. size_t n1 = strlen(s1), n2 = strlen(s2);
  502. if (n2>n1) /* then they can't be the same; figure out which is bigger */
  503. return strcasecmp(s1,s2);
  504. else
  505. return strncasecmp(s1+(n1-n2), s2, n2);
  506. }
  507. /** Compare the value of the string <b>prefix</b> with the start of the
  508. * <b>memlen</b>-byte memory chunk at <b>mem</b>. Return as for strcmp.
  509. *
  510. * [As memcmp(mem, prefix, strlen(prefix)) but returns -1 if memlen is less
  511. * than strlen(prefix).]
  512. */
  513. int
  514. memcmpstart(const void *mem, size_t memlen,
  515. const char *prefix)
  516. {
  517. size_t plen = strlen(prefix);
  518. if (memlen < plen)
  519. return -1;
  520. return memcmp(mem, prefix, plen);
  521. }
  522. /** Return a pointer to the first char of s that is not whitespace and
  523. * not a comment, or to the terminating NUL if no such character exists.
  524. */
  525. const char *
  526. eat_whitespace(const char *s)
  527. {
  528. tor_assert(s);
  529. while (1) {
  530. switch (*s) {
  531. case '\0':
  532. default:
  533. return s;
  534. case ' ':
  535. case '\t':
  536. case '\n':
  537. case '\r':
  538. ++s;
  539. break;
  540. case '#':
  541. ++s;
  542. while (*s && *s != '\n')
  543. ++s;
  544. }
  545. }
  546. }
  547. /** Return a pointer to the first char of s that is not whitespace and
  548. * not a comment, or to the terminating NUL if no such character exists.
  549. */
  550. const char *
  551. eat_whitespace_eos(const char *s, const char *eos)
  552. {
  553. tor_assert(s);
  554. tor_assert(eos && s <= eos);
  555. while (s < eos) {
  556. switch (*s) {
  557. case '\0':
  558. default:
  559. return s;
  560. case ' ':
  561. case '\t':
  562. case '\n':
  563. case '\r':
  564. ++s;
  565. break;
  566. case '#':
  567. ++s;
  568. while (s < eos && *s && *s != '\n')
  569. ++s;
  570. }
  571. }
  572. return s;
  573. }
  574. /** Return a pointer to the first char of s that is not a space or a tab
  575. * or a \\r, or to the terminating NUL if no such character exists. */
  576. const char *
  577. eat_whitespace_no_nl(const char *s)
  578. {
  579. while (*s == ' ' || *s == '\t' || *s == '\r')
  580. ++s;
  581. return s;
  582. }
  583. /** As eat_whitespace_no_nl, but stop at <b>eos</b> whether we have
  584. * found a non-whitespace character or not. */
  585. const char *
  586. eat_whitespace_eos_no_nl(const char *s, const char *eos)
  587. {
  588. while (s < eos && (*s == ' ' || *s == '\t' || *s == '\r'))
  589. ++s;
  590. return s;
  591. }
  592. /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
  593. * or to the terminating NUL if no such character exists.
  594. */
  595. const char *
  596. find_whitespace(const char *s)
  597. {
  598. /* tor_assert(s); */
  599. while (1) {
  600. switch (*s)
  601. {
  602. case '\0':
  603. case '#':
  604. case ' ':
  605. case '\r':
  606. case '\n':
  607. case '\t':
  608. return s;
  609. default:
  610. ++s;
  611. }
  612. }
  613. }
  614. /** As find_whitespace, but stop at <b>eos</b> whether we have found a
  615. * whitespace or not. */
  616. const char *
  617. find_whitespace_eos(const char *s, const char *eos)
  618. {
  619. /* tor_assert(s); */
  620. while (s < eos) {
  621. switch (*s)
  622. {
  623. case '\0':
  624. case '#':
  625. case ' ':
  626. case '\r':
  627. case '\n':
  628. case '\t':
  629. return s;
  630. default:
  631. ++s;
  632. }
  633. }
  634. return s;
  635. }
  636. /** Return the first occurrence of <b>needle</b> in <b>haystack</b> that
  637. * occurs at the start of a line (that is, at the beginning of <b>haystack</b>
  638. * or immediately after a newline). Return NULL if no such string is found.
  639. */
  640. const char *
  641. find_str_at_start_of_line(const char *haystack, const char *needle)
  642. {
  643. size_t needle_len = strlen(needle);
  644. do {
  645. if (!strncmp(haystack, needle, needle_len))
  646. return haystack;
  647. haystack = strchr(haystack, '\n');
  648. if (!haystack)
  649. return NULL;
  650. else
  651. ++haystack;
  652. } while (*haystack);
  653. return NULL;
  654. }
  655. /** Return true iff the 'len' bytes at 'mem' are all zero. */
  656. int
  657. tor_mem_is_zero(const char *mem, size_t len)
  658. {
  659. static const char ZERO[] = {
  660. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  661. };
  662. while (len >= sizeof(ZERO)) {
  663. if (memcmp(mem, ZERO, sizeof(ZERO)))
  664. return 0;
  665. len -= sizeof(ZERO);
  666. mem += sizeof(ZERO);
  667. }
  668. /* Deal with leftover bytes. */
  669. if (len)
  670. return ! memcmp(mem, ZERO, len);
  671. return 1;
  672. }
  673. /** Return true iff the DIGEST_LEN bytes in digest are all zero. */
  674. int
  675. tor_digest_is_zero(const char *digest)
  676. {
  677. return tor_mem_is_zero(digest, DIGEST_LEN);
  678. }
  679. /** Return true iff the DIGEST256_LEN bytes in digest are all zero. */
  680. int
  681. tor_digest256_is_zero(const char *digest)
  682. {
  683. return tor_mem_is_zero(digest, DIGEST256_LEN);
  684. }
  685. /* Helper: common code to check whether the result of a strtol or strtoul or
  686. * strtoll is correct. */
  687. #define CHECK_STRTOX_RESULT() \
  688. /* Was at least one character converted? */ \
  689. if (endptr == s) \
  690. goto err; \
  691. /* Were there unexpected unconverted characters? */ \
  692. if (!next && *endptr) \
  693. goto err; \
  694. /* Is r within limits? */ \
  695. if (r < min || r > max) \
  696. goto err; \
  697. if (ok) *ok = 1; \
  698. if (next) *next = endptr; \
  699. return r; \
  700. err: \
  701. if (ok) *ok = 0; \
  702. if (next) *next = endptr; \
  703. return 0
  704. /** Extract a long from the start of s, in the given numeric base. If
  705. * there is unconverted data and next is provided, set *next to the
  706. * first unconverted character. An error has occurred if no characters
  707. * are converted; or if there are unconverted characters and next is NULL; or
  708. * if the parsed value is not between min and max. When no error occurs,
  709. * return the parsed value and set *ok (if provided) to 1. When an error
  710. * occurs, return 0 and set *ok (if provided) to 0.
  711. */
  712. long
  713. tor_parse_long(const char *s, int base, long min, long max,
  714. int *ok, char **next)
  715. {
  716. char *endptr;
  717. long r;
  718. r = strtol(s, &endptr, base);
  719. CHECK_STRTOX_RESULT();
  720. }
  721. /** As tor_parse_long(), but return an unsigned long. */
  722. unsigned long
  723. tor_parse_ulong(const char *s, int base, unsigned long min,
  724. unsigned long max, int *ok, char **next)
  725. {
  726. char *endptr;
  727. unsigned long r;
  728. r = strtoul(s, &endptr, base);
  729. CHECK_STRTOX_RESULT();
  730. }
  731. /** As tor_parse_long(), but return a double. */
  732. double
  733. tor_parse_double(const char *s, double min, double max, int *ok, char **next)
  734. {
  735. char *endptr;
  736. double r;
  737. r = strtod(s, &endptr);
  738. CHECK_STRTOX_RESULT();
  739. }
  740. /** As tor_parse_long, but return a uint64_t. Only base 10 is guaranteed to
  741. * work for now. */
  742. uint64_t
  743. tor_parse_uint64(const char *s, int base, uint64_t min,
  744. uint64_t max, int *ok, char **next)
  745. {
  746. char *endptr;
  747. uint64_t r;
  748. #ifdef HAVE_STRTOULL
  749. r = (uint64_t)strtoull(s, &endptr, base);
  750. #elif defined(MS_WINDOWS)
  751. #if defined(_MSC_VER) && _MSC_VER < 1300
  752. tor_assert(base <= 10);
  753. r = (uint64_t)_atoi64(s);
  754. endptr = (char*)s;
  755. while (TOR_ISSPACE(*endptr)) endptr++;
  756. while (TOR_ISDIGIT(*endptr)) endptr++;
  757. #else
  758. r = (uint64_t)_strtoui64(s, &endptr, base);
  759. #endif
  760. #elif SIZEOF_LONG == 8
  761. r = (uint64_t)strtoul(s, &endptr, base);
  762. #else
  763. #error "I don't know how to parse 64-bit numbers."
  764. #endif
  765. CHECK_STRTOX_RESULT();
  766. }
  767. /** Encode the <b>srclen</b> bytes at <b>src</b> in a NUL-terminated,
  768. * uppercase hexadecimal string; store it in the <b>destlen</b>-byte buffer
  769. * <b>dest</b>.
  770. */
  771. void
  772. base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  773. {
  774. const char *end;
  775. char *cp;
  776. tor_assert(destlen >= srclen*2+1);
  777. tor_assert(destlen < SIZE_T_CEILING);
  778. cp = dest;
  779. end = src+srclen;
  780. while (src<end) {
  781. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) >> 4 ];
  782. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) & 0xf ];
  783. ++src;
  784. }
  785. *cp = '\0';
  786. }
  787. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  788. static INLINE int
  789. _hex_decode_digit(char c)
  790. {
  791. switch (c) {
  792. case '0': return 0;
  793. case '1': return 1;
  794. case '2': return 2;
  795. case '3': return 3;
  796. case '4': return 4;
  797. case '5': return 5;
  798. case '6': return 6;
  799. case '7': return 7;
  800. case '8': return 8;
  801. case '9': return 9;
  802. case 'A': case 'a': return 10;
  803. case 'B': case 'b': return 11;
  804. case 'C': case 'c': return 12;
  805. case 'D': case 'd': return 13;
  806. case 'E': case 'e': return 14;
  807. case 'F': case 'f': return 15;
  808. default:
  809. return -1;
  810. }
  811. }
  812. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  813. int
  814. hex_decode_digit(char c)
  815. {
  816. return _hex_decode_digit(c);
  817. }
  818. /** Given a hexadecimal string of <b>srclen</b> bytes in <b>src</b>, decode it
  819. * and store the result in the <b>destlen</b>-byte buffer at <b>dest</b>.
  820. * Return 0 on success, -1 on failure. */
  821. int
  822. base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  823. {
  824. const char *end;
  825. int v1,v2;
  826. if ((srclen % 2) != 0)
  827. return -1;
  828. if (destlen < srclen/2 || destlen > SIZE_T_CEILING)
  829. return -1;
  830. end = src+srclen;
  831. while (src<end) {
  832. v1 = _hex_decode_digit(*src);
  833. v2 = _hex_decode_digit(*(src+1));
  834. if (v1<0||v2<0)
  835. return -1;
  836. *(uint8_t*)dest = (v1<<4)|v2;
  837. ++dest;
  838. src+=2;
  839. }
  840. return 0;
  841. }
  842. /** Allocate and return a new string representing the contents of <b>s</b>,
  843. * surrounded by quotes and using standard C escapes.
  844. *
  845. * Generally, we use this for logging values that come in over the network to
  846. * keep them from tricking users, and for sending certain values to the
  847. * controller.
  848. *
  849. * We trust values from the resolver, OS, configuration file, and command line
  850. * to not be maliciously ill-formed. We validate incoming routerdescs and
  851. * SOCKS requests and addresses from BEGIN cells as they're parsed;
  852. * afterwards, we trust them as non-malicious.
  853. */
  854. char *
  855. esc_for_log(const char *s)
  856. {
  857. const char *cp;
  858. char *result, *outp;
  859. size_t len = 3;
  860. if (!s) {
  861. return tor_strdup("");
  862. }
  863. for (cp = s; *cp; ++cp) {
  864. switch (*cp) {
  865. case '\\':
  866. case '\"':
  867. case '\'':
  868. case '\r':
  869. case '\n':
  870. case '\t':
  871. len += 2;
  872. break;
  873. default:
  874. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127)
  875. ++len;
  876. else
  877. len += 4;
  878. break;
  879. }
  880. }
  881. result = outp = tor_malloc(len);
  882. *outp++ = '\"';
  883. for (cp = s; *cp; ++cp) {
  884. switch (*cp) {
  885. case '\\':
  886. case '\"':
  887. case '\'':
  888. *outp++ = '\\';
  889. *outp++ = *cp;
  890. break;
  891. case '\n':
  892. *outp++ = '\\';
  893. *outp++ = 'n';
  894. break;
  895. case '\t':
  896. *outp++ = '\\';
  897. *outp++ = 't';
  898. break;
  899. case '\r':
  900. *outp++ = '\\';
  901. *outp++ = 'r';
  902. break;
  903. default:
  904. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127) {
  905. *outp++ = *cp;
  906. } else {
  907. tor_snprintf(outp, 5, "\\%03o", (int)(uint8_t) *cp);
  908. outp += 4;
  909. }
  910. break;
  911. }
  912. }
  913. *outp++ = '\"';
  914. *outp++ = 0;
  915. return result;
  916. }
  917. /** Allocate and return a new string representing the contents of <b>s</b>,
  918. * surrounded by quotes and using standard C escapes.
  919. *
  920. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  921. * thread. Also, each call invalidates the last-returned value, so don't
  922. * try log_warn(LD_GENERAL, "%s %s", escaped(a), escaped(b));
  923. */
  924. const char *
  925. escaped(const char *s)
  926. {
  927. static char *_escaped_val = NULL;
  928. tor_free(_escaped_val);
  929. if (s)
  930. _escaped_val = esc_for_log(s);
  931. else
  932. _escaped_val = NULL;
  933. return _escaped_val;
  934. }
  935. /** Rudimentary string wrapping code: given a un-wrapped <b>string</b> (no
  936. * newlines!), break the string into newline-terminated lines of no more than
  937. * <b>width</b> characters long (not counting newline) and insert them into
  938. * <b>out</b> in order. Precede the first line with prefix0, and subsequent
  939. * lines with prefixRest.
  940. */
  941. /* This uses a stupid greedy wrapping algorithm right now:
  942. * - For each line:
  943. * - Try to fit as much stuff as possible, but break on a space.
  944. * - If the first "word" of the line will extend beyond the allowable
  945. * width, break the word at the end of the width.
  946. */
  947. void
  948. wrap_string(smartlist_t *out, const char *string, size_t width,
  949. const char *prefix0, const char *prefixRest)
  950. {
  951. size_t p0Len, pRestLen, pCurLen;
  952. const char *eos, *prefixCur;
  953. tor_assert(out);
  954. tor_assert(string);
  955. tor_assert(width);
  956. if (!prefix0)
  957. prefix0 = "";
  958. if (!prefixRest)
  959. prefixRest = "";
  960. p0Len = strlen(prefix0);
  961. pRestLen = strlen(prefixRest);
  962. tor_assert(width > p0Len && width > pRestLen);
  963. eos = strchr(string, '\0');
  964. tor_assert(eos);
  965. pCurLen = p0Len;
  966. prefixCur = prefix0;
  967. while ((eos-string)+pCurLen > width) {
  968. const char *eol = string + width - pCurLen;
  969. while (eol > string && *eol != ' ')
  970. --eol;
  971. /* eol is now the last space that can fit, or the start of the string. */
  972. if (eol > string) {
  973. size_t line_len = (eol-string) + pCurLen + 2;
  974. char *line = tor_malloc(line_len);
  975. memcpy(line, prefixCur, pCurLen);
  976. memcpy(line+pCurLen, string, eol-string);
  977. line[line_len-2] = '\n';
  978. line[line_len-1] = '\0';
  979. smartlist_add(out, line);
  980. string = eol + 1;
  981. } else {
  982. size_t line_len = width + 2;
  983. char *line = tor_malloc(line_len);
  984. memcpy(line, prefixCur, pCurLen);
  985. memcpy(line+pCurLen, string, width - pCurLen);
  986. line[line_len-2] = '\n';
  987. line[line_len-1] = '\0';
  988. smartlist_add(out, line);
  989. string += width-pCurLen;
  990. }
  991. prefixCur = prefixRest;
  992. pCurLen = pRestLen;
  993. }
  994. if (string < eos) {
  995. size_t line_len = (eos-string) + pCurLen + 2;
  996. char *line = tor_malloc(line_len);
  997. memcpy(line, prefixCur, pCurLen);
  998. memcpy(line+pCurLen, string, eos-string);
  999. line[line_len-2] = '\n';
  1000. line[line_len-1] = '\0';
  1001. smartlist_add(out, line);
  1002. }
  1003. }
  1004. /* =====
  1005. * Time
  1006. * ===== */
  1007. /**
  1008. * Converts struct timeval to a double value.
  1009. * Preserves microsecond precision, but just barely.
  1010. * Error is approx +/- 0.1 usec when dealing with epoch values.
  1011. */
  1012. double
  1013. tv_to_double(const struct timeval *tv)
  1014. {
  1015. double conv = tv->tv_sec;
  1016. conv += tv->tv_usec/1000000.0;
  1017. return conv;
  1018. }
  1019. /**
  1020. * Converts timeval to milliseconds.
  1021. */
  1022. int64_t
  1023. tv_to_msec(const struct timeval *tv)
  1024. {
  1025. int64_t conv = ((int64_t)tv->tv_sec)*1000L;
  1026. /* Round ghetto-style */
  1027. conv += ((int64_t)tv->tv_usec+500)/1000L;
  1028. return conv;
  1029. }
  1030. /**
  1031. * Converts timeval to microseconds.
  1032. */
  1033. int64_t
  1034. tv_to_usec(const struct timeval *tv)
  1035. {
  1036. int64_t conv = ((int64_t)tv->tv_sec)*1000000L;
  1037. conv += tv->tv_usec;
  1038. return conv;
  1039. }
  1040. /** Return the number of microseconds elapsed between *start and *end.
  1041. */
  1042. long
  1043. tv_udiff(const struct timeval *start, const struct timeval *end)
  1044. {
  1045. long udiff;
  1046. long secdiff = end->tv_sec - start->tv_sec;
  1047. if (labs(secdiff+1) > LONG_MAX/1000000) {
  1048. log_warn(LD_GENERAL, "comparing times on microsecond detail too far "
  1049. "apart: %ld seconds", secdiff);
  1050. return LONG_MAX;
  1051. }
  1052. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  1053. return udiff;
  1054. }
  1055. /** Return the number of milliseconds elapsed between *start and *end.
  1056. */
  1057. long
  1058. tv_mdiff(const struct timeval *start, const struct timeval *end)
  1059. {
  1060. long mdiff;
  1061. long secdiff = end->tv_sec - start->tv_sec;
  1062. if (labs(secdiff+1) > LONG_MAX/1000) {
  1063. log_warn(LD_GENERAL, "comparing times on millisecond detail too far "
  1064. "apart: %ld seconds", secdiff);
  1065. return LONG_MAX;
  1066. }
  1067. /* Subtract and round */
  1068. mdiff = secdiff*1000L +
  1069. ((long)end->tv_usec - (long)start->tv_usec + 500L) / 1000L;
  1070. return mdiff;
  1071. }
  1072. /** Yield true iff <b>y</b> is a leap-year. */
  1073. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  1074. /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
  1075. static int
  1076. n_leapdays(int y1, int y2)
  1077. {
  1078. --y1;
  1079. --y2;
  1080. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  1081. }
  1082. /** Number of days per month in non-leap year; used by tor_timegm. */
  1083. static const int days_per_month[] =
  1084. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  1085. /** Return a time_t given a struct tm. The result is given in GMT, and
  1086. * does not account for leap seconds.
  1087. */
  1088. time_t
  1089. tor_timegm(struct tm *tm)
  1090. {
  1091. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  1092. * It's way more brute-force than fiddling with tzset().
  1093. */
  1094. time_t year, days, hours, minutes, seconds;
  1095. int i;
  1096. year = tm->tm_year + 1900;
  1097. if (year < 1970 || tm->tm_mon < 0 || tm->tm_mon > 11) {
  1098. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  1099. return -1;
  1100. }
  1101. tor_assert(year < INT_MAX);
  1102. days = 365 * (year-1970) + n_leapdays(1970,(int)year);
  1103. for (i = 0; i < tm->tm_mon; ++i)
  1104. days += days_per_month[i];
  1105. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  1106. ++days;
  1107. days += tm->tm_mday - 1;
  1108. hours = days*24 + tm->tm_hour;
  1109. minutes = hours*60 + tm->tm_min;
  1110. seconds = minutes*60 + tm->tm_sec;
  1111. return seconds;
  1112. }
  1113. /* strftime is locale-specific, so we need to replace those parts */
  1114. /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
  1115. static const char *WEEKDAY_NAMES[] =
  1116. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1117. /** A c-locale array of 3-letter names of months, starting with Jan. */
  1118. static const char *MONTH_NAMES[] =
  1119. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  1120. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1121. /** Set <b>buf</b> to the RFC1123 encoding of the GMT value of <b>t</b>.
  1122. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  1123. *
  1124. * (RFC1123 format is Fri, 29 Sep 2006 15:54:20 GMT)
  1125. */
  1126. void
  1127. format_rfc1123_time(char *buf, time_t t)
  1128. {
  1129. struct tm tm;
  1130. tor_gmtime_r(&t, &tm);
  1131. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  1132. tor_assert(tm.tm_wday >= 0);
  1133. tor_assert(tm.tm_wday <= 6);
  1134. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  1135. tor_assert(tm.tm_wday >= 0);
  1136. tor_assert(tm.tm_mon <= 11);
  1137. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  1138. }
  1139. /** Parse the RFC1123 encoding of some time (in GMT) from <b>buf</b>,
  1140. * and store the result in *<b>t</b>.
  1141. *
  1142. * Return 0 on success, -1 on failure.
  1143. */
  1144. int
  1145. parse_rfc1123_time(const char *buf, time_t *t)
  1146. {
  1147. struct tm tm;
  1148. char month[4];
  1149. char weekday[4];
  1150. int i, m;
  1151. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1152. if (strlen(buf) != RFC1123_TIME_LEN)
  1153. return -1;
  1154. memset(&tm, 0, sizeof(tm));
  1155. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  1156. &tm_mday, month, &tm_year, &tm_hour,
  1157. &tm_min, &tm_sec) < 7) {
  1158. char *esc = esc_for_log(buf);
  1159. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1160. tor_free(esc);
  1161. return -1;
  1162. }
  1163. if (tm_mday > 31 || tm_hour > 23 || tm_min > 59 || tm_sec > 61) {
  1164. char *esc = esc_for_log(buf);
  1165. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1166. tor_free(esc);
  1167. return -1;
  1168. }
  1169. tm.tm_mday = (int)tm_mday;
  1170. tm.tm_year = (int)tm_year;
  1171. tm.tm_hour = (int)tm_hour;
  1172. tm.tm_min = (int)tm_min;
  1173. tm.tm_sec = (int)tm_sec;
  1174. m = -1;
  1175. for (i = 0; i < 12; ++i) {
  1176. if (!strcmp(month, MONTH_NAMES[i])) {
  1177. m = i;
  1178. break;
  1179. }
  1180. }
  1181. if (m<0) {
  1182. char *esc = esc_for_log(buf);
  1183. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  1184. tor_free(esc);
  1185. return -1;
  1186. }
  1187. tm.tm_mon = m;
  1188. if (tm.tm_year < 1970) {
  1189. char *esc = esc_for_log(buf);
  1190. log_warn(LD_GENERAL,
  1191. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  1192. tor_free(esc);
  1193. return -1;
  1194. }
  1195. tm.tm_year -= 1900;
  1196. *t = tor_timegm(&tm);
  1197. return 0;
  1198. }
  1199. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  1200. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1201. *
  1202. * (ISO8601 format is 2006-10-29 10:57:20)
  1203. */
  1204. void
  1205. format_local_iso_time(char *buf, time_t t)
  1206. {
  1207. struct tm tm;
  1208. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  1209. }
  1210. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  1211. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1212. */
  1213. void
  1214. format_iso_time(char *buf, time_t t)
  1215. {
  1216. struct tm tm;
  1217. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  1218. }
  1219. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  1220. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  1221. * failure. Ignore extraneous stuff in <b>cp</b> separated by whitespace from
  1222. * the end of the time string. */
  1223. int
  1224. parse_iso_time(const char *cp, time_t *t)
  1225. {
  1226. struct tm st_tm;
  1227. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  1228. if (tor_sscanf(cp, "%u-%2u-%2u %2u:%2u:%2u", &year, &month,
  1229. &day, &hour, &minute, &second) < 6) {
  1230. char *esc = esc_for_log(cp);
  1231. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  1232. tor_free(esc);
  1233. return -1;
  1234. }
  1235. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  1236. hour > 23 || minute > 59 || second > 61) {
  1237. char *esc = esc_for_log(cp);
  1238. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  1239. tor_free(esc);
  1240. return -1;
  1241. }
  1242. st_tm.tm_year = year-1900;
  1243. st_tm.tm_mon = month-1;
  1244. st_tm.tm_mday = day;
  1245. st_tm.tm_hour = hour;
  1246. st_tm.tm_min = minute;
  1247. st_tm.tm_sec = second;
  1248. if (st_tm.tm_year < 70) {
  1249. char *esc = esc_for_log(cp);
  1250. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  1251. tor_free(esc);
  1252. return -1;
  1253. }
  1254. *t = tor_timegm(&st_tm);
  1255. return 0;
  1256. }
  1257. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  1258. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  1259. int
  1260. parse_http_time(const char *date, struct tm *tm)
  1261. {
  1262. const char *cp;
  1263. char month[4];
  1264. char wkday[4];
  1265. int i;
  1266. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1267. tor_assert(tm);
  1268. memset(tm, 0, sizeof(*tm));
  1269. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  1270. if ((cp = strchr(date, ','))) {
  1271. ++cp;
  1272. if (tor_sscanf(date, "%2u %3s %4u %2u:%2u:%2u GMT",
  1273. &tm_mday, month, &tm_year,
  1274. &tm_hour, &tm_min, &tm_sec) == 6) {
  1275. /* rfc1123-date */
  1276. tm_year -= 1900;
  1277. } else if (tor_sscanf(date, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  1278. &tm_mday, month, &tm_year,
  1279. &tm_hour, &tm_min, &tm_sec) == 6) {
  1280. /* rfc850-date */
  1281. } else {
  1282. return -1;
  1283. }
  1284. } else {
  1285. /* No comma; possibly asctime() format. */
  1286. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  1287. wkday, month, &tm_mday,
  1288. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  1289. tm_year -= 1900;
  1290. } else {
  1291. return -1;
  1292. }
  1293. }
  1294. tm->tm_mday = (int)tm_mday;
  1295. tm->tm_year = (int)tm_year;
  1296. tm->tm_hour = (int)tm_hour;
  1297. tm->tm_min = (int)tm_min;
  1298. tm->tm_sec = (int)tm_sec;
  1299. month[3] = '\0';
  1300. /* Okay, now decode the month. */
  1301. for (i = 0; i < 12; ++i) {
  1302. if (!strcasecmp(MONTH_NAMES[i], month)) {
  1303. tm->tm_mon = i+1;
  1304. }
  1305. }
  1306. if (tm->tm_year < 0 ||
  1307. tm->tm_mon < 1 || tm->tm_mon > 12 ||
  1308. tm->tm_mday < 0 || tm->tm_mday > 31 ||
  1309. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1310. tm->tm_min < 0 || tm->tm_min > 59 ||
  1311. tm->tm_sec < 0 || tm->tm_sec > 61)
  1312. return -1; /* Out of range, or bad month. */
  1313. return 0;
  1314. }
  1315. /** Given an <b>interval</b> in seconds, try to write it to the
  1316. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  1317. * Return 0 on success, -1 on failure.
  1318. */
  1319. int
  1320. format_time_interval(char *out, size_t out_len, long interval)
  1321. {
  1322. /* We only report seconds if there's no hours. */
  1323. long sec = 0, min = 0, hour = 0, day = 0;
  1324. if (interval < 0)
  1325. interval = -interval;
  1326. if (interval >= 86400) {
  1327. day = interval / 86400;
  1328. interval %= 86400;
  1329. }
  1330. if (interval >= 3600) {
  1331. hour = interval / 3600;
  1332. interval %= 3600;
  1333. }
  1334. if (interval >= 60) {
  1335. min = interval / 60;
  1336. interval %= 60;
  1337. }
  1338. sec = interval;
  1339. if (day) {
  1340. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  1341. day, hour, min);
  1342. } else if (hour) {
  1343. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  1344. } else if (min) {
  1345. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  1346. } else {
  1347. return tor_snprintf(out, out_len, "%ld seconds", sec);
  1348. }
  1349. }
  1350. /* =====
  1351. * Cached time
  1352. * ===== */
  1353. #ifndef TIME_IS_FAST
  1354. /** Cached estimate of the current time. Updated around once per second;
  1355. * may be a few seconds off if we are really busy. This is a hack to avoid
  1356. * calling time(NULL) (which not everybody has optimized) on critical paths.
  1357. */
  1358. static time_t cached_approx_time = 0;
  1359. /** Return a cached estimate of the current time from when
  1360. * update_approx_time() was last called. This is a hack to avoid calling
  1361. * time(NULL) on critical paths: please do not even think of calling it
  1362. * anywhere else. */
  1363. time_t
  1364. approx_time(void)
  1365. {
  1366. return cached_approx_time;
  1367. }
  1368. /** Update the cached estimate of the current time. This function SHOULD be
  1369. * called once per second, and MUST be called before the first call to
  1370. * get_approx_time. */
  1371. void
  1372. update_approx_time(time_t now)
  1373. {
  1374. cached_approx_time = now;
  1375. }
  1376. #endif
  1377. /* =====
  1378. * Fuzzy time
  1379. * XXXX022 Use this consistently or rip most of it out.
  1380. * ===== */
  1381. /* In a perfect world, everybody would run NTP, and NTP would be perfect, so
  1382. * if we wanted to know "Is the current time before time X?" we could just say
  1383. * "time(NULL) < X".
  1384. *
  1385. * But unfortunately, many users are running Tor in an imperfect world, on
  1386. * even more imperfect computers. Hence, we need to track time oddly. We
  1387. * model the user's computer as being "skewed" from accurate time by
  1388. * -<b>ftime_skew</b> seconds, such that our best guess of the current time is
  1389. * time(NULL)+ftime_skew. We also assume that our measurements of time may
  1390. * have up to <b>ftime_slop</b> seconds of inaccuracy; IOW, our window of
  1391. * estimate for the current time is now + ftime_skew +/- ftime_slop.
  1392. */
  1393. /** Our current estimate of our skew, such that we think the current time is
  1394. * closest to time(NULL)+ftime_skew. */
  1395. static int ftime_skew = 0;
  1396. /** Tolerance during time comparisons, in seconds. */
  1397. static int ftime_slop = 60;
  1398. /** Set the largest amount of sloppiness we'll allow in fuzzy time
  1399. * comparisons. */
  1400. void
  1401. ftime_set_maximum_sloppiness(int seconds)
  1402. {
  1403. tor_assert(seconds >= 0);
  1404. ftime_slop = seconds;
  1405. }
  1406. /** Set the amount by which we believe our system clock to differ from
  1407. * real time. */
  1408. void
  1409. ftime_set_estimated_skew(int seconds)
  1410. {
  1411. ftime_skew = seconds;
  1412. }
  1413. #if 0
  1414. void
  1415. ftime_get_window(time_t now, ftime_t *ft_out)
  1416. {
  1417. ft_out->earliest = now + ftime_skew - ftime_slop;
  1418. ft_out->latest = now + ftime_skew + ftime_slop;
  1419. }
  1420. #endif
  1421. /** Return true iff we think that <b>now</b> might be after <b>when</b>. */
  1422. int
  1423. ftime_maybe_after(time_t now, time_t when)
  1424. {
  1425. /* It may be after when iff the latest possible current time is after when */
  1426. return (now + ftime_skew + ftime_slop) >= when;
  1427. }
  1428. /** Return true iff we think that <b>now</b> might be before <b>when</b>. */
  1429. int
  1430. ftime_maybe_before(time_t now, time_t when)
  1431. {
  1432. /* It may be before when iff the earliest possible current time is before */
  1433. return (now + ftime_skew - ftime_slop) < when;
  1434. }
  1435. /** Return true if we think that <b>now</b> is definitely after <b>when</b>. */
  1436. int
  1437. ftime_definitely_after(time_t now, time_t when)
  1438. {
  1439. /* It is definitely after when if the earliest time it could be is still
  1440. * after when. */
  1441. return (now + ftime_skew - ftime_slop) >= when;
  1442. }
  1443. /** Return true if we think that <b>now</b> is definitely before <b>when</b>.
  1444. */
  1445. int
  1446. ftime_definitely_before(time_t now, time_t when)
  1447. {
  1448. /* It is definitely before when if the latest time it could be is still
  1449. * before when. */
  1450. return (now + ftime_skew + ftime_slop) < when;
  1451. }
  1452. /* =====
  1453. * Rate limiting
  1454. * ===== */
  1455. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return the number
  1456. * of calls to rate_limit_is_ready (including this one!) since the last time
  1457. * rate_limit_is_ready returned nonzero. Otherwise return 0. */
  1458. static int
  1459. rate_limit_is_ready(ratelim_t *lim, time_t now)
  1460. {
  1461. if (lim->rate + lim->last_allowed <= now) {
  1462. int res = lim->n_calls_since_last_time + 1;
  1463. lim->last_allowed = now;
  1464. lim->n_calls_since_last_time = 0;
  1465. return res;
  1466. } else {
  1467. ++lim->n_calls_since_last_time;
  1468. return 0;
  1469. }
  1470. }
  1471. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return a newly
  1472. * allocated string indicating how many messages were suppressed, suitable to
  1473. * append to a log message. Otherwise return NULL. */
  1474. char *
  1475. rate_limit_log(ratelim_t *lim, time_t now)
  1476. {
  1477. int n;
  1478. if ((n = rate_limit_is_ready(lim, now))) {
  1479. if (n == 1) {
  1480. return tor_strdup("");
  1481. } else {
  1482. char *cp=NULL;
  1483. tor_asprintf(&cp,
  1484. " [%d similar message(s) suppressed in last %d seconds]",
  1485. n-1, lim->rate);
  1486. return cp;
  1487. }
  1488. } else {
  1489. return NULL;
  1490. }
  1491. }
  1492. /* =====
  1493. * File helpers
  1494. * ===== */
  1495. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1496. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1497. * was returned by open(). Return the number of bytes written, or -1
  1498. * on error. Only use if fd is a blocking fd. */
  1499. ssize_t
  1500. write_all(int fd, const char *buf, size_t count, int isSocket)
  1501. {
  1502. size_t written = 0;
  1503. ssize_t result;
  1504. tor_assert(count < SSIZE_T_MAX);
  1505. while (written != count) {
  1506. if (isSocket)
  1507. result = tor_socket_send(fd, buf+written, count-written, 0);
  1508. else
  1509. result = write(fd, buf+written, count-written);
  1510. if (result<0)
  1511. return -1;
  1512. written += result;
  1513. }
  1514. return (ssize_t)count;
  1515. }
  1516. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1517. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1518. * was returned by socket() or accept(), and 0 if fd was returned by
  1519. * open(). Return the number of bytes read, or -1 on error. Only use
  1520. * if fd is a blocking fd. */
  1521. ssize_t
  1522. read_all(int fd, char *buf, size_t count, int isSocket)
  1523. {
  1524. size_t numread = 0;
  1525. ssize_t result;
  1526. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  1527. return -1;
  1528. while (numread != count) {
  1529. if (isSocket)
  1530. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1531. else
  1532. result = read(fd, buf+numread, count-numread);
  1533. if (result<0)
  1534. return -1;
  1535. else if (result == 0)
  1536. break;
  1537. numread += result;
  1538. }
  1539. return (ssize_t)numread;
  1540. }
  1541. /*
  1542. * Filesystem operations.
  1543. */
  1544. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1545. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1546. * the root of a disk. */
  1547. static void
  1548. clean_name_for_stat(char *name)
  1549. {
  1550. #ifdef MS_WINDOWS
  1551. size_t len = strlen(name);
  1552. if (!len)
  1553. return;
  1554. if (name[len-1]=='\\' || name[len-1]=='/') {
  1555. if (len == 1 || (len==3 && name[1]==':'))
  1556. return;
  1557. name[len-1]='\0';
  1558. }
  1559. #else
  1560. (void)name;
  1561. #endif
  1562. }
  1563. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1564. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1565. * directory. On FN_ERROR, sets errno. */
  1566. file_status_t
  1567. file_status(const char *fname)
  1568. {
  1569. struct stat st;
  1570. char *f;
  1571. int r;
  1572. f = tor_strdup(fname);
  1573. clean_name_for_stat(f);
  1574. r = stat(f, &st);
  1575. tor_free(f);
  1576. if (r) {
  1577. if (errno == ENOENT) {
  1578. return FN_NOENT;
  1579. }
  1580. return FN_ERROR;
  1581. }
  1582. if (st.st_mode & S_IFDIR)
  1583. return FN_DIR;
  1584. else if (st.st_mode & S_IFREG)
  1585. return FN_FILE;
  1586. else
  1587. return FN_ERROR;
  1588. }
  1589. /** Check whether dirname exists and is private. If yes return 0. If
  1590. * it does not exist, and check==CPD_CREATE is set, try to create it
  1591. * and return 0 on success. If it does not exist, and
  1592. * check==CPD_CHECK, and we think we can create it, return 0. Else
  1593. * return -1. */
  1594. int
  1595. check_private_dir(const char *dirname, cpd_check_t check)
  1596. {
  1597. int r;
  1598. struct stat st;
  1599. char *f;
  1600. tor_assert(dirname);
  1601. f = tor_strdup(dirname);
  1602. clean_name_for_stat(f);
  1603. r = stat(f, &st);
  1604. tor_free(f);
  1605. if (r) {
  1606. if (errno != ENOENT) {
  1607. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1608. strerror(errno));
  1609. return -1;
  1610. }
  1611. if (check == CPD_NONE) {
  1612. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1613. return -1;
  1614. } else if (check == CPD_CREATE) {
  1615. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1616. #if defined (MS_WINDOWS) && !defined (WINCE)
  1617. r = mkdir(dirname);
  1618. #else
  1619. r = mkdir(dirname, 0700);
  1620. #endif
  1621. if (r) {
  1622. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1623. strerror(errno));
  1624. return -1;
  1625. }
  1626. }
  1627. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1628. * parent directory a little harder. */
  1629. return 0;
  1630. }
  1631. if (!(st.st_mode & S_IFDIR)) {
  1632. log_warn(LD_FS, "%s is not a directory", dirname);
  1633. return -1;
  1634. }
  1635. #ifndef MS_WINDOWS
  1636. if (st.st_uid != getuid()) {
  1637. struct passwd *pw = NULL;
  1638. char *process_ownername = NULL;
  1639. pw = getpwuid(getuid());
  1640. process_ownername = pw ? tor_strdup(pw->pw_name) : tor_strdup("<unknown>");
  1641. pw = getpwuid(st.st_uid);
  1642. log_warn(LD_FS, "%s is not owned by this user (%s, %d) but by "
  1643. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1644. dirname, process_ownername, (int)getuid(),
  1645. pw ? pw->pw_name : "<unknown>", (int)st.st_uid);
  1646. tor_free(process_ownername);
  1647. return -1;
  1648. }
  1649. if (st.st_mode & 0077) {
  1650. log_warn(LD_FS, "Fixing permissions on directory %s", dirname);
  1651. if (chmod(dirname, 0700)) {
  1652. log_warn(LD_FS, "Could not chmod directory %s: %s", dirname,
  1653. strerror(errno));
  1654. return -1;
  1655. } else {
  1656. return 0;
  1657. }
  1658. }
  1659. #endif
  1660. return 0;
  1661. }
  1662. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1663. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1664. *
  1665. * This function replaces the old file atomically, if possible. This
  1666. * function, and all other functions in util.c that create files, create them
  1667. * with mode 0600.
  1668. */
  1669. int
  1670. write_str_to_file(const char *fname, const char *str, int bin)
  1671. {
  1672. #ifdef MS_WINDOWS
  1673. if (!bin && strchr(str, '\r')) {
  1674. log_warn(LD_BUG,
  1675. "We're writing a text string that already contains a CR.");
  1676. }
  1677. #endif
  1678. return write_bytes_to_file(fname, str, strlen(str), bin);
  1679. }
  1680. /** Represents a file that we're writing to, with support for atomic commit:
  1681. * we can write into a temporary file, and either remove the file on
  1682. * failure, or replace the original file on success. */
  1683. struct open_file_t {
  1684. char *tempname; /**< Name of the temporary file. */
  1685. char *filename; /**< Name of the original file. */
  1686. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  1687. unsigned binary:1; /**< Did we open in binary mode? */
  1688. int fd; /**< fd for the open file. */
  1689. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  1690. };
  1691. /** Try to start writing to the file in <b>fname</b>, passing the flags
  1692. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  1693. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  1694. * original file. Otherwise, we open a new temporary file in the same
  1695. * directory, and either replace the original or remove the temporary file
  1696. * when we're done.
  1697. *
  1698. * Return the fd for the newly opened file, and store working data in
  1699. * *<b>data_out</b>. The caller should not close the fd manually:
  1700. * instead, call finish_writing_to_file() or abort_writing_to_file().
  1701. * Returns -1 on failure.
  1702. *
  1703. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  1704. * as true and the flag O_EXCL is treated as false.
  1705. *
  1706. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  1707. * write()". We don't do that.
  1708. */
  1709. int
  1710. start_writing_to_file(const char *fname, int open_flags, int mode,
  1711. open_file_t **data_out)
  1712. {
  1713. size_t tempname_len = strlen(fname)+16;
  1714. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  1715. const char *open_name;
  1716. int append = 0;
  1717. tor_assert(fname);
  1718. tor_assert(data_out);
  1719. #if (O_BINARY != 0 && O_TEXT != 0)
  1720. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  1721. #endif
  1722. new_file->fd = -1;
  1723. tor_assert(tempname_len > strlen(fname)); /*check for overflow*/
  1724. new_file->filename = tor_strdup(fname);
  1725. if (open_flags & O_APPEND) {
  1726. open_name = fname;
  1727. new_file->rename_on_close = 0;
  1728. append = 1;
  1729. open_flags &= ~O_APPEND;
  1730. } else {
  1731. open_name = new_file->tempname = tor_malloc(tempname_len);
  1732. if (tor_snprintf(new_file->tempname, tempname_len, "%s.tmp", fname)<0) {
  1733. log_warn(LD_GENERAL, "Failed to generate filename");
  1734. goto err;
  1735. }
  1736. /* We always replace an existing temporary file if there is one. */
  1737. open_flags |= O_CREAT|O_TRUNC;
  1738. open_flags &= ~O_EXCL;
  1739. new_file->rename_on_close = 1;
  1740. }
  1741. if (open_flags & O_BINARY)
  1742. new_file->binary = 1;
  1743. new_file->fd = open(open_name, open_flags, mode);
  1744. if (new_file->fd < 0) {
  1745. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  1746. open_name, fname, strerror(errno));
  1747. goto err;
  1748. }
  1749. if (append) {
  1750. if (tor_fd_seekend(new_file->fd) < 0) {
  1751. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  1752. strerror(errno));
  1753. goto err;
  1754. }
  1755. }
  1756. *data_out = new_file;
  1757. return new_file->fd;
  1758. err:
  1759. if (new_file->fd >= 0)
  1760. close(new_file->fd);
  1761. *data_out = NULL;
  1762. tor_free(new_file->filename);
  1763. tor_free(new_file->tempname);
  1764. tor_free(new_file);
  1765. return -1;
  1766. }
  1767. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  1768. * that can be used to write to the same file. The caller should not mix
  1769. * stdio calls with non-stdio calls. */
  1770. FILE *
  1771. fdopen_file(open_file_t *file_data)
  1772. {
  1773. tor_assert(file_data);
  1774. if (file_data->stdio_file)
  1775. return file_data->stdio_file;
  1776. tor_assert(file_data->fd >= 0);
  1777. if (!(file_data->stdio_file = fdopen(file_data->fd,
  1778. file_data->binary?"ab":"a"))) {
  1779. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  1780. file_data->fd, strerror(errno));
  1781. }
  1782. return file_data->stdio_file;
  1783. }
  1784. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  1785. * for start_writing_to_file, but */
  1786. FILE *
  1787. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  1788. open_file_t **data_out)
  1789. {
  1790. FILE *res;
  1791. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  1792. return NULL;
  1793. if (!(res = fdopen_file(*data_out))) {
  1794. abort_writing_to_file(*data_out);
  1795. *data_out = NULL;
  1796. }
  1797. return res;
  1798. }
  1799. /** Helper function: close and free the underlying file and memory in
  1800. * <b>file_data</b>. If we were writing into a temporary file, then delete
  1801. * that file (if abort_write is true) or replaces the target file with
  1802. * the temporary file (if abort_write is false). */
  1803. static int
  1804. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  1805. {
  1806. int r = 0;
  1807. tor_assert(file_data && file_data->filename);
  1808. if (file_data->stdio_file) {
  1809. if (fclose(file_data->stdio_file)) {
  1810. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  1811. strerror(errno));
  1812. abort_write = r = -1;
  1813. }
  1814. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  1815. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  1816. strerror(errno));
  1817. abort_write = r = -1;
  1818. }
  1819. if (file_data->rename_on_close) {
  1820. tor_assert(file_data->tempname && file_data->filename);
  1821. if (abort_write) {
  1822. unlink(file_data->tempname);
  1823. } else {
  1824. tor_assert(strcmp(file_data->filename, file_data->tempname));
  1825. if (replace_file(file_data->tempname, file_data->filename)) {
  1826. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  1827. strerror(errno));
  1828. r = -1;
  1829. }
  1830. }
  1831. }
  1832. tor_free(file_data->filename);
  1833. tor_free(file_data->tempname);
  1834. tor_free(file_data);
  1835. return r;
  1836. }
  1837. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1838. * needed, and if using a temporary file, replace the original file with
  1839. * the temporary file. */
  1840. int
  1841. finish_writing_to_file(open_file_t *file_data)
  1842. {
  1843. return finish_writing_to_file_impl(file_data, 0);
  1844. }
  1845. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1846. * needed, and if using a temporary file, delete it. */
  1847. int
  1848. abort_writing_to_file(open_file_t *file_data)
  1849. {
  1850. return finish_writing_to_file_impl(file_data, 1);
  1851. }
  1852. /** Helper: given a set of flags as passed to open(2), open the file
  1853. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  1854. * the file. Do so as atomically as possible e.g. by opening temp files and
  1855. * renaming. */
  1856. static int
  1857. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  1858. int open_flags)
  1859. {
  1860. open_file_t *file = NULL;
  1861. int fd;
  1862. ssize_t result;
  1863. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  1864. if (fd<0)
  1865. return -1;
  1866. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  1867. {
  1868. result = write_all(fd, chunk->bytes, chunk->len, 0);
  1869. if (result < 0) {
  1870. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  1871. strerror(errno));
  1872. goto err;
  1873. }
  1874. tor_assert((size_t)result == chunk->len);
  1875. });
  1876. return finish_writing_to_file(file);
  1877. err:
  1878. abort_writing_to_file(file);
  1879. return -1;
  1880. }
  1881. /** Given a smartlist of sized_chunk_t, write them atomically to a file
  1882. * <b>fname</b>, overwriting or creating the file as necessary. */
  1883. int
  1884. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin)
  1885. {
  1886. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1887. return write_chunks_to_file_impl(fname, chunks, flags);
  1888. }
  1889. /** As write_str_to_file, but does not assume a NUL-terminated
  1890. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  1891. int
  1892. write_bytes_to_file(const char *fname, const char *str, size_t len,
  1893. int bin)
  1894. {
  1895. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1896. int r;
  1897. sized_chunk_t c = { str, len };
  1898. smartlist_t *chunks = smartlist_create();
  1899. smartlist_add(chunks, &c);
  1900. r = write_chunks_to_file_impl(fname, chunks, flags);
  1901. smartlist_free(chunks);
  1902. return r;
  1903. }
  1904. /** As write_bytes_to_file, but if the file already exists, append the bytes
  1905. * to the end of the file instead of overwriting it. */
  1906. int
  1907. append_bytes_to_file(const char *fname, const char *str, size_t len,
  1908. int bin)
  1909. {
  1910. int flags = OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT);
  1911. int r;
  1912. sized_chunk_t c = { str, len };
  1913. smartlist_t *chunks = smartlist_create();
  1914. smartlist_add(chunks, &c);
  1915. r = write_chunks_to_file_impl(fname, chunks, flags);
  1916. smartlist_free(chunks);
  1917. return r;
  1918. }
  1919. /** Read the contents of <b>filename</b> into a newly allocated
  1920. * string; return the string on success or NULL on failure.
  1921. *
  1922. * If <b>stat_out</b> is provided, store the result of stat()ing the
  1923. * file into <b>stat_out</b>.
  1924. *
  1925. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  1926. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  1927. * doesn't exist.
  1928. */
  1929. /*
  1930. * This function <em>may</em> return an erroneous result if the file
  1931. * is modified while it is running, but must not crash or overflow.
  1932. * Right now, the error case occurs when the file length grows between
  1933. * the call to stat and the call to read_all: the resulting string will
  1934. * be truncated.
  1935. */
  1936. char *
  1937. read_file_to_str(const char *filename, int flags, struct stat *stat_out)
  1938. {
  1939. int fd; /* router file */
  1940. struct stat statbuf;
  1941. char *string;
  1942. ssize_t r;
  1943. int bin = flags & RFTS_BIN;
  1944. tor_assert(filename);
  1945. fd = open(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  1946. if (fd<0) {
  1947. int severity = LOG_WARN;
  1948. int save_errno = errno;
  1949. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  1950. severity = LOG_INFO;
  1951. log_fn(severity, LD_FS,"Could not open \"%s\": %s ",filename,
  1952. strerror(errno));
  1953. errno = save_errno;
  1954. return NULL;
  1955. }
  1956. if (fstat(fd, &statbuf)<0) {
  1957. int save_errno = errno;
  1958. close(fd);
  1959. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  1960. errno = save_errno;
  1961. return NULL;
  1962. }
  1963. if ((uint64_t)(statbuf.st_size)+1 > SIZE_T_CEILING)
  1964. return NULL;
  1965. string = tor_malloc((size_t)(statbuf.st_size+1));
  1966. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  1967. if (r<0) {
  1968. int save_errno = errno;
  1969. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  1970. strerror(errno));
  1971. tor_free(string);
  1972. close(fd);
  1973. errno = save_errno;
  1974. return NULL;
  1975. }
  1976. string[r] = '\0'; /* NUL-terminate the result. */
  1977. #ifdef MS_WINDOWS
  1978. if (!bin && strchr(string, '\r')) {
  1979. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  1980. "when reading %s. Coping.",
  1981. filename);
  1982. tor_strstrip(string, "\r");
  1983. r = strlen(string);
  1984. }
  1985. if (!bin) {
  1986. statbuf.st_size = (size_t) r;
  1987. } else
  1988. #endif
  1989. if (r != statbuf.st_size) {
  1990. /* Unless we're using text mode on win32, we'd better have an exact
  1991. * match for size. */
  1992. int save_errno = errno;
  1993. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  1994. (int)r, (long)statbuf.st_size,filename);
  1995. tor_free(string);
  1996. close(fd);
  1997. errno = save_errno;
  1998. return NULL;
  1999. }
  2000. close(fd);
  2001. if (stat_out) {
  2002. memcpy(stat_out, &statbuf, sizeof(struct stat));
  2003. }
  2004. return string;
  2005. }
  2006. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  2007. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  2008. * decode its contents into a newly allocated string. On success, assign this
  2009. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  2010. * provided), and return a pointer to the position in <b>s</b> immediately
  2011. * after the string. On failure, return NULL.
  2012. */
  2013. static const char *
  2014. unescape_string(const char *s, char **result, size_t *size_out)
  2015. {
  2016. const char *cp;
  2017. char *out;
  2018. if (s[0] != '\"')
  2019. return NULL;
  2020. cp = s+1;
  2021. while (1) {
  2022. switch (*cp) {
  2023. case '\0':
  2024. case '\n':
  2025. return NULL;
  2026. case '\"':
  2027. goto end_of_loop;
  2028. case '\\':
  2029. if ((cp[1] == 'x' || cp[1] == 'X')
  2030. && TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])) {
  2031. cp += 4;
  2032. } else if (TOR_ISODIGIT(cp[1])) {
  2033. cp += 2;
  2034. if (TOR_ISODIGIT(*cp)) ++cp;
  2035. if (TOR_ISODIGIT(*cp)) ++cp;
  2036. } else if (cp[1]) {
  2037. cp += 2;
  2038. } else {
  2039. return NULL;
  2040. }
  2041. break;
  2042. default:
  2043. ++cp;
  2044. break;
  2045. }
  2046. }
  2047. end_of_loop:
  2048. out = *result = tor_malloc(cp-s + 1);
  2049. cp = s+1;
  2050. while (1) {
  2051. switch (*cp)
  2052. {
  2053. case '\"':
  2054. *out = '\0';
  2055. if (size_out) *size_out = out - *result;
  2056. return cp+1;
  2057. case '\0':
  2058. tor_fragile_assert();
  2059. tor_free(*result);
  2060. return NULL;
  2061. case '\\':
  2062. switch (cp[1])
  2063. {
  2064. case 'n': *out++ = '\n'; cp += 2; break;
  2065. case 'r': *out++ = '\r'; cp += 2; break;
  2066. case 't': *out++ = '\t'; cp += 2; break;
  2067. case 'x': case 'X':
  2068. *out++ = ((hex_decode_digit(cp[2])<<4) +
  2069. hex_decode_digit(cp[3]));
  2070. cp += 4;
  2071. break;
  2072. case '0': case '1': case '2': case '3': case '4': case '5':
  2073. case '6': case '7':
  2074. {
  2075. int n = cp[1]-'0';
  2076. cp += 2;
  2077. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2078. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2079. if (n > 255) { tor_free(*result); return NULL; }
  2080. *out++ = (char)n;
  2081. }
  2082. break;
  2083. case '\'':
  2084. case '\"':
  2085. case '\\':
  2086. case '\?':
  2087. *out++ = cp[1];
  2088. cp += 2;
  2089. break;
  2090. default:
  2091. tor_free(*result); return NULL;
  2092. }
  2093. break;
  2094. default:
  2095. *out++ = *cp++;
  2096. }
  2097. }
  2098. }
  2099. /** Given a string containing part of a configuration file or similar format,
  2100. * advance past comments and whitespace and try to parse a single line. If we
  2101. * parse a line successfully, set *<b>key_out</b> to a new string holding the
  2102. * key portion and *<b>value_out</b> to a new string holding the value portion
  2103. * of the line, and return a pointer to the start of the next line. If we run
  2104. * out of data, return a pointer to the end of the string. If we encounter an
  2105. * error, return NULL.
  2106. */
  2107. const char *
  2108. parse_config_line_from_str(const char *line, char **key_out, char **value_out)
  2109. {
  2110. /* I believe the file format here is supposed to be:
  2111. FILE = (EMPTYLINE | LINE)* (EMPTYLASTLINE | LASTLINE)?
  2112. EMPTYLASTLINE = SPACE* | COMMENT
  2113. EMPTYLINE = EMPTYLASTLINE NL
  2114. SPACE = ' ' | '\r' | '\t'
  2115. COMMENT = '#' NOT-NL*
  2116. NOT-NL = Any character except '\n'
  2117. NL = '\n'
  2118. LASTLINE = SPACE* KEY SPACE* VALUES
  2119. LINE = LASTLINE NL
  2120. KEY = KEYCHAR+
  2121. KEYCHAR = Any character except ' ', '\r', '\n', '\t', '#', "\"
  2122. VALUES = QUOTEDVALUE | NORMALVALUE
  2123. QUOTEDVALUE = QUOTE QVITEM* QUOTE EOLSPACE?
  2124. QUOTE = '"'
  2125. QVCHAR = KEYCHAR | ESC ('n' | 't' | 'r' | '"' | ESC |'\'' | OCTAL | HEX)
  2126. ESC = "\\"
  2127. OCTAL = ODIGIT (ODIGIT ODIGIT?)?
  2128. HEX = ('x' | 'X') HEXDIGIT HEXDIGIT
  2129. ODIGIT = '0' .. '7'
  2130. HEXDIGIT = '0'..'9' | 'a' .. 'f' | 'A' .. 'F'
  2131. EOLSPACE = SPACE* COMMENT?
  2132. NORMALVALUE = (VALCHAR | ESC ESC_IGNORE | CONTINUATION)* EOLSPACE?
  2133. VALCHAR = Any character except ESC, '#', and '\n'
  2134. ESC_IGNORE = Any character except '#' or '\n'
  2135. CONTINUATION = ESC NL ( COMMENT NL )*
  2136. */
  2137. const char *key, *val, *cp;
  2138. int continuation = 0;
  2139. tor_assert(key_out);
  2140. tor_assert(value_out);
  2141. *key_out = *value_out = NULL;
  2142. key = val = NULL;
  2143. /* Skip until the first keyword. */
  2144. while (1) {
  2145. while (TOR_ISSPACE(*line))
  2146. ++line;
  2147. if (*line == '#') {
  2148. while (*line && *line != '\n')
  2149. ++line;
  2150. } else {
  2151. break;
  2152. }
  2153. }
  2154. if (!*line) { /* End of string? */
  2155. *key_out = *value_out = NULL;
  2156. return line;
  2157. }
  2158. /* Skip until the next space or \ followed by newline. */
  2159. key = line;
  2160. while (*line && !TOR_ISSPACE(*line) && *line != '#' &&
  2161. ! (line[0] == '\\' && line[1] == '\n'))
  2162. ++line;
  2163. *key_out = tor_strndup(key, line-key);
  2164. /* Skip until the value. */
  2165. while (*line == ' ' || *line == '\t')
  2166. ++line;
  2167. val = line;
  2168. /* Find the end of the line. */
  2169. if (*line == '\"') { // XXX No continuation handling is done here
  2170. if (!(line = unescape_string(line, value_out, NULL)))
  2171. return NULL;
  2172. while (*line == ' ' || *line == '\t')
  2173. ++line;
  2174. if (*line && *line != '#' && *line != '\n')
  2175. return NULL;
  2176. } else {
  2177. /* Look for the end of the line. */
  2178. while (*line && *line != '\n' && (*line != '#' || continuation)) {
  2179. if (*line == '\\' && line[1] == '\n') {
  2180. continuation = 1;
  2181. line += 2;
  2182. } else if (*line == '#') {
  2183. do {
  2184. ++line;
  2185. } while (*line && *line != '\n');
  2186. if (*line == '\n')
  2187. ++line;
  2188. } else {
  2189. ++line;
  2190. }
  2191. }
  2192. if (*line == '\n') {
  2193. cp = line++;
  2194. } else {
  2195. cp = line;
  2196. }
  2197. /* Now back cp up to be the last nonspace character */
  2198. while (cp>val && TOR_ISSPACE(*(cp-1)))
  2199. --cp;
  2200. tor_assert(cp >= val);
  2201. /* Now copy out and decode the value. */
  2202. *value_out = tor_strndup(val, cp-val);
  2203. if (continuation) {
  2204. char *v_out, *v_in;
  2205. v_out = v_in = *value_out;
  2206. while (*v_in) {
  2207. if (*v_in == '#') {
  2208. do {
  2209. ++v_in;
  2210. } while (*v_in && *v_in != '\n');
  2211. if (*v_in == '\n')
  2212. ++v_in;
  2213. } else if (v_in[0] == '\\' && v_in[1] == '\n') {
  2214. v_in += 2;
  2215. } else {
  2216. *v_out++ = *v_in++;
  2217. }
  2218. }
  2219. *v_out = '\0';
  2220. }
  2221. }
  2222. if (*line == '#') {
  2223. do {
  2224. ++line;
  2225. } while (*line && *line != '\n');
  2226. }
  2227. while (TOR_ISSPACE(*line)) ++line;
  2228. return line;
  2229. }
  2230. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  2231. * string. */
  2232. char *
  2233. expand_filename(const char *filename)
  2234. {
  2235. tor_assert(filename);
  2236. #ifdef MS_WINDOWS
  2237. return tor_strdup(filename);
  2238. #else
  2239. if (*filename == '~') {
  2240. char *home, *result=NULL;
  2241. const char *rest;
  2242. if (filename[1] == '/' || filename[1] == '\0') {
  2243. home = getenv("HOME");
  2244. if (!home) {
  2245. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  2246. "expanding \"%s\"; defaulting to \"\".", filename);
  2247. home = tor_strdup("");
  2248. } else {
  2249. home = tor_strdup(home);
  2250. }
  2251. rest = strlen(filename)>=2?(filename+2):"";
  2252. } else {
  2253. #ifdef HAVE_PWD_H
  2254. char *username, *slash;
  2255. slash = strchr(filename, '/');
  2256. if (slash)
  2257. username = tor_strndup(filename+1,slash-filename-1);
  2258. else
  2259. username = tor_strdup(filename+1);
  2260. if (!(home = get_user_homedir(username))) {
  2261. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2262. tor_free(username);
  2263. return NULL;
  2264. }
  2265. tor_free(username);
  2266. rest = slash ? (slash+1) : "";
  2267. #else
  2268. log_warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
  2269. return tor_strdup(filename);
  2270. #endif
  2271. }
  2272. tor_assert(home);
  2273. /* Remove trailing slash. */
  2274. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2275. home[strlen(home)-1] = '\0';
  2276. }
  2277. tor_asprintf(&result,"%s"PATH_SEPARATOR"%s",home,rest);
  2278. tor_free(home);
  2279. return result;
  2280. } else {
  2281. return tor_strdup(filename);
  2282. }
  2283. #endif
  2284. }
  2285. #define MAX_SCANF_WIDTH 9999
  2286. /** Helper: given an ASCII-encoded decimal digit, return its numeric value.
  2287. * NOTE: requires that its input be in-bounds. */
  2288. static int
  2289. digit_to_num(char d)
  2290. {
  2291. int num = ((int)d) - (int)'0';
  2292. tor_assert(num <= 9 && num >= 0);
  2293. return num;
  2294. }
  2295. /** Helper: Read an unsigned int from *<b>bufp</b> of up to <b>width</b>
  2296. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2297. * success, store the result in <b>out</b>, advance bufp to the next
  2298. * character, and return 0. On failure, return -1. */
  2299. static int
  2300. scan_unsigned(const char **bufp, unsigned *out, int width)
  2301. {
  2302. unsigned result = 0;
  2303. int scanned_so_far = 0;
  2304. if (!bufp || !*bufp || !out)
  2305. return -1;
  2306. if (width<0)
  2307. width=MAX_SCANF_WIDTH;
  2308. while (**bufp && TOR_ISDIGIT(**bufp) && scanned_so_far < width) {
  2309. int digit = digit_to_num(*(*bufp)++);
  2310. unsigned new_result = result * 10 + digit;
  2311. if (new_result > UINT32_MAX || new_result < result)
  2312. return -1; /* over/underflow. */
  2313. result = new_result;
  2314. ++scanned_so_far;
  2315. }
  2316. if (!scanned_so_far) /* No actual digits scanned */
  2317. return -1;
  2318. *out = result;
  2319. return 0;
  2320. }
  2321. /** Helper: copy up to <b>width</b> non-space characters from <b>bufp</b> to
  2322. * <b>out</b>. Make sure <b>out</b> is nul-terminated. Advance <b>bufp</b>
  2323. * to the next non-space character or the EOS. */
  2324. static int
  2325. scan_string(const char **bufp, char *out, int width)
  2326. {
  2327. int scanned_so_far = 0;
  2328. if (!bufp || !out || width < 0)
  2329. return -1;
  2330. while (**bufp && ! TOR_ISSPACE(**bufp) && scanned_so_far < width) {
  2331. *out++ = *(*bufp)++;
  2332. ++scanned_so_far;
  2333. }
  2334. *out = '\0';
  2335. return 0;
  2336. }
  2337. /** Locale-independent, minimal, no-surprises scanf variant, accepting only a
  2338. * restricted pattern format. For more info on what it supports, see
  2339. * tor_sscanf() documentation. */
  2340. int
  2341. tor_vsscanf(const char *buf, const char *pattern, va_list ap)
  2342. {
  2343. int n_matched = 0;
  2344. while (*pattern) {
  2345. if (*pattern != '%') {
  2346. if (*buf == *pattern) {
  2347. ++buf;
  2348. ++pattern;
  2349. continue;
  2350. } else {
  2351. return n_matched;
  2352. }
  2353. } else {
  2354. int width = -1;
  2355. ++pattern;
  2356. if (TOR_ISDIGIT(*pattern)) {
  2357. width = digit_to_num(*pattern++);
  2358. while (TOR_ISDIGIT(*pattern)) {
  2359. width *= 10;
  2360. width += digit_to_num(*pattern++);
  2361. if (width > MAX_SCANF_WIDTH)
  2362. return -1;
  2363. }
  2364. if (!width) /* No zero-width things. */
  2365. return -1;
  2366. }
  2367. if (*pattern == 'u') {
  2368. unsigned *u = va_arg(ap, unsigned *);
  2369. if (!*buf)
  2370. return n_matched;
  2371. if (scan_unsigned(&buf, u, width)<0)
  2372. return n_matched;
  2373. ++pattern;
  2374. ++n_matched;
  2375. } else if (*pattern == 's') {
  2376. char *s = va_arg(ap, char *);
  2377. if (width < 0)
  2378. return -1;
  2379. if (scan_string(&buf, s, width)<0)
  2380. return n_matched;
  2381. ++pattern;
  2382. ++n_matched;
  2383. } else if (*pattern == 'c') {
  2384. char *ch = va_arg(ap, char *);
  2385. if (width != -1)
  2386. return -1;
  2387. if (!*buf)
  2388. return n_matched;
  2389. *ch = *buf++;
  2390. ++pattern;
  2391. ++n_matched;
  2392. } else if (*pattern == '%') {
  2393. if (*buf != '%')
  2394. return -1;
  2395. ++buf;
  2396. ++pattern;
  2397. } else {
  2398. return -1; /* Unrecognized pattern component. */
  2399. }
  2400. }
  2401. }
  2402. return n_matched;
  2403. }
  2404. /** Minimal sscanf replacement: parse <b>buf</b> according to <b>pattern</b>
  2405. * and store the results in the corresponding argument fields. Differs from
  2406. * sscanf in that it: Only handles %u and %Ns. Does not handle arbitrarily
  2407. * long widths. %u does not consume any space. Is locale-independent.
  2408. * Returns -1 on malformed patterns.
  2409. *
  2410. * (As with other locale-independent functions, we need this to parse data that
  2411. * is in ASCII without worrying that the C library's locale-handling will make
  2412. * miscellaneous characters look like numbers, spaces, and so on.)
  2413. */
  2414. int
  2415. tor_sscanf(const char *buf, const char *pattern, ...)
  2416. {
  2417. int r;
  2418. va_list ap;
  2419. va_start(ap, pattern);
  2420. r = tor_vsscanf(buf, pattern, ap);
  2421. va_end(ap);
  2422. return r;
  2423. }
  2424. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  2425. * Return NULL on error or if <b>dirname</b> is not a directory.
  2426. */
  2427. smartlist_t *
  2428. tor_listdir(const char *dirname)
  2429. {
  2430. smartlist_t *result;
  2431. #ifdef MS_WINDOWS
  2432. char *pattern;
  2433. TCHAR tpattern[MAX_PATH] = {0};
  2434. char name[MAX_PATH] = {0};
  2435. HANDLE handle;
  2436. WIN32_FIND_DATA findData;
  2437. size_t pattern_len = strlen(dirname)+16;
  2438. pattern = tor_malloc(pattern_len);
  2439. tor_snprintf(pattern, pattern_len, "%s\\*", dirname);
  2440. #ifdef UNICODE
  2441. mbstowcs(tpattern,pattern,MAX_PATH);
  2442. #else
  2443. strlcpy(tpattern, pattern, MAX_PATH);
  2444. #endif
  2445. if (INVALID_HANDLE_VALUE == (handle = FindFirstFile(tpattern, &findData))) {
  2446. tor_free(pattern);
  2447. return NULL;
  2448. }
  2449. result = smartlist_create();
  2450. while (1) {
  2451. #ifdef UNICODE
  2452. wcstombs(name,findData.cFileName,MAX_PATH);
  2453. #else
  2454. strlcpy(name,findData.cFileName,sizeof(name));
  2455. #endif
  2456. if (strcmp(name, ".") &&
  2457. strcmp(name, "..")) {
  2458. smartlist_add(result, tor_strdup(name));
  2459. }
  2460. if (!FindNextFile(handle, &findData)) {
  2461. DWORD err;
  2462. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  2463. char *errstr = format_win32_error(err);
  2464. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  2465. tor_free(errstr);
  2466. }
  2467. break;
  2468. }
  2469. }
  2470. FindClose(handle);
  2471. tor_free(pattern);
  2472. #else
  2473. DIR *d;
  2474. struct dirent *de;
  2475. if (!(d = opendir(dirname)))
  2476. return NULL;
  2477. result = smartlist_create();
  2478. while ((de = readdir(d))) {
  2479. if (!strcmp(de->d_name, ".") ||
  2480. !strcmp(de->d_name, ".."))
  2481. continue;
  2482. smartlist_add(result, tor_strdup(de->d_name));
  2483. }
  2484. closedir(d);
  2485. #endif
  2486. return result;
  2487. }
  2488. /** Return true iff <b>filename</b> is a relative path. */
  2489. int
  2490. path_is_relative(const char *filename)
  2491. {
  2492. if (filename && filename[0] == '/')
  2493. return 0;
  2494. #ifdef MS_WINDOWS
  2495. else if (filename && filename[0] == '\\')
  2496. return 0;
  2497. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  2498. filename[1] == ':' && filename[2] == '\\')
  2499. return 0;
  2500. #endif
  2501. else
  2502. return 1;
  2503. }
  2504. /* =====
  2505. * Process helpers
  2506. * ===== */
  2507. #ifndef MS_WINDOWS
  2508. /* Based on code contributed by christian grothoff */
  2509. /** True iff we've called start_daemon(). */
  2510. static int start_daemon_called = 0;
  2511. /** True iff we've called finish_daemon(). */
  2512. static int finish_daemon_called = 0;
  2513. /** Socketpair used to communicate between parent and child process while
  2514. * daemonizing. */
  2515. static int daemon_filedes[2];
  2516. /** Start putting the process into daemon mode: fork and drop all resources
  2517. * except standard fds. The parent process never returns, but stays around
  2518. * until finish_daemon is called. (Note: it's safe to call this more
  2519. * than once: calls after the first are ignored.)
  2520. */
  2521. void
  2522. start_daemon(void)
  2523. {
  2524. pid_t pid;
  2525. if (start_daemon_called)
  2526. return;
  2527. start_daemon_called = 1;
  2528. if (pipe(daemon_filedes)) {
  2529. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  2530. exit(1);
  2531. }
  2532. pid = fork();
  2533. if (pid < 0) {
  2534. log_err(LD_GENERAL,"fork failed. Exiting.");
  2535. exit(1);
  2536. }
  2537. if (pid) { /* Parent */
  2538. int ok;
  2539. char c;
  2540. close(daemon_filedes[1]); /* we only read */
  2541. ok = -1;
  2542. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  2543. if (c == '.')
  2544. ok = 1;
  2545. }
  2546. fflush(stdout);
  2547. if (ok == 1)
  2548. exit(0);
  2549. else
  2550. exit(1); /* child reported error */
  2551. } else { /* Child */
  2552. close(daemon_filedes[0]); /* we only write */
  2553. pid = setsid(); /* Detach from controlling terminal */
  2554. /*
  2555. * Fork one more time, so the parent (the session group leader) can exit.
  2556. * This means that we, as a non-session group leader, can never regain a
  2557. * controlling terminal. This part is recommended by Stevens's
  2558. * _Advanced Programming in the Unix Environment_.
  2559. */
  2560. if (fork() != 0) {
  2561. exit(0);
  2562. }
  2563. set_main_thread(); /* We are now the main thread. */
  2564. return;
  2565. }
  2566. }
  2567. /** Finish putting the process into daemon mode: drop standard fds, and tell
  2568. * the parent process to exit. (Note: it's safe to call this more than once:
  2569. * calls after the first are ignored. Calls start_daemon first if it hasn't
  2570. * been called already.)
  2571. */
  2572. void
  2573. finish_daemon(const char *desired_cwd)
  2574. {
  2575. int nullfd;
  2576. char c = '.';
  2577. if (finish_daemon_called)
  2578. return;
  2579. if (!start_daemon_called)
  2580. start_daemon();
  2581. finish_daemon_called = 1;
  2582. if (!desired_cwd)
  2583. desired_cwd = "/";
  2584. /* Don't hold the wrong FS mounted */
  2585. if (chdir(desired_cwd) < 0) {
  2586. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  2587. exit(1);
  2588. }
  2589. nullfd = open("/dev/null", O_RDWR);
  2590. if (nullfd < 0) {
  2591. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  2592. exit(1);
  2593. }
  2594. /* close fds linking to invoking terminal, but
  2595. * close usual incoming fds, but redirect them somewhere
  2596. * useful so the fds don't get reallocated elsewhere.
  2597. */
  2598. if (dup2(nullfd,0) < 0 ||
  2599. dup2(nullfd,1) < 0 ||
  2600. dup2(nullfd,2) < 0) {
  2601. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  2602. exit(1);
  2603. }
  2604. if (nullfd > 2)
  2605. close(nullfd);
  2606. /* signal success */
  2607. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  2608. log_err(LD_GENERAL,"write failed. Exiting.");
  2609. }
  2610. close(daemon_filedes[1]);
  2611. }
  2612. #else
  2613. /* defined(MS_WINDOWS) */
  2614. void
  2615. start_daemon(void)
  2616. {
  2617. }
  2618. void
  2619. finish_daemon(const char *cp)
  2620. {
  2621. (void)cp;
  2622. }
  2623. #endif
  2624. /** Write the current process ID, followed by NL, into <b>filename</b>.
  2625. */
  2626. void
  2627. write_pidfile(char *filename)
  2628. {
  2629. FILE *pidfile;
  2630. if ((pidfile = fopen(filename, "w")) == NULL) {
  2631. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  2632. strerror(errno));
  2633. } else {
  2634. #ifdef MS_WINDOWS
  2635. fprintf(pidfile, "%d\n", (int)_getpid());
  2636. #else
  2637. fprintf(pidfile, "%d\n", (int)getpid());
  2638. #endif
  2639. fclose(pidfile);
  2640. }
  2641. }
  2642. #ifdef MS_WINDOWS
  2643. HANDLE
  2644. load_windows_system_library(const TCHAR *library_name)
  2645. {
  2646. TCHAR path[MAX_PATH];
  2647. unsigned n;
  2648. n = GetSystemDirectory(path, MAX_PATH);
  2649. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  2650. return 0;
  2651. _tcscat(path, TEXT("\\"));
  2652. _tcscat(path, library_name);
  2653. return LoadLibrary(path);
  2654. }
  2655. #endif