util.c 125 KB

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