util.c 89 KB

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