util.c 125 KB

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