util.c 125 KB

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