util.c 74 KB

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