util.c 76 KB

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