util.c 144 KB

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