util.c 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369
  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 _WIN32
  26. #include <io.h>
  27. #include <direct.h>
  28. #include <process.h>
  29. #include <tchar.h>
  30. #include <Winbase.h>
  31. #else
  32. #include <dirent.h>
  33. #include <pwd.h>
  34. #include <grp.h>
  35. #endif
  36. /* math.h needs this on Linux */
  37. #ifndef __USE_ISOC99
  38. #define __USE_ISOC99 1
  39. #endif
  40. #include <math.h>
  41. #include <stdlib.h>
  42. #include <stdio.h>
  43. #include <string.h>
  44. #include <assert.h>
  45. #include <signal.h>
  46. #ifdef HAVE_NETINET_IN_H
  47. #include <netinet/in.h>
  48. #endif
  49. #ifdef HAVE_ARPA_INET_H
  50. #include <arpa/inet.h>
  51. #endif
  52. #ifdef HAVE_ERRNO_H
  53. #include <errno.h>
  54. #endif
  55. #ifdef HAVE_SYS_SOCKET_H
  56. #include <sys/socket.h>
  57. #endif
  58. #ifdef HAVE_SYS_TIME_H
  59. #include <sys/time.h>
  60. #endif
  61. #ifdef HAVE_UNISTD_H
  62. #include <unistd.h>
  63. #endif
  64. #ifdef HAVE_SYS_STAT_H
  65. #include <sys/stat.h>
  66. #endif
  67. #ifdef HAVE_SYS_FCNTL_H
  68. #include <sys/fcntl.h>
  69. #endif
  70. #ifdef HAVE_TIME_H
  71. #include <time.h>
  72. #endif
  73. #ifdef HAVE_MALLOC_MALLOC_H
  74. #include <malloc/malloc.h>
  75. #endif
  76. #ifdef HAVE_MALLOC_H
  77. #ifndef OPENBSD
  78. /* OpenBSD has a malloc.h, but for our purposes, it only exists in order to
  79. * scold us for being so stupid as to autodetect its presence. To be fair,
  80. * they've done this since 1996, when autoconf was only 5 years old. */
  81. #include <malloc.h>
  82. #endif
  83. #endif
  84. #ifdef HAVE_MALLOC_NP_H
  85. #include <malloc_np.h>
  86. #endif
  87. #ifdef HAVE_SYS_WAIT_H
  88. #include <sys/wait.h>
  89. #endif
  90. /* =====
  91. * Memory management
  92. * ===== */
  93. #ifdef USE_DMALLOC
  94. #undef strndup
  95. #include <dmalloc.h>
  96. /* Macro to pass the extra dmalloc args to another function. */
  97. #define DMALLOC_FN_ARGS , file, line
  98. #if defined(HAVE_DMALLOC_STRDUP)
  99. /* the dmalloc_strdup should be fine as defined */
  100. #elif defined(HAVE_DMALLOC_STRNDUP)
  101. #define dmalloc_strdup(file, line, string, xalloc_b) \
  102. dmalloc_strndup(file, line, (string), -1, xalloc_b)
  103. #else
  104. #error "No dmalloc_strdup or equivalent"
  105. #endif
  106. #else /* not using dmalloc */
  107. #define DMALLOC_FN_ARGS
  108. #endif
  109. /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
  110. * result. On error, log and terminate the process. (Same as malloc(size),
  111. * but never returns NULL.)
  112. *
  113. * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
  114. * ignored otherwise.
  115. */
  116. void *
  117. _tor_malloc(size_t size DMALLOC_PARAMS)
  118. {
  119. void *result;
  120. tor_assert(size < SIZE_T_CEILING);
  121. #ifndef MALLOC_ZERO_WORKS
  122. /* Some libc mallocs don't work when size==0. Override them. */
  123. if (size==0) {
  124. size=1;
  125. }
  126. #endif
  127. #ifdef USE_DMALLOC
  128. result = dmalloc_malloc(file, line, size, DMALLOC_FUNC_MALLOC, 0, 0);
  129. #else
  130. result = malloc(size);
  131. #endif
  132. if (PREDICT_UNLIKELY(result == NULL)) {
  133. log_err(LD_MM,"Out of memory on malloc(). Dying.");
  134. /* If these functions die within a worker process, they won't call
  135. * spawn_exit, but that's ok, since the parent will run out of memory soon
  136. * anyway. */
  137. exit(1);
  138. }
  139. return result;
  140. }
  141. /** Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
  142. * zero bytes, and return a pointer to the result. Log and terminate
  143. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  144. */
  145. void *
  146. _tor_malloc_zero(size_t size DMALLOC_PARAMS)
  147. {
  148. /* You may ask yourself, "wouldn't it be smart to use calloc instead of
  149. * malloc+memset? Perhaps libc's calloc knows some nifty optimization trick
  150. * we don't!" Indeed it does, but its optimizations are only a big win when
  151. * we're allocating something very big (it knows if it just got the memory
  152. * from the OS in a pre-zeroed state). We don't want to use tor_malloc_zero
  153. * for big stuff, so we don't bother with calloc. */
  154. void *result = _tor_malloc(size DMALLOC_FN_ARGS);
  155. memset(result, 0, size);
  156. return result;
  157. }
  158. /** Allocate a chunk of <b>nmemb</b>*<b>size</b> bytes of memory, fill
  159. * the memory with zero bytes, and return a pointer to the result.
  160. * Log and terminate the process on error. (Same as
  161. * calloc(<b>nmemb</b>,<b>size</b>), but never returns NULL.)
  162. *
  163. * XXXX This implementation probably asserts in cases where it could
  164. * work, because it only tries dividing SIZE_MAX by size (according to
  165. * the calloc(3) man page, the size of an element of the nmemb-element
  166. * array to be allocated), not by nmemb (which could in theory be
  167. * smaller than size). Don't do that then.
  168. */
  169. void *
  170. _tor_calloc(size_t nmemb, size_t size DMALLOC_PARAMS)
  171. {
  172. /* You may ask yourself, "wouldn't it be smart to use calloc instead of
  173. * malloc+memset? Perhaps libc's calloc knows some nifty optimization trick
  174. * we don't!" Indeed it does, but its optimizations are only a big win when
  175. * we're allocating something very big (it knows if it just got the memory
  176. * from the OS in a pre-zeroed state). We don't want to use tor_malloc_zero
  177. * for big stuff, so we don't bother with calloc. */
  178. void *result;
  179. size_t max_nmemb = (size == 0) ? SIZE_MAX : SIZE_MAX/size;
  180. tor_assert(nmemb < max_nmemb);
  181. result = _tor_malloc_zero((nmemb * size) DMALLOC_FN_ARGS);
  182. return result;
  183. }
  184. /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
  185. * bytes long; return the new memory block. On error, log and
  186. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  187. */
  188. void *
  189. _tor_realloc(void *ptr, size_t size DMALLOC_PARAMS)
  190. {
  191. void *result;
  192. tor_assert(size < SIZE_T_CEILING);
  193. #ifdef USE_DMALLOC
  194. result = dmalloc_realloc(file, line, ptr, size, DMALLOC_FUNC_REALLOC, 0);
  195. #else
  196. result = realloc(ptr, size);
  197. #endif
  198. if (PREDICT_UNLIKELY(result == NULL)) {
  199. log_err(LD_MM,"Out of memory on realloc(). Dying.");
  200. exit(1);
  201. }
  202. return result;
  203. }
  204. /** Return a newly allocated copy of the NUL-terminated string s. On
  205. * error, log and terminate. (Like strdup(s), but never returns
  206. * NULL.)
  207. */
  208. char *
  209. _tor_strdup(const char *s DMALLOC_PARAMS)
  210. {
  211. char *dup;
  212. tor_assert(s);
  213. #ifdef USE_DMALLOC
  214. dup = dmalloc_strdup(file, line, s, 0);
  215. #else
  216. dup = strdup(s);
  217. #endif
  218. if (PREDICT_UNLIKELY(dup == NULL)) {
  219. log_err(LD_MM,"Out of memory on strdup(). Dying.");
  220. exit(1);
  221. }
  222. return dup;
  223. }
  224. /** Allocate and return a new string containing the first <b>n</b>
  225. * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
  226. * characters, only the first <b>n</b> are copied. The result is
  227. * always NUL-terminated. (Like strndup(s,n), but never returns
  228. * NULL.)
  229. */
  230. char *
  231. _tor_strndup(const char *s, size_t n DMALLOC_PARAMS)
  232. {
  233. char *dup;
  234. tor_assert(s);
  235. tor_assert(n < SIZE_T_CEILING);
  236. dup = _tor_malloc((n+1) DMALLOC_FN_ARGS);
  237. /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
  238. * this function gets called a whole lot, and platform strncpy is
  239. * much faster than strlcpy when strlen(s) is much longer than n.
  240. */
  241. strncpy(dup, s, n);
  242. dup[n]='\0';
  243. return dup;
  244. }
  245. /** Allocate a chunk of <b>len</b> bytes, with the same contents as the
  246. * <b>len</b> bytes starting at <b>mem</b>. */
  247. void *
  248. _tor_memdup(const void *mem, size_t len DMALLOC_PARAMS)
  249. {
  250. char *dup;
  251. tor_assert(len < SIZE_T_CEILING);
  252. tor_assert(mem);
  253. dup = _tor_malloc(len DMALLOC_FN_ARGS);
  254. memcpy(dup, mem, len);
  255. return dup;
  256. }
  257. /** Helper for places that need to take a function pointer to the right
  258. * spelling of "free()". */
  259. void
  260. _tor_free(void *mem)
  261. {
  262. tor_free(mem);
  263. }
  264. #if defined(HAVE_MALLOC_GOOD_SIZE) && !defined(HAVE_MALLOC_GOOD_SIZE_PROTOTYPE)
  265. /* Some version of Mac OSX have malloc_good_size in their libc, but not
  266. * actually defined in malloc/malloc.h. We detect this and work around it by
  267. * prototyping.
  268. */
  269. extern size_t malloc_good_size(size_t size);
  270. #endif
  271. /** Allocate and return a chunk of memory of size at least *<b>size</b>, using
  272. * the same resources we would use to malloc *<b>sizep</b>. Set *<b>sizep</b>
  273. * to the number of usable bytes in the chunk of memory. */
  274. void *
  275. _tor_malloc_roundup(size_t *sizep DMALLOC_PARAMS)
  276. {
  277. #ifdef HAVE_MALLOC_GOOD_SIZE
  278. tor_assert(*sizep < SIZE_T_CEILING);
  279. *sizep = malloc_good_size(*sizep);
  280. return _tor_malloc(*sizep DMALLOC_FN_ARGS);
  281. #elif 0 && defined(HAVE_MALLOC_USABLE_SIZE) && !defined(USE_DMALLOC)
  282. /* Never use malloc_usable_size(); it makes valgrind really unhappy,
  283. * and doesn't win much in terms of usable space where it exists. */
  284. void *result;
  285. tor_assert(*sizep < SIZE_T_CEILING);
  286. result = _tor_malloc(*sizep DMALLOC_FN_ARGS);
  287. *sizep = malloc_usable_size(result);
  288. return result;
  289. #else
  290. return _tor_malloc(*sizep DMALLOC_FN_ARGS);
  291. #endif
  292. }
  293. /** Call the platform malloc info function, and dump the results to the log at
  294. * level <b>severity</b>. If no such function exists, do nothing. */
  295. void
  296. tor_log_mallinfo(int severity)
  297. {
  298. #ifdef HAVE_MALLINFO
  299. struct mallinfo mi;
  300. memset(&mi, 0, sizeof(mi));
  301. mi = mallinfo();
  302. tor_log(severity, LD_MM,
  303. "mallinfo() said: arena=%d, ordblks=%d, smblks=%d, hblks=%d, "
  304. "hblkhd=%d, usmblks=%d, fsmblks=%d, uordblks=%d, fordblks=%d, "
  305. "keepcost=%d",
  306. mi.arena, mi.ordblks, mi.smblks, mi.hblks,
  307. mi.hblkhd, mi.usmblks, mi.fsmblks, mi.uordblks, mi.fordblks,
  308. mi.keepcost);
  309. #else
  310. (void)severity;
  311. #endif
  312. #ifdef USE_DMALLOC
  313. dmalloc_log_changed(0, /* Since the program started. */
  314. 1, /* Log info about non-freed pointers. */
  315. 0, /* Do not log info about freed pointers. */
  316. 0 /* Do not log individual pointers. */
  317. );
  318. #endif
  319. }
  320. /* =====
  321. * Math
  322. * ===== */
  323. /**
  324. * Returns the natural logarithm of d base 2. We define this wrapper here so
  325. * as to make it easier not to conflict with Tor's log() macro.
  326. */
  327. double
  328. tor_mathlog(double d)
  329. {
  330. return log(d);
  331. }
  332. /** Return the long integer closest to d. We define this wrapper here so
  333. * that not all users of math.h need to use the right incancations to get
  334. * the c99 functions. */
  335. long
  336. tor_lround(double d)
  337. {
  338. #if defined(HAVE_LROUND)
  339. return lround(d);
  340. #elif defined(HAVE_RINT)
  341. return (long)rint(d);
  342. #else
  343. return (long)(d > 0 ? d + 0.5 : ceil(d - 0.5));
  344. #endif
  345. }
  346. /** Returns floor(log2(u64)). If u64 is 0, (incorrectly) returns 0. */
  347. int
  348. tor_log2(uint64_t u64)
  349. {
  350. int r = 0;
  351. if (u64 >= (U64_LITERAL(1)<<32)) {
  352. u64 >>= 32;
  353. r = 32;
  354. }
  355. if (u64 >= (U64_LITERAL(1)<<16)) {
  356. u64 >>= 16;
  357. r += 16;
  358. }
  359. if (u64 >= (U64_LITERAL(1)<<8)) {
  360. u64 >>= 8;
  361. r += 8;
  362. }
  363. if (u64 >= (U64_LITERAL(1)<<4)) {
  364. u64 >>= 4;
  365. r += 4;
  366. }
  367. if (u64 >= (U64_LITERAL(1)<<2)) {
  368. u64 >>= 2;
  369. r += 2;
  370. }
  371. if (u64 >= (U64_LITERAL(1)<<1)) {
  372. u64 >>= 1;
  373. r += 1;
  374. }
  375. return r;
  376. }
  377. /** Return the power of 2 closest to <b>u64</b>. */
  378. uint64_t
  379. round_to_power_of_2(uint64_t u64)
  380. {
  381. int lg2 = tor_log2(u64);
  382. uint64_t low = U64_LITERAL(1) << lg2, high = U64_LITERAL(1) << (lg2+1);
  383. if (high - u64 < u64 - low)
  384. return high;
  385. else
  386. return low;
  387. }
  388. /** Return the lowest x such that x is at least <b>number</b>, and x modulo
  389. * <b>divisor</b> == 0. */
  390. unsigned
  391. round_to_next_multiple_of(unsigned number, unsigned divisor)
  392. {
  393. number += divisor - 1;
  394. number -= number % divisor;
  395. return number;
  396. }
  397. /** Return the lowest x such that x is at least <b>number</b>, and x modulo
  398. * <b>divisor</b> == 0. */
  399. uint32_t
  400. round_uint32_to_next_multiple_of(uint32_t number, uint32_t divisor)
  401. {
  402. number += divisor - 1;
  403. number -= number % divisor;
  404. return number;
  405. }
  406. /** Return the lowest x such that x is at least <b>number</b>, and x modulo
  407. * <b>divisor</b> == 0. */
  408. uint64_t
  409. round_uint64_to_next_multiple_of(uint64_t number, uint64_t divisor)
  410. {
  411. number += divisor - 1;
  412. number -= number % divisor;
  413. return number;
  414. }
  415. /** Return the number of bits set in <b>v</b>. */
  416. int
  417. n_bits_set_u8(uint8_t v)
  418. {
  419. static const int nybble_table[] = {
  420. 0, /* 0000 */
  421. 1, /* 0001 */
  422. 1, /* 0010 */
  423. 2, /* 0011 */
  424. 1, /* 0100 */
  425. 2, /* 0101 */
  426. 2, /* 0110 */
  427. 3, /* 0111 */
  428. 1, /* 1000 */
  429. 2, /* 1001 */
  430. 2, /* 1010 */
  431. 3, /* 1011 */
  432. 2, /* 1100 */
  433. 3, /* 1101 */
  434. 3, /* 1110 */
  435. 4, /* 1111 */
  436. };
  437. return nybble_table[v & 15] + nybble_table[v>>4];
  438. }
  439. /* =====
  440. * String manipulation
  441. * ===== */
  442. /** Remove from the string <b>s</b> every character which appears in
  443. * <b>strip</b>. */
  444. void
  445. tor_strstrip(char *s, const char *strip)
  446. {
  447. char *read = s;
  448. while (*read) {
  449. if (strchr(strip, *read)) {
  450. ++read;
  451. } else {
  452. *s++ = *read++;
  453. }
  454. }
  455. *s = '\0';
  456. }
  457. /** Return a pointer to a NUL-terminated hexadecimal string encoding
  458. * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
  459. * result does not need to be deallocated, but repeated calls to
  460. * hex_str will trash old results.
  461. */
  462. const char *
  463. hex_str(const char *from, size_t fromlen)
  464. {
  465. static char buf[65];
  466. if (fromlen>(sizeof(buf)-1)/2)
  467. fromlen = (sizeof(buf)-1)/2;
  468. base16_encode(buf,sizeof(buf),from,fromlen);
  469. return buf;
  470. }
  471. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  472. * lowercase. */
  473. void
  474. tor_strlower(char *s)
  475. {
  476. while (*s) {
  477. *s = TOR_TOLOWER(*s);
  478. ++s;
  479. }
  480. }
  481. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  482. * lowercase. */
  483. void
  484. tor_strupper(char *s)
  485. {
  486. while (*s) {
  487. *s = TOR_TOUPPER(*s);
  488. ++s;
  489. }
  490. }
  491. /** Return 1 if every character in <b>s</b> is printable, else return 0.
  492. */
  493. int
  494. tor_strisprint(const char *s)
  495. {
  496. while (*s) {
  497. if (!TOR_ISPRINT(*s))
  498. return 0;
  499. s++;
  500. }
  501. return 1;
  502. }
  503. /** Return 1 if no character in <b>s</b> is uppercase, else return 0.
  504. */
  505. int
  506. tor_strisnonupper(const char *s)
  507. {
  508. while (*s) {
  509. if (TOR_ISUPPER(*s))
  510. return 0;
  511. s++;
  512. }
  513. return 1;
  514. }
  515. /** As strcmp, except that either string may be NULL. The NULL string is
  516. * considered to be before any non-NULL string. */
  517. int
  518. strcmp_opt(const char *s1, const char *s2)
  519. {
  520. if (!s1) {
  521. if (!s2)
  522. return 0;
  523. else
  524. return -1;
  525. } else if (!s2) {
  526. return 1;
  527. } else {
  528. return strcmp(s1, s2);
  529. }
  530. }
  531. /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
  532. * strcmp.
  533. */
  534. int
  535. strcmpstart(const char *s1, const char *s2)
  536. {
  537. size_t n = strlen(s2);
  538. return strncmp(s1, s2, n);
  539. }
  540. /** Compare the s1_len-byte string <b>s1</b> with <b>s2</b>,
  541. * without depending on a terminating nul in s1. Sorting order is first by
  542. * length, then lexically; return values are as for strcmp.
  543. */
  544. int
  545. strcmp_len(const char *s1, const char *s2, size_t s1_len)
  546. {
  547. size_t s2_len = strlen(s2);
  548. if (s1_len < s2_len)
  549. return -1;
  550. if (s1_len > s2_len)
  551. return 1;
  552. return fast_memcmp(s1, s2, s2_len);
  553. }
  554. /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
  555. * strcasecmp.
  556. */
  557. int
  558. strcasecmpstart(const char *s1, const char *s2)
  559. {
  560. size_t n = strlen(s2);
  561. return strncasecmp(s1, s2, n);
  562. }
  563. /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
  564. * strcmp.
  565. */
  566. int
  567. strcmpend(const char *s1, const char *s2)
  568. {
  569. size_t n1 = strlen(s1), n2 = strlen(s2);
  570. if (n2>n1)
  571. return strcmp(s1,s2);
  572. else
  573. return strncmp(s1+(n1-n2), s2, n2);
  574. }
  575. /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
  576. * strcasecmp.
  577. */
  578. int
  579. strcasecmpend(const char *s1, const char *s2)
  580. {
  581. size_t n1 = strlen(s1), n2 = strlen(s2);
  582. if (n2>n1) /* then they can't be the same; figure out which is bigger */
  583. return strcasecmp(s1,s2);
  584. else
  585. return strncasecmp(s1+(n1-n2), s2, n2);
  586. }
  587. /** Compare the value of the string <b>prefix</b> with the start of the
  588. * <b>memlen</b>-byte memory chunk at <b>mem</b>. Return as for strcmp.
  589. *
  590. * [As fast_memcmp(mem, prefix, strlen(prefix)) but returns -1 if memlen is
  591. * less than strlen(prefix).]
  592. */
  593. int
  594. fast_memcmpstart(const void *mem, size_t memlen,
  595. const char *prefix)
  596. {
  597. size_t plen = strlen(prefix);
  598. if (memlen < plen)
  599. return -1;
  600. return fast_memcmp(mem, prefix, plen);
  601. }
  602. /** Return a pointer to the first char of s that is not whitespace and
  603. * not a comment, or to the terminating NUL if no such character exists.
  604. */
  605. const char *
  606. eat_whitespace(const char *s)
  607. {
  608. tor_assert(s);
  609. while (1) {
  610. switch (*s) {
  611. case '\0':
  612. default:
  613. return s;
  614. case ' ':
  615. case '\t':
  616. case '\n':
  617. case '\r':
  618. ++s;
  619. break;
  620. case '#':
  621. ++s;
  622. while (*s && *s != '\n')
  623. ++s;
  624. }
  625. }
  626. }
  627. /** Return a pointer to the first char of s that is not whitespace and
  628. * not a comment, or to the terminating NUL if no such character exists.
  629. */
  630. const char *
  631. eat_whitespace_eos(const char *s, const char *eos)
  632. {
  633. tor_assert(s);
  634. tor_assert(eos && s <= eos);
  635. while (s < eos) {
  636. switch (*s) {
  637. case '\0':
  638. default:
  639. return s;
  640. case ' ':
  641. case '\t':
  642. case '\n':
  643. case '\r':
  644. ++s;
  645. break;
  646. case '#':
  647. ++s;
  648. while (s < eos && *s && *s != '\n')
  649. ++s;
  650. }
  651. }
  652. return s;
  653. }
  654. /** Return a pointer to the first char of s that is not a space or a tab
  655. * or a \\r, or to the terminating NUL if no such character exists. */
  656. const char *
  657. eat_whitespace_no_nl(const char *s)
  658. {
  659. while (*s == ' ' || *s == '\t' || *s == '\r')
  660. ++s;
  661. return s;
  662. }
  663. /** As eat_whitespace_no_nl, but stop at <b>eos</b> whether we have
  664. * found a non-whitespace character or not. */
  665. const char *
  666. eat_whitespace_eos_no_nl(const char *s, const char *eos)
  667. {
  668. while (s < eos && (*s == ' ' || *s == '\t' || *s == '\r'))
  669. ++s;
  670. return s;
  671. }
  672. /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
  673. * or to the terminating NUL if no such character exists.
  674. */
  675. const char *
  676. find_whitespace(const char *s)
  677. {
  678. /* tor_assert(s); */
  679. while (1) {
  680. switch (*s)
  681. {
  682. case '\0':
  683. case '#':
  684. case ' ':
  685. case '\r':
  686. case '\n':
  687. case '\t':
  688. return s;
  689. default:
  690. ++s;
  691. }
  692. }
  693. }
  694. /** As find_whitespace, but stop at <b>eos</b> whether we have found a
  695. * whitespace or not. */
  696. const char *
  697. find_whitespace_eos(const char *s, const char *eos)
  698. {
  699. /* tor_assert(s); */
  700. while (s < eos) {
  701. switch (*s)
  702. {
  703. case '\0':
  704. case '#':
  705. case ' ':
  706. case '\r':
  707. case '\n':
  708. case '\t':
  709. return s;
  710. default:
  711. ++s;
  712. }
  713. }
  714. return s;
  715. }
  716. /** Return the first occurrence of <b>needle</b> in <b>haystack</b> that
  717. * occurs at the start of a line (that is, at the beginning of <b>haystack</b>
  718. * or immediately after a newline). Return NULL if no such string is found.
  719. */
  720. const char *
  721. find_str_at_start_of_line(const char *haystack, const char *needle)
  722. {
  723. size_t needle_len = strlen(needle);
  724. do {
  725. if (!strncmp(haystack, needle, needle_len))
  726. return haystack;
  727. haystack = strchr(haystack, '\n');
  728. if (!haystack)
  729. return NULL;
  730. else
  731. ++haystack;
  732. } while (*haystack);
  733. return NULL;
  734. }
  735. /** Returns true if <b>string</b> could be a C identifier.
  736. A C identifier must begin with a letter or an underscore and the
  737. rest of its characters can be letters, numbers or underscores. No
  738. length limit is imposed. */
  739. int
  740. string_is_C_identifier(const char *string)
  741. {
  742. size_t iter;
  743. size_t length = strlen(string);
  744. if (!length)
  745. return 0;
  746. for (iter = 0; iter < length ; iter++) {
  747. if (iter == 0) {
  748. if (!(TOR_ISALPHA(string[iter]) ||
  749. string[iter] == '_'))
  750. return 0;
  751. } else {
  752. if (!(TOR_ISALPHA(string[iter]) ||
  753. TOR_ISDIGIT(string[iter]) ||
  754. string[iter] == '_'))
  755. return 0;
  756. }
  757. }
  758. return 1;
  759. }
  760. /** Return true iff the 'len' bytes at 'mem' are all zero. */
  761. int
  762. tor_mem_is_zero(const char *mem, size_t len)
  763. {
  764. static const char ZERO[] = {
  765. 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,
  766. };
  767. while (len >= sizeof(ZERO)) {
  768. /* It's safe to use fast_memcmp here, since the very worst thing an
  769. * attacker could learn is how many initial bytes of a secret were zero */
  770. if (fast_memcmp(mem, ZERO, sizeof(ZERO)))
  771. return 0;
  772. len -= sizeof(ZERO);
  773. mem += sizeof(ZERO);
  774. }
  775. /* Deal with leftover bytes. */
  776. if (len)
  777. return fast_memeq(mem, ZERO, len);
  778. return 1;
  779. }
  780. /** Return true iff the DIGEST_LEN bytes in digest are all zero. */
  781. int
  782. tor_digest_is_zero(const char *digest)
  783. {
  784. static const uint8_t ZERO_DIGEST[] = {
  785. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
  786. };
  787. return tor_memeq(digest, ZERO_DIGEST, DIGEST_LEN);
  788. }
  789. /** Return true iff the DIGEST256_LEN bytes in digest are all zero. */
  790. int
  791. tor_digest256_is_zero(const char *digest)
  792. {
  793. return tor_mem_is_zero(digest, DIGEST256_LEN);
  794. }
  795. /* Helper: common code to check whether the result of a strtol or strtoul or
  796. * strtoll is correct. */
  797. #define CHECK_STRTOX_RESULT() \
  798. /* Was at least one character converted? */ \
  799. if (endptr == s) \
  800. goto err; \
  801. /* Were there unexpected unconverted characters? */ \
  802. if (!next && *endptr) \
  803. goto err; \
  804. /* Is r within limits? */ \
  805. if (r < min || r > max) \
  806. goto err; \
  807. if (ok) *ok = 1; \
  808. if (next) *next = endptr; \
  809. return r; \
  810. err: \
  811. if (ok) *ok = 0; \
  812. if (next) *next = endptr; \
  813. return 0
  814. /** Extract a long from the start of <b>s</b>, in the given numeric
  815. * <b>base</b>. If <b>base</b> is 0, <b>s</b> is parsed as a decimal,
  816. * octal, or hex number in the syntax of a C integer literal. If
  817. * there is unconverted data and <b>next</b> is provided, set
  818. * *<b>next</b> to the first unconverted character. An error has
  819. * occurred if no characters are converted; or if there are
  820. * unconverted characters and <b>next</b> is NULL; or if the parsed
  821. * value is not between <b>min</b> and <b>max</b>. When no error
  822. * occurs, return the parsed value and set *<b>ok</b> (if provided) to
  823. * 1. When an error occurs, return 0 and set *<b>ok</b> (if provided)
  824. * to 0.
  825. */
  826. long
  827. tor_parse_long(const char *s, int base, long min, long max,
  828. int *ok, char **next)
  829. {
  830. char *endptr;
  831. long r;
  832. r = strtol(s, &endptr, base);
  833. CHECK_STRTOX_RESULT();
  834. }
  835. /** As tor_parse_long(), but return an unsigned long. */
  836. unsigned long
  837. tor_parse_ulong(const char *s, int base, unsigned long min,
  838. unsigned long max, int *ok, char **next)
  839. {
  840. char *endptr;
  841. unsigned long r;
  842. r = strtoul(s, &endptr, base);
  843. CHECK_STRTOX_RESULT();
  844. }
  845. /** As tor_parse_long(), but return a double. */
  846. double
  847. tor_parse_double(const char *s, double min, double max, int *ok, char **next)
  848. {
  849. char *endptr;
  850. double r;
  851. r = strtod(s, &endptr);
  852. CHECK_STRTOX_RESULT();
  853. }
  854. /** As tor_parse_long, but return a uint64_t. Only base 10 is guaranteed to
  855. * work for now. */
  856. uint64_t
  857. tor_parse_uint64(const char *s, int base, uint64_t min,
  858. uint64_t max, int *ok, char **next)
  859. {
  860. char *endptr;
  861. uint64_t r;
  862. #ifdef HAVE_STRTOULL
  863. r = (uint64_t)strtoull(s, &endptr, base);
  864. #elif defined(_WIN32)
  865. #if defined(_MSC_VER) && _MSC_VER < 1300
  866. tor_assert(base <= 10);
  867. r = (uint64_t)_atoi64(s);
  868. endptr = (char*)s;
  869. while (TOR_ISSPACE(*endptr)) endptr++;
  870. while (TOR_ISDIGIT(*endptr)) endptr++;
  871. #else
  872. r = (uint64_t)_strtoui64(s, &endptr, base);
  873. #endif
  874. #elif SIZEOF_LONG == 8
  875. r = (uint64_t)strtoul(s, &endptr, base);
  876. #else
  877. #error "I don't know how to parse 64-bit numbers."
  878. #endif
  879. CHECK_STRTOX_RESULT();
  880. }
  881. /** Encode the <b>srclen</b> bytes at <b>src</b> in a NUL-terminated,
  882. * uppercase hexadecimal string; store it in the <b>destlen</b>-byte buffer
  883. * <b>dest</b>.
  884. */
  885. void
  886. base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  887. {
  888. const char *end;
  889. char *cp;
  890. tor_assert(destlen >= srclen*2+1);
  891. tor_assert(destlen < SIZE_T_CEILING);
  892. cp = dest;
  893. end = src+srclen;
  894. while (src<end) {
  895. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) >> 4 ];
  896. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) & 0xf ];
  897. ++src;
  898. }
  899. *cp = '\0';
  900. }
  901. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  902. static INLINE int
  903. _hex_decode_digit(char c)
  904. {
  905. switch (c) {
  906. case '0': return 0;
  907. case '1': return 1;
  908. case '2': return 2;
  909. case '3': return 3;
  910. case '4': return 4;
  911. case '5': return 5;
  912. case '6': return 6;
  913. case '7': return 7;
  914. case '8': return 8;
  915. case '9': return 9;
  916. case 'A': case 'a': return 10;
  917. case 'B': case 'b': return 11;
  918. case 'C': case 'c': return 12;
  919. case 'D': case 'd': return 13;
  920. case 'E': case 'e': return 14;
  921. case 'F': case 'f': return 15;
  922. default:
  923. return -1;
  924. }
  925. }
  926. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  927. int
  928. hex_decode_digit(char c)
  929. {
  930. return _hex_decode_digit(c);
  931. }
  932. /** Given a hexadecimal string of <b>srclen</b> bytes in <b>src</b>, decode it
  933. * and store the result in the <b>destlen</b>-byte buffer at <b>dest</b>.
  934. * Return 0 on success, -1 on failure. */
  935. int
  936. base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  937. {
  938. const char *end;
  939. int v1,v2;
  940. if ((srclen % 2) != 0)
  941. return -1;
  942. if (destlen < srclen/2 || destlen > SIZE_T_CEILING)
  943. return -1;
  944. end = src+srclen;
  945. while (src<end) {
  946. v1 = _hex_decode_digit(*src);
  947. v2 = _hex_decode_digit(*(src+1));
  948. if (v1<0||v2<0)
  949. return -1;
  950. *(uint8_t*)dest = (v1<<4)|v2;
  951. ++dest;
  952. src+=2;
  953. }
  954. return 0;
  955. }
  956. /** Allocate and return a new string representing the contents of <b>s</b>,
  957. * surrounded by quotes and using standard C escapes.
  958. *
  959. * Generally, we use this for logging values that come in over the network to
  960. * keep them from tricking users, and for sending certain values to the
  961. * controller.
  962. *
  963. * We trust values from the resolver, OS, configuration file, and command line
  964. * to not be maliciously ill-formed. We validate incoming routerdescs and
  965. * SOCKS requests and addresses from BEGIN cells as they're parsed;
  966. * afterwards, we trust them as non-malicious.
  967. */
  968. char *
  969. esc_for_log(const char *s)
  970. {
  971. const char *cp;
  972. char *result, *outp;
  973. size_t len = 3;
  974. if (!s) {
  975. return tor_strdup("(null)");
  976. }
  977. for (cp = s; *cp; ++cp) {
  978. switch (*cp) {
  979. case '\\':
  980. case '\"':
  981. case '\'':
  982. case '\r':
  983. case '\n':
  984. case '\t':
  985. len += 2;
  986. break;
  987. default:
  988. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127)
  989. ++len;
  990. else
  991. len += 4;
  992. break;
  993. }
  994. }
  995. result = outp = tor_malloc(len);
  996. *outp++ = '\"';
  997. for (cp = s; *cp; ++cp) {
  998. switch (*cp) {
  999. case '\\':
  1000. case '\"':
  1001. case '\'':
  1002. *outp++ = '\\';
  1003. *outp++ = *cp;
  1004. break;
  1005. case '\n':
  1006. *outp++ = '\\';
  1007. *outp++ = 'n';
  1008. break;
  1009. case '\t':
  1010. *outp++ = '\\';
  1011. *outp++ = 't';
  1012. break;
  1013. case '\r':
  1014. *outp++ = '\\';
  1015. *outp++ = 'r';
  1016. break;
  1017. default:
  1018. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127) {
  1019. *outp++ = *cp;
  1020. } else {
  1021. tor_snprintf(outp, 5, "\\%03o", (int)(uint8_t) *cp);
  1022. outp += 4;
  1023. }
  1024. break;
  1025. }
  1026. }
  1027. *outp++ = '\"';
  1028. *outp++ = 0;
  1029. return result;
  1030. }
  1031. /** Allocate and return a new string representing the contents of <b>s</b>,
  1032. * surrounded by quotes and using standard C escapes.
  1033. *
  1034. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  1035. * thread. Also, each call invalidates the last-returned value, so don't
  1036. * try log_warn(LD_GENERAL, "%s %s", escaped(a), escaped(b));
  1037. */
  1038. const char *
  1039. escaped(const char *s)
  1040. {
  1041. static char *_escaped_val = NULL;
  1042. tor_free(_escaped_val);
  1043. if (s)
  1044. _escaped_val = esc_for_log(s);
  1045. else
  1046. _escaped_val = NULL;
  1047. return _escaped_val;
  1048. }
  1049. /** Rudimentary string wrapping code: given a un-wrapped <b>string</b> (no
  1050. * newlines!), break the string into newline-terminated lines of no more than
  1051. * <b>width</b> characters long (not counting newline) and insert them into
  1052. * <b>out</b> in order. Precede the first line with prefix0, and subsequent
  1053. * lines with prefixRest.
  1054. */
  1055. /* This uses a stupid greedy wrapping algorithm right now:
  1056. * - For each line:
  1057. * - Try to fit as much stuff as possible, but break on a space.
  1058. * - If the first "word" of the line will extend beyond the allowable
  1059. * width, break the word at the end of the width.
  1060. */
  1061. void
  1062. wrap_string(smartlist_t *out, const char *string, size_t width,
  1063. const char *prefix0, const char *prefixRest)
  1064. {
  1065. size_t p0Len, pRestLen, pCurLen;
  1066. const char *eos, *prefixCur;
  1067. tor_assert(out);
  1068. tor_assert(string);
  1069. tor_assert(width);
  1070. if (!prefix0)
  1071. prefix0 = "";
  1072. if (!prefixRest)
  1073. prefixRest = "";
  1074. p0Len = strlen(prefix0);
  1075. pRestLen = strlen(prefixRest);
  1076. tor_assert(width > p0Len && width > pRestLen);
  1077. eos = strchr(string, '\0');
  1078. tor_assert(eos);
  1079. pCurLen = p0Len;
  1080. prefixCur = prefix0;
  1081. while ((eos-string)+pCurLen > width) {
  1082. const char *eol = string + width - pCurLen;
  1083. while (eol > string && *eol != ' ')
  1084. --eol;
  1085. /* eol is now the last space that can fit, or the start of the string. */
  1086. if (eol > string) {
  1087. size_t line_len = (eol-string) + pCurLen + 2;
  1088. char *line = tor_malloc(line_len);
  1089. memcpy(line, prefixCur, pCurLen);
  1090. memcpy(line+pCurLen, string, eol-string);
  1091. line[line_len-2] = '\n';
  1092. line[line_len-1] = '\0';
  1093. smartlist_add(out, line);
  1094. string = eol + 1;
  1095. } else {
  1096. size_t line_len = width + 2;
  1097. char *line = tor_malloc(line_len);
  1098. memcpy(line, prefixCur, pCurLen);
  1099. memcpy(line+pCurLen, string, width - pCurLen);
  1100. line[line_len-2] = '\n';
  1101. line[line_len-1] = '\0';
  1102. smartlist_add(out, line);
  1103. string += width-pCurLen;
  1104. }
  1105. prefixCur = prefixRest;
  1106. pCurLen = pRestLen;
  1107. }
  1108. if (string < eos) {
  1109. size_t line_len = (eos-string) + pCurLen + 2;
  1110. char *line = tor_malloc(line_len);
  1111. memcpy(line, prefixCur, pCurLen);
  1112. memcpy(line+pCurLen, string, eos-string);
  1113. line[line_len-2] = '\n';
  1114. line[line_len-1] = '\0';
  1115. smartlist_add(out, line);
  1116. }
  1117. }
  1118. /* =====
  1119. * Time
  1120. * ===== */
  1121. /**
  1122. * Converts struct timeval to a double value.
  1123. * Preserves microsecond precision, but just barely.
  1124. * Error is approx +/- 0.1 usec when dealing with epoch values.
  1125. */
  1126. double
  1127. tv_to_double(const struct timeval *tv)
  1128. {
  1129. double conv = tv->tv_sec;
  1130. conv += tv->tv_usec/1000000.0;
  1131. return conv;
  1132. }
  1133. /**
  1134. * Converts timeval to milliseconds.
  1135. */
  1136. int64_t
  1137. tv_to_msec(const struct timeval *tv)
  1138. {
  1139. int64_t conv = ((int64_t)tv->tv_sec)*1000L;
  1140. /* Round ghetto-style */
  1141. conv += ((int64_t)tv->tv_usec+500)/1000L;
  1142. return conv;
  1143. }
  1144. /**
  1145. * Converts timeval to microseconds.
  1146. */
  1147. int64_t
  1148. tv_to_usec(const struct timeval *tv)
  1149. {
  1150. int64_t conv = ((int64_t)tv->tv_sec)*1000000L;
  1151. conv += tv->tv_usec;
  1152. return conv;
  1153. }
  1154. /** Return the number of microseconds elapsed between *start and *end.
  1155. */
  1156. long
  1157. tv_udiff(const struct timeval *start, const struct timeval *end)
  1158. {
  1159. long udiff;
  1160. long secdiff = end->tv_sec - start->tv_sec;
  1161. if (labs(secdiff+1) > LONG_MAX/1000000) {
  1162. log_warn(LD_GENERAL, "comparing times on microsecond detail too far "
  1163. "apart: %ld seconds", secdiff);
  1164. return LONG_MAX;
  1165. }
  1166. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  1167. return udiff;
  1168. }
  1169. /** Return the number of milliseconds elapsed between *start and *end.
  1170. */
  1171. long
  1172. tv_mdiff(const struct timeval *start, const struct timeval *end)
  1173. {
  1174. long mdiff;
  1175. long secdiff = end->tv_sec - start->tv_sec;
  1176. if (labs(secdiff+1) > LONG_MAX/1000) {
  1177. log_warn(LD_GENERAL, "comparing times on millisecond detail too far "
  1178. "apart: %ld seconds", secdiff);
  1179. return LONG_MAX;
  1180. }
  1181. /* Subtract and round */
  1182. mdiff = secdiff*1000L +
  1183. ((long)end->tv_usec - (long)start->tv_usec + 500L) / 1000L;
  1184. return mdiff;
  1185. }
  1186. /** Yield true iff <b>y</b> is a leap-year. */
  1187. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  1188. /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
  1189. static int
  1190. n_leapdays(int y1, int y2)
  1191. {
  1192. --y1;
  1193. --y2;
  1194. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  1195. }
  1196. /** Number of days per month in non-leap year; used by tor_timegm. */
  1197. static const int days_per_month[] =
  1198. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  1199. /** Return a time_t given a struct tm. The result is given in GMT, and
  1200. * does not account for leap seconds.
  1201. */
  1202. time_t
  1203. tor_timegm(struct tm *tm)
  1204. {
  1205. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  1206. * It's way more brute-force than fiddling with tzset().
  1207. */
  1208. time_t year, days, hours, minutes, seconds;
  1209. int i;
  1210. year = tm->tm_year + 1900;
  1211. if (year < 1970 || tm->tm_mon < 0 || tm->tm_mon > 11) {
  1212. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  1213. return -1;
  1214. }
  1215. tor_assert(year < INT_MAX);
  1216. days = 365 * (year-1970) + n_leapdays(1970,(int)year);
  1217. for (i = 0; i < tm->tm_mon; ++i)
  1218. days += days_per_month[i];
  1219. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  1220. ++days;
  1221. days += tm->tm_mday - 1;
  1222. hours = days*24 + tm->tm_hour;
  1223. minutes = hours*60 + tm->tm_min;
  1224. seconds = minutes*60 + tm->tm_sec;
  1225. return seconds;
  1226. }
  1227. /* strftime is locale-specific, so we need to replace those parts */
  1228. /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
  1229. static const char *WEEKDAY_NAMES[] =
  1230. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1231. /** A c-locale array of 3-letter names of months, starting with Jan. */
  1232. static const char *MONTH_NAMES[] =
  1233. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  1234. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1235. /** Set <b>buf</b> to the RFC1123 encoding of the GMT value of <b>t</b>.
  1236. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  1237. *
  1238. * (RFC1123 format is Fri, 29 Sep 2006 15:54:20 GMT)
  1239. */
  1240. void
  1241. format_rfc1123_time(char *buf, time_t t)
  1242. {
  1243. struct tm tm;
  1244. tor_gmtime_r(&t, &tm);
  1245. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  1246. tor_assert(tm.tm_wday >= 0);
  1247. tor_assert(tm.tm_wday <= 6);
  1248. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  1249. tor_assert(tm.tm_wday >= 0);
  1250. tor_assert(tm.tm_mon <= 11);
  1251. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  1252. }
  1253. /** Parse the RFC1123 encoding of some time (in GMT) from <b>buf</b>,
  1254. * and store the result in *<b>t</b>.
  1255. *
  1256. * Return 0 on success, -1 on failure.
  1257. */
  1258. int
  1259. parse_rfc1123_time(const char *buf, time_t *t)
  1260. {
  1261. struct tm tm;
  1262. char month[4];
  1263. char weekday[4];
  1264. int i, m;
  1265. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1266. if (strlen(buf) != RFC1123_TIME_LEN)
  1267. return -1;
  1268. memset(&tm, 0, sizeof(tm));
  1269. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  1270. &tm_mday, month, &tm_year, &tm_hour,
  1271. &tm_min, &tm_sec) < 7) {
  1272. char *esc = esc_for_log(buf);
  1273. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1274. tor_free(esc);
  1275. return -1;
  1276. }
  1277. if (tm_mday > 31 || tm_hour > 23 || tm_min > 59 || tm_sec > 61) {
  1278. char *esc = esc_for_log(buf);
  1279. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1280. tor_free(esc);
  1281. return -1;
  1282. }
  1283. tm.tm_mday = (int)tm_mday;
  1284. tm.tm_year = (int)tm_year;
  1285. tm.tm_hour = (int)tm_hour;
  1286. tm.tm_min = (int)tm_min;
  1287. tm.tm_sec = (int)tm_sec;
  1288. m = -1;
  1289. for (i = 0; i < 12; ++i) {
  1290. if (!strcmp(month, MONTH_NAMES[i])) {
  1291. m = i;
  1292. break;
  1293. }
  1294. }
  1295. if (m<0) {
  1296. char *esc = esc_for_log(buf);
  1297. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  1298. tor_free(esc);
  1299. return -1;
  1300. }
  1301. tm.tm_mon = m;
  1302. if (tm.tm_year < 1970) {
  1303. char *esc = esc_for_log(buf);
  1304. log_warn(LD_GENERAL,
  1305. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  1306. tor_free(esc);
  1307. return -1;
  1308. }
  1309. tm.tm_year -= 1900;
  1310. *t = tor_timegm(&tm);
  1311. return 0;
  1312. }
  1313. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  1314. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1315. *
  1316. * (ISO8601 format is 2006-10-29 10:57:20)
  1317. */
  1318. void
  1319. format_local_iso_time(char *buf, time_t t)
  1320. {
  1321. struct tm tm;
  1322. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  1323. }
  1324. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  1325. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1326. */
  1327. void
  1328. format_iso_time(char *buf, time_t t)
  1329. {
  1330. struct tm tm;
  1331. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  1332. }
  1333. /** As format_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  1334. * embedding an internal space. */
  1335. void
  1336. format_iso_time_nospace(char *buf, time_t t)
  1337. {
  1338. format_iso_time(buf, t);
  1339. buf[10] = 'T';
  1340. }
  1341. /** As format_iso_time_nospace, but include microseconds in decimal
  1342. * fixed-point format. Requires that buf be at least ISO_TIME_USEC_LEN+1
  1343. * bytes long. */
  1344. void
  1345. format_iso_time_nospace_usec(char *buf, const struct timeval *tv)
  1346. {
  1347. tor_assert(tv);
  1348. format_iso_time_nospace(buf, tv->tv_sec);
  1349. tor_snprintf(buf+ISO_TIME_LEN, 8, ".%06d", (int)tv->tv_usec);
  1350. }
  1351. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  1352. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  1353. * failure. Ignore extraneous stuff in <b>cp</b> separated by whitespace from
  1354. * the end of the time string. */
  1355. int
  1356. parse_iso_time(const char *cp, time_t *t)
  1357. {
  1358. struct tm st_tm;
  1359. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  1360. if (tor_sscanf(cp, "%u-%2u-%2u %2u:%2u:%2u", &year, &month,
  1361. &day, &hour, &minute, &second) < 6) {
  1362. char *esc = esc_for_log(cp);
  1363. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  1364. tor_free(esc);
  1365. return -1;
  1366. }
  1367. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  1368. hour > 23 || minute > 59 || second > 61) {
  1369. char *esc = esc_for_log(cp);
  1370. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  1371. tor_free(esc);
  1372. return -1;
  1373. }
  1374. st_tm.tm_year = year-1900;
  1375. st_tm.tm_mon = month-1;
  1376. st_tm.tm_mday = day;
  1377. st_tm.tm_hour = hour;
  1378. st_tm.tm_min = minute;
  1379. st_tm.tm_sec = second;
  1380. if (st_tm.tm_year < 70) {
  1381. char *esc = esc_for_log(cp);
  1382. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  1383. tor_free(esc);
  1384. return -1;
  1385. }
  1386. *t = tor_timegm(&st_tm);
  1387. return 0;
  1388. }
  1389. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  1390. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  1391. int
  1392. parse_http_time(const char *date, struct tm *tm)
  1393. {
  1394. const char *cp;
  1395. char month[4];
  1396. char wkday[4];
  1397. int i;
  1398. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1399. tor_assert(tm);
  1400. memset(tm, 0, sizeof(*tm));
  1401. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  1402. if ((cp = strchr(date, ','))) {
  1403. ++cp;
  1404. if (tor_sscanf(date, "%2u %3s %4u %2u:%2u:%2u GMT",
  1405. &tm_mday, month, &tm_year,
  1406. &tm_hour, &tm_min, &tm_sec) == 6) {
  1407. /* rfc1123-date */
  1408. tm_year -= 1900;
  1409. } else if (tor_sscanf(date, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  1410. &tm_mday, month, &tm_year,
  1411. &tm_hour, &tm_min, &tm_sec) == 6) {
  1412. /* rfc850-date */
  1413. } else {
  1414. return -1;
  1415. }
  1416. } else {
  1417. /* No comma; possibly asctime() format. */
  1418. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  1419. wkday, month, &tm_mday,
  1420. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  1421. tm_year -= 1900;
  1422. } else {
  1423. return -1;
  1424. }
  1425. }
  1426. tm->tm_mday = (int)tm_mday;
  1427. tm->tm_year = (int)tm_year;
  1428. tm->tm_hour = (int)tm_hour;
  1429. tm->tm_min = (int)tm_min;
  1430. tm->tm_sec = (int)tm_sec;
  1431. month[3] = '\0';
  1432. /* Okay, now decode the month. */
  1433. for (i = 0; i < 12; ++i) {
  1434. if (!strcasecmp(MONTH_NAMES[i], month)) {
  1435. tm->tm_mon = i+1;
  1436. }
  1437. }
  1438. if (tm->tm_year < 0 ||
  1439. tm->tm_mon < 1 || tm->tm_mon > 12 ||
  1440. tm->tm_mday < 0 || tm->tm_mday > 31 ||
  1441. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1442. tm->tm_min < 0 || tm->tm_min > 59 ||
  1443. tm->tm_sec < 0 || tm->tm_sec > 61)
  1444. return -1; /* Out of range, or bad month. */
  1445. return 0;
  1446. }
  1447. /** Given an <b>interval</b> in seconds, try to write it to the
  1448. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  1449. * Return 0 on success, -1 on failure.
  1450. */
  1451. int
  1452. format_time_interval(char *out, size_t out_len, long interval)
  1453. {
  1454. /* We only report seconds if there's no hours. */
  1455. long sec = 0, min = 0, hour = 0, day = 0;
  1456. if (interval < 0)
  1457. interval = -interval;
  1458. if (interval >= 86400) {
  1459. day = interval / 86400;
  1460. interval %= 86400;
  1461. }
  1462. if (interval >= 3600) {
  1463. hour = interval / 3600;
  1464. interval %= 3600;
  1465. }
  1466. if (interval >= 60) {
  1467. min = interval / 60;
  1468. interval %= 60;
  1469. }
  1470. sec = interval;
  1471. if (day) {
  1472. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  1473. day, hour, min);
  1474. } else if (hour) {
  1475. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  1476. } else if (min) {
  1477. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  1478. } else {
  1479. return tor_snprintf(out, out_len, "%ld seconds", sec);
  1480. }
  1481. }
  1482. /* =====
  1483. * Cached time
  1484. * ===== */
  1485. #ifndef TIME_IS_FAST
  1486. /** Cached estimate of the current time. Updated around once per second;
  1487. * may be a few seconds off if we are really busy. This is a hack to avoid
  1488. * calling time(NULL) (which not everybody has optimized) on critical paths.
  1489. */
  1490. static time_t cached_approx_time = 0;
  1491. /** Return a cached estimate of the current time from when
  1492. * update_approx_time() was last called. This is a hack to avoid calling
  1493. * time(NULL) on critical paths: please do not even think of calling it
  1494. * anywhere else. */
  1495. time_t
  1496. approx_time(void)
  1497. {
  1498. return cached_approx_time;
  1499. }
  1500. /** Update the cached estimate of the current time. This function SHOULD be
  1501. * called once per second, and MUST be called before the first call to
  1502. * get_approx_time. */
  1503. void
  1504. update_approx_time(time_t now)
  1505. {
  1506. cached_approx_time = now;
  1507. }
  1508. #endif
  1509. /* =====
  1510. * Rate limiting
  1511. * ===== */
  1512. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return the number
  1513. * of calls to rate_limit_is_ready (including this one!) since the last time
  1514. * rate_limit_is_ready returned nonzero. Otherwise return 0. */
  1515. static int
  1516. rate_limit_is_ready(ratelim_t *lim, time_t now)
  1517. {
  1518. if (lim->rate + lim->last_allowed <= now) {
  1519. int res = lim->n_calls_since_last_time + 1;
  1520. lim->last_allowed = now;
  1521. lim->n_calls_since_last_time = 0;
  1522. return res;
  1523. } else {
  1524. ++lim->n_calls_since_last_time;
  1525. return 0;
  1526. }
  1527. }
  1528. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return a newly
  1529. * allocated string indicating how many messages were suppressed, suitable to
  1530. * append to a log message. Otherwise return NULL. */
  1531. char *
  1532. rate_limit_log(ratelim_t *lim, time_t now)
  1533. {
  1534. int n;
  1535. if ((n = rate_limit_is_ready(lim, now))) {
  1536. if (n == 1) {
  1537. return tor_strdup("");
  1538. } else {
  1539. char *cp=NULL;
  1540. tor_asprintf(&cp,
  1541. " [%d similar message(s) suppressed in last %d seconds]",
  1542. n-1, lim->rate);
  1543. return cp;
  1544. }
  1545. } else {
  1546. return NULL;
  1547. }
  1548. }
  1549. /* =====
  1550. * File helpers
  1551. * ===== */
  1552. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1553. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1554. * was returned by open(). Return the number of bytes written, or -1
  1555. * on error. Only use if fd is a blocking fd. */
  1556. ssize_t
  1557. write_all(tor_socket_t fd, const char *buf, size_t count, int isSocket)
  1558. {
  1559. size_t written = 0;
  1560. ssize_t result;
  1561. tor_assert(count < SSIZE_T_MAX);
  1562. while (written != count) {
  1563. if (isSocket)
  1564. result = tor_socket_send(fd, buf+written, count-written, 0);
  1565. else
  1566. result = write((int)fd, buf+written, count-written);
  1567. if (result<0)
  1568. return -1;
  1569. written += result;
  1570. }
  1571. return (ssize_t)count;
  1572. }
  1573. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1574. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1575. * was returned by socket() or accept(), and 0 if fd was returned by
  1576. * open(). Return the number of bytes read, or -1 on error. Only use
  1577. * if fd is a blocking fd. */
  1578. ssize_t
  1579. read_all(tor_socket_t fd, char *buf, size_t count, int isSocket)
  1580. {
  1581. size_t numread = 0;
  1582. ssize_t result;
  1583. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  1584. return -1;
  1585. while (numread != count) {
  1586. if (isSocket)
  1587. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1588. else
  1589. result = read((int)fd, buf+numread, count-numread);
  1590. if (result<0)
  1591. return -1;
  1592. else if (result == 0)
  1593. break;
  1594. numread += result;
  1595. }
  1596. return (ssize_t)numread;
  1597. }
  1598. /*
  1599. * Filesystem operations.
  1600. */
  1601. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1602. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1603. * the root of a disk. */
  1604. static void
  1605. clean_name_for_stat(char *name)
  1606. {
  1607. #ifdef _WIN32
  1608. size_t len = strlen(name);
  1609. if (!len)
  1610. return;
  1611. if (name[len-1]=='\\' || name[len-1]=='/') {
  1612. if (len == 1 || (len==3 && name[1]==':'))
  1613. return;
  1614. name[len-1]='\0';
  1615. }
  1616. #else
  1617. (void)name;
  1618. #endif
  1619. }
  1620. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1621. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1622. * directory. On FN_ERROR, sets errno. */
  1623. file_status_t
  1624. file_status(const char *fname)
  1625. {
  1626. struct stat st;
  1627. char *f;
  1628. int r;
  1629. f = tor_strdup(fname);
  1630. clean_name_for_stat(f);
  1631. r = stat(f, &st);
  1632. tor_free(f);
  1633. if (r) {
  1634. if (errno == ENOENT) {
  1635. return FN_NOENT;
  1636. }
  1637. return FN_ERROR;
  1638. }
  1639. if (st.st_mode & S_IFDIR)
  1640. return FN_DIR;
  1641. else if (st.st_mode & S_IFREG)
  1642. return FN_FILE;
  1643. else
  1644. return FN_ERROR;
  1645. }
  1646. /** Check whether <b>dirname</b> exists and is private. If yes return 0. If
  1647. * it does not exist, and <b>check</b>&CPD_CREATE is set, try to create it
  1648. * and return 0 on success. If it does not exist, and
  1649. * <b>check</b>&CPD_CHECK, and we think we can create it, return 0. Else
  1650. * return -1. If CPD_GROUP_OK is set, then it's okay if the directory
  1651. * is group-readable, but in all cases we create the directory mode 0700.
  1652. * If CPD_CHECK_MODE_ONLY is set, then we don't alter the directory permissions
  1653. * if they are too permissive: we just return -1.
  1654. * When effective_user is not NULL, check permissions against the given user
  1655. * and its primary group.
  1656. */
  1657. int
  1658. check_private_dir(const char *dirname, cpd_check_t check,
  1659. const char *effective_user)
  1660. {
  1661. int r;
  1662. struct stat st;
  1663. char *f;
  1664. #ifndef _WIN32
  1665. int mask;
  1666. struct passwd *pw = NULL;
  1667. uid_t running_uid;
  1668. gid_t running_gid;
  1669. #else
  1670. (void)effective_user;
  1671. #endif
  1672. tor_assert(dirname);
  1673. f = tor_strdup(dirname);
  1674. clean_name_for_stat(f);
  1675. r = stat(f, &st);
  1676. tor_free(f);
  1677. if (r) {
  1678. if (errno != ENOENT) {
  1679. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1680. strerror(errno));
  1681. return -1;
  1682. }
  1683. if (check & CPD_CREATE) {
  1684. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1685. #if defined (_WIN32) && !defined (WINCE)
  1686. r = mkdir(dirname);
  1687. #else
  1688. r = mkdir(dirname, 0700);
  1689. #endif
  1690. if (r) {
  1691. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1692. strerror(errno));
  1693. return -1;
  1694. }
  1695. } else if (!(check & CPD_CHECK)) {
  1696. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1697. return -1;
  1698. }
  1699. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1700. * parent directory a little harder. */
  1701. return 0;
  1702. }
  1703. if (!(st.st_mode & S_IFDIR)) {
  1704. log_warn(LD_FS, "%s is not a directory", dirname);
  1705. return -1;
  1706. }
  1707. #ifndef _WIN32
  1708. if (effective_user) {
  1709. /* Look up the user and group information.
  1710. * If we have a problem, bail out. */
  1711. pw = getpwnam(effective_user);
  1712. if (pw == NULL) {
  1713. log_warn(LD_CONFIG, "Error setting configured user: %s not found",
  1714. effective_user);
  1715. return -1;
  1716. }
  1717. running_uid = pw->pw_uid;
  1718. running_gid = pw->pw_gid;
  1719. } else {
  1720. running_uid = getuid();
  1721. running_gid = getgid();
  1722. }
  1723. if (st.st_uid != running_uid) {
  1724. struct passwd *pw = NULL;
  1725. char *process_ownername = NULL;
  1726. pw = getpwuid(running_uid);
  1727. process_ownername = pw ? tor_strdup(pw->pw_name) : tor_strdup("<unknown>");
  1728. pw = getpwuid(st.st_uid);
  1729. log_warn(LD_FS, "%s is not owned by this user (%s, %d) but by "
  1730. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1731. dirname, process_ownername, (int)running_uid,
  1732. pw ? pw->pw_name : "<unknown>", (int)st.st_uid);
  1733. tor_free(process_ownername);
  1734. return -1;
  1735. }
  1736. if ((check & CPD_GROUP_OK) && st.st_gid != running_gid) {
  1737. struct group *gr;
  1738. char *process_groupname = NULL;
  1739. gr = getgrgid(running_gid);
  1740. process_groupname = gr ? tor_strdup(gr->gr_name) : tor_strdup("<unknown>");
  1741. gr = getgrgid(st.st_gid);
  1742. log_warn(LD_FS, "%s is not owned by this group (%s, %d) but by group "
  1743. "%s (%d). Are you running Tor as the wrong user?",
  1744. dirname, process_groupname, (int)running_gid,
  1745. gr ? gr->gr_name : "<unknown>", (int)st.st_gid);
  1746. tor_free(process_groupname);
  1747. return -1;
  1748. }
  1749. if (check & CPD_GROUP_OK) {
  1750. mask = 0027;
  1751. } else {
  1752. mask = 0077;
  1753. }
  1754. if (st.st_mode & mask) {
  1755. unsigned new_mode;
  1756. if (check & CPD_CHECK_MODE_ONLY) {
  1757. log_warn(LD_FS, "Permissions on directory %s are too permissive.",
  1758. dirname);
  1759. return -1;
  1760. }
  1761. log_warn(LD_FS, "Fixing permissions on directory %s", dirname);
  1762. new_mode = st.st_mode;
  1763. new_mode |= 0700; /* Owner should have rwx */
  1764. new_mode &= ~mask; /* Clear the other bits that we didn't want set...*/
  1765. if (chmod(dirname, new_mode)) {
  1766. log_warn(LD_FS, "Could not chmod directory %s: %s", dirname,
  1767. strerror(errno));
  1768. return -1;
  1769. } else {
  1770. return 0;
  1771. }
  1772. }
  1773. #endif
  1774. return 0;
  1775. }
  1776. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1777. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1778. *
  1779. * This function replaces the old file atomically, if possible. This
  1780. * function, and all other functions in util.c that create files, create them
  1781. * with mode 0600.
  1782. */
  1783. int
  1784. write_str_to_file(const char *fname, const char *str, int bin)
  1785. {
  1786. #ifdef _WIN32
  1787. if (!bin && strchr(str, '\r')) {
  1788. log_warn(LD_BUG,
  1789. "We're writing a text string that already contains a CR.");
  1790. }
  1791. #endif
  1792. return write_bytes_to_file(fname, str, strlen(str), bin);
  1793. }
  1794. /** Represents a file that we're writing to, with support for atomic commit:
  1795. * we can write into a temporary file, and either remove the file on
  1796. * failure, or replace the original file on success. */
  1797. struct open_file_t {
  1798. char *tempname; /**< Name of the temporary file. */
  1799. char *filename; /**< Name of the original file. */
  1800. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  1801. unsigned binary:1; /**< Did we open in binary mode? */
  1802. int fd; /**< fd for the open file. */
  1803. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  1804. };
  1805. /** Try to start writing to the file in <b>fname</b>, passing the flags
  1806. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  1807. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  1808. * original file. Otherwise, we open a new temporary file in the same
  1809. * directory, and either replace the original or remove the temporary file
  1810. * when we're done.
  1811. *
  1812. * Return the fd for the newly opened file, and store working data in
  1813. * *<b>data_out</b>. The caller should not close the fd manually:
  1814. * instead, call finish_writing_to_file() or abort_writing_to_file().
  1815. * Returns -1 on failure.
  1816. *
  1817. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  1818. * as true and the flag O_EXCL is treated as false.
  1819. *
  1820. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  1821. * write()". We don't do that.
  1822. */
  1823. int
  1824. start_writing_to_file(const char *fname, int open_flags, int mode,
  1825. open_file_t **data_out)
  1826. {
  1827. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  1828. const char *open_name;
  1829. int append = 0;
  1830. tor_assert(fname);
  1831. tor_assert(data_out);
  1832. #if (O_BINARY != 0 && O_TEXT != 0)
  1833. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  1834. #endif
  1835. new_file->fd = -1;
  1836. new_file->filename = tor_strdup(fname);
  1837. if (open_flags & O_APPEND) {
  1838. open_name = fname;
  1839. new_file->rename_on_close = 0;
  1840. append = 1;
  1841. open_flags &= ~O_APPEND;
  1842. } else {
  1843. tor_asprintf(&new_file->tempname, "%s.tmp", fname);
  1844. open_name = new_file->tempname;
  1845. /* We always replace an existing temporary file if there is one. */
  1846. open_flags |= O_CREAT|O_TRUNC;
  1847. open_flags &= ~O_EXCL;
  1848. new_file->rename_on_close = 1;
  1849. }
  1850. if (open_flags & O_BINARY)
  1851. new_file->binary = 1;
  1852. new_file->fd = tor_open_cloexec(open_name, open_flags, mode);
  1853. if (new_file->fd < 0) {
  1854. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  1855. open_name, fname, strerror(errno));
  1856. goto err;
  1857. }
  1858. if (append) {
  1859. if (tor_fd_seekend(new_file->fd) < 0) {
  1860. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  1861. strerror(errno));
  1862. goto err;
  1863. }
  1864. }
  1865. *data_out = new_file;
  1866. return new_file->fd;
  1867. err:
  1868. if (new_file->fd >= 0)
  1869. close(new_file->fd);
  1870. *data_out = NULL;
  1871. tor_free(new_file->filename);
  1872. tor_free(new_file->tempname);
  1873. tor_free(new_file);
  1874. return -1;
  1875. }
  1876. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  1877. * that can be used to write to the same file. The caller should not mix
  1878. * stdio calls with non-stdio calls. */
  1879. FILE *
  1880. fdopen_file(open_file_t *file_data)
  1881. {
  1882. tor_assert(file_data);
  1883. if (file_data->stdio_file)
  1884. return file_data->stdio_file;
  1885. tor_assert(file_data->fd >= 0);
  1886. if (!(file_data->stdio_file = fdopen(file_data->fd,
  1887. file_data->binary?"ab":"a"))) {
  1888. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  1889. file_data->fd, strerror(errno));
  1890. }
  1891. return file_data->stdio_file;
  1892. }
  1893. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  1894. * for start_writing_to_file, but */
  1895. FILE *
  1896. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  1897. open_file_t **data_out)
  1898. {
  1899. FILE *res;
  1900. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  1901. return NULL;
  1902. if (!(res = fdopen_file(*data_out))) {
  1903. abort_writing_to_file(*data_out);
  1904. *data_out = NULL;
  1905. }
  1906. return res;
  1907. }
  1908. /** Helper function: close and free the underlying file and memory in
  1909. * <b>file_data</b>. If we were writing into a temporary file, then delete
  1910. * that file (if abort_write is true) or replaces the target file with
  1911. * the temporary file (if abort_write is false). */
  1912. static int
  1913. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  1914. {
  1915. int r = 0;
  1916. tor_assert(file_data && file_data->filename);
  1917. if (file_data->stdio_file) {
  1918. if (fclose(file_data->stdio_file)) {
  1919. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  1920. strerror(errno));
  1921. abort_write = r = -1;
  1922. }
  1923. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  1924. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  1925. strerror(errno));
  1926. abort_write = r = -1;
  1927. }
  1928. if (file_data->rename_on_close) {
  1929. tor_assert(file_data->tempname && file_data->filename);
  1930. if (abort_write) {
  1931. unlink(file_data->tempname);
  1932. } else {
  1933. tor_assert(strcmp(file_data->filename, file_data->tempname));
  1934. if (replace_file(file_data->tempname, file_data->filename)) {
  1935. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  1936. strerror(errno));
  1937. r = -1;
  1938. }
  1939. }
  1940. }
  1941. tor_free(file_data->filename);
  1942. tor_free(file_data->tempname);
  1943. tor_free(file_data);
  1944. return r;
  1945. }
  1946. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1947. * needed, and if using a temporary file, replace the original file with
  1948. * the temporary file. */
  1949. int
  1950. finish_writing_to_file(open_file_t *file_data)
  1951. {
  1952. return finish_writing_to_file_impl(file_data, 0);
  1953. }
  1954. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1955. * needed, and if using a temporary file, delete it. */
  1956. int
  1957. abort_writing_to_file(open_file_t *file_data)
  1958. {
  1959. return finish_writing_to_file_impl(file_data, 1);
  1960. }
  1961. /** Helper: given a set of flags as passed to open(2), open the file
  1962. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  1963. * the file. Do so as atomically as possible e.g. by opening temp files and
  1964. * renaming. */
  1965. static int
  1966. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  1967. int open_flags)
  1968. {
  1969. open_file_t *file = NULL;
  1970. int fd;
  1971. ssize_t result;
  1972. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  1973. if (fd<0)
  1974. return -1;
  1975. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  1976. {
  1977. result = write_all(fd, chunk->bytes, chunk->len, 0);
  1978. if (result < 0) {
  1979. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  1980. strerror(errno));
  1981. goto err;
  1982. }
  1983. tor_assert((size_t)result == chunk->len);
  1984. });
  1985. return finish_writing_to_file(file);
  1986. err:
  1987. abort_writing_to_file(file);
  1988. return -1;
  1989. }
  1990. /** Given a smartlist of sized_chunk_t, write them atomically to a file
  1991. * <b>fname</b>, overwriting or creating the file as necessary. */
  1992. int
  1993. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin)
  1994. {
  1995. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1996. return write_chunks_to_file_impl(fname, chunks, flags);
  1997. }
  1998. /** Write <b>len</b> bytes, starting at <b>str</b>, to <b>fname</b>
  1999. using the open() flags passed in <b>flags</b>. */
  2000. static int
  2001. write_bytes_to_file_impl(const char *fname, const char *str, size_t len,
  2002. int flags)
  2003. {
  2004. int r;
  2005. sized_chunk_t c = { str, len };
  2006. smartlist_t *chunks = smartlist_new();
  2007. smartlist_add(chunks, &c);
  2008. r = write_chunks_to_file_impl(fname, chunks, flags);
  2009. smartlist_free(chunks);
  2010. return r;
  2011. }
  2012. /** As write_str_to_file, but does not assume a NUL-terminated
  2013. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  2014. int
  2015. write_bytes_to_file(const char *fname, const char *str, size_t len,
  2016. int bin)
  2017. {
  2018. return write_bytes_to_file_impl(fname, str, len,
  2019. OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT));
  2020. }
  2021. /** As write_bytes_to_file, but if the file already exists, append the bytes
  2022. * to the end of the file instead of overwriting it. */
  2023. int
  2024. append_bytes_to_file(const char *fname, const char *str, size_t len,
  2025. int bin)
  2026. {
  2027. return write_bytes_to_file_impl(fname, str, len,
  2028. OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT));
  2029. }
  2030. /** Like write_str_to_file(), but also return -1 if there was a file
  2031. already residing in <b>fname</b>. */
  2032. int
  2033. write_bytes_to_new_file(const char *fname, const char *str, size_t len,
  2034. int bin)
  2035. {
  2036. return write_bytes_to_file_impl(fname, str, len,
  2037. OPEN_FLAGS_DONT_REPLACE|
  2038. (bin?O_BINARY:O_TEXT));
  2039. }
  2040. /** Read the contents of <b>filename</b> into a newly allocated
  2041. * string; return the string on success or NULL on failure.
  2042. *
  2043. * If <b>stat_out</b> is provided, store the result of stat()ing the
  2044. * file into <b>stat_out</b>.
  2045. *
  2046. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  2047. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  2048. * doesn't exist.
  2049. */
  2050. /*
  2051. * This function <em>may</em> return an erroneous result if the file
  2052. * is modified while it is running, but must not crash or overflow.
  2053. * Right now, the error case occurs when the file length grows between
  2054. * the call to stat and the call to read_all: the resulting string will
  2055. * be truncated.
  2056. */
  2057. char *
  2058. read_file_to_str(const char *filename, int flags, struct stat *stat_out)
  2059. {
  2060. int fd; /* router file */
  2061. struct stat statbuf;
  2062. char *string;
  2063. ssize_t r;
  2064. int bin = flags & RFTS_BIN;
  2065. tor_assert(filename);
  2066. fd = tor_open_cloexec(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  2067. if (fd<0) {
  2068. int severity = LOG_WARN;
  2069. int save_errno = errno;
  2070. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  2071. severity = LOG_INFO;
  2072. log_fn(severity, LD_FS,"Could not open \"%s\": %s",filename,
  2073. strerror(errno));
  2074. errno = save_errno;
  2075. return NULL;
  2076. }
  2077. if (fstat(fd, &statbuf)<0) {
  2078. int save_errno = errno;
  2079. close(fd);
  2080. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  2081. errno = save_errno;
  2082. return NULL;
  2083. }
  2084. if ((uint64_t)(statbuf.st_size)+1 >= SIZE_T_CEILING)
  2085. return NULL;
  2086. string = tor_malloc((size_t)(statbuf.st_size+1));
  2087. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  2088. if (r<0) {
  2089. int save_errno = errno;
  2090. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  2091. strerror(errno));
  2092. tor_free(string);
  2093. close(fd);
  2094. errno = save_errno;
  2095. return NULL;
  2096. }
  2097. string[r] = '\0'; /* NUL-terminate the result. */
  2098. #ifdef _WIN32
  2099. if (!bin && strchr(string, '\r')) {
  2100. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  2101. "when reading %s. Coping.",
  2102. filename);
  2103. tor_strstrip(string, "\r");
  2104. r = strlen(string);
  2105. }
  2106. if (!bin) {
  2107. statbuf.st_size = (size_t) r;
  2108. } else
  2109. #endif
  2110. if (r != statbuf.st_size) {
  2111. /* Unless we're using text mode on win32, we'd better have an exact
  2112. * match for size. */
  2113. int save_errno = errno;
  2114. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  2115. (int)r, (long)statbuf.st_size,filename);
  2116. tor_free(string);
  2117. close(fd);
  2118. errno = save_errno;
  2119. return NULL;
  2120. }
  2121. close(fd);
  2122. if (stat_out) {
  2123. memcpy(stat_out, &statbuf, sizeof(struct stat));
  2124. }
  2125. return string;
  2126. }
  2127. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  2128. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  2129. * decode its contents into a newly allocated string. On success, assign this
  2130. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  2131. * provided), and return a pointer to the position in <b>s</b> immediately
  2132. * after the string. On failure, return NULL.
  2133. */
  2134. static const char *
  2135. unescape_string(const char *s, char **result, size_t *size_out)
  2136. {
  2137. const char *cp;
  2138. char *out;
  2139. if (s[0] != '\"')
  2140. return NULL;
  2141. cp = s+1;
  2142. while (1) {
  2143. switch (*cp) {
  2144. case '\0':
  2145. case '\n':
  2146. return NULL;
  2147. case '\"':
  2148. goto end_of_loop;
  2149. case '\\':
  2150. if ((cp[1] == 'x' || cp[1] == 'X')
  2151. && TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])) {
  2152. cp += 4;
  2153. } else if (TOR_ISODIGIT(cp[1])) {
  2154. cp += 2;
  2155. if (TOR_ISODIGIT(*cp)) ++cp;
  2156. if (TOR_ISODIGIT(*cp)) ++cp;
  2157. } else if (cp[1]) {
  2158. cp += 2;
  2159. } else {
  2160. return NULL;
  2161. }
  2162. break;
  2163. default:
  2164. ++cp;
  2165. break;
  2166. }
  2167. }
  2168. end_of_loop:
  2169. out = *result = tor_malloc(cp-s + 1);
  2170. cp = s+1;
  2171. while (1) {
  2172. switch (*cp)
  2173. {
  2174. case '\"':
  2175. *out = '\0';
  2176. if (size_out) *size_out = out - *result;
  2177. return cp+1;
  2178. case '\0':
  2179. tor_fragile_assert();
  2180. tor_free(*result);
  2181. return NULL;
  2182. case '\\':
  2183. switch (cp[1])
  2184. {
  2185. case 'n': *out++ = '\n'; cp += 2; break;
  2186. case 'r': *out++ = '\r'; cp += 2; break;
  2187. case 't': *out++ = '\t'; cp += 2; break;
  2188. case 'x': case 'X':
  2189. *out++ = ((hex_decode_digit(cp[2])<<4) +
  2190. hex_decode_digit(cp[3]));
  2191. cp += 4;
  2192. break;
  2193. case '0': case '1': case '2': case '3': case '4': case '5':
  2194. case '6': case '7':
  2195. {
  2196. int n = cp[1]-'0';
  2197. cp += 2;
  2198. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2199. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2200. if (n > 255) { tor_free(*result); return NULL; }
  2201. *out++ = (char)n;
  2202. }
  2203. break;
  2204. case '\'':
  2205. case '\"':
  2206. case '\\':
  2207. case '\?':
  2208. *out++ = cp[1];
  2209. cp += 2;
  2210. break;
  2211. default:
  2212. tor_free(*result); return NULL;
  2213. }
  2214. break;
  2215. default:
  2216. *out++ = *cp++;
  2217. }
  2218. }
  2219. }
  2220. /** Given a string containing part of a configuration file or similar format,
  2221. * advance past comments and whitespace and try to parse a single line. If we
  2222. * parse a line successfully, set *<b>key_out</b> to a new string holding the
  2223. * key portion and *<b>value_out</b> to a new string holding the value portion
  2224. * of the line, and return a pointer to the start of the next line. If we run
  2225. * out of data, return a pointer to the end of the string. If we encounter an
  2226. * error, return NULL.
  2227. */
  2228. const char *
  2229. parse_config_line_from_str(const char *line, char **key_out, char **value_out)
  2230. {
  2231. /* I believe the file format here is supposed to be:
  2232. FILE = (EMPTYLINE | LINE)* (EMPTYLASTLINE | LASTLINE)?
  2233. EMPTYLASTLINE = SPACE* | COMMENT
  2234. EMPTYLINE = EMPTYLASTLINE NL
  2235. SPACE = ' ' | '\r' | '\t'
  2236. COMMENT = '#' NOT-NL*
  2237. NOT-NL = Any character except '\n'
  2238. NL = '\n'
  2239. LASTLINE = SPACE* KEY SPACE* VALUES
  2240. LINE = LASTLINE NL
  2241. KEY = KEYCHAR+
  2242. KEYCHAR = Any character except ' ', '\r', '\n', '\t', '#', "\"
  2243. VALUES = QUOTEDVALUE | NORMALVALUE
  2244. QUOTEDVALUE = QUOTE QVITEM* QUOTE EOLSPACE?
  2245. QUOTE = '"'
  2246. QVCHAR = KEYCHAR | ESC ('n' | 't' | 'r' | '"' | ESC |'\'' | OCTAL | HEX)
  2247. ESC = "\\"
  2248. OCTAL = ODIGIT (ODIGIT ODIGIT?)?
  2249. HEX = ('x' | 'X') HEXDIGIT HEXDIGIT
  2250. ODIGIT = '0' .. '7'
  2251. HEXDIGIT = '0'..'9' | 'a' .. 'f' | 'A' .. 'F'
  2252. EOLSPACE = SPACE* COMMENT?
  2253. NORMALVALUE = (VALCHAR | ESC ESC_IGNORE | CONTINUATION)* EOLSPACE?
  2254. VALCHAR = Any character except ESC, '#', and '\n'
  2255. ESC_IGNORE = Any character except '#' or '\n'
  2256. CONTINUATION = ESC NL ( COMMENT NL )*
  2257. */
  2258. const char *key, *val, *cp;
  2259. int continuation = 0;
  2260. tor_assert(key_out);
  2261. tor_assert(value_out);
  2262. *key_out = *value_out = NULL;
  2263. key = val = NULL;
  2264. /* Skip until the first keyword. */
  2265. while (1) {
  2266. while (TOR_ISSPACE(*line))
  2267. ++line;
  2268. if (*line == '#') {
  2269. while (*line && *line != '\n')
  2270. ++line;
  2271. } else {
  2272. break;
  2273. }
  2274. }
  2275. if (!*line) { /* End of string? */
  2276. *key_out = *value_out = NULL;
  2277. return line;
  2278. }
  2279. /* Skip until the next space or \ followed by newline. */
  2280. key = line;
  2281. while (*line && !TOR_ISSPACE(*line) && *line != '#' &&
  2282. ! (line[0] == '\\' && line[1] == '\n'))
  2283. ++line;
  2284. *key_out = tor_strndup(key, line-key);
  2285. /* Skip until the value. */
  2286. while (*line == ' ' || *line == '\t')
  2287. ++line;
  2288. val = line;
  2289. /* Find the end of the line. */
  2290. if (*line == '\"') { // XXX No continuation handling is done here
  2291. if (!(line = unescape_string(line, value_out, NULL)))
  2292. return NULL;
  2293. while (*line == ' ' || *line == '\t')
  2294. ++line;
  2295. if (*line && *line != '#' && *line != '\n')
  2296. return NULL;
  2297. } else {
  2298. /* Look for the end of the line. */
  2299. while (*line && *line != '\n' && (*line != '#' || continuation)) {
  2300. if (*line == '\\' && line[1] == '\n') {
  2301. continuation = 1;
  2302. line += 2;
  2303. } else if (*line == '#') {
  2304. do {
  2305. ++line;
  2306. } while (*line && *line != '\n');
  2307. if (*line == '\n')
  2308. ++line;
  2309. } else {
  2310. ++line;
  2311. }
  2312. }
  2313. if (*line == '\n') {
  2314. cp = line++;
  2315. } else {
  2316. cp = line;
  2317. }
  2318. /* Now back cp up to be the last nonspace character */
  2319. while (cp>val && TOR_ISSPACE(*(cp-1)))
  2320. --cp;
  2321. tor_assert(cp >= val);
  2322. /* Now copy out and decode the value. */
  2323. *value_out = tor_strndup(val, cp-val);
  2324. if (continuation) {
  2325. char *v_out, *v_in;
  2326. v_out = v_in = *value_out;
  2327. while (*v_in) {
  2328. if (*v_in == '#') {
  2329. do {
  2330. ++v_in;
  2331. } while (*v_in && *v_in != '\n');
  2332. if (*v_in == '\n')
  2333. ++v_in;
  2334. } else if (v_in[0] == '\\' && v_in[1] == '\n') {
  2335. v_in += 2;
  2336. } else {
  2337. *v_out++ = *v_in++;
  2338. }
  2339. }
  2340. *v_out = '\0';
  2341. }
  2342. }
  2343. if (*line == '#') {
  2344. do {
  2345. ++line;
  2346. } while (*line && *line != '\n');
  2347. }
  2348. while (TOR_ISSPACE(*line)) ++line;
  2349. return line;
  2350. }
  2351. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  2352. * string. */
  2353. char *
  2354. expand_filename(const char *filename)
  2355. {
  2356. tor_assert(filename);
  2357. #ifdef _WIN32
  2358. return tor_strdup(filename);
  2359. #else
  2360. if (*filename == '~') {
  2361. char *home, *result=NULL;
  2362. const char *rest;
  2363. if (filename[1] == '/' || filename[1] == '\0') {
  2364. home = getenv("HOME");
  2365. if (!home) {
  2366. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  2367. "expanding \"%s\"; defaulting to \"\".", filename);
  2368. home = tor_strdup("");
  2369. } else {
  2370. home = tor_strdup(home);
  2371. }
  2372. rest = strlen(filename)>=2?(filename+2):"";
  2373. } else {
  2374. #ifdef HAVE_PWD_H
  2375. char *username, *slash;
  2376. slash = strchr(filename, '/');
  2377. if (slash)
  2378. username = tor_strndup(filename+1,slash-filename-1);
  2379. else
  2380. username = tor_strdup(filename+1);
  2381. if (!(home = get_user_homedir(username))) {
  2382. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2383. tor_free(username);
  2384. return NULL;
  2385. }
  2386. tor_free(username);
  2387. rest = slash ? (slash+1) : "";
  2388. #else
  2389. log_warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
  2390. return tor_strdup(filename);
  2391. #endif
  2392. }
  2393. tor_assert(home);
  2394. /* Remove trailing slash. */
  2395. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2396. home[strlen(home)-1] = '\0';
  2397. }
  2398. tor_asprintf(&result,"%s"PATH_SEPARATOR"%s",home,rest);
  2399. tor_free(home);
  2400. return result;
  2401. } else {
  2402. return tor_strdup(filename);
  2403. }
  2404. #endif
  2405. }
  2406. #define MAX_SCANF_WIDTH 9999
  2407. /** Helper: given an ASCII-encoded decimal digit, return its numeric value.
  2408. * NOTE: requires that its input be in-bounds. */
  2409. static int
  2410. digit_to_num(char d)
  2411. {
  2412. int num = ((int)d) - (int)'0';
  2413. tor_assert(num <= 9 && num >= 0);
  2414. return num;
  2415. }
  2416. /** Helper: Read an unsigned int from *<b>bufp</b> of up to <b>width</b>
  2417. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2418. * success, store the result in <b>out</b>, advance bufp to the next
  2419. * character, and return 0. On failure, return -1. */
  2420. static int
  2421. scan_unsigned(const char **bufp, unsigned *out, int width, int base)
  2422. {
  2423. unsigned result = 0;
  2424. int scanned_so_far = 0;
  2425. const int hex = base==16;
  2426. tor_assert(base == 10 || base == 16);
  2427. if (!bufp || !*bufp || !out)
  2428. return -1;
  2429. if (width<0)
  2430. width=MAX_SCANF_WIDTH;
  2431. while (**bufp && (hex?TOR_ISXDIGIT(**bufp):TOR_ISDIGIT(**bufp))
  2432. && scanned_so_far < width) {
  2433. int digit = hex?hex_decode_digit(*(*bufp)++):digit_to_num(*(*bufp)++);
  2434. unsigned new_result = result * base + digit;
  2435. if (new_result > UINT32_MAX || new_result < result)
  2436. return -1; /* over/underflow. */
  2437. result = new_result;
  2438. ++scanned_so_far;
  2439. }
  2440. if (!scanned_so_far) /* No actual digits scanned */
  2441. return -1;
  2442. *out = result;
  2443. return 0;
  2444. }
  2445. /** Helper: copy up to <b>width</b> non-space characters from <b>bufp</b> to
  2446. * <b>out</b>. Make sure <b>out</b> is nul-terminated. Advance <b>bufp</b>
  2447. * to the next non-space character or the EOS. */
  2448. static int
  2449. scan_string(const char **bufp, char *out, int width)
  2450. {
  2451. int scanned_so_far = 0;
  2452. if (!bufp || !out || width < 0)
  2453. return -1;
  2454. while (**bufp && ! TOR_ISSPACE(**bufp) && scanned_so_far < width) {
  2455. *out++ = *(*bufp)++;
  2456. ++scanned_so_far;
  2457. }
  2458. *out = '\0';
  2459. return 0;
  2460. }
  2461. /** Locale-independent, minimal, no-surprises scanf variant, accepting only a
  2462. * restricted pattern format. For more info on what it supports, see
  2463. * tor_sscanf() documentation. */
  2464. int
  2465. tor_vsscanf(const char *buf, const char *pattern, va_list ap)
  2466. {
  2467. int n_matched = 0;
  2468. while (*pattern) {
  2469. if (*pattern != '%') {
  2470. if (*buf == *pattern) {
  2471. ++buf;
  2472. ++pattern;
  2473. continue;
  2474. } else {
  2475. return n_matched;
  2476. }
  2477. } else {
  2478. int width = -1;
  2479. ++pattern;
  2480. if (TOR_ISDIGIT(*pattern)) {
  2481. width = digit_to_num(*pattern++);
  2482. while (TOR_ISDIGIT(*pattern)) {
  2483. width *= 10;
  2484. width += digit_to_num(*pattern++);
  2485. if (width > MAX_SCANF_WIDTH)
  2486. return -1;
  2487. }
  2488. if (!width) /* No zero-width things. */
  2489. return -1;
  2490. }
  2491. if (*pattern == 'u' || *pattern == 'x') {
  2492. unsigned *u = va_arg(ap, unsigned *);
  2493. const int base = (*pattern == 'u') ? 10 : 16;
  2494. if (!*buf)
  2495. return n_matched;
  2496. if (scan_unsigned(&buf, u, width, base)<0)
  2497. return n_matched;
  2498. ++pattern;
  2499. ++n_matched;
  2500. } else if (*pattern == 's') {
  2501. char *s = va_arg(ap, char *);
  2502. if (width < 0)
  2503. return -1;
  2504. if (scan_string(&buf, s, width)<0)
  2505. return n_matched;
  2506. ++pattern;
  2507. ++n_matched;
  2508. } else if (*pattern == 'c') {
  2509. char *ch = va_arg(ap, char *);
  2510. if (width != -1)
  2511. return -1;
  2512. if (!*buf)
  2513. return n_matched;
  2514. *ch = *buf++;
  2515. ++pattern;
  2516. ++n_matched;
  2517. } else if (*pattern == '%') {
  2518. if (*buf != '%')
  2519. return -1;
  2520. ++buf;
  2521. ++pattern;
  2522. } else {
  2523. return -1; /* Unrecognized pattern component. */
  2524. }
  2525. }
  2526. }
  2527. return n_matched;
  2528. }
  2529. /** Minimal sscanf replacement: parse <b>buf</b> according to <b>pattern</b>
  2530. * and store the results in the corresponding argument fields. Differs from
  2531. * sscanf in that it: Only handles %u and %x and %Ns. Does not handle
  2532. * arbitrarily long widths. %u and %x do not consume any space. Is
  2533. * locale-independent. Returns -1 on malformed patterns.
  2534. *
  2535. * (As with other locale-independent functions, we need this to parse data that
  2536. * is in ASCII without worrying that the C library's locale-handling will make
  2537. * miscellaneous characters look like numbers, spaces, and so on.)
  2538. */
  2539. int
  2540. tor_sscanf(const char *buf, const char *pattern, ...)
  2541. {
  2542. int r;
  2543. va_list ap;
  2544. va_start(ap, pattern);
  2545. r = tor_vsscanf(buf, pattern, ap);
  2546. va_end(ap);
  2547. return r;
  2548. }
  2549. /** Append the string produced by tor_asprintf(<b>pattern</b>, <b>...</b>)
  2550. * to <b>sl</b>. */
  2551. void
  2552. smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern, ...)
  2553. {
  2554. va_list ap;
  2555. va_start(ap, pattern);
  2556. smartlist_add_vasprintf(sl, pattern, ap);
  2557. va_end(ap);
  2558. }
  2559. /** va_list-based backend of smartlist_add_asprintf. */
  2560. void
  2561. smartlist_add_vasprintf(struct smartlist_t *sl, const char *pattern,
  2562. va_list args)
  2563. {
  2564. char *str = NULL;
  2565. tor_vasprintf(&str, pattern, args);
  2566. tor_assert(str != NULL);
  2567. smartlist_add(sl, str);
  2568. }
  2569. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  2570. * Return NULL on error or if <b>dirname</b> is not a directory.
  2571. */
  2572. smartlist_t *
  2573. tor_listdir(const char *dirname)
  2574. {
  2575. smartlist_t *result;
  2576. #ifdef _WIN32
  2577. char *pattern=NULL;
  2578. TCHAR tpattern[MAX_PATH] = {0};
  2579. char name[MAX_PATH] = {0};
  2580. HANDLE handle;
  2581. WIN32_FIND_DATA findData;
  2582. tor_asprintf(&pattern, "%s\\*", dirname);
  2583. #ifdef UNICODE
  2584. mbstowcs(tpattern,pattern,MAX_PATH);
  2585. #else
  2586. strlcpy(tpattern, pattern, MAX_PATH);
  2587. #endif
  2588. if (INVALID_HANDLE_VALUE == (handle = FindFirstFile(tpattern, &findData))) {
  2589. tor_free(pattern);
  2590. return NULL;
  2591. }
  2592. result = smartlist_new();
  2593. while (1) {
  2594. #ifdef UNICODE
  2595. wcstombs(name,findData.cFileName,MAX_PATH);
  2596. #else
  2597. strlcpy(name,findData.cFileName,sizeof(name));
  2598. #endif
  2599. if (strcmp(name, ".") &&
  2600. strcmp(name, "..")) {
  2601. smartlist_add(result, tor_strdup(name));
  2602. }
  2603. if (!FindNextFile(handle, &findData)) {
  2604. DWORD err;
  2605. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  2606. char *errstr = format_win32_error(err);
  2607. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  2608. tor_free(errstr);
  2609. }
  2610. break;
  2611. }
  2612. }
  2613. FindClose(handle);
  2614. tor_free(pattern);
  2615. #else
  2616. DIR *d;
  2617. struct dirent *de;
  2618. if (!(d = opendir(dirname)))
  2619. return NULL;
  2620. result = smartlist_new();
  2621. while ((de = readdir(d))) {
  2622. if (!strcmp(de->d_name, ".") ||
  2623. !strcmp(de->d_name, ".."))
  2624. continue;
  2625. smartlist_add(result, tor_strdup(de->d_name));
  2626. }
  2627. closedir(d);
  2628. #endif
  2629. return result;
  2630. }
  2631. /** Return true iff <b>filename</b> is a relative path. */
  2632. int
  2633. path_is_relative(const char *filename)
  2634. {
  2635. if (filename && filename[0] == '/')
  2636. return 0;
  2637. #ifdef _WIN32
  2638. else if (filename && filename[0] == '\\')
  2639. return 0;
  2640. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  2641. filename[1] == ':' && filename[2] == '\\')
  2642. return 0;
  2643. #endif
  2644. else
  2645. return 1;
  2646. }
  2647. /* =====
  2648. * Process helpers
  2649. * ===== */
  2650. #ifndef _WIN32
  2651. /* Based on code contributed by christian grothoff */
  2652. /** True iff we've called start_daemon(). */
  2653. static int start_daemon_called = 0;
  2654. /** True iff we've called finish_daemon(). */
  2655. static int finish_daemon_called = 0;
  2656. /** Socketpair used to communicate between parent and child process while
  2657. * daemonizing. */
  2658. static int daemon_filedes[2];
  2659. /** Start putting the process into daemon mode: fork and drop all resources
  2660. * except standard fds. The parent process never returns, but stays around
  2661. * until finish_daemon is called. (Note: it's safe to call this more
  2662. * than once: calls after the first are ignored.)
  2663. */
  2664. void
  2665. start_daemon(void)
  2666. {
  2667. pid_t pid;
  2668. if (start_daemon_called)
  2669. return;
  2670. start_daemon_called = 1;
  2671. if (pipe(daemon_filedes)) {
  2672. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  2673. exit(1);
  2674. }
  2675. pid = fork();
  2676. if (pid < 0) {
  2677. log_err(LD_GENERAL,"fork failed. Exiting.");
  2678. exit(1);
  2679. }
  2680. if (pid) { /* Parent */
  2681. int ok;
  2682. char c;
  2683. close(daemon_filedes[1]); /* we only read */
  2684. ok = -1;
  2685. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  2686. if (c == '.')
  2687. ok = 1;
  2688. }
  2689. fflush(stdout);
  2690. if (ok == 1)
  2691. exit(0);
  2692. else
  2693. exit(1); /* child reported error */
  2694. } else { /* Child */
  2695. close(daemon_filedes[0]); /* we only write */
  2696. pid = setsid(); /* Detach from controlling terminal */
  2697. /*
  2698. * Fork one more time, so the parent (the session group leader) can exit.
  2699. * This means that we, as a non-session group leader, can never regain a
  2700. * controlling terminal. This part is recommended by Stevens's
  2701. * _Advanced Programming in the Unix Environment_.
  2702. */
  2703. if (fork() != 0) {
  2704. exit(0);
  2705. }
  2706. set_main_thread(); /* We are now the main thread. */
  2707. return;
  2708. }
  2709. }
  2710. /** Finish putting the process into daemon mode: drop standard fds, and tell
  2711. * the parent process to exit. (Note: it's safe to call this more than once:
  2712. * calls after the first are ignored. Calls start_daemon first if it hasn't
  2713. * been called already.)
  2714. */
  2715. void
  2716. finish_daemon(const char *desired_cwd)
  2717. {
  2718. int nullfd;
  2719. char c = '.';
  2720. if (finish_daemon_called)
  2721. return;
  2722. if (!start_daemon_called)
  2723. start_daemon();
  2724. finish_daemon_called = 1;
  2725. if (!desired_cwd)
  2726. desired_cwd = "/";
  2727. /* Don't hold the wrong FS mounted */
  2728. if (chdir(desired_cwd) < 0) {
  2729. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  2730. exit(1);
  2731. }
  2732. nullfd = tor_open_cloexec("/dev/null", O_RDWR, 0);
  2733. if (nullfd < 0) {
  2734. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  2735. exit(1);
  2736. }
  2737. /* close fds linking to invoking terminal, but
  2738. * close usual incoming fds, but redirect them somewhere
  2739. * useful so the fds don't get reallocated elsewhere.
  2740. */
  2741. if (dup2(nullfd,0) < 0 ||
  2742. dup2(nullfd,1) < 0 ||
  2743. dup2(nullfd,2) < 0) {
  2744. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  2745. exit(1);
  2746. }
  2747. if (nullfd > 2)
  2748. close(nullfd);
  2749. /* signal success */
  2750. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  2751. log_err(LD_GENERAL,"write failed. Exiting.");
  2752. }
  2753. close(daemon_filedes[1]);
  2754. }
  2755. #else
  2756. /* defined(_WIN32) */
  2757. void
  2758. start_daemon(void)
  2759. {
  2760. }
  2761. void
  2762. finish_daemon(const char *cp)
  2763. {
  2764. (void)cp;
  2765. }
  2766. #endif
  2767. /** Write the current process ID, followed by NL, into <b>filename</b>.
  2768. */
  2769. void
  2770. write_pidfile(char *filename)
  2771. {
  2772. FILE *pidfile;
  2773. if ((pidfile = fopen(filename, "w")) == NULL) {
  2774. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  2775. strerror(errno));
  2776. } else {
  2777. #ifdef _WIN32
  2778. fprintf(pidfile, "%d\n", (int)_getpid());
  2779. #else
  2780. fprintf(pidfile, "%d\n", (int)getpid());
  2781. #endif
  2782. fclose(pidfile);
  2783. }
  2784. }
  2785. #ifdef _WIN32
  2786. HANDLE
  2787. load_windows_system_library(const TCHAR *library_name)
  2788. {
  2789. TCHAR path[MAX_PATH];
  2790. unsigned n;
  2791. n = GetSystemDirectory(path, MAX_PATH);
  2792. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  2793. return 0;
  2794. _tcscat(path, TEXT("\\"));
  2795. _tcscat(path, library_name);
  2796. return LoadLibrary(path);
  2797. }
  2798. #endif
  2799. /** Format a single argument for being put on a Windows command line.
  2800. * Returns a newly allocated string */
  2801. static char *
  2802. format_win_cmdline_argument(const char *arg)
  2803. {
  2804. char *formatted_arg;
  2805. char need_quotes;
  2806. const char *c;
  2807. int i;
  2808. int bs_counter = 0;
  2809. /* Backslash we can point to when one is inserted into the string */
  2810. const char backslash = '\\';
  2811. /* Smartlist of *char */
  2812. smartlist_t *arg_chars;
  2813. arg_chars = smartlist_new();
  2814. /* Quote string if it contains whitespace or is empty */
  2815. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  2816. /* Build up smartlist of *chars */
  2817. for (c=arg; *c != '\0'; c++) {
  2818. if ('"' == *c) {
  2819. /* Double up backslashes preceding a quote */
  2820. for (i=0; i<(bs_counter*2); i++)
  2821. smartlist_add(arg_chars, (void*)&backslash);
  2822. bs_counter = 0;
  2823. /* Escape the quote */
  2824. smartlist_add(arg_chars, (void*)&backslash);
  2825. smartlist_add(arg_chars, (void*)c);
  2826. } else if ('\\' == *c) {
  2827. /* Count backslashes until we know whether to double up */
  2828. bs_counter++;
  2829. } else {
  2830. /* Don't double up slashes preceding a non-quote */
  2831. for (i=0; i<bs_counter; i++)
  2832. smartlist_add(arg_chars, (void*)&backslash);
  2833. bs_counter = 0;
  2834. smartlist_add(arg_chars, (void*)c);
  2835. }
  2836. }
  2837. /* Don't double up trailing backslashes */
  2838. for (i=0; i<bs_counter; i++)
  2839. smartlist_add(arg_chars, (void*)&backslash);
  2840. /* Allocate space for argument, quotes (if needed), and terminator */
  2841. formatted_arg = tor_malloc(sizeof(char) *
  2842. (smartlist_len(arg_chars) + (need_quotes?2:0) + 1));
  2843. /* Add leading quote */
  2844. i=0;
  2845. if (need_quotes)
  2846. formatted_arg[i++] = '"';
  2847. /* Add characters */
  2848. SMARTLIST_FOREACH(arg_chars, char*, c,
  2849. {
  2850. formatted_arg[i++] = *c;
  2851. });
  2852. /* Add trailing quote */
  2853. if (need_quotes)
  2854. formatted_arg[i++] = '"';
  2855. formatted_arg[i] = '\0';
  2856. smartlist_free(arg_chars);
  2857. return formatted_arg;
  2858. }
  2859. /** Format a command line for use on Windows, which takes the command as a
  2860. * string rather than string array. Follows the rules from "Parsing C++
  2861. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  2862. * Python subprocess module. Returns a newly allocated string */
  2863. char *
  2864. tor_join_win_cmdline(const char *argv[])
  2865. {
  2866. smartlist_t *argv_list;
  2867. char *joined_argv;
  2868. int i;
  2869. /* Format each argument and put the result in a smartlist */
  2870. argv_list = smartlist_new();
  2871. for (i=0; argv[i] != NULL; i++) {
  2872. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  2873. }
  2874. /* Join the arguments with whitespace */
  2875. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  2876. /* Free the newly allocated arguments, and the smartlist */
  2877. SMARTLIST_FOREACH(argv_list, char *, arg,
  2878. {
  2879. tor_free(arg);
  2880. });
  2881. smartlist_free(argv_list);
  2882. return joined_argv;
  2883. }
  2884. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  2885. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  2886. * safe.
  2887. *
  2888. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE bytes available.
  2889. *
  2890. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  2891. * with spaces. Note that there is no trailing \0. CHILD_STATE indicates where
  2892. * in the processs of starting the child process did the failure occur (see
  2893. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  2894. * errno when the failure occurred.
  2895. */
  2896. void
  2897. format_helper_exit_status(unsigned char child_state, int saved_errno,
  2898. char *hex_errno)
  2899. {
  2900. unsigned int unsigned_errno;
  2901. char *cur;
  2902. size_t i;
  2903. /* Fill hex_errno with spaces, and a trailing newline (memset may
  2904. not be signal handler safe, so we can't use it) */
  2905. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  2906. hex_errno[i] = ' ';
  2907. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  2908. /* Convert errno to be unsigned for hex conversion */
  2909. if (saved_errno < 0) {
  2910. unsigned_errno = (unsigned int) -saved_errno;
  2911. } else {
  2912. unsigned_errno = (unsigned int) saved_errno;
  2913. }
  2914. /* Convert errno to hex (start before \n) */
  2915. cur = hex_errno + HEX_ERRNO_SIZE - 2;
  2916. /* Check for overflow on first iteration of the loop */
  2917. if (cur < hex_errno)
  2918. return;
  2919. do {
  2920. *cur-- = "0123456789ABCDEF"[unsigned_errno % 16];
  2921. unsigned_errno /= 16;
  2922. } while (unsigned_errno != 0 && cur >= hex_errno);
  2923. /* Prepend the minus sign if errno was negative */
  2924. if (saved_errno < 0 && cur >= hex_errno)
  2925. *cur-- = '-';
  2926. /* Leave a gap */
  2927. if (cur >= hex_errno)
  2928. *cur-- = '/';
  2929. /* Check for overflow on first iteration of the loop */
  2930. if (cur < hex_errno)
  2931. return;
  2932. /* Convert child_state to hex */
  2933. do {
  2934. *cur-- = "0123456789ABCDEF"[child_state % 16];
  2935. child_state /= 16;
  2936. } while (child_state != 0 && cur >= hex_errno);
  2937. }
  2938. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  2939. #define DEFAULT_MAX_FD 256
  2940. /** Terminate the process of <b>process_handle</b>.
  2941. * Code borrowed from Python's os.kill. */
  2942. int
  2943. tor_terminate_process(process_handle_t *process_handle)
  2944. {
  2945. #ifdef _WIN32
  2946. if (tor_get_exit_code(process_handle, 0, NULL) == PROCESS_EXIT_RUNNING) {
  2947. HANDLE handle;
  2948. /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
  2949. attempt to open and terminate the process. */
  2950. handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE,
  2951. process_handle->pid.dwProcessId);
  2952. if (!handle)
  2953. return -1;
  2954. if (!TerminateProcess(handle, 0))
  2955. return -1;
  2956. else
  2957. return 0;
  2958. }
  2959. #else /* Unix */
  2960. return kill(process_handle->pid, SIGTERM);
  2961. #endif
  2962. return -1;
  2963. }
  2964. /** Return the Process ID of <b>process_handle</b>. */
  2965. int
  2966. tor_process_get_pid(process_handle_t *process_handle)
  2967. {
  2968. #ifdef _WIN32
  2969. return (int) process_handle->pid.dwProcessId;
  2970. #else
  2971. return (int) process_handle->pid;
  2972. #endif
  2973. }
  2974. #ifdef _WIN32
  2975. HANDLE
  2976. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  2977. {
  2978. return process_handle->stdout_pipe;
  2979. }
  2980. #else
  2981. FILE *
  2982. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  2983. {
  2984. return process_handle->stdout_handle;
  2985. }
  2986. #endif
  2987. static process_handle_t *
  2988. process_handle_new(void)
  2989. {
  2990. process_handle_t *out = tor_malloc_zero(sizeof(process_handle_t));
  2991. #ifndef _WIN32
  2992. out->stdout_pipe = -1;
  2993. out->stderr_pipe = -1;
  2994. #endif
  2995. return out;
  2996. }
  2997. /*DOCDOC*/
  2998. #define CHILD_STATE_INIT 0
  2999. #define CHILD_STATE_PIPE 1
  3000. #define CHILD_STATE_MAXFD 2
  3001. #define CHILD_STATE_FORK 3
  3002. #define CHILD_STATE_DUPOUT 4
  3003. #define CHILD_STATE_DUPERR 5
  3004. #define CHILD_STATE_REDIRECT 6
  3005. #define CHILD_STATE_CLOSEFD 7
  3006. #define CHILD_STATE_EXEC 8
  3007. #define CHILD_STATE_FAILEXEC 9
  3008. /** Start a program in the background. If <b>filename</b> contains a '/', then
  3009. * it will be treated as an absolute or relative path. Otherwise, on
  3010. * non-Windows systems, the system path will be searched for <b>filename</b>.
  3011. * On Windows, only the current directory will be searched. Here, to search the
  3012. * system path (as well as the application directory, current working
  3013. * directory, and system directories), set filename to NULL.
  3014. *
  3015. * The strings in <b>argv</b> will be passed as the command line arguments of
  3016. * the child program (following convention, argv[0] should normally be the
  3017. * filename of the executable, and this must be the case if <b>filename</b> is
  3018. * NULL). The last element of argv must be NULL. A handle to the child process
  3019. * will be returned in process_handle (which must be non-NULL). Read
  3020. * process_handle.status to find out if the process was successfully launched.
  3021. * For convenience, process_handle.status is returned by this function.
  3022. *
  3023. * Some parts of this code are based on the POSIX subprocess module from
  3024. * Python, and example code from
  3025. * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
  3026. */
  3027. int
  3028. tor_spawn_background(const char *const filename, const char **argv,
  3029. #ifdef _WIN32
  3030. LPVOID envp,
  3031. #else
  3032. const char **envp,
  3033. #endif
  3034. process_handle_t **process_handle_out)
  3035. {
  3036. #ifdef _WIN32
  3037. HANDLE stdout_pipe_read = NULL;
  3038. HANDLE stdout_pipe_write = NULL;
  3039. HANDLE stderr_pipe_read = NULL;
  3040. HANDLE stderr_pipe_write = NULL;
  3041. process_handle_t *process_handle;
  3042. int status;
  3043. STARTUPINFO siStartInfo;
  3044. BOOL retval = FALSE;
  3045. SECURITY_ATTRIBUTES saAttr;
  3046. char *joined_argv;
  3047. (void)envp; // Unused on Windows
  3048. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  3049. saAttr.bInheritHandle = TRUE;
  3050. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3051. saAttr.lpSecurityDescriptor = NULL;
  3052. /* Assume failure to start process */
  3053. status = PROCESS_STATUS_ERROR;
  3054. /* Set up pipe for stdout */
  3055. if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, &saAttr, 0)) {
  3056. log_warn(LD_GENERAL,
  3057. "Failed to create pipe for stdout communication with child process: %s",
  3058. format_win32_error(GetLastError()));
  3059. return status;
  3060. }
  3061. if (!SetHandleInformation(stdout_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3062. log_warn(LD_GENERAL,
  3063. "Failed to configure pipe for stdout communication with child "
  3064. "process: %s", format_win32_error(GetLastError()));
  3065. return status;
  3066. }
  3067. /* Set up pipe for stderr */
  3068. if (!CreatePipe(&stderr_pipe_read, &stderr_pipe_write, &saAttr, 0)) {
  3069. log_warn(LD_GENERAL,
  3070. "Failed to create pipe for stderr communication with child process: %s",
  3071. format_win32_error(GetLastError()));
  3072. return status;
  3073. }
  3074. if (!SetHandleInformation(stderr_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3075. log_warn(LD_GENERAL,
  3076. "Failed to configure pipe for stderr communication with child "
  3077. "process: %s", format_win32_error(GetLastError()));
  3078. return status;
  3079. }
  3080. /* Create the child process */
  3081. /* Windows expects argv to be a whitespace delimited string, so join argv up
  3082. */
  3083. joined_argv = tor_join_win_cmdline(argv);
  3084. process_handle = process_handle_new();
  3085. process_handle->status = status;
  3086. ZeroMemory(&(process_handle->pid), sizeof(PROCESS_INFORMATION));
  3087. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  3088. siStartInfo.cb = sizeof(STARTUPINFO);
  3089. siStartInfo.hStdError = stderr_pipe_write;
  3090. siStartInfo.hStdOutput = stdout_pipe_write;
  3091. siStartInfo.hStdInput = NULL;
  3092. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  3093. /* Create the child process */
  3094. retval = CreateProcess(filename, // module name
  3095. joined_argv, // command line
  3096. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3097. NULL, // process security attributes
  3098. NULL, // primary thread security attributes
  3099. TRUE, // handles are inherited
  3100. /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
  3101. * work?) */
  3102. 0, // creation flags
  3103. envp, // use parent's environment
  3104. NULL, // use parent's current directory
  3105. &siStartInfo, // STARTUPINFO pointer
  3106. &(process_handle->pid)); // receives PROCESS_INFORMATION
  3107. tor_free(joined_argv);
  3108. if (!retval) {
  3109. log_warn(LD_GENERAL,
  3110. "Failed to create child process %s: %s", filename?filename:argv[0],
  3111. format_win32_error(GetLastError()));
  3112. tor_free(process_handle);
  3113. } else {
  3114. /* TODO: Close hProcess and hThread in process_handle->pid? */
  3115. process_handle->stdout_pipe = stdout_pipe_read;
  3116. process_handle->stderr_pipe = stderr_pipe_read;
  3117. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3118. }
  3119. /* TODO: Close pipes on exit */
  3120. *process_handle_out = process_handle;
  3121. return status;
  3122. #else // _WIN32
  3123. pid_t pid;
  3124. int stdout_pipe[2];
  3125. int stderr_pipe[2];
  3126. int fd, retval;
  3127. ssize_t nbytes;
  3128. process_handle_t *process_handle;
  3129. int status;
  3130. const char *error_message = SPAWN_ERROR_MESSAGE;
  3131. size_t error_message_length;
  3132. /* Represents where in the process of spawning the program is;
  3133. this is used for printing out the error message */
  3134. unsigned char child_state = CHILD_STATE_INIT;
  3135. char hex_errno[HEX_ERRNO_SIZE];
  3136. static int max_fd = -1;
  3137. status = PROCESS_STATUS_ERROR;
  3138. /* We do the strlen here because strlen() is not signal handler safe,
  3139. and we are not allowed to use unsafe functions between fork and exec */
  3140. error_message_length = strlen(error_message);
  3141. child_state = CHILD_STATE_PIPE;
  3142. /* Set up pipe for redirecting stdout and stderr of child */
  3143. retval = pipe(stdout_pipe);
  3144. if (-1 == retval) {
  3145. log_warn(LD_GENERAL,
  3146. "Failed to set up pipe for stdout communication with child process: %s",
  3147. strerror(errno));
  3148. return status;
  3149. }
  3150. retval = pipe(stderr_pipe);
  3151. if (-1 == retval) {
  3152. log_warn(LD_GENERAL,
  3153. "Failed to set up pipe for stderr communication with child process: %s",
  3154. strerror(errno));
  3155. return status;
  3156. }
  3157. child_state = CHILD_STATE_MAXFD;
  3158. #ifdef _SC_OPEN_MAX
  3159. if (-1 != max_fd) {
  3160. max_fd = (int) sysconf(_SC_OPEN_MAX);
  3161. if (max_fd == -1)
  3162. max_fd = DEFAULT_MAX_FD;
  3163. log_warn(LD_GENERAL,
  3164. "Cannot find maximum file descriptor, assuming %d", max_fd);
  3165. }
  3166. #else
  3167. max_fd = DEFAULT_MAX_FD;
  3168. #endif
  3169. child_state = CHILD_STATE_FORK;
  3170. pid = fork();
  3171. if (0 == pid) {
  3172. /* In child */
  3173. child_state = CHILD_STATE_DUPOUT;
  3174. /* Link child stdout to the write end of the pipe */
  3175. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  3176. if (-1 == retval)
  3177. goto error;
  3178. child_state = CHILD_STATE_DUPERR;
  3179. /* Link child stderr to the write end of the pipe */
  3180. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  3181. if (-1 == retval)
  3182. goto error;
  3183. child_state = CHILD_STATE_REDIRECT;
  3184. /* Link stdin to /dev/null */
  3185. fd = open("/dev/null", O_RDONLY); /* NOT cloexec, obviously. */
  3186. if (fd != -1)
  3187. dup2(fd, STDIN_FILENO);
  3188. else
  3189. goto error;
  3190. child_state = CHILD_STATE_CLOSEFD;
  3191. close(stderr_pipe[0]);
  3192. close(stderr_pipe[1]);
  3193. close(stdout_pipe[0]);
  3194. close(stdout_pipe[1]);
  3195. close(fd);
  3196. /* Close all other fds, including the read end of the pipe */
  3197. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  3198. * this needless. */
  3199. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  3200. close(fd);
  3201. }
  3202. child_state = CHILD_STATE_EXEC;
  3203. /* Call the requested program. We need the cast because
  3204. execvp doesn't define argv as const, even though it
  3205. does not modify the arguments */
  3206. if (envp)
  3207. execve(filename, (char *const *) argv, (char*const*)envp);
  3208. else
  3209. execvp(filename, (char *const *) argv);
  3210. /* If we got here, the exec or open(/dev/null) failed */
  3211. child_state = CHILD_STATE_FAILEXEC;
  3212. error:
  3213. /* XXX: are we leaking fds from the pipe? */
  3214. format_helper_exit_status(child_state, errno, hex_errno);
  3215. /* Write the error message. GCC requires that we check the return
  3216. value, but there is nothing we can do if it fails */
  3217. /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
  3218. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  3219. nbytes = write(STDOUT_FILENO, hex_errno, sizeof(hex_errno));
  3220. (void) nbytes;
  3221. _exit(255);
  3222. /* Never reached, but avoids compiler warning */
  3223. return status;
  3224. }
  3225. /* In parent */
  3226. if (-1 == pid) {
  3227. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  3228. close(stdout_pipe[0]);
  3229. close(stdout_pipe[1]);
  3230. close(stderr_pipe[0]);
  3231. close(stderr_pipe[1]);
  3232. return status;
  3233. }
  3234. process_handle = process_handle_new();
  3235. process_handle->status = status;
  3236. process_handle->pid = pid;
  3237. /* TODO: If the child process forked but failed to exec, waitpid it */
  3238. /* Return read end of the pipes to caller, and close write end */
  3239. process_handle->stdout_pipe = stdout_pipe[0];
  3240. retval = close(stdout_pipe[1]);
  3241. if (-1 == retval) {
  3242. log_warn(LD_GENERAL,
  3243. "Failed to close write end of stdout pipe in parent process: %s",
  3244. strerror(errno));
  3245. }
  3246. process_handle->stderr_pipe = stderr_pipe[0];
  3247. retval = close(stderr_pipe[1]);
  3248. if (-1 == retval) {
  3249. log_warn(LD_GENERAL,
  3250. "Failed to close write end of stderr pipe in parent process: %s",
  3251. strerror(errno));
  3252. }
  3253. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3254. /* Set stdout/stderr pipes to be non-blocking */
  3255. fcntl(process_handle->stdout_pipe, F_SETFL, O_NONBLOCK);
  3256. fcntl(process_handle->stderr_pipe, F_SETFL, O_NONBLOCK);
  3257. /* Open the buffered IO streams */
  3258. process_handle->stdout_handle = fdopen(process_handle->stdout_pipe, "r");
  3259. process_handle->stderr_handle = fdopen(process_handle->stderr_pipe, "r");
  3260. *process_handle_out = process_handle;
  3261. return process_handle->status;
  3262. #endif // _WIN32
  3263. }
  3264. /** Destroy all resources allocated by the process handle in
  3265. * <b>process_handle</b>.
  3266. * If <b>also_terminate_process</b> is true, also terminate the
  3267. * process of the process handle. */
  3268. void
  3269. tor_process_handle_destroy(process_handle_t *process_handle,
  3270. int also_terminate_process)
  3271. {
  3272. if (!process_handle)
  3273. return;
  3274. if (also_terminate_process) {
  3275. if (tor_terminate_process(process_handle) < 0) {
  3276. log_notice(LD_GENERAL, "Failed to terminate process with PID '%d'",
  3277. tor_process_get_pid(process_handle));
  3278. } else {
  3279. log_info(LD_GENERAL, "Terminated process with PID '%d'",
  3280. tor_process_get_pid(process_handle));
  3281. }
  3282. }
  3283. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  3284. #ifdef _WIN32
  3285. if (process_handle->stdout_pipe)
  3286. CloseHandle(process_handle->stdout_pipe);
  3287. if (process_handle->stderr_pipe)
  3288. CloseHandle(process_handle->stderr_pipe);
  3289. #else
  3290. if (process_handle->stdout_handle)
  3291. fclose(process_handle->stdout_handle);
  3292. if (process_handle->stderr_handle)
  3293. fclose(process_handle->stderr_handle);
  3294. #endif
  3295. memset(process_handle, 0x0f, sizeof(process_handle_t));
  3296. tor_free(process_handle);
  3297. }
  3298. /** Get the exit code of a process specified by <b>process_handle</b> and store
  3299. * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
  3300. * to true, the call will block until the process has exited. Otherwise if
  3301. * the process is still running, the function will return
  3302. * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
  3303. * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
  3304. * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
  3305. * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
  3306. * probably not work in Tor, because waitpid() is called in main.c to reap any
  3307. * terminated child processes.*/
  3308. int
  3309. tor_get_exit_code(const process_handle_t *process_handle,
  3310. int block, int *exit_code)
  3311. {
  3312. #ifdef _WIN32
  3313. DWORD retval;
  3314. BOOL success;
  3315. if (block) {
  3316. /* Wait for the process to exit */
  3317. retval = WaitForSingleObject(process_handle->pid.hProcess, INFINITE);
  3318. if (retval != WAIT_OBJECT_0) {
  3319. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3320. (int)retval, format_win32_error(GetLastError()));
  3321. return PROCESS_EXIT_ERROR;
  3322. }
  3323. } else {
  3324. retval = WaitForSingleObject(process_handle->pid.hProcess, 0);
  3325. if (WAIT_TIMEOUT == retval) {
  3326. /* Process has not exited */
  3327. return PROCESS_EXIT_RUNNING;
  3328. } else if (retval != WAIT_OBJECT_0) {
  3329. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3330. (int)retval, format_win32_error(GetLastError()));
  3331. return PROCESS_EXIT_ERROR;
  3332. }
  3333. }
  3334. if (exit_code != NULL) {
  3335. success = GetExitCodeProcess(process_handle->pid.hProcess,
  3336. (PDWORD)exit_code);
  3337. if (!success) {
  3338. log_warn(LD_GENERAL, "GetExitCodeProcess() failed: %s",
  3339. format_win32_error(GetLastError()));
  3340. return PROCESS_EXIT_ERROR;
  3341. }
  3342. }
  3343. #else
  3344. int stat_loc;
  3345. int retval;
  3346. retval = waitpid(process_handle->pid, &stat_loc, block?0:WNOHANG);
  3347. if (!block && 0 == retval) {
  3348. /* Process has not exited */
  3349. return PROCESS_EXIT_RUNNING;
  3350. } else if (retval != process_handle->pid) {
  3351. log_warn(LD_GENERAL, "waitpid() failed for PID %d: %s",
  3352. process_handle->pid, strerror(errno));
  3353. return PROCESS_EXIT_ERROR;
  3354. }
  3355. if (!WIFEXITED(stat_loc)) {
  3356. log_warn(LD_GENERAL, "Process %d did not exit normally",
  3357. process_handle->pid);
  3358. return PROCESS_EXIT_ERROR;
  3359. }
  3360. if (exit_code != NULL)
  3361. *exit_code = WEXITSTATUS(stat_loc);
  3362. #endif // _WIN32
  3363. return PROCESS_EXIT_EXITED;
  3364. }
  3365. /** Return non-zero iff getenv would consider <b>s1</b> and <b>s2</b>
  3366. * to have the same name as strings in a process's environment. */
  3367. int
  3368. environment_variable_names_equal(const char *s1, const char *s2)
  3369. {
  3370. size_t s1_name_len = strcspn(s1, "=");
  3371. size_t s2_name_len = strcspn(s2, "=");
  3372. return (s1_name_len == s2_name_len &&
  3373. tor_memeq(s1, s2, s1_name_len));
  3374. }
  3375. /** Free <b>env</b> (assuming it was produced by
  3376. * process_environment_make). */
  3377. void
  3378. process_environment_free(process_environment_t *env)
  3379. {
  3380. if (env == NULL) return;
  3381. /* As both an optimization hack to reduce consing on Unixoid systems
  3382. * and a nice way to ensure that some otherwise-Windows-specific
  3383. * code will always get tested before changes to it get merged, the
  3384. * strings which env->unixoid_environment_block points to are packed
  3385. * into env->windows_environment_block. */
  3386. tor_free(env->unixoid_environment_block);
  3387. tor_free(env->windows_environment_block);
  3388. tor_free(env);
  3389. }
  3390. /** Make a process_environment_t containing the environment variables
  3391. * specified in <b>env_vars</b> (as C strings of the form
  3392. * "NAME=VALUE"). */
  3393. process_environment_t *
  3394. process_environment_make(struct smartlist_t *env_vars)
  3395. {
  3396. process_environment_t *env = tor_malloc_zero(sizeof(process_environment_t));
  3397. size_t n_env_vars = smartlist_len(env_vars);
  3398. size_t i;
  3399. size_t total_env_length;
  3400. smartlist_t *env_vars_sorted;
  3401. tor_assert(n_env_vars + 1 != 0);
  3402. env->unixoid_environment_block = tor_calloc(n_env_vars + 1, sizeof(char *));
  3403. /* env->unixoid_environment_block is already NULL-terminated,
  3404. * because we assume that NULL == 0 (and check that during compilation). */
  3405. total_env_length = 1; /* terminating NUL of terminating empty string */
  3406. for (i = 0; i < n_env_vars; ++i) {
  3407. const char *s = smartlist_get(env_vars, i);
  3408. size_t slen = strlen(s);
  3409. tor_assert(slen + 1 != 0);
  3410. tor_assert(slen + 1 < SIZE_MAX - total_env_length);
  3411. total_env_length += slen + 1;
  3412. }
  3413. env->windows_environment_block = tor_malloc_zero(total_env_length);
  3414. /* env->windows_environment_block is already
  3415. * (NUL-terminated-empty-string)-terminated. */
  3416. /* Some versions of Windows supposedly require that environment
  3417. * blocks be sorted. Or maybe some Windows programs (or their
  3418. * runtime libraries) fail to look up strings in non-sorted
  3419. * environment blocks.
  3420. *
  3421. * Also, sorting strings makes it easy to find duplicate environment
  3422. * variables and environment-variable strings without an '=' on all
  3423. * OSes, and they can cause badness. Let's complain about those. */
  3424. env_vars_sorted = smartlist_new();
  3425. smartlist_add_all(env_vars_sorted, env_vars);
  3426. smartlist_sort_strings(env_vars_sorted);
  3427. /* Now copy the strings into the environment blocks. */
  3428. {
  3429. char *cp = env->windows_environment_block;
  3430. const char *prev_env_var = NULL;
  3431. for (i = 0; i < n_env_vars; ++i) {
  3432. const char *s = smartlist_get(env_vars_sorted, i);
  3433. size_t slen = strlen(s);
  3434. size_t s_name_len = strcspn(s, "=");
  3435. if (s_name_len == slen) {
  3436. log_warn(LD_GENERAL,
  3437. "Preparing an environment containing a variable "
  3438. "without a value: %s",
  3439. s);
  3440. }
  3441. if (prev_env_var != NULL &&
  3442. environment_variable_names_equal(s, prev_env_var)) {
  3443. log_warn(LD_GENERAL,
  3444. "Preparing an environment containing two variables "
  3445. "with the same name: %s and %s",
  3446. prev_env_var, s);
  3447. }
  3448. prev_env_var = s;
  3449. /* Actually copy the string into the environment. */
  3450. memcpy(cp, s, slen+1);
  3451. env->unixoid_environment_block[i] = cp;
  3452. cp += slen+1;
  3453. }
  3454. tor_assert(cp == env->windows_environment_block + total_env_length - 1);
  3455. }
  3456. return env;
  3457. }
  3458. /** Return a newly allocated smartlist containing every variable in
  3459. * this process's environment, as a NUL-terminated string of the form
  3460. * "NAME=VALUE". Note that on some/many/most/all OSes, the parent
  3461. * process can put strings not of that form in our environment;
  3462. * callers should try to not get crashed by that.
  3463. *
  3464. * The returned strings are statically allocated, and must be treated
  3465. * as read-only. */
  3466. struct smartlist_t *
  3467. get_current_process_environment_variables(void)
  3468. {
  3469. smartlist_t *sl = smartlist_new();
  3470. char **environ_tmp; /* Not const char ** ? Really? */
  3471. for (environ_tmp = environ; *environ_tmp; ++environ_tmp) {
  3472. smartlist_add(sl, (void *)(*environ_tmp));
  3473. }
  3474. return sl;
  3475. }
  3476. /** For each string s in <b>env_vars</b> such that
  3477. * environment_variable_names_equal(s, <b>new_var</b>), remove it; if
  3478. * <b>free_p</b> is non-zero, call <b>free_old</b>(s). If
  3479. * <b>new_var</b> contains '=', insert it into <b>env_vars</b>. */
  3480. void
  3481. set_environment_variable_in_smartlist(struct smartlist_t *env_vars,
  3482. const char *new_var,
  3483. void (*free_old)(void*),
  3484. int free_p)
  3485. {
  3486. SMARTLIST_FOREACH_BEGIN(env_vars, const char *, s) {
  3487. if (environment_variable_names_equal(s, new_var)) {
  3488. SMARTLIST_DEL_CURRENT(env_vars, s);
  3489. if (free_p) {
  3490. free_old((void *)s);
  3491. }
  3492. }
  3493. } SMARTLIST_FOREACH_END(s);
  3494. if (strchr(new_var, '=') != NULL) {
  3495. smartlist_add(env_vars, (void *)new_var);
  3496. }
  3497. }
  3498. #ifdef _WIN32
  3499. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3500. * <b>hProcess</b> is NULL, the function will return immediately if there is
  3501. * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
  3502. * to the process owning the <b>h</b>. In this case, the function will exit
  3503. * only once the process has exited, or <b>count</b> bytes are read. Returns
  3504. * the number of bytes read, or -1 on error. */
  3505. ssize_t
  3506. tor_read_all_handle(HANDLE h, char *buf, size_t count,
  3507. const process_handle_t *process)
  3508. {
  3509. size_t numread = 0;
  3510. BOOL retval;
  3511. DWORD byte_count;
  3512. BOOL process_exited = FALSE;
  3513. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  3514. return -1;
  3515. while (numread != count) {
  3516. /* Check if there is anything to read */
  3517. retval = PeekNamedPipe(h, NULL, 0, NULL, &byte_count, NULL);
  3518. if (!retval) {
  3519. log_warn(LD_GENERAL,
  3520. "Failed to peek from handle: %s",
  3521. format_win32_error(GetLastError()));
  3522. return -1;
  3523. } else if (0 == byte_count) {
  3524. /* Nothing available: process exited or it is busy */
  3525. /* Exit if we don't know whether the process is running */
  3526. if (NULL == process)
  3527. break;
  3528. /* The process exited and there's nothing left to read from it */
  3529. if (process_exited)
  3530. break;
  3531. /* If process is not running, check for output one more time in case
  3532. it wrote something after the peek was performed. Otherwise keep on
  3533. waiting for output */
  3534. tor_assert(process != NULL);
  3535. byte_count = WaitForSingleObject(process->pid.hProcess, 0);
  3536. if (WAIT_TIMEOUT != byte_count)
  3537. process_exited = TRUE;
  3538. continue;
  3539. }
  3540. /* There is data to read; read it */
  3541. retval = ReadFile(h, buf+numread, count-numread, &byte_count, NULL);
  3542. tor_assert(byte_count + numread <= count);
  3543. if (!retval) {
  3544. log_warn(LD_GENERAL, "Failed to read from handle: %s",
  3545. format_win32_error(GetLastError()));
  3546. return -1;
  3547. } else if (0 == byte_count) {
  3548. /* End of file */
  3549. break;
  3550. }
  3551. numread += byte_count;
  3552. }
  3553. return (ssize_t)numread;
  3554. }
  3555. #else
  3556. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3557. * <b>process</b> is NULL, the function will return immediately if there is
  3558. * nothing more to read. Otherwise data will be read until end of file, or
  3559. * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
  3560. * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
  3561. * file has been reached. */
  3562. ssize_t
  3563. tor_read_all_handle(FILE *h, char *buf, size_t count,
  3564. const process_handle_t *process,
  3565. int *eof)
  3566. {
  3567. size_t numread = 0;
  3568. char *retval;
  3569. if (eof)
  3570. *eof = 0;
  3571. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  3572. return -1;
  3573. while (numread != count) {
  3574. /* Use fgets because that is what we use in log_from_pipe() */
  3575. retval = fgets(buf+numread, (int)(count-numread), h);
  3576. if (NULL == retval) {
  3577. if (feof(h)) {
  3578. log_debug(LD_GENERAL, "fgets() reached end of file");
  3579. if (eof)
  3580. *eof = 1;
  3581. break;
  3582. } else {
  3583. if (EAGAIN == errno) {
  3584. if (process)
  3585. continue;
  3586. else
  3587. break;
  3588. } else {
  3589. log_warn(LD_GENERAL, "fgets() from handle failed: %s",
  3590. strerror(errno));
  3591. return -1;
  3592. }
  3593. }
  3594. }
  3595. tor_assert(retval != NULL);
  3596. tor_assert(strlen(retval) + numread <= count);
  3597. numread += strlen(retval);
  3598. }
  3599. log_debug(LD_GENERAL, "fgets() read %d bytes from handle", (int)numread);
  3600. return (ssize_t)numread;
  3601. }
  3602. #endif
  3603. /** Read from stdout of a process until the process exits. */
  3604. ssize_t
  3605. tor_read_all_from_process_stdout(const process_handle_t *process_handle,
  3606. char *buf, size_t count)
  3607. {
  3608. #ifdef _WIN32
  3609. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  3610. process_handle);
  3611. #else
  3612. return tor_read_all_handle(process_handle->stdout_handle, buf, count,
  3613. process_handle, NULL);
  3614. #endif
  3615. }
  3616. /** Read from stdout of a process until the process exits. */
  3617. ssize_t
  3618. tor_read_all_from_process_stderr(const process_handle_t *process_handle,
  3619. char *buf, size_t count)
  3620. {
  3621. #ifdef _WIN32
  3622. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  3623. process_handle);
  3624. #else
  3625. return tor_read_all_handle(process_handle->stderr_handle, buf, count,
  3626. process_handle, NULL);
  3627. #endif
  3628. }
  3629. /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
  3630. * modified. The resulting smartlist will consist of pointers to buf, so there
  3631. * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
  3632. * string. <b>len</b> should be set to the length of the buffer excluding the
  3633. * NUL. Non-printable characters (including NUL) will be replaced with "." */
  3634. int
  3635. tor_split_lines(smartlist_t *sl, char *buf, int len)
  3636. {
  3637. /* Index in buf of the start of the current line */
  3638. int start = 0;
  3639. /* Index in buf of the current character being processed */
  3640. int cur = 0;
  3641. /* Are we currently in a line */
  3642. char in_line = 0;
  3643. /* Loop over string */
  3644. while (cur < len) {
  3645. /* Loop until end of line or end of string */
  3646. for (; cur < len; cur++) {
  3647. if (in_line) {
  3648. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  3649. /* End of line */
  3650. buf[cur] = '\0';
  3651. /* Point cur to the next line */
  3652. cur++;
  3653. /* Line starts at start and ends with a nul */
  3654. break;
  3655. } else {
  3656. if (!TOR_ISPRINT(buf[cur]))
  3657. buf[cur] = '.';
  3658. }
  3659. } else {
  3660. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  3661. /* Skip leading vertical space */
  3662. ;
  3663. } else {
  3664. in_line = 1;
  3665. start = cur;
  3666. if (!TOR_ISPRINT(buf[cur]))
  3667. buf[cur] = '.';
  3668. }
  3669. }
  3670. }
  3671. /* We are at the end of the line or end of string. If in_line is true there
  3672. * is a line which starts at buf+start and ends at a NUL. cur points to
  3673. * the character after the NUL. */
  3674. if (in_line)
  3675. smartlist_add(sl, (void *)(buf+start));
  3676. in_line = 0;
  3677. }
  3678. return smartlist_len(sl);
  3679. }
  3680. #ifdef _WIN32
  3681. /** Read from stream, and send lines to log at the specified log level.
  3682. * Returns -1 if there is a error reading, and 0 otherwise.
  3683. * If the generated stream is flushed more often than on new lines, or
  3684. * a read exceeds 256 bytes, lines will be truncated. This should be fixed,
  3685. * along with the corresponding problem on *nix (see bug #2045).
  3686. */
  3687. static int
  3688. log_from_handle(HANDLE *pipe, int severity)
  3689. {
  3690. char buf[256];
  3691. int pos;
  3692. smartlist_t *lines;
  3693. pos = tor_read_all_handle(pipe, buf, sizeof(buf) - 1, NULL);
  3694. if (pos < 0) {
  3695. /* Error */
  3696. log_warn(LD_GENERAL, "Failed to read data from subprocess");
  3697. return -1;
  3698. }
  3699. if (0 == pos) {
  3700. /* There's nothing to read (process is busy or has exited) */
  3701. log_debug(LD_GENERAL, "Subprocess had nothing to say");
  3702. return 0;
  3703. }
  3704. /* End with a null even if there isn't a \r\n at the end */
  3705. /* TODO: What if this is a partial line? */
  3706. buf[pos] = '\0';
  3707. log_debug(LD_GENERAL, "Subprocess had %d bytes to say", pos);
  3708. /* Split up the buffer */
  3709. lines = smartlist_new();
  3710. tor_split_lines(lines, buf, pos);
  3711. /* Log each line */
  3712. SMARTLIST_FOREACH(lines, char *, line,
  3713. {
  3714. log_fn(severity, LD_GENERAL, "Port forwarding helper says: %s", line);
  3715. });
  3716. smartlist_free(lines);
  3717. return 0;
  3718. }
  3719. #else
  3720. /** Read from stream, and send lines to log at the specified log level.
  3721. * Returns 1 if stream is closed normally, -1 if there is a error reading, and
  3722. * 0 otherwise. Handles lines from tor-fw-helper and
  3723. * tor_spawn_background() specially.
  3724. */
  3725. static int
  3726. log_from_pipe(FILE *stream, int severity, const char *executable,
  3727. int *child_status)
  3728. {
  3729. char buf[256];
  3730. enum stream_status r;
  3731. for (;;) {
  3732. r = get_string_from_pipe(stream, buf, sizeof(buf) - 1);
  3733. if (r == IO_STREAM_CLOSED) {
  3734. return 1;
  3735. } else if (r == IO_STREAM_EAGAIN) {
  3736. return 0;
  3737. } else if (r == IO_STREAM_TERM) {
  3738. return -1;
  3739. }
  3740. tor_assert(r == IO_STREAM_OKAY);
  3741. /* Check if buf starts with SPAWN_ERROR_MESSAGE */
  3742. if (strcmpstart(buf, SPAWN_ERROR_MESSAGE) == 0) {
  3743. /* Parse error message */
  3744. int retval, child_state, saved_errno;
  3745. retval = tor_sscanf(buf, SPAWN_ERROR_MESSAGE "%x/%x",
  3746. &child_state, &saved_errno);
  3747. if (retval == 2) {
  3748. log_warn(LD_GENERAL,
  3749. "Failed to start child process \"%s\" in state %d: %s",
  3750. executable, child_state, strerror(saved_errno));
  3751. if (child_status)
  3752. *child_status = 1;
  3753. } else {
  3754. /* Failed to parse message from child process, log it as a
  3755. warning */
  3756. log_warn(LD_GENERAL,
  3757. "Unexpected message from port forwarding helper \"%s\": %s",
  3758. executable, buf);
  3759. }
  3760. } else {
  3761. log_fn(severity, LD_GENERAL, "Port forwarding helper says: %s", buf);
  3762. }
  3763. }
  3764. /* We should never get here */
  3765. return -1;
  3766. }
  3767. #endif
  3768. /** Reads from <b>stream</b> and stores input in <b>buf_out</b> making
  3769. * sure it's below <b>count</b> bytes.
  3770. * If the string has a trailing newline, we strip it off.
  3771. *
  3772. * This function is specifically created to handle input from managed
  3773. * proxies, according to the pluggable transports spec. Make sure it
  3774. * fits your needs before using it.
  3775. *
  3776. * Returns:
  3777. * IO_STREAM_CLOSED: If the stream is closed.
  3778. * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
  3779. * later.
  3780. * IO_STREAM_TERM: If something is wrong with the stream.
  3781. * IO_STREAM_OKAY: If everything went okay and we got a string
  3782. * in <b>buf_out</b>. */
  3783. enum stream_status
  3784. get_string_from_pipe(FILE *stream, char *buf_out, size_t count)
  3785. {
  3786. char *retval;
  3787. size_t len;
  3788. tor_assert(count <= INT_MAX);
  3789. retval = fgets(buf_out, (int)count, stream);
  3790. if (!retval) {
  3791. if (feof(stream)) {
  3792. /* Program has closed stream (probably it exited) */
  3793. /* TODO: check error */
  3794. return IO_STREAM_CLOSED;
  3795. } else {
  3796. if (EAGAIN == errno) {
  3797. /* Nothing more to read, try again next time */
  3798. return IO_STREAM_EAGAIN;
  3799. } else {
  3800. /* There was a problem, abandon this child process */
  3801. return IO_STREAM_TERM;
  3802. }
  3803. }
  3804. } else {
  3805. len = strlen(buf_out);
  3806. tor_assert(len>0);
  3807. if (buf_out[len - 1] == '\n') {
  3808. /* Remove the trailing newline */
  3809. buf_out[len - 1] = '\0';
  3810. } else {
  3811. /* No newline; check whether we overflowed the buffer */
  3812. if (!feof(stream))
  3813. log_info(LD_GENERAL,
  3814. "Line from stream was truncated: %s", buf_out);
  3815. /* TODO: What to do with this error? */
  3816. }
  3817. return IO_STREAM_OKAY;
  3818. }
  3819. /* We should never get here */
  3820. return IO_STREAM_TERM;
  3821. }
  3822. void
  3823. tor_check_port_forwarding(const char *filename, int dir_port, int or_port,
  3824. time_t now)
  3825. {
  3826. /* When fw-helper succeeds, how long do we wait until running it again */
  3827. #define TIME_TO_EXEC_FWHELPER_SUCCESS 300
  3828. /* When fw-helper failed to start, how long do we wait until running it again
  3829. */
  3830. #define TIME_TO_EXEC_FWHELPER_FAIL 60
  3831. /* Static variables are initialized to zero, so child_handle.status=0
  3832. * which corresponds to it not running on startup */
  3833. static process_handle_t *child_handle=NULL;
  3834. static time_t time_to_run_helper = 0;
  3835. int stdout_status, stderr_status, retval;
  3836. const char *argv[10];
  3837. char s_dirport[6], s_orport[6];
  3838. tor_assert(filename);
  3839. /* Set up command line for tor-fw-helper */
  3840. snprintf(s_dirport, sizeof s_dirport, "%d", dir_port);
  3841. snprintf(s_orport, sizeof s_orport, "%d", or_port);
  3842. /* TODO: Allow different internal and external ports */
  3843. argv[0] = filename;
  3844. argv[1] = "--internal-or-port";
  3845. argv[2] = s_orport;
  3846. argv[3] = "--external-or-port";
  3847. argv[4] = s_orport;
  3848. argv[5] = "--internal-dir-port";
  3849. argv[6] = s_dirport;
  3850. argv[7] = "--external-dir-port";
  3851. argv[8] = s_dirport;
  3852. argv[9] = NULL;
  3853. /* Start the child, if it is not already running */
  3854. if ((!child_handle || child_handle->status != PROCESS_STATUS_RUNNING) &&
  3855. time_to_run_helper < now) {
  3856. int status;
  3857. /* Assume tor-fw-helper will succeed, start it later*/
  3858. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_SUCCESS;
  3859. if (child_handle) {
  3860. tor_process_handle_destroy(child_handle, 1);
  3861. child_handle = NULL;
  3862. }
  3863. #ifdef _WIN32
  3864. /* Passing NULL as lpApplicationName makes Windows search for the .exe */
  3865. status = tor_spawn_background(NULL, argv, NULL, &child_handle);
  3866. #else
  3867. status = tor_spawn_background(filename, argv, NULL, &child_handle);
  3868. #endif
  3869. if (PROCESS_STATUS_ERROR == status) {
  3870. log_warn(LD_GENERAL, "Failed to start port forwarding helper %s",
  3871. filename);
  3872. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_FAIL;
  3873. return;
  3874. }
  3875. log_info(LD_GENERAL,
  3876. "Started port forwarding helper (%s) with pid '%d'",
  3877. filename, tor_process_get_pid(child_handle));
  3878. }
  3879. /* If child is running, read from its stdout and stderr) */
  3880. if (child_handle && PROCESS_STATUS_RUNNING == child_handle->status) {
  3881. /* Read from stdout/stderr and log result */
  3882. retval = 0;
  3883. #ifdef _WIN32
  3884. stdout_status = log_from_handle(child_handle->stdout_pipe, LOG_INFO);
  3885. stderr_status = log_from_handle(child_handle->stderr_pipe, LOG_WARN);
  3886. /* If we got this far (on Windows), the process started */
  3887. retval = 0;
  3888. #else
  3889. stdout_status = log_from_pipe(child_handle->stdout_handle,
  3890. LOG_INFO, filename, &retval);
  3891. stderr_status = log_from_pipe(child_handle->stderr_handle,
  3892. LOG_WARN, filename, &retval);
  3893. #endif
  3894. if (retval) {
  3895. /* There was a problem in the child process */
  3896. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_FAIL;
  3897. }
  3898. /* Combine the two statuses in order of severity */
  3899. if (-1 == stdout_status || -1 == stderr_status)
  3900. /* There was a failure */
  3901. retval = -1;
  3902. #ifdef _WIN32
  3903. else if (!child_handle || tor_get_exit_code(child_handle, 0, NULL) !=
  3904. PROCESS_EXIT_RUNNING) {
  3905. /* process has exited or there was an error */
  3906. /* TODO: Do something with the process return value */
  3907. /* TODO: What if the process output something since
  3908. * between log_from_handle and tor_get_exit_code? */
  3909. retval = 1;
  3910. }
  3911. #else
  3912. else if (1 == stdout_status || 1 == stderr_status)
  3913. /* stdout or stderr was closed, the process probably
  3914. * exited. It will be reaped by waitpid() in main.c */
  3915. /* TODO: Do something with the process return value */
  3916. retval = 1;
  3917. #endif
  3918. else
  3919. /* Both are fine */
  3920. retval = 0;
  3921. /* If either pipe indicates a failure, act on it */
  3922. if (0 != retval) {
  3923. if (1 == retval) {
  3924. log_info(LD_GENERAL, "Port forwarding helper terminated");
  3925. child_handle->status = PROCESS_STATUS_NOTRUNNING;
  3926. } else {
  3927. log_warn(LD_GENERAL, "Failed to read from port forwarding helper");
  3928. child_handle->status = PROCESS_STATUS_ERROR;
  3929. }
  3930. /* TODO: The child might not actually be finished (maybe it failed or
  3931. closed stdout/stderr), so maybe we shouldn't start another? */
  3932. }
  3933. }
  3934. }