util.c 102 KB

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