util.c 145 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241
  1. /* Copyright (c) 2003, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2014, 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 and
  1243. * parse_rfc1123_time. */
  1244. static const int days_per_month[] =
  1245. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  1246. /** Compute a time_t given a struct tm. The result is given in UTC, and
  1247. * does not account for leap seconds. Return 0 on success, -1 on failure.
  1248. */
  1249. int
  1250. tor_timegm(const struct tm *tm, time_t *time_out)
  1251. {
  1252. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  1253. * It's way more brute-force than fiddling with tzset().
  1254. */
  1255. time_t year, days, hours, minutes, seconds;
  1256. int i, invalid_year, dpm;
  1257. /* avoid int overflow on addition */
  1258. if (tm->tm_year < INT32_MAX-1900) {
  1259. year = tm->tm_year + 1900;
  1260. } else {
  1261. /* clamp year */
  1262. year = INT32_MAX;
  1263. }
  1264. invalid_year = (year < 1970 || tm->tm_year >= INT32_MAX-1900);
  1265. if (tm->tm_mon >= 0 && tm->tm_mon <= 11) {
  1266. dpm = days_per_month[tm->tm_mon];
  1267. if (tm->tm_mon == 1 && !invalid_year && IS_LEAPYEAR(tm->tm_year)) {
  1268. dpm = 29;
  1269. }
  1270. } else {
  1271. /* invalid month - default to 0 days per month */
  1272. dpm = 0;
  1273. }
  1274. if (invalid_year ||
  1275. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  1276. tm->tm_mday < 1 || tm->tm_mday > dpm ||
  1277. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1278. tm->tm_min < 0 || tm->tm_min > 59 ||
  1279. tm->tm_sec < 0 || tm->tm_sec > 60) {
  1280. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  1281. return -1;
  1282. }
  1283. days = 365 * (year-1970) + n_leapdays(1970,(int)year);
  1284. for (i = 0; i < tm->tm_mon; ++i)
  1285. days += days_per_month[i];
  1286. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  1287. ++days;
  1288. days += tm->tm_mday - 1;
  1289. hours = days*24 + tm->tm_hour;
  1290. minutes = hours*60 + tm->tm_min;
  1291. seconds = minutes*60 + tm->tm_sec;
  1292. *time_out = seconds;
  1293. return 0;
  1294. }
  1295. /* strftime is locale-specific, so we need to replace those parts */
  1296. /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
  1297. static const char *WEEKDAY_NAMES[] =
  1298. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1299. /** A c-locale array of 3-letter names of months, starting with Jan. */
  1300. static const char *MONTH_NAMES[] =
  1301. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  1302. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1303. /** Set <b>buf</b> to the RFC1123 encoding of the UTC value of <b>t</b>.
  1304. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  1305. *
  1306. * (RFC1123 format is "Fri, 29 Sep 2006 15:54:20 GMT". Note the "GMT"
  1307. * rather than "UTC".)
  1308. */
  1309. void
  1310. format_rfc1123_time(char *buf, time_t t)
  1311. {
  1312. struct tm tm;
  1313. tor_gmtime_r(&t, &tm);
  1314. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  1315. tor_assert(tm.tm_wday >= 0);
  1316. tor_assert(tm.tm_wday <= 6);
  1317. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  1318. tor_assert(tm.tm_mon >= 0);
  1319. tor_assert(tm.tm_mon <= 11);
  1320. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  1321. }
  1322. /** Parse the (a subset of) the RFC1123 encoding of some time (in UTC) from
  1323. * <b>buf</b>, and store the result in *<b>t</b>.
  1324. *
  1325. * Note that we only accept the subset generated by format_rfc1123_time above,
  1326. * not the full range of formats suggested by RFC 1123.
  1327. *
  1328. * Return 0 on success, -1 on failure.
  1329. */
  1330. int
  1331. parse_rfc1123_time(const char *buf, time_t *t)
  1332. {
  1333. struct tm tm;
  1334. char month[4];
  1335. char weekday[4];
  1336. int i, m, invalid_year;
  1337. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1338. unsigned dpm;
  1339. if (strlen(buf) != RFC1123_TIME_LEN)
  1340. return -1;
  1341. memset(&tm, 0, sizeof(tm));
  1342. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  1343. &tm_mday, month, &tm_year, &tm_hour,
  1344. &tm_min, &tm_sec) < 7) {
  1345. char *esc = esc_for_log(buf);
  1346. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1347. tor_free(esc);
  1348. return -1;
  1349. }
  1350. m = -1;
  1351. for (i = 0; i < 12; ++i) {
  1352. if (!strcmp(month, MONTH_NAMES[i])) {
  1353. m = i;
  1354. break;
  1355. }
  1356. }
  1357. if (m<0) {
  1358. char *esc = esc_for_log(buf);
  1359. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  1360. tor_free(esc);
  1361. return -1;
  1362. }
  1363. tm.tm_mon = m;
  1364. invalid_year = (tm_year >= INT32_MAX || tm_year < 1970);
  1365. tor_assert(m >= 0 && m <= 11);
  1366. dpm = days_per_month[m];
  1367. if (m == 1 && !invalid_year && IS_LEAPYEAR(tm_year)) {
  1368. dpm = 29;
  1369. }
  1370. if (invalid_year || tm_mday < 1 || tm_mday > dpm ||
  1371. tm_hour > 23 || tm_min > 59 || tm_sec > 60) {
  1372. char *esc = esc_for_log(buf);
  1373. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1374. tor_free(esc);
  1375. return -1;
  1376. }
  1377. tm.tm_mday = (int)tm_mday;
  1378. tm.tm_year = (int)tm_year;
  1379. tm.tm_hour = (int)tm_hour;
  1380. tm.tm_min = (int)tm_min;
  1381. tm.tm_sec = (int)tm_sec;
  1382. if (tm.tm_year < 1970) {
  1383. char *esc = esc_for_log(buf);
  1384. log_warn(LD_GENERAL,
  1385. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  1386. tor_free(esc);
  1387. return -1;
  1388. }
  1389. tm.tm_year -= 1900;
  1390. return tor_timegm(&tm, t);
  1391. }
  1392. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  1393. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1394. *
  1395. * (ISO8601 format is 2006-10-29 10:57:20)
  1396. */
  1397. void
  1398. format_local_iso_time(char *buf, time_t t)
  1399. {
  1400. struct tm tm;
  1401. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  1402. }
  1403. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  1404. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1405. */
  1406. void
  1407. format_iso_time(char *buf, time_t t)
  1408. {
  1409. struct tm tm;
  1410. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  1411. }
  1412. /** As format_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  1413. * embedding an internal space. */
  1414. void
  1415. format_iso_time_nospace(char *buf, time_t t)
  1416. {
  1417. format_iso_time(buf, t);
  1418. buf[10] = 'T';
  1419. }
  1420. /** As format_iso_time_nospace, but include microseconds in decimal
  1421. * fixed-point format. Requires that buf be at least ISO_TIME_USEC_LEN+1
  1422. * bytes long. */
  1423. void
  1424. format_iso_time_nospace_usec(char *buf, const struct timeval *tv)
  1425. {
  1426. tor_assert(tv);
  1427. format_iso_time_nospace(buf, (time_t)tv->tv_sec);
  1428. tor_snprintf(buf+ISO_TIME_LEN, 8, ".%06d", (int)tv->tv_usec);
  1429. }
  1430. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  1431. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  1432. * failure. Ignore extraneous stuff in <b>cp</b> separated by whitespace from
  1433. * the end of the time string. */
  1434. int
  1435. parse_iso_time(const char *cp, time_t *t)
  1436. {
  1437. struct tm st_tm;
  1438. unsigned int year=0, month=0, day=0, hour=0, minute=0, second=0;
  1439. if (tor_sscanf(cp, "%u-%2u-%2u %2u:%2u:%2u", &year, &month,
  1440. &day, &hour, &minute, &second) < 6) {
  1441. char *esc = esc_for_log(cp);
  1442. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  1443. tor_free(esc);
  1444. return -1;
  1445. }
  1446. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  1447. hour > 23 || minute > 59 || second > 60 || year >= INT32_MAX) {
  1448. char *esc = esc_for_log(cp);
  1449. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  1450. tor_free(esc);
  1451. return -1;
  1452. }
  1453. st_tm.tm_year = (int)year-1900;
  1454. st_tm.tm_mon = month-1;
  1455. st_tm.tm_mday = day;
  1456. st_tm.tm_hour = hour;
  1457. st_tm.tm_min = minute;
  1458. st_tm.tm_sec = second;
  1459. if (st_tm.tm_year < 70) {
  1460. char *esc = esc_for_log(cp);
  1461. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  1462. tor_free(esc);
  1463. return -1;
  1464. }
  1465. return tor_timegm(&st_tm, t);
  1466. }
  1467. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  1468. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  1469. int
  1470. parse_http_time(const char *date, struct tm *tm)
  1471. {
  1472. const char *cp;
  1473. char month[4];
  1474. char wkday[4];
  1475. int i;
  1476. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1477. tor_assert(tm);
  1478. memset(tm, 0, sizeof(*tm));
  1479. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  1480. if ((cp = strchr(date, ','))) {
  1481. ++cp;
  1482. if (*cp != ' ')
  1483. return -1;
  1484. ++cp;
  1485. if (tor_sscanf(cp, "%2u %3s %4u %2u:%2u:%2u GMT",
  1486. &tm_mday, month, &tm_year,
  1487. &tm_hour, &tm_min, &tm_sec) == 6) {
  1488. /* rfc1123-date */
  1489. tm_year -= 1900;
  1490. } else if (tor_sscanf(cp, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  1491. &tm_mday, month, &tm_year,
  1492. &tm_hour, &tm_min, &tm_sec) == 6) {
  1493. /* rfc850-date */
  1494. } else {
  1495. return -1;
  1496. }
  1497. } else {
  1498. /* No comma; possibly asctime() format. */
  1499. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  1500. wkday, month, &tm_mday,
  1501. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  1502. tm_year -= 1900;
  1503. } else {
  1504. return -1;
  1505. }
  1506. }
  1507. tm->tm_mday = (int)tm_mday;
  1508. tm->tm_year = (int)tm_year;
  1509. tm->tm_hour = (int)tm_hour;
  1510. tm->tm_min = (int)tm_min;
  1511. tm->tm_sec = (int)tm_sec;
  1512. month[3] = '\0';
  1513. /* Okay, now decode the month. */
  1514. /* set tm->tm_mon to dummy value so the check below fails. */
  1515. tm->tm_mon = -1;
  1516. for (i = 0; i < 12; ++i) {
  1517. if (!strcasecmp(MONTH_NAMES[i], month)) {
  1518. tm->tm_mon = i;
  1519. }
  1520. }
  1521. if (tm->tm_year < 0 ||
  1522. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  1523. tm->tm_mday < 1 || tm->tm_mday > 31 ||
  1524. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1525. tm->tm_min < 0 || tm->tm_min > 59 ||
  1526. tm->tm_sec < 0 || tm->tm_sec > 60)
  1527. return -1; /* Out of range, or bad month. */
  1528. return 0;
  1529. }
  1530. /** Given an <b>interval</b> in seconds, try to write it to the
  1531. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  1532. * Return 0 on success, -1 on failure.
  1533. */
  1534. int
  1535. format_time_interval(char *out, size_t out_len, long interval)
  1536. {
  1537. /* We only report seconds if there's no hours. */
  1538. long sec = 0, min = 0, hour = 0, day = 0;
  1539. /* -LONG_MIN is LONG_MAX + 1, which causes signed overflow */
  1540. if (interval < -LONG_MAX)
  1541. interval = LONG_MAX;
  1542. else if (interval < 0)
  1543. interval = -interval;
  1544. if (interval >= 86400) {
  1545. day = interval / 86400;
  1546. interval %= 86400;
  1547. }
  1548. if (interval >= 3600) {
  1549. hour = interval / 3600;
  1550. interval %= 3600;
  1551. }
  1552. if (interval >= 60) {
  1553. min = interval / 60;
  1554. interval %= 60;
  1555. }
  1556. sec = interval;
  1557. if (day) {
  1558. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  1559. day, hour, min);
  1560. } else if (hour) {
  1561. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  1562. } else if (min) {
  1563. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  1564. } else {
  1565. return tor_snprintf(out, out_len, "%ld seconds", sec);
  1566. }
  1567. }
  1568. /* =====
  1569. * Cached time
  1570. * ===== */
  1571. #ifndef TIME_IS_FAST
  1572. /** Cached estimate of the current time. Updated around once per second;
  1573. * may be a few seconds off if we are really busy. This is a hack to avoid
  1574. * calling time(NULL) (which not everybody has optimized) on critical paths.
  1575. */
  1576. static time_t cached_approx_time = 0;
  1577. /** Return a cached estimate of the current time from when
  1578. * update_approx_time() was last called. This is a hack to avoid calling
  1579. * time(NULL) on critical paths: please do not even think of calling it
  1580. * anywhere else. */
  1581. time_t
  1582. approx_time(void)
  1583. {
  1584. return cached_approx_time;
  1585. }
  1586. /** Update the cached estimate of the current time. This function SHOULD be
  1587. * called once per second, and MUST be called before the first call to
  1588. * get_approx_time. */
  1589. void
  1590. update_approx_time(time_t now)
  1591. {
  1592. cached_approx_time = now;
  1593. }
  1594. #endif
  1595. /* =====
  1596. * Rate limiting
  1597. * ===== */
  1598. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return the number
  1599. * of calls to rate_limit_is_ready (including this one!) since the last time
  1600. * rate_limit_is_ready returned nonzero. Otherwise return 0. */
  1601. static int
  1602. rate_limit_is_ready(ratelim_t *lim, time_t now)
  1603. {
  1604. if (lim->rate + lim->last_allowed <= now) {
  1605. int res = lim->n_calls_since_last_time + 1;
  1606. lim->last_allowed = now;
  1607. lim->n_calls_since_last_time = 0;
  1608. return res;
  1609. } else {
  1610. ++lim->n_calls_since_last_time;
  1611. return 0;
  1612. }
  1613. }
  1614. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return a newly
  1615. * allocated string indicating how many messages were suppressed, suitable to
  1616. * append to a log message. Otherwise return NULL. */
  1617. char *
  1618. rate_limit_log(ratelim_t *lim, time_t now)
  1619. {
  1620. int n;
  1621. if ((n = rate_limit_is_ready(lim, now))) {
  1622. if (n == 1) {
  1623. return tor_strdup("");
  1624. } else {
  1625. char *cp=NULL;
  1626. tor_asprintf(&cp,
  1627. " [%d similar message(s) suppressed in last %d seconds]",
  1628. n-1, lim->rate);
  1629. return cp;
  1630. }
  1631. } else {
  1632. return NULL;
  1633. }
  1634. }
  1635. /* =====
  1636. * File helpers
  1637. * ===== */
  1638. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1639. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1640. * was returned by open(). Return the number of bytes written, or -1
  1641. * on error. Only use if fd is a blocking fd. */
  1642. ssize_t
  1643. write_all(tor_socket_t fd, const char *buf, size_t count, int isSocket)
  1644. {
  1645. size_t written = 0;
  1646. ssize_t result;
  1647. tor_assert(count < SSIZE_MAX);
  1648. while (written != count) {
  1649. if (isSocket)
  1650. result = tor_socket_send(fd, buf+written, count-written, 0);
  1651. else
  1652. result = write((int)fd, buf+written, count-written);
  1653. if (result<0)
  1654. return -1;
  1655. written += result;
  1656. }
  1657. return (ssize_t)count;
  1658. }
  1659. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1660. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1661. * was returned by socket() or accept(), and 0 if fd was returned by
  1662. * open(). Return the number of bytes read, or -1 on error. Only use
  1663. * if fd is a blocking fd. */
  1664. ssize_t
  1665. read_all(tor_socket_t fd, char *buf, size_t count, int isSocket)
  1666. {
  1667. size_t numread = 0;
  1668. ssize_t result;
  1669. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  1670. return -1;
  1671. while (numread != count) {
  1672. if (isSocket)
  1673. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1674. else
  1675. result = read((int)fd, buf+numread, count-numread);
  1676. if (result<0)
  1677. return -1;
  1678. else if (result == 0)
  1679. break;
  1680. numread += result;
  1681. }
  1682. return (ssize_t)numread;
  1683. }
  1684. /*
  1685. * Filesystem operations.
  1686. */
  1687. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1688. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1689. * the root of a disk. */
  1690. static void
  1691. clean_name_for_stat(char *name)
  1692. {
  1693. #ifdef _WIN32
  1694. size_t len = strlen(name);
  1695. if (!len)
  1696. return;
  1697. if (name[len-1]=='\\' || name[len-1]=='/') {
  1698. if (len == 1 || (len==3 && name[1]==':'))
  1699. return;
  1700. name[len-1]='\0';
  1701. }
  1702. #else
  1703. (void)name;
  1704. #endif
  1705. }
  1706. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1707. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1708. * directory. On FN_ERROR, sets errno. */
  1709. file_status_t
  1710. file_status(const char *fname)
  1711. {
  1712. struct stat st;
  1713. char *f;
  1714. int r;
  1715. f = tor_strdup(fname);
  1716. clean_name_for_stat(f);
  1717. log_debug(LD_FS, "stat()ing %s", f);
  1718. r = stat(sandbox_intern_string(f), &st);
  1719. tor_free(f);
  1720. if (r) {
  1721. if (errno == ENOENT) {
  1722. return FN_NOENT;
  1723. }
  1724. return FN_ERROR;
  1725. }
  1726. if (st.st_mode & S_IFDIR)
  1727. return FN_DIR;
  1728. else if (st.st_mode & S_IFREG)
  1729. return FN_FILE;
  1730. #ifndef _WIN32
  1731. else if (st.st_mode & S_IFIFO)
  1732. return FN_FILE;
  1733. #endif
  1734. else
  1735. return FN_ERROR;
  1736. }
  1737. /** Check whether <b>dirname</b> exists and is private. If yes return 0. If
  1738. * it does not exist, and <b>check</b>&CPD_CREATE is set, try to create it
  1739. * and return 0 on success. If it does not exist, and
  1740. * <b>check</b>&CPD_CHECK, and we think we can create it, return 0. Else
  1741. * return -1. If CPD_GROUP_OK is set, then it's okay if the directory
  1742. * is group-readable, but in all cases we create the directory mode 0700.
  1743. * If CPD_CHECK_MODE_ONLY is set, then we don't alter the directory permissions
  1744. * if they are too permissive: we just return -1.
  1745. * When effective_user is not NULL, check permissions against the given user
  1746. * and its primary group.
  1747. */
  1748. int
  1749. check_private_dir(const char *dirname, cpd_check_t check,
  1750. const char *effective_user)
  1751. {
  1752. int r;
  1753. struct stat st;
  1754. char *f;
  1755. #ifndef _WIN32
  1756. int mask;
  1757. const struct passwd *pw = NULL;
  1758. uid_t running_uid;
  1759. gid_t running_gid;
  1760. #else
  1761. (void)effective_user;
  1762. #endif
  1763. tor_assert(dirname);
  1764. f = tor_strdup(dirname);
  1765. clean_name_for_stat(f);
  1766. log_debug(LD_FS, "stat()ing %s", f);
  1767. r = stat(sandbox_intern_string(f), &st);
  1768. tor_free(f);
  1769. if (r) {
  1770. if (errno != ENOENT) {
  1771. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1772. strerror(errno));
  1773. return -1;
  1774. }
  1775. if (check & CPD_CREATE) {
  1776. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1777. #if defined (_WIN32)
  1778. r = mkdir(dirname);
  1779. #else
  1780. r = mkdir(dirname, 0700);
  1781. #endif
  1782. if (r) {
  1783. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1784. strerror(errno));
  1785. return -1;
  1786. }
  1787. } else if (!(check & CPD_CHECK)) {
  1788. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1789. return -1;
  1790. }
  1791. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1792. * parent directory a little harder. */
  1793. return 0;
  1794. }
  1795. if (!(st.st_mode & S_IFDIR)) {
  1796. log_warn(LD_FS, "%s is not a directory", dirname);
  1797. return -1;
  1798. }
  1799. #ifndef _WIN32
  1800. if (effective_user) {
  1801. /* Look up the user and group information.
  1802. * If we have a problem, bail out. */
  1803. pw = tor_getpwnam(effective_user);
  1804. if (pw == NULL) {
  1805. log_warn(LD_CONFIG, "Error setting configured user: %s not found",
  1806. effective_user);
  1807. return -1;
  1808. }
  1809. running_uid = pw->pw_uid;
  1810. running_gid = pw->pw_gid;
  1811. } else {
  1812. running_uid = getuid();
  1813. running_gid = getgid();
  1814. }
  1815. if (st.st_uid != running_uid) {
  1816. const struct passwd *pw = NULL;
  1817. char *process_ownername = NULL;
  1818. pw = tor_getpwuid(running_uid);
  1819. process_ownername = pw ? tor_strdup(pw->pw_name) : tor_strdup("<unknown>");
  1820. pw = tor_getpwuid(st.st_uid);
  1821. log_warn(LD_FS, "%s is not owned by this user (%s, %d) but by "
  1822. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1823. dirname, process_ownername, (int)running_uid,
  1824. pw ? pw->pw_name : "<unknown>", (int)st.st_uid);
  1825. tor_free(process_ownername);
  1826. return -1;
  1827. }
  1828. if ((check & CPD_GROUP_OK) && st.st_gid != running_gid) {
  1829. struct group *gr;
  1830. char *process_groupname = NULL;
  1831. gr = getgrgid(running_gid);
  1832. process_groupname = gr ? tor_strdup(gr->gr_name) : tor_strdup("<unknown>");
  1833. gr = getgrgid(st.st_gid);
  1834. log_warn(LD_FS, "%s is not owned by this group (%s, %d) but by group "
  1835. "%s (%d). Are you running Tor as the wrong user?",
  1836. dirname, process_groupname, (int)running_gid,
  1837. gr ? gr->gr_name : "<unknown>", (int)st.st_gid);
  1838. tor_free(process_groupname);
  1839. return -1;
  1840. }
  1841. if (check & CPD_GROUP_OK) {
  1842. mask = 0027;
  1843. } else {
  1844. mask = 0077;
  1845. }
  1846. if (st.st_mode & mask) {
  1847. unsigned new_mode;
  1848. if (check & CPD_CHECK_MODE_ONLY) {
  1849. log_warn(LD_FS, "Permissions on directory %s are too permissive.",
  1850. dirname);
  1851. return -1;
  1852. }
  1853. log_warn(LD_FS, "Fixing permissions on directory %s", dirname);
  1854. new_mode = st.st_mode;
  1855. new_mode |= 0700; /* Owner should have rwx */
  1856. new_mode &= ~mask; /* Clear the other bits that we didn't want set...*/
  1857. if (chmod(dirname, new_mode)) {
  1858. log_warn(LD_FS, "Could not chmod directory %s: %s", dirname,
  1859. strerror(errno));
  1860. return -1;
  1861. } else {
  1862. return 0;
  1863. }
  1864. }
  1865. #endif
  1866. return 0;
  1867. }
  1868. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1869. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1870. *
  1871. * This function replaces the old file atomically, if possible. This
  1872. * function, and all other functions in util.c that create files, create them
  1873. * with mode 0600.
  1874. */
  1875. int
  1876. write_str_to_file(const char *fname, const char *str, int bin)
  1877. {
  1878. #ifdef _WIN32
  1879. if (!bin && strchr(str, '\r')) {
  1880. log_warn(LD_BUG,
  1881. "We're writing a text string that already contains a CR to %s",
  1882. escaped(fname));
  1883. }
  1884. #endif
  1885. return write_bytes_to_file(fname, str, strlen(str), bin);
  1886. }
  1887. /** Represents a file that we're writing to, with support for atomic commit:
  1888. * we can write into a temporary file, and either remove the file on
  1889. * failure, or replace the original file on success. */
  1890. struct open_file_t {
  1891. char *tempname; /**< Name of the temporary file. */
  1892. char *filename; /**< Name of the original file. */
  1893. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  1894. unsigned binary:1; /**< Did we open in binary mode? */
  1895. int fd; /**< fd for the open file. */
  1896. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  1897. };
  1898. /** Try to start writing to the file in <b>fname</b>, passing the flags
  1899. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  1900. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  1901. * original file. Otherwise, we open a new temporary file in the same
  1902. * directory, and either replace the original or remove the temporary file
  1903. * when we're done.
  1904. *
  1905. * Return the fd for the newly opened file, and store working data in
  1906. * *<b>data_out</b>. The caller should not close the fd manually:
  1907. * instead, call finish_writing_to_file() or abort_writing_to_file().
  1908. * Returns -1 on failure.
  1909. *
  1910. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  1911. * as true and the flag O_EXCL is treated as false.
  1912. *
  1913. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  1914. * write()". We don't do that.
  1915. */
  1916. int
  1917. start_writing_to_file(const char *fname, int open_flags, int mode,
  1918. open_file_t **data_out)
  1919. {
  1920. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  1921. const char *open_name;
  1922. int append = 0;
  1923. tor_assert(fname);
  1924. tor_assert(data_out);
  1925. #if (O_BINARY != 0 && O_TEXT != 0)
  1926. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  1927. #endif
  1928. new_file->fd = -1;
  1929. new_file->filename = tor_strdup(fname);
  1930. if (open_flags & O_APPEND) {
  1931. open_name = fname;
  1932. new_file->rename_on_close = 0;
  1933. append = 1;
  1934. open_flags &= ~O_APPEND;
  1935. } else {
  1936. tor_asprintf(&new_file->tempname, "%s.tmp", fname);
  1937. open_name = new_file->tempname;
  1938. /* We always replace an existing temporary file if there is one. */
  1939. open_flags |= O_CREAT|O_TRUNC;
  1940. open_flags &= ~O_EXCL;
  1941. new_file->rename_on_close = 1;
  1942. }
  1943. #if O_BINARY != 0
  1944. if (open_flags & O_BINARY)
  1945. new_file->binary = 1;
  1946. #endif
  1947. new_file->fd = tor_open_cloexec(open_name, open_flags, mode);
  1948. if (new_file->fd < 0) {
  1949. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  1950. open_name, fname, strerror(errno));
  1951. goto err;
  1952. }
  1953. if (append) {
  1954. if (tor_fd_seekend(new_file->fd) < 0) {
  1955. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  1956. strerror(errno));
  1957. goto err;
  1958. }
  1959. }
  1960. *data_out = new_file;
  1961. return new_file->fd;
  1962. err:
  1963. if (new_file->fd >= 0)
  1964. close(new_file->fd);
  1965. *data_out = NULL;
  1966. tor_free(new_file->filename);
  1967. tor_free(new_file->tempname);
  1968. tor_free(new_file);
  1969. return -1;
  1970. }
  1971. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  1972. * that can be used to write to the same file. The caller should not mix
  1973. * stdio calls with non-stdio calls. */
  1974. FILE *
  1975. fdopen_file(open_file_t *file_data)
  1976. {
  1977. tor_assert(file_data);
  1978. if (file_data->stdio_file)
  1979. return file_data->stdio_file;
  1980. tor_assert(file_data->fd >= 0);
  1981. if (!(file_data->stdio_file = fdopen(file_data->fd,
  1982. file_data->binary?"ab":"a"))) {
  1983. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  1984. file_data->fd, strerror(errno));
  1985. }
  1986. return file_data->stdio_file;
  1987. }
  1988. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  1989. * for start_writing_to_file, but */
  1990. FILE *
  1991. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  1992. open_file_t **data_out)
  1993. {
  1994. FILE *res;
  1995. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  1996. return NULL;
  1997. if (!(res = fdopen_file(*data_out))) {
  1998. abort_writing_to_file(*data_out);
  1999. *data_out = NULL;
  2000. }
  2001. return res;
  2002. }
  2003. /** Helper function: close and free the underlying file and memory in
  2004. * <b>file_data</b>. If we were writing into a temporary file, then delete
  2005. * that file (if abort_write is true) or replaces the target file with
  2006. * the temporary file (if abort_write is false). */
  2007. static int
  2008. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  2009. {
  2010. int r = 0;
  2011. tor_assert(file_data && file_data->filename);
  2012. if (file_data->stdio_file) {
  2013. if (fclose(file_data->stdio_file)) {
  2014. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  2015. strerror(errno));
  2016. abort_write = r = -1;
  2017. }
  2018. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  2019. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  2020. strerror(errno));
  2021. abort_write = r = -1;
  2022. }
  2023. if (file_data->rename_on_close) {
  2024. tor_assert(file_data->tempname && file_data->filename);
  2025. if (abort_write) {
  2026. int res = unlink(file_data->tempname);
  2027. if (res != 0) {
  2028. /* We couldn't unlink and we'll leave a mess behind */
  2029. log_warn(LD_FS, "Failed to unlink %s: %s",
  2030. file_data->tempname, strerror(errno));
  2031. r = -1;
  2032. }
  2033. } else {
  2034. tor_assert(strcmp(file_data->filename, file_data->tempname));
  2035. if (replace_file(file_data->tempname, file_data->filename)) {
  2036. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  2037. strerror(errno));
  2038. r = -1;
  2039. }
  2040. }
  2041. }
  2042. tor_free(file_data->filename);
  2043. tor_free(file_data->tempname);
  2044. tor_free(file_data);
  2045. return r;
  2046. }
  2047. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  2048. * needed, and if using a temporary file, replace the original file with
  2049. * the temporary file. */
  2050. int
  2051. finish_writing_to_file(open_file_t *file_data)
  2052. {
  2053. return finish_writing_to_file_impl(file_data, 0);
  2054. }
  2055. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  2056. * needed, and if using a temporary file, delete it. */
  2057. int
  2058. abort_writing_to_file(open_file_t *file_data)
  2059. {
  2060. return finish_writing_to_file_impl(file_data, 1);
  2061. }
  2062. /** Helper: given a set of flags as passed to open(2), open the file
  2063. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  2064. * the file. Do so as atomically as possible e.g. by opening temp files and
  2065. * renaming. */
  2066. static int
  2067. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  2068. int open_flags)
  2069. {
  2070. open_file_t *file = NULL;
  2071. int fd;
  2072. ssize_t result;
  2073. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  2074. if (fd<0)
  2075. return -1;
  2076. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  2077. {
  2078. result = write_all(fd, chunk->bytes, chunk->len, 0);
  2079. if (result < 0) {
  2080. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  2081. strerror(errno));
  2082. goto err;
  2083. }
  2084. tor_assert((size_t)result == chunk->len);
  2085. });
  2086. return finish_writing_to_file(file);
  2087. err:
  2088. abort_writing_to_file(file);
  2089. return -1;
  2090. }
  2091. /** Given a smartlist of sized_chunk_t, write them to a file
  2092. * <b>fname</b>, overwriting or creating the file as necessary.
  2093. * If <b>no_tempfile</b> is 0 then the file will be written
  2094. * atomically. */
  2095. int
  2096. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin,
  2097. int no_tempfile)
  2098. {
  2099. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  2100. if (no_tempfile) {
  2101. /* O_APPEND stops write_chunks_to_file from using tempfiles */
  2102. flags |= O_APPEND;
  2103. }
  2104. return write_chunks_to_file_impl(fname, chunks, flags);
  2105. }
  2106. /** Write <b>len</b> bytes, starting at <b>str</b>, to <b>fname</b>
  2107. using the open() flags passed in <b>flags</b>. */
  2108. static int
  2109. write_bytes_to_file_impl(const char *fname, const char *str, size_t len,
  2110. int flags)
  2111. {
  2112. int r;
  2113. sized_chunk_t c = { str, len };
  2114. smartlist_t *chunks = smartlist_new();
  2115. smartlist_add(chunks, &c);
  2116. r = write_chunks_to_file_impl(fname, chunks, flags);
  2117. smartlist_free(chunks);
  2118. return r;
  2119. }
  2120. /** As write_str_to_file, but does not assume a NUL-terminated
  2121. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  2122. MOCK_IMPL(int,
  2123. write_bytes_to_file,(const char *fname, const char *str, size_t len,
  2124. int bin))
  2125. {
  2126. return write_bytes_to_file_impl(fname, str, len,
  2127. OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT));
  2128. }
  2129. /** As write_bytes_to_file, but if the file already exists, append the bytes
  2130. * to the end of the file instead of overwriting it. */
  2131. int
  2132. append_bytes_to_file(const char *fname, const char *str, size_t len,
  2133. int bin)
  2134. {
  2135. return write_bytes_to_file_impl(fname, str, len,
  2136. OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT));
  2137. }
  2138. /** Like write_str_to_file(), but also return -1 if there was a file
  2139. already residing in <b>fname</b>. */
  2140. int
  2141. write_bytes_to_new_file(const char *fname, const char *str, size_t len,
  2142. int bin)
  2143. {
  2144. return write_bytes_to_file_impl(fname, str, len,
  2145. OPEN_FLAGS_DONT_REPLACE|
  2146. (bin?O_BINARY:O_TEXT));
  2147. }
  2148. /**
  2149. * Read the contents of the open file <b>fd</b> presuming it is a FIFO
  2150. * (or similar) file descriptor for which the size of the file isn't
  2151. * known ahead of time. Return NULL on failure, and a NUL-terminated
  2152. * string on success. On success, set <b>sz_out</b> to the number of
  2153. * bytes read.
  2154. */
  2155. char *
  2156. read_file_to_str_until_eof(int fd, size_t max_bytes_to_read, size_t *sz_out)
  2157. {
  2158. ssize_t r;
  2159. size_t pos = 0;
  2160. char *string = NULL;
  2161. size_t string_max = 0;
  2162. if (max_bytes_to_read+1 >= SIZE_T_CEILING)
  2163. return NULL;
  2164. do {
  2165. /* XXXX This "add 1K" approach is a little goofy; if we care about
  2166. * performance here, we should be doubling. But in practice we shouldn't
  2167. * be using this function on big files anyway. */
  2168. string_max = pos + 1024;
  2169. if (string_max > max_bytes_to_read)
  2170. string_max = max_bytes_to_read + 1;
  2171. string = tor_realloc(string, string_max);
  2172. r = read(fd, string + pos, string_max - pos - 1);
  2173. if (r < 0) {
  2174. tor_free(string);
  2175. return NULL;
  2176. }
  2177. pos += r;
  2178. } while (r > 0 && pos < max_bytes_to_read);
  2179. tor_assert(pos < string_max);
  2180. *sz_out = pos;
  2181. string[pos] = '\0';
  2182. return string;
  2183. }
  2184. /** Read the contents of <b>filename</b> into a newly allocated
  2185. * string; return the string on success or NULL on failure.
  2186. *
  2187. * If <b>stat_out</b> is provided, store the result of stat()ing the
  2188. * file into <b>stat_out</b>.
  2189. *
  2190. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  2191. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  2192. * doesn't exist.
  2193. */
  2194. /*
  2195. * This function <em>may</em> return an erroneous result if the file
  2196. * is modified while it is running, but must not crash or overflow.
  2197. * Right now, the error case occurs when the file length grows between
  2198. * the call to stat and the call to read_all: the resulting string will
  2199. * be truncated.
  2200. */
  2201. char *
  2202. read_file_to_str(const char *filename, int flags, struct stat *stat_out)
  2203. {
  2204. int fd; /* router file */
  2205. struct stat statbuf;
  2206. char *string;
  2207. ssize_t r;
  2208. int bin = flags & RFTS_BIN;
  2209. tor_assert(filename);
  2210. fd = tor_open_cloexec(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  2211. if (fd<0) {
  2212. int severity = LOG_WARN;
  2213. int save_errno = errno;
  2214. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  2215. severity = LOG_INFO;
  2216. log_fn(severity, LD_FS,"Could not open \"%s\": %s",filename,
  2217. strerror(errno));
  2218. errno = save_errno;
  2219. return NULL;
  2220. }
  2221. if (fstat(fd, &statbuf)<0) {
  2222. int save_errno = errno;
  2223. close(fd);
  2224. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  2225. errno = save_errno;
  2226. return NULL;
  2227. }
  2228. #ifndef _WIN32
  2229. /** When we detect that we're reading from a FIFO, don't read more than
  2230. * this many bytes. It's insane overkill for most uses. */
  2231. #define FIFO_READ_MAX (1024*1024)
  2232. if (S_ISFIFO(statbuf.st_mode)) {
  2233. size_t sz = 0;
  2234. string = read_file_to_str_until_eof(fd, FIFO_READ_MAX, &sz);
  2235. if (string && stat_out) {
  2236. statbuf.st_size = sz;
  2237. memcpy(stat_out, &statbuf, sizeof(struct stat));
  2238. }
  2239. close(fd);
  2240. return string;
  2241. }
  2242. #endif
  2243. if ((uint64_t)(statbuf.st_size)+1 >= SIZE_T_CEILING) {
  2244. close(fd);
  2245. return NULL;
  2246. }
  2247. string = tor_malloc((size_t)(statbuf.st_size+1));
  2248. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  2249. if (r<0) {
  2250. int save_errno = errno;
  2251. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  2252. strerror(errno));
  2253. tor_free(string);
  2254. close(fd);
  2255. errno = save_errno;
  2256. return NULL;
  2257. }
  2258. string[r] = '\0'; /* NUL-terminate the result. */
  2259. #if defined(_WIN32) || defined(__CYGWIN__)
  2260. if (!bin && strchr(string, '\r')) {
  2261. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  2262. "when reading %s. Coping.",
  2263. filename);
  2264. tor_strstrip(string, "\r");
  2265. r = strlen(string);
  2266. }
  2267. if (!bin) {
  2268. statbuf.st_size = (size_t) r;
  2269. } else
  2270. #endif
  2271. if (r != statbuf.st_size) {
  2272. /* Unless we're using text mode on win32, we'd better have an exact
  2273. * match for size. */
  2274. int save_errno = errno;
  2275. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  2276. (int)r, (long)statbuf.st_size,filename);
  2277. tor_free(string);
  2278. close(fd);
  2279. errno = save_errno;
  2280. return NULL;
  2281. }
  2282. close(fd);
  2283. if (stat_out) {
  2284. memcpy(stat_out, &statbuf, sizeof(struct stat));
  2285. }
  2286. return string;
  2287. }
  2288. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  2289. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  2290. * decode its contents into a newly allocated string. On success, assign this
  2291. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  2292. * provided), and return a pointer to the position in <b>s</b> immediately
  2293. * after the string. On failure, return NULL.
  2294. */
  2295. static const char *
  2296. unescape_string(const char *s, char **result, size_t *size_out)
  2297. {
  2298. const char *cp;
  2299. char *out;
  2300. if (s[0] != '\"')
  2301. return NULL;
  2302. cp = s+1;
  2303. while (1) {
  2304. switch (*cp) {
  2305. case '\0':
  2306. case '\n':
  2307. return NULL;
  2308. case '\"':
  2309. goto end_of_loop;
  2310. case '\\':
  2311. if (cp[1] == 'x' || cp[1] == 'X') {
  2312. if (!(TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])))
  2313. return NULL;
  2314. cp += 4;
  2315. } else if (TOR_ISODIGIT(cp[1])) {
  2316. cp += 2;
  2317. if (TOR_ISODIGIT(*cp)) ++cp;
  2318. if (TOR_ISODIGIT(*cp)) ++cp;
  2319. } else if (cp[1] == 'n' || cp[1] == 'r' || cp[1] == 't' || cp[1] == '"'
  2320. || cp[1] == '\\' || cp[1] == '\'') {
  2321. cp += 2;
  2322. } else {
  2323. return NULL;
  2324. }
  2325. break;
  2326. default:
  2327. ++cp;
  2328. break;
  2329. }
  2330. }
  2331. end_of_loop:
  2332. out = *result = tor_malloc(cp-s + 1);
  2333. cp = s+1;
  2334. while (1) {
  2335. switch (*cp)
  2336. {
  2337. case '\"':
  2338. *out = '\0';
  2339. if (size_out) *size_out = out - *result;
  2340. return cp+1;
  2341. case '\0':
  2342. tor_fragile_assert();
  2343. tor_free(*result);
  2344. return NULL;
  2345. case '\\':
  2346. switch (cp[1])
  2347. {
  2348. case 'n': *out++ = '\n'; cp += 2; break;
  2349. case 'r': *out++ = '\r'; cp += 2; break;
  2350. case 't': *out++ = '\t'; cp += 2; break;
  2351. case 'x': case 'X':
  2352. {
  2353. int x1, x2;
  2354. x1 = hex_decode_digit(cp[2]);
  2355. x2 = hex_decode_digit(cp[3]);
  2356. if (x1 == -1 || x2 == -1) {
  2357. tor_free(*result);
  2358. return NULL;
  2359. }
  2360. *out++ = ((x1<<4) + x2);
  2361. cp += 4;
  2362. }
  2363. break;
  2364. case '0': case '1': case '2': case '3': case '4': case '5':
  2365. case '6': case '7':
  2366. {
  2367. int n = cp[1]-'0';
  2368. cp += 2;
  2369. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2370. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2371. if (n > 255) { tor_free(*result); return NULL; }
  2372. *out++ = (char)n;
  2373. }
  2374. break;
  2375. case '\'':
  2376. case '\"':
  2377. case '\\':
  2378. case '\?':
  2379. *out++ = cp[1];
  2380. cp += 2;
  2381. break;
  2382. default:
  2383. tor_free(*result); return NULL;
  2384. }
  2385. break;
  2386. default:
  2387. *out++ = *cp++;
  2388. }
  2389. }
  2390. }
  2391. /** Given a string containing part of a configuration file or similar format,
  2392. * advance past comments and whitespace and try to parse a single line. If we
  2393. * parse a line successfully, set *<b>key_out</b> to a new string holding the
  2394. * key portion and *<b>value_out</b> to a new string holding the value portion
  2395. * of the line, and return a pointer to the start of the next line. If we run
  2396. * out of data, return a pointer to the end of the string. If we encounter an
  2397. * error, return NULL and set *<b>err_out</b> (if provided) to an error
  2398. * message.
  2399. */
  2400. const char *
  2401. parse_config_line_from_str_verbose(const char *line, char **key_out,
  2402. char **value_out,
  2403. const char **err_out)
  2404. {
  2405. /* I believe the file format here is supposed to be:
  2406. FILE = (EMPTYLINE | LINE)* (EMPTYLASTLINE | LASTLINE)?
  2407. EMPTYLASTLINE = SPACE* | COMMENT
  2408. EMPTYLINE = EMPTYLASTLINE NL
  2409. SPACE = ' ' | '\r' | '\t'
  2410. COMMENT = '#' NOT-NL*
  2411. NOT-NL = Any character except '\n'
  2412. NL = '\n'
  2413. LASTLINE = SPACE* KEY SPACE* VALUES
  2414. LINE = LASTLINE NL
  2415. KEY = KEYCHAR+
  2416. KEYCHAR = Any character except ' ', '\r', '\n', '\t', '#', "\"
  2417. VALUES = QUOTEDVALUE | NORMALVALUE
  2418. QUOTEDVALUE = QUOTE QVCHAR* QUOTE EOLSPACE?
  2419. QUOTE = '"'
  2420. QVCHAR = KEYCHAR | ESC ('n' | 't' | 'r' | '"' | ESC |'\'' | OCTAL | HEX)
  2421. ESC = "\\"
  2422. OCTAL = ODIGIT (ODIGIT ODIGIT?)?
  2423. HEX = ('x' | 'X') HEXDIGIT HEXDIGIT
  2424. ODIGIT = '0' .. '7'
  2425. HEXDIGIT = '0'..'9' | 'a' .. 'f' | 'A' .. 'F'
  2426. EOLSPACE = SPACE* COMMENT?
  2427. NORMALVALUE = (VALCHAR | ESC ESC_IGNORE | CONTINUATION)* EOLSPACE?
  2428. VALCHAR = Any character except ESC, '#', and '\n'
  2429. ESC_IGNORE = Any character except '#' or '\n'
  2430. CONTINUATION = ESC NL ( COMMENT NL )*
  2431. */
  2432. const char *key, *val, *cp;
  2433. int continuation = 0;
  2434. tor_assert(key_out);
  2435. tor_assert(value_out);
  2436. *key_out = *value_out = NULL;
  2437. key = val = NULL;
  2438. /* Skip until the first keyword. */
  2439. while (1) {
  2440. while (TOR_ISSPACE(*line))
  2441. ++line;
  2442. if (*line == '#') {
  2443. while (*line && *line != '\n')
  2444. ++line;
  2445. } else {
  2446. break;
  2447. }
  2448. }
  2449. if (!*line) { /* End of string? */
  2450. *key_out = *value_out = NULL;
  2451. return line;
  2452. }
  2453. /* Skip until the next space or \ followed by newline. */
  2454. key = line;
  2455. while (*line && !TOR_ISSPACE(*line) && *line != '#' &&
  2456. ! (line[0] == '\\' && line[1] == '\n'))
  2457. ++line;
  2458. *key_out = tor_strndup(key, line-key);
  2459. /* Skip until the value. */
  2460. while (*line == ' ' || *line == '\t')
  2461. ++line;
  2462. val = line;
  2463. /* Find the end of the line. */
  2464. if (*line == '\"') { // XXX No continuation handling is done here
  2465. if (!(line = unescape_string(line, value_out, NULL))) {
  2466. if (err_out)
  2467. *err_out = "Invalid escape sequence in quoted string";
  2468. return NULL;
  2469. }
  2470. while (*line == ' ' || *line == '\t')
  2471. ++line;
  2472. if (*line && *line != '#' && *line != '\n') {
  2473. if (err_out)
  2474. *err_out = "Excess data after quoted string";
  2475. return NULL;
  2476. }
  2477. } else {
  2478. /* Look for the end of the line. */
  2479. while (*line && *line != '\n' && (*line != '#' || continuation)) {
  2480. if (*line == '\\' && line[1] == '\n') {
  2481. continuation = 1;
  2482. line += 2;
  2483. } else if (*line == '#') {
  2484. do {
  2485. ++line;
  2486. } while (*line && *line != '\n');
  2487. if (*line == '\n')
  2488. ++line;
  2489. } else {
  2490. ++line;
  2491. }
  2492. }
  2493. if (*line == '\n') {
  2494. cp = line++;
  2495. } else {
  2496. cp = line;
  2497. }
  2498. /* Now back cp up to be the last nonspace character */
  2499. while (cp>val && TOR_ISSPACE(*(cp-1)))
  2500. --cp;
  2501. tor_assert(cp >= val);
  2502. /* Now copy out and decode the value. */
  2503. *value_out = tor_strndup(val, cp-val);
  2504. if (continuation) {
  2505. char *v_out, *v_in;
  2506. v_out = v_in = *value_out;
  2507. while (*v_in) {
  2508. if (*v_in == '#') {
  2509. do {
  2510. ++v_in;
  2511. } while (*v_in && *v_in != '\n');
  2512. if (*v_in == '\n')
  2513. ++v_in;
  2514. } else if (v_in[0] == '\\' && v_in[1] == '\n') {
  2515. v_in += 2;
  2516. } else {
  2517. *v_out++ = *v_in++;
  2518. }
  2519. }
  2520. *v_out = '\0';
  2521. }
  2522. }
  2523. if (*line == '#') {
  2524. do {
  2525. ++line;
  2526. } while (*line && *line != '\n');
  2527. }
  2528. while (TOR_ISSPACE(*line)) ++line;
  2529. return line;
  2530. }
  2531. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  2532. * string. */
  2533. char *
  2534. expand_filename(const char *filename)
  2535. {
  2536. tor_assert(filename);
  2537. #ifdef _WIN32
  2538. return tor_strdup(filename);
  2539. #else
  2540. if (*filename == '~') {
  2541. char *home, *result=NULL;
  2542. const char *rest;
  2543. if (filename[1] == '/' || filename[1] == '\0') {
  2544. home = getenv("HOME");
  2545. if (!home) {
  2546. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  2547. "expanding \"%s\"; defaulting to \"\".", filename);
  2548. home = tor_strdup("");
  2549. } else {
  2550. home = tor_strdup(home);
  2551. }
  2552. rest = strlen(filename)>=2?(filename+2):"";
  2553. } else {
  2554. #ifdef HAVE_PWD_H
  2555. char *username, *slash;
  2556. slash = strchr(filename, '/');
  2557. if (slash)
  2558. username = tor_strndup(filename+1,slash-filename-1);
  2559. else
  2560. username = tor_strdup(filename+1);
  2561. if (!(home = get_user_homedir(username))) {
  2562. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2563. tor_free(username);
  2564. return NULL;
  2565. }
  2566. tor_free(username);
  2567. rest = slash ? (slash+1) : "";
  2568. #else
  2569. log_warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
  2570. return tor_strdup(filename);
  2571. #endif
  2572. }
  2573. tor_assert(home);
  2574. /* Remove trailing slash. */
  2575. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2576. home[strlen(home)-1] = '\0';
  2577. }
  2578. tor_asprintf(&result,"%s"PATH_SEPARATOR"%s",home,rest);
  2579. tor_free(home);
  2580. return result;
  2581. } else {
  2582. return tor_strdup(filename);
  2583. }
  2584. #endif
  2585. }
  2586. #define MAX_SCANF_WIDTH 9999
  2587. /** Helper: given an ASCII-encoded decimal digit, return its numeric value.
  2588. * NOTE: requires that its input be in-bounds. */
  2589. static int
  2590. digit_to_num(char d)
  2591. {
  2592. int num = ((int)d) - (int)'0';
  2593. tor_assert(num <= 9 && num >= 0);
  2594. return num;
  2595. }
  2596. /** Helper: Read an unsigned int from *<b>bufp</b> of up to <b>width</b>
  2597. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2598. * success, store the result in <b>out</b>, advance bufp to the next
  2599. * character, and return 0. On failure, return -1. */
  2600. static int
  2601. scan_unsigned(const char **bufp, unsigned long *out, int width, int base)
  2602. {
  2603. unsigned long result = 0;
  2604. int scanned_so_far = 0;
  2605. const int hex = base==16;
  2606. tor_assert(base == 10 || base == 16);
  2607. if (!bufp || !*bufp || !out)
  2608. return -1;
  2609. if (width<0)
  2610. width=MAX_SCANF_WIDTH;
  2611. while (**bufp && (hex?TOR_ISXDIGIT(**bufp):TOR_ISDIGIT(**bufp))
  2612. && scanned_so_far < width) {
  2613. int digit = hex?hex_decode_digit(*(*bufp)++):digit_to_num(*(*bufp)++);
  2614. // Check for overflow beforehand, without actually causing any overflow
  2615. // This preserves functionality on compilers that don't wrap overflow
  2616. // (i.e. that trap or optimise away overflow)
  2617. // result * base + digit > ULONG_MAX
  2618. // result * base > ULONG_MAX - digit
  2619. if (result > (ULONG_MAX - digit)/base)
  2620. return -1; /* Processing this digit would overflow */
  2621. result = result * base + digit;
  2622. ++scanned_so_far;
  2623. }
  2624. if (!scanned_so_far) /* No actual digits scanned */
  2625. return -1;
  2626. *out = result;
  2627. return 0;
  2628. }
  2629. /** Helper: Read an signed int from *<b>bufp</b> of up to <b>width</b>
  2630. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2631. * success, store the result in <b>out</b>, advance bufp to the next
  2632. * character, and return 0. On failure, return -1. */
  2633. static int
  2634. scan_signed(const char **bufp, long *out, int width)
  2635. {
  2636. int neg = 0;
  2637. unsigned long result = 0;
  2638. if (!bufp || !*bufp || !out)
  2639. return -1;
  2640. if (width<0)
  2641. width=MAX_SCANF_WIDTH;
  2642. if (**bufp == '-') {
  2643. neg = 1;
  2644. ++*bufp;
  2645. --width;
  2646. }
  2647. if (scan_unsigned(bufp, &result, width, 10) < 0)
  2648. return -1;
  2649. if (neg && result > 0) {
  2650. if (result > ((unsigned long)LONG_MAX) + 1)
  2651. return -1; /* Underflow */
  2652. // Avoid overflow on the cast to signed long when result is LONG_MIN
  2653. // by subtracting 1 from the unsigned long positive value,
  2654. // then, after it has been cast to signed and negated,
  2655. // subtracting the original 1 (the double-subtraction is intentional).
  2656. // Otherwise, the cast to signed could cause a temporary long
  2657. // to equal LONG_MAX + 1, which is undefined.
  2658. // We avoid underflow on the subtraction by treating -0 as positive.
  2659. *out = (-(long)(result - 1)) - 1;
  2660. } else {
  2661. if (result > LONG_MAX)
  2662. return -1; /* Overflow */
  2663. *out = (long)result;
  2664. }
  2665. return 0;
  2666. }
  2667. /** Helper: Read a decimal-formatted double from *<b>bufp</b> of up to
  2668. * <b>width</b> characters. (Handle arbitrary width if <b>width</b> is less
  2669. * than 0.) On success, store the result in <b>out</b>, advance bufp to the
  2670. * next character, and return 0. On failure, return -1. */
  2671. static int
  2672. scan_double(const char **bufp, double *out, int width)
  2673. {
  2674. int neg = 0;
  2675. double result = 0;
  2676. int scanned_so_far = 0;
  2677. if (!bufp || !*bufp || !out)
  2678. return -1;
  2679. if (width<0)
  2680. width=MAX_SCANF_WIDTH;
  2681. if (**bufp == '-') {
  2682. neg = 1;
  2683. ++*bufp;
  2684. }
  2685. while (**bufp && TOR_ISDIGIT(**bufp) && scanned_so_far < width) {
  2686. const int digit = digit_to_num(*(*bufp)++);
  2687. result = result * 10 + digit;
  2688. ++scanned_so_far;
  2689. }
  2690. if (**bufp == '.') {
  2691. double fracval = 0, denominator = 1;
  2692. ++*bufp;
  2693. ++scanned_so_far;
  2694. while (**bufp && TOR_ISDIGIT(**bufp) && scanned_so_far < width) {
  2695. const int digit = digit_to_num(*(*bufp)++);
  2696. fracval = fracval * 10 + digit;
  2697. denominator *= 10;
  2698. ++scanned_so_far;
  2699. }
  2700. result += fracval / denominator;
  2701. }
  2702. if (!scanned_so_far) /* No actual digits scanned */
  2703. return -1;
  2704. *out = neg ? -result : result;
  2705. return 0;
  2706. }
  2707. /** Helper: copy up to <b>width</b> non-space characters from <b>bufp</b> to
  2708. * <b>out</b>. Make sure <b>out</b> is nul-terminated. Advance <b>bufp</b>
  2709. * to the next non-space character or the EOS. */
  2710. static int
  2711. scan_string(const char **bufp, char *out, int width)
  2712. {
  2713. int scanned_so_far = 0;
  2714. if (!bufp || !out || width < 0)
  2715. return -1;
  2716. while (**bufp && ! TOR_ISSPACE(**bufp) && scanned_so_far < width) {
  2717. *out++ = *(*bufp)++;
  2718. ++scanned_so_far;
  2719. }
  2720. *out = '\0';
  2721. return 0;
  2722. }
  2723. /** Locale-independent, minimal, no-surprises scanf variant, accepting only a
  2724. * restricted pattern format. For more info on what it supports, see
  2725. * tor_sscanf() documentation. */
  2726. int
  2727. tor_vsscanf(const char *buf, const char *pattern, va_list ap)
  2728. {
  2729. int n_matched = 0;
  2730. while (*pattern) {
  2731. if (*pattern != '%') {
  2732. if (*buf == *pattern) {
  2733. ++buf;
  2734. ++pattern;
  2735. continue;
  2736. } else {
  2737. return n_matched;
  2738. }
  2739. } else {
  2740. int width = -1;
  2741. int longmod = 0;
  2742. ++pattern;
  2743. if (TOR_ISDIGIT(*pattern)) {
  2744. width = digit_to_num(*pattern++);
  2745. while (TOR_ISDIGIT(*pattern)) {
  2746. width *= 10;
  2747. width += digit_to_num(*pattern++);
  2748. if (width > MAX_SCANF_WIDTH)
  2749. return -1;
  2750. }
  2751. if (!width) /* No zero-width things. */
  2752. return -1;
  2753. }
  2754. if (*pattern == 'l') {
  2755. longmod = 1;
  2756. ++pattern;
  2757. }
  2758. if (*pattern == 'u' || *pattern == 'x') {
  2759. unsigned long u;
  2760. const int base = (*pattern == 'u') ? 10 : 16;
  2761. if (!*buf)
  2762. return n_matched;
  2763. if (scan_unsigned(&buf, &u, width, base)<0)
  2764. return n_matched;
  2765. if (longmod) {
  2766. unsigned long *out = va_arg(ap, unsigned long *);
  2767. *out = u;
  2768. } else {
  2769. unsigned *out = va_arg(ap, unsigned *);
  2770. if (u > UINT_MAX)
  2771. return n_matched;
  2772. *out = (unsigned) u;
  2773. }
  2774. ++pattern;
  2775. ++n_matched;
  2776. } else if (*pattern == 'f') {
  2777. double *d = va_arg(ap, double *);
  2778. if (!longmod)
  2779. return -1; /* float not supported */
  2780. if (!*buf)
  2781. return n_matched;
  2782. if (scan_double(&buf, d, width)<0)
  2783. return n_matched;
  2784. ++pattern;
  2785. ++n_matched;
  2786. } else if (*pattern == 'd') {
  2787. long lng=0;
  2788. if (scan_signed(&buf, &lng, width)<0)
  2789. return n_matched;
  2790. if (longmod) {
  2791. long *out = va_arg(ap, long *);
  2792. *out = lng;
  2793. } else {
  2794. int *out = va_arg(ap, int *);
  2795. if (lng < INT_MIN || lng > INT_MAX)
  2796. return n_matched;
  2797. *out = (int)lng;
  2798. }
  2799. ++pattern;
  2800. ++n_matched;
  2801. } else if (*pattern == 's') {
  2802. char *s = va_arg(ap, char *);
  2803. if (longmod)
  2804. return -1;
  2805. if (width < 0)
  2806. return -1;
  2807. if (scan_string(&buf, s, width)<0)
  2808. return n_matched;
  2809. ++pattern;
  2810. ++n_matched;
  2811. } else if (*pattern == 'c') {
  2812. char *ch = va_arg(ap, char *);
  2813. if (longmod)
  2814. return -1;
  2815. if (width != -1)
  2816. return -1;
  2817. if (!*buf)
  2818. return n_matched;
  2819. *ch = *buf++;
  2820. ++pattern;
  2821. ++n_matched;
  2822. } else if (*pattern == '%') {
  2823. if (*buf != '%')
  2824. return n_matched;
  2825. if (longmod)
  2826. return -1;
  2827. ++buf;
  2828. ++pattern;
  2829. } else {
  2830. return -1; /* Unrecognized pattern component. */
  2831. }
  2832. }
  2833. }
  2834. return n_matched;
  2835. }
  2836. /** Minimal sscanf replacement: parse <b>buf</b> according to <b>pattern</b>
  2837. * and store the results in the corresponding argument fields. Differs from
  2838. * sscanf in that:
  2839. * <ul><li>It only handles %u, %lu, %x, %lx, %[NUM]s, %d, %ld, %lf, and %c.
  2840. * <li>It only handles decimal inputs for %lf. (12.3, not 1.23e1)
  2841. * <li>It does not handle arbitrarily long widths.
  2842. * <li>Numbers do not consume any space characters.
  2843. * <li>It is locale-independent.
  2844. * <li>%u and %x do not consume any space.
  2845. * <li>It returns -1 on malformed patterns.</ul>
  2846. *
  2847. * (As with other locale-independent functions, we need this to parse data that
  2848. * is in ASCII without worrying that the C library's locale-handling will make
  2849. * miscellaneous characters look like numbers, spaces, and so on.)
  2850. */
  2851. int
  2852. tor_sscanf(const char *buf, const char *pattern, ...)
  2853. {
  2854. int r;
  2855. va_list ap;
  2856. va_start(ap, pattern);
  2857. r = tor_vsscanf(buf, pattern, ap);
  2858. va_end(ap);
  2859. return r;
  2860. }
  2861. /** Append the string produced by tor_asprintf(<b>pattern</b>, <b>...</b>)
  2862. * to <b>sl</b>. */
  2863. void
  2864. smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern, ...)
  2865. {
  2866. va_list ap;
  2867. va_start(ap, pattern);
  2868. smartlist_add_vasprintf(sl, pattern, ap);
  2869. va_end(ap);
  2870. }
  2871. /** va_list-based backend of smartlist_add_asprintf. */
  2872. void
  2873. smartlist_add_vasprintf(struct smartlist_t *sl, const char *pattern,
  2874. va_list args)
  2875. {
  2876. char *str = NULL;
  2877. tor_vasprintf(&str, pattern, args);
  2878. tor_assert(str != NULL);
  2879. smartlist_add(sl, str);
  2880. }
  2881. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  2882. * Return NULL on error or if <b>dirname</b> is not a directory.
  2883. */
  2884. smartlist_t *
  2885. tor_listdir(const char *dirname)
  2886. {
  2887. smartlist_t *result;
  2888. #ifdef _WIN32
  2889. char *pattern=NULL;
  2890. TCHAR tpattern[MAX_PATH] = {0};
  2891. char name[MAX_PATH*2+1] = {0};
  2892. HANDLE handle;
  2893. WIN32_FIND_DATA findData;
  2894. tor_asprintf(&pattern, "%s\\*", dirname);
  2895. #ifdef UNICODE
  2896. mbstowcs(tpattern,pattern,MAX_PATH);
  2897. #else
  2898. strlcpy(tpattern, pattern, MAX_PATH);
  2899. #endif
  2900. if (INVALID_HANDLE_VALUE == (handle = FindFirstFile(tpattern, &findData))) {
  2901. tor_free(pattern);
  2902. return NULL;
  2903. }
  2904. result = smartlist_new();
  2905. while (1) {
  2906. #ifdef UNICODE
  2907. wcstombs(name,findData.cFileName,MAX_PATH);
  2908. name[sizeof(name)-1] = '\0';
  2909. #else
  2910. strlcpy(name,findData.cFileName,sizeof(name));
  2911. #endif
  2912. if (strcmp(name, ".") &&
  2913. strcmp(name, "..")) {
  2914. smartlist_add(result, tor_strdup(name));
  2915. }
  2916. if (!FindNextFile(handle, &findData)) {
  2917. DWORD err;
  2918. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  2919. char *errstr = format_win32_error(err);
  2920. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  2921. tor_free(errstr);
  2922. }
  2923. break;
  2924. }
  2925. }
  2926. FindClose(handle);
  2927. tor_free(pattern);
  2928. #else
  2929. const char *prot_dname = sandbox_intern_string(dirname);
  2930. DIR *d;
  2931. struct dirent *de;
  2932. if (!(d = opendir(prot_dname)))
  2933. return NULL;
  2934. result = smartlist_new();
  2935. while ((de = readdir(d))) {
  2936. if (!strcmp(de->d_name, ".") ||
  2937. !strcmp(de->d_name, ".."))
  2938. continue;
  2939. smartlist_add(result, tor_strdup(de->d_name));
  2940. }
  2941. closedir(d);
  2942. #endif
  2943. return result;
  2944. }
  2945. /** Return true iff <b>filename</b> is a relative path. */
  2946. int
  2947. path_is_relative(const char *filename)
  2948. {
  2949. if (filename && filename[0] == '/')
  2950. return 0;
  2951. #ifdef _WIN32
  2952. else if (filename && filename[0] == '\\')
  2953. return 0;
  2954. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  2955. filename[1] == ':' && filename[2] == '\\')
  2956. return 0;
  2957. #endif
  2958. else
  2959. return 1;
  2960. }
  2961. /* =====
  2962. * Process helpers
  2963. * ===== */
  2964. #ifndef _WIN32
  2965. /* Based on code contributed by christian grothoff */
  2966. /** True iff we've called start_daemon(). */
  2967. static int start_daemon_called = 0;
  2968. /** True iff we've called finish_daemon(). */
  2969. static int finish_daemon_called = 0;
  2970. /** Socketpair used to communicate between parent and child process while
  2971. * daemonizing. */
  2972. static int daemon_filedes[2];
  2973. /** Start putting the process into daemon mode: fork and drop all resources
  2974. * except standard fds. The parent process never returns, but stays around
  2975. * until finish_daemon is called. (Note: it's safe to call this more
  2976. * than once: calls after the first are ignored.)
  2977. */
  2978. void
  2979. start_daemon(void)
  2980. {
  2981. pid_t pid;
  2982. if (start_daemon_called)
  2983. return;
  2984. start_daemon_called = 1;
  2985. if (pipe(daemon_filedes)) {
  2986. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  2987. exit(1);
  2988. }
  2989. pid = fork();
  2990. if (pid < 0) {
  2991. log_err(LD_GENERAL,"fork failed. Exiting.");
  2992. exit(1);
  2993. }
  2994. if (pid) { /* Parent */
  2995. int ok;
  2996. char c;
  2997. close(daemon_filedes[1]); /* we only read */
  2998. ok = -1;
  2999. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  3000. if (c == '.')
  3001. ok = 1;
  3002. }
  3003. fflush(stdout);
  3004. if (ok == 1)
  3005. exit(0);
  3006. else
  3007. exit(1); /* child reported error */
  3008. } else { /* Child */
  3009. close(daemon_filedes[0]); /* we only write */
  3010. pid = setsid(); /* Detach from controlling terminal */
  3011. /*
  3012. * Fork one more time, so the parent (the session group leader) can exit.
  3013. * This means that we, as a non-session group leader, can never regain a
  3014. * controlling terminal. This part is recommended by Stevens's
  3015. * _Advanced Programming in the Unix Environment_.
  3016. */
  3017. if (fork() != 0) {
  3018. exit(0);
  3019. }
  3020. set_main_thread(); /* We are now the main thread. */
  3021. return;
  3022. }
  3023. }
  3024. /** Finish putting the process into daemon mode: drop standard fds, and tell
  3025. * the parent process to exit. (Note: it's safe to call this more than once:
  3026. * calls after the first are ignored. Calls start_daemon first if it hasn't
  3027. * been called already.)
  3028. */
  3029. void
  3030. finish_daemon(const char *desired_cwd)
  3031. {
  3032. int nullfd;
  3033. char c = '.';
  3034. if (finish_daemon_called)
  3035. return;
  3036. if (!start_daemon_called)
  3037. start_daemon();
  3038. finish_daemon_called = 1;
  3039. if (!desired_cwd)
  3040. desired_cwd = "/";
  3041. /* Don't hold the wrong FS mounted */
  3042. if (chdir(desired_cwd) < 0) {
  3043. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  3044. exit(1);
  3045. }
  3046. nullfd = tor_open_cloexec("/dev/null", O_RDWR, 0);
  3047. if (nullfd < 0) {
  3048. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  3049. exit(1);
  3050. }
  3051. /* close fds linking to invoking terminal, but
  3052. * close usual incoming fds, but redirect them somewhere
  3053. * useful so the fds don't get reallocated elsewhere.
  3054. */
  3055. if (dup2(nullfd,0) < 0 ||
  3056. dup2(nullfd,1) < 0 ||
  3057. dup2(nullfd,2) < 0) {
  3058. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  3059. exit(1);
  3060. }
  3061. if (nullfd > 2)
  3062. close(nullfd);
  3063. /* signal success */
  3064. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  3065. log_err(LD_GENERAL,"write failed. Exiting.");
  3066. }
  3067. close(daemon_filedes[1]);
  3068. }
  3069. #else
  3070. /* defined(_WIN32) */
  3071. void
  3072. start_daemon(void)
  3073. {
  3074. }
  3075. void
  3076. finish_daemon(const char *cp)
  3077. {
  3078. (void)cp;
  3079. }
  3080. #endif
  3081. /** Write the current process ID, followed by NL, into <b>filename</b>.
  3082. */
  3083. void
  3084. write_pidfile(char *filename)
  3085. {
  3086. FILE *pidfile;
  3087. if ((pidfile = fopen(filename, "w")) == NULL) {
  3088. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  3089. strerror(errno));
  3090. } else {
  3091. #ifdef _WIN32
  3092. fprintf(pidfile, "%d\n", (int)_getpid());
  3093. #else
  3094. fprintf(pidfile, "%d\n", (int)getpid());
  3095. #endif
  3096. fclose(pidfile);
  3097. }
  3098. }
  3099. #ifdef _WIN32
  3100. HANDLE
  3101. load_windows_system_library(const TCHAR *library_name)
  3102. {
  3103. TCHAR path[MAX_PATH];
  3104. unsigned n;
  3105. n = GetSystemDirectory(path, MAX_PATH);
  3106. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  3107. return 0;
  3108. _tcscat(path, TEXT("\\"));
  3109. _tcscat(path, library_name);
  3110. return LoadLibrary(path);
  3111. }
  3112. #endif
  3113. /** Format a single argument for being put on a Windows command line.
  3114. * Returns a newly allocated string */
  3115. static char *
  3116. format_win_cmdline_argument(const char *arg)
  3117. {
  3118. char *formatted_arg;
  3119. char need_quotes;
  3120. const char *c;
  3121. int i;
  3122. int bs_counter = 0;
  3123. /* Backslash we can point to when one is inserted into the string */
  3124. const char backslash = '\\';
  3125. /* Smartlist of *char */
  3126. smartlist_t *arg_chars;
  3127. arg_chars = smartlist_new();
  3128. /* Quote string if it contains whitespace or is empty */
  3129. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  3130. /* Build up smartlist of *chars */
  3131. for (c=arg; *c != '\0'; c++) {
  3132. if ('"' == *c) {
  3133. /* Double up backslashes preceding a quote */
  3134. for (i=0; i<(bs_counter*2); i++)
  3135. smartlist_add(arg_chars, (void*)&backslash);
  3136. bs_counter = 0;
  3137. /* Escape the quote */
  3138. smartlist_add(arg_chars, (void*)&backslash);
  3139. smartlist_add(arg_chars, (void*)c);
  3140. } else if ('\\' == *c) {
  3141. /* Count backslashes until we know whether to double up */
  3142. bs_counter++;
  3143. } else {
  3144. /* Don't double up slashes preceding a non-quote */
  3145. for (i=0; i<bs_counter; i++)
  3146. smartlist_add(arg_chars, (void*)&backslash);
  3147. bs_counter = 0;
  3148. smartlist_add(arg_chars, (void*)c);
  3149. }
  3150. }
  3151. /* Don't double up trailing backslashes */
  3152. for (i=0; i<bs_counter; i++)
  3153. smartlist_add(arg_chars, (void*)&backslash);
  3154. /* Allocate space for argument, quotes (if needed), and terminator */
  3155. formatted_arg = tor_calloc(sizeof(char),
  3156. (smartlist_len(arg_chars) + (need_quotes ? 2 : 0) + 1));
  3157. /* Add leading quote */
  3158. i=0;
  3159. if (need_quotes)
  3160. formatted_arg[i++] = '"';
  3161. /* Add characters */
  3162. SMARTLIST_FOREACH(arg_chars, char*, c,
  3163. {
  3164. formatted_arg[i++] = *c;
  3165. });
  3166. /* Add trailing quote */
  3167. if (need_quotes)
  3168. formatted_arg[i++] = '"';
  3169. formatted_arg[i] = '\0';
  3170. smartlist_free(arg_chars);
  3171. return formatted_arg;
  3172. }
  3173. /** Format a command line for use on Windows, which takes the command as a
  3174. * string rather than string array. Follows the rules from "Parsing C++
  3175. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  3176. * Python subprocess module. Returns a newly allocated string */
  3177. char *
  3178. tor_join_win_cmdline(const char *argv[])
  3179. {
  3180. smartlist_t *argv_list;
  3181. char *joined_argv;
  3182. int i;
  3183. /* Format each argument and put the result in a smartlist */
  3184. argv_list = smartlist_new();
  3185. for (i=0; argv[i] != NULL; i++) {
  3186. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  3187. }
  3188. /* Join the arguments with whitespace */
  3189. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  3190. /* Free the newly allocated arguments, and the smartlist */
  3191. SMARTLIST_FOREACH(argv_list, char *, arg,
  3192. {
  3193. tor_free(arg);
  3194. });
  3195. smartlist_free(argv_list);
  3196. return joined_argv;
  3197. }
  3198. /* As format_{hex,dex}_number_sigsafe, but takes a <b>radix</b> argument
  3199. * in range 2..16 inclusive. */
  3200. static int
  3201. format_number_sigsafe(unsigned long x, char *buf, int buf_len,
  3202. unsigned int radix)
  3203. {
  3204. unsigned long tmp;
  3205. int len;
  3206. char *cp;
  3207. /* NOT tor_assert. This needs to be safe to run from within a signal handler,
  3208. * and from within the 'tor_assert() has failed' code. */
  3209. if (radix < 2 || radix > 16)
  3210. return 0;
  3211. /* Count how many digits we need. */
  3212. tmp = x;
  3213. len = 1;
  3214. while (tmp >= radix) {
  3215. tmp /= radix;
  3216. ++len;
  3217. }
  3218. /* Not long enough */
  3219. if (!buf || len >= buf_len)
  3220. return 0;
  3221. cp = buf + len;
  3222. *cp = '\0';
  3223. do {
  3224. unsigned digit = (unsigned) (x % radix);
  3225. tor_assert(cp > buf);
  3226. --cp;
  3227. *cp = "0123456789ABCDEF"[digit];
  3228. x /= radix;
  3229. } while (x);
  3230. /* NOT tor_assert; see above. */
  3231. if (cp != buf) {
  3232. abort();
  3233. }
  3234. return len;
  3235. }
  3236. /**
  3237. * Helper function to output hex numbers from within a signal handler.
  3238. *
  3239. * Writes the nul-terminated hexadecimal digits of <b>x</b> into a buffer
  3240. * <b>buf</b> of size <b>buf_len</b>, and return the actual number of digits
  3241. * written, not counting the terminal NUL.
  3242. *
  3243. * If there is insufficient space, write nothing and return 0.
  3244. *
  3245. * This accepts an unsigned int because format_helper_exit_status() needs to
  3246. * call it with a signed int and an unsigned char, and since the C standard
  3247. * does not guarantee that an int is wider than a char (an int must be at
  3248. * least 16 bits but it is permitted for a char to be that wide as well), we
  3249. * can't assume a signed int is sufficient to accomodate an unsigned char.
  3250. * Thus, format_helper_exit_status() will still need to emit any require '-'
  3251. * on its own.
  3252. *
  3253. * For most purposes, you'd want to use tor_snprintf("%x") instead of this
  3254. * function; it's designed to be used in code paths where you can't call
  3255. * arbitrary C functions.
  3256. */
  3257. int
  3258. format_hex_number_sigsafe(unsigned long x, char *buf, int buf_len)
  3259. {
  3260. return format_number_sigsafe(x, buf, buf_len, 16);
  3261. }
  3262. /** As format_hex_number_sigsafe, but format the number in base 10. */
  3263. int
  3264. format_dec_number_sigsafe(unsigned long x, char *buf, int buf_len)
  3265. {
  3266. return format_number_sigsafe(x, buf, buf_len, 10);
  3267. }
  3268. #ifndef _WIN32
  3269. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  3270. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  3271. * safe.
  3272. *
  3273. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE+1 bytes available.
  3274. *
  3275. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  3276. * with spaces. CHILD_STATE indicates where
  3277. * in the processs of starting the child process did the failure occur (see
  3278. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  3279. * errno when the failure occurred.
  3280. *
  3281. * On success return the number of characters added to hex_errno, not counting
  3282. * the terminating NUL; return -1 on error.
  3283. */
  3284. STATIC int
  3285. format_helper_exit_status(unsigned char child_state, int saved_errno,
  3286. char *hex_errno)
  3287. {
  3288. unsigned int unsigned_errno;
  3289. int written, left;
  3290. char *cur;
  3291. size_t i;
  3292. int res = -1;
  3293. /* Fill hex_errno with spaces, and a trailing newline (memset may
  3294. not be signal handler safe, so we can't use it) */
  3295. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  3296. hex_errno[i] = ' ';
  3297. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  3298. /* Convert errno to be unsigned for hex conversion */
  3299. if (saved_errno < 0) {
  3300. // Avoid overflow on the cast to unsigned int when result is INT_MIN
  3301. // by adding 1 to the signed int negative value,
  3302. // then, after it has been negated and cast to unsigned,
  3303. // adding the original 1 back (the double-addition is intentional).
  3304. // Otherwise, the cast to signed could cause a temporary int
  3305. // to equal INT_MAX + 1, which is undefined.
  3306. unsigned_errno = ((unsigned int) -(saved_errno + 1)) + 1;
  3307. } else {
  3308. unsigned_errno = (unsigned int) saved_errno;
  3309. }
  3310. /*
  3311. * Count how many chars of space we have left, and keep a pointer into the
  3312. * current point in the buffer.
  3313. */
  3314. left = HEX_ERRNO_SIZE+1;
  3315. cur = hex_errno;
  3316. /* Emit child_state */
  3317. written = format_hex_number_sigsafe(child_state, cur, left);
  3318. if (written <= 0)
  3319. goto err;
  3320. /* Adjust left and cur */
  3321. left -= written;
  3322. cur += written;
  3323. if (left <= 0)
  3324. goto err;
  3325. /* Now the '/' */
  3326. *cur = '/';
  3327. /* Adjust left and cur */
  3328. ++cur;
  3329. --left;
  3330. if (left <= 0)
  3331. goto err;
  3332. /* Need minus? */
  3333. if (saved_errno < 0) {
  3334. *cur = '-';
  3335. ++cur;
  3336. --left;
  3337. if (left <= 0)
  3338. goto err;
  3339. }
  3340. /* Emit unsigned_errno */
  3341. written = format_hex_number_sigsafe(unsigned_errno, cur, left);
  3342. if (written <= 0)
  3343. goto err;
  3344. /* Adjust left and cur */
  3345. left -= written;
  3346. cur += written;
  3347. /* Check that we have enough space left for a newline and a NUL */
  3348. if (left <= 1)
  3349. goto err;
  3350. /* Emit the newline and NUL */
  3351. *cur++ = '\n';
  3352. *cur++ = '\0';
  3353. res = (int)(cur - hex_errno - 1);
  3354. goto done;
  3355. err:
  3356. /*
  3357. * In error exit, just write a '\0' in the first char so whatever called
  3358. * this at least won't fall off the end.
  3359. */
  3360. *hex_errno = '\0';
  3361. done:
  3362. return res;
  3363. }
  3364. #endif
  3365. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  3366. #define DEFAULT_MAX_FD 256
  3367. /** Terminate the process of <b>process_handle</b>.
  3368. * Code borrowed from Python's os.kill. */
  3369. int
  3370. tor_terminate_process(process_handle_t *process_handle)
  3371. {
  3372. #ifdef _WIN32
  3373. if (tor_get_exit_code(process_handle, 0, NULL) == PROCESS_EXIT_RUNNING) {
  3374. HANDLE handle = process_handle->pid.hProcess;
  3375. if (!TerminateProcess(handle, 0))
  3376. return -1;
  3377. else
  3378. return 0;
  3379. }
  3380. #else /* Unix */
  3381. if (process_handle->waitpid_cb) {
  3382. /* We haven't got a waitpid yet, so we can just kill off the process. */
  3383. return kill(process_handle->pid, SIGTERM);
  3384. }
  3385. #endif
  3386. return -1;
  3387. }
  3388. /** Return the Process ID of <b>process_handle</b>. */
  3389. int
  3390. tor_process_get_pid(process_handle_t *process_handle)
  3391. {
  3392. #ifdef _WIN32
  3393. return (int) process_handle->pid.dwProcessId;
  3394. #else
  3395. return (int) process_handle->pid;
  3396. #endif
  3397. }
  3398. #ifdef _WIN32
  3399. HANDLE
  3400. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  3401. {
  3402. return process_handle->stdout_pipe;
  3403. }
  3404. #else
  3405. /* DOCDOC tor_process_get_stdout_pipe */
  3406. FILE *
  3407. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  3408. {
  3409. return process_handle->stdout_handle;
  3410. }
  3411. #endif
  3412. /* DOCDOC process_handle_new */
  3413. static process_handle_t *
  3414. process_handle_new(void)
  3415. {
  3416. process_handle_t *out = tor_malloc_zero(sizeof(process_handle_t));
  3417. #ifdef _WIN32
  3418. out->stdout_pipe = INVALID_HANDLE_VALUE;
  3419. out->stderr_pipe = INVALID_HANDLE_VALUE;
  3420. #else
  3421. out->stdout_pipe = -1;
  3422. out->stderr_pipe = -1;
  3423. #endif
  3424. return out;
  3425. }
  3426. #ifndef _WIN32
  3427. /** Invoked when a process that we've launched via tor_spawn_background() has
  3428. * been found to have terminated.
  3429. */
  3430. static void
  3431. process_handle_waitpid_cb(int status, void *arg)
  3432. {
  3433. process_handle_t *process_handle = arg;
  3434. process_handle->waitpid_exit_status = status;
  3435. clear_waitpid_callback(process_handle->waitpid_cb);
  3436. if (process_handle->status == PROCESS_STATUS_RUNNING)
  3437. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  3438. process_handle->waitpid_cb = 0;
  3439. }
  3440. #endif
  3441. /**
  3442. * @name child-process states
  3443. *
  3444. * Each of these values represents a possible state that a child process can
  3445. * be in. They're used to determine what to say when telling the parent how
  3446. * far along we were before failure.
  3447. *
  3448. * @{
  3449. */
  3450. #define CHILD_STATE_INIT 0
  3451. #define CHILD_STATE_PIPE 1
  3452. #define CHILD_STATE_MAXFD 2
  3453. #define CHILD_STATE_FORK 3
  3454. #define CHILD_STATE_DUPOUT 4
  3455. #define CHILD_STATE_DUPERR 5
  3456. #define CHILD_STATE_REDIRECT 6
  3457. #define CHILD_STATE_CLOSEFD 7
  3458. #define CHILD_STATE_EXEC 8
  3459. #define CHILD_STATE_FAILEXEC 9
  3460. /** @} */
  3461. /** Start a program in the background. If <b>filename</b> contains a '/', then
  3462. * it will be treated as an absolute or relative path. Otherwise, on
  3463. * non-Windows systems, the system path will be searched for <b>filename</b>.
  3464. * On Windows, only the current directory will be searched. Here, to search the
  3465. * system path (as well as the application directory, current working
  3466. * directory, and system directories), set filename to NULL.
  3467. *
  3468. * The strings in <b>argv</b> will be passed as the command line arguments of
  3469. * the child program (following convention, argv[0] should normally be the
  3470. * filename of the executable, and this must be the case if <b>filename</b> is
  3471. * NULL). The last element of argv must be NULL. A handle to the child process
  3472. * will be returned in process_handle (which must be non-NULL). Read
  3473. * process_handle.status to find out if the process was successfully launched.
  3474. * For convenience, process_handle.status is returned by this function.
  3475. *
  3476. * Some parts of this code are based on the POSIX subprocess module from
  3477. * Python, and example code from
  3478. * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
  3479. */
  3480. int
  3481. tor_spawn_background(const char *const filename, const char **argv,
  3482. process_environment_t *env,
  3483. process_handle_t **process_handle_out)
  3484. {
  3485. #ifdef _WIN32
  3486. HANDLE stdout_pipe_read = NULL;
  3487. HANDLE stdout_pipe_write = NULL;
  3488. HANDLE stderr_pipe_read = NULL;
  3489. HANDLE stderr_pipe_write = NULL;
  3490. process_handle_t *process_handle;
  3491. int status;
  3492. STARTUPINFOA siStartInfo;
  3493. BOOL retval = FALSE;
  3494. SECURITY_ATTRIBUTES saAttr;
  3495. char *joined_argv;
  3496. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  3497. saAttr.bInheritHandle = TRUE;
  3498. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3499. saAttr.lpSecurityDescriptor = NULL;
  3500. /* Assume failure to start process */
  3501. status = PROCESS_STATUS_ERROR;
  3502. /* Set up pipe for stdout */
  3503. if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, &saAttr, 0)) {
  3504. log_warn(LD_GENERAL,
  3505. "Failed to create pipe for stdout communication with child process: %s",
  3506. format_win32_error(GetLastError()));
  3507. return status;
  3508. }
  3509. if (!SetHandleInformation(stdout_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3510. log_warn(LD_GENERAL,
  3511. "Failed to configure pipe for stdout communication with child "
  3512. "process: %s", format_win32_error(GetLastError()));
  3513. return status;
  3514. }
  3515. /* Set up pipe for stderr */
  3516. if (!CreatePipe(&stderr_pipe_read, &stderr_pipe_write, &saAttr, 0)) {
  3517. log_warn(LD_GENERAL,
  3518. "Failed to create pipe for stderr communication with child process: %s",
  3519. format_win32_error(GetLastError()));
  3520. return status;
  3521. }
  3522. if (!SetHandleInformation(stderr_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3523. log_warn(LD_GENERAL,
  3524. "Failed to configure pipe for stderr communication with child "
  3525. "process: %s", format_win32_error(GetLastError()));
  3526. return status;
  3527. }
  3528. /* Create the child process */
  3529. /* Windows expects argv to be a whitespace delimited string, so join argv up
  3530. */
  3531. joined_argv = tor_join_win_cmdline(argv);
  3532. process_handle = process_handle_new();
  3533. process_handle->status = status;
  3534. ZeroMemory(&(process_handle->pid), sizeof(PROCESS_INFORMATION));
  3535. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  3536. siStartInfo.cb = sizeof(STARTUPINFO);
  3537. siStartInfo.hStdError = stderr_pipe_write;
  3538. siStartInfo.hStdOutput = stdout_pipe_write;
  3539. siStartInfo.hStdInput = NULL;
  3540. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  3541. /* Create the child process */
  3542. retval = CreateProcessA(filename, // module name
  3543. joined_argv, // command line
  3544. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3545. NULL, // process security attributes
  3546. NULL, // primary thread security attributes
  3547. TRUE, // handles are inherited
  3548. /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
  3549. * work?) */
  3550. CREATE_NO_WINDOW, // creation flags
  3551. (env==NULL) ? NULL : env->windows_environment_block,
  3552. NULL, // use parent's current directory
  3553. &siStartInfo, // STARTUPINFO pointer
  3554. &(process_handle->pid)); // receives PROCESS_INFORMATION
  3555. tor_free(joined_argv);
  3556. if (!retval) {
  3557. log_warn(LD_GENERAL,
  3558. "Failed to create child process %s: %s", filename?filename:argv[0],
  3559. format_win32_error(GetLastError()));
  3560. tor_free(process_handle);
  3561. } else {
  3562. /* TODO: Close hProcess and hThread in process_handle->pid? */
  3563. process_handle->stdout_pipe = stdout_pipe_read;
  3564. process_handle->stderr_pipe = stderr_pipe_read;
  3565. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3566. }
  3567. /* TODO: Close pipes on exit */
  3568. *process_handle_out = process_handle;
  3569. return status;
  3570. #else // _WIN32
  3571. pid_t pid;
  3572. int stdout_pipe[2];
  3573. int stderr_pipe[2];
  3574. int fd, retval;
  3575. ssize_t nbytes;
  3576. process_handle_t *process_handle;
  3577. int status;
  3578. const char *error_message = SPAWN_ERROR_MESSAGE;
  3579. size_t error_message_length;
  3580. /* Represents where in the process of spawning the program is;
  3581. this is used for printing out the error message */
  3582. unsigned char child_state = CHILD_STATE_INIT;
  3583. char hex_errno[HEX_ERRNO_SIZE + 2]; /* + 1 should be sufficient actually */
  3584. static int max_fd = -1;
  3585. status = PROCESS_STATUS_ERROR;
  3586. /* We do the strlen here because strlen() is not signal handler safe,
  3587. and we are not allowed to use unsafe functions between fork and exec */
  3588. error_message_length = strlen(error_message);
  3589. child_state = CHILD_STATE_PIPE;
  3590. /* Set up pipe for redirecting stdout and stderr of child */
  3591. retval = pipe(stdout_pipe);
  3592. if (-1 == retval) {
  3593. log_warn(LD_GENERAL,
  3594. "Failed to set up pipe for stdout communication with child process: %s",
  3595. strerror(errno));
  3596. return status;
  3597. }
  3598. retval = pipe(stderr_pipe);
  3599. if (-1 == retval) {
  3600. log_warn(LD_GENERAL,
  3601. "Failed to set up pipe for stderr communication with child process: %s",
  3602. strerror(errno));
  3603. close(stdout_pipe[0]);
  3604. close(stdout_pipe[1]);
  3605. return status;
  3606. }
  3607. child_state = CHILD_STATE_MAXFD;
  3608. #ifdef _SC_OPEN_MAX
  3609. if (-1 == max_fd) {
  3610. max_fd = (int) sysconf(_SC_OPEN_MAX);
  3611. if (max_fd == -1) {
  3612. max_fd = DEFAULT_MAX_FD;
  3613. log_warn(LD_GENERAL,
  3614. "Cannot find maximum file descriptor, assuming %d", max_fd);
  3615. }
  3616. }
  3617. #else
  3618. max_fd = DEFAULT_MAX_FD;
  3619. #endif
  3620. child_state = CHILD_STATE_FORK;
  3621. pid = fork();
  3622. if (0 == pid) {
  3623. /* In child */
  3624. child_state = CHILD_STATE_DUPOUT;
  3625. /* Link child stdout to the write end of the pipe */
  3626. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  3627. if (-1 == retval)
  3628. goto error;
  3629. child_state = CHILD_STATE_DUPERR;
  3630. /* Link child stderr to the write end of the pipe */
  3631. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  3632. if (-1 == retval)
  3633. goto error;
  3634. child_state = CHILD_STATE_REDIRECT;
  3635. /* Link stdin to /dev/null */
  3636. fd = open("/dev/null", O_RDONLY); /* NOT cloexec, obviously. */
  3637. if (fd != -1)
  3638. dup2(fd, STDIN_FILENO);
  3639. else
  3640. goto error;
  3641. child_state = CHILD_STATE_CLOSEFD;
  3642. close(stderr_pipe[0]);
  3643. close(stderr_pipe[1]);
  3644. close(stdout_pipe[0]);
  3645. close(stdout_pipe[1]);
  3646. close(fd);
  3647. /* Close all other fds, including the read end of the pipe */
  3648. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  3649. * this needless. */
  3650. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  3651. close(fd);
  3652. }
  3653. child_state = CHILD_STATE_EXEC;
  3654. /* Call the requested program. We need the cast because
  3655. execvp doesn't define argv as const, even though it
  3656. does not modify the arguments */
  3657. if (env)
  3658. execve(filename, (char *const *) argv, env->unixoid_environment_block);
  3659. else
  3660. execvp(filename, (char *const *) argv);
  3661. /* If we got here, the exec or open(/dev/null) failed */
  3662. child_state = CHILD_STATE_FAILEXEC;
  3663. error:
  3664. {
  3665. /* XXX: are we leaking fds from the pipe? */
  3666. int n;
  3667. n = format_helper_exit_status(child_state, errno, hex_errno);
  3668. if (n >= 0) {
  3669. /* Write the error message. GCC requires that we check the return
  3670. value, but there is nothing we can do if it fails */
  3671. /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
  3672. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  3673. nbytes = write(STDOUT_FILENO, hex_errno, n);
  3674. }
  3675. }
  3676. (void) nbytes;
  3677. _exit(255);
  3678. /* Never reached, but avoids compiler warning */
  3679. return status;
  3680. }
  3681. /* In parent */
  3682. if (-1 == pid) {
  3683. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  3684. close(stdout_pipe[0]);
  3685. close(stdout_pipe[1]);
  3686. close(stderr_pipe[0]);
  3687. close(stderr_pipe[1]);
  3688. return status;
  3689. }
  3690. process_handle = process_handle_new();
  3691. process_handle->status = status;
  3692. process_handle->pid = pid;
  3693. /* TODO: If the child process forked but failed to exec, waitpid it */
  3694. /* Return read end of the pipes to caller, and close write end */
  3695. process_handle->stdout_pipe = stdout_pipe[0];
  3696. retval = close(stdout_pipe[1]);
  3697. if (-1 == retval) {
  3698. log_warn(LD_GENERAL,
  3699. "Failed to close write end of stdout pipe in parent process: %s",
  3700. strerror(errno));
  3701. }
  3702. process_handle->waitpid_cb = set_waitpid_callback(pid,
  3703. process_handle_waitpid_cb,
  3704. process_handle);
  3705. process_handle->stderr_pipe = stderr_pipe[0];
  3706. retval = close(stderr_pipe[1]);
  3707. if (-1 == retval) {
  3708. log_warn(LD_GENERAL,
  3709. "Failed to close write end of stderr pipe in parent process: %s",
  3710. strerror(errno));
  3711. }
  3712. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3713. /* Set stdout/stderr pipes to be non-blocking */
  3714. if (fcntl(process_handle->stdout_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  3715. fcntl(process_handle->stderr_pipe, F_SETFL, O_NONBLOCK) < 0) {
  3716. log_warn(LD_GENERAL, "Failed to set stderror/stdout pipes nonblocking "
  3717. "in parent process: %s", strerror(errno));
  3718. }
  3719. /* Open the buffered IO streams */
  3720. process_handle->stdout_handle = fdopen(process_handle->stdout_pipe, "r");
  3721. process_handle->stderr_handle = fdopen(process_handle->stderr_pipe, "r");
  3722. *process_handle_out = process_handle;
  3723. return process_handle->status;
  3724. #endif // _WIN32
  3725. }
  3726. /** Destroy all resources allocated by the process handle in
  3727. * <b>process_handle</b>.
  3728. * If <b>also_terminate_process</b> is true, also terminate the
  3729. * process of the process handle. */
  3730. MOCK_IMPL(void,
  3731. tor_process_handle_destroy,(process_handle_t *process_handle,
  3732. int also_terminate_process))
  3733. {
  3734. if (!process_handle)
  3735. return;
  3736. if (also_terminate_process) {
  3737. if (tor_terminate_process(process_handle) < 0) {
  3738. const char *errstr =
  3739. #ifdef _WIN32
  3740. format_win32_error(GetLastError());
  3741. #else
  3742. strerror(errno);
  3743. #endif
  3744. log_notice(LD_GENERAL, "Failed to terminate process with "
  3745. "PID '%d' ('%s').", tor_process_get_pid(process_handle),
  3746. errstr);
  3747. } else {
  3748. log_info(LD_GENERAL, "Terminated process with PID '%d'.",
  3749. tor_process_get_pid(process_handle));
  3750. }
  3751. }
  3752. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  3753. #ifdef _WIN32
  3754. if (process_handle->stdout_pipe)
  3755. CloseHandle(process_handle->stdout_pipe);
  3756. if (process_handle->stderr_pipe)
  3757. CloseHandle(process_handle->stderr_pipe);
  3758. #else
  3759. if (process_handle->stdout_handle)
  3760. fclose(process_handle->stdout_handle);
  3761. if (process_handle->stderr_handle)
  3762. fclose(process_handle->stderr_handle);
  3763. clear_waitpid_callback(process_handle->waitpid_cb);
  3764. #endif
  3765. memset(process_handle, 0x0f, sizeof(process_handle_t));
  3766. tor_free(process_handle);
  3767. }
  3768. /** Get the exit code of a process specified by <b>process_handle</b> and store
  3769. * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
  3770. * to true, the call will block until the process has exited. Otherwise if
  3771. * the process is still running, the function will return
  3772. * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
  3773. * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
  3774. * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
  3775. * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
  3776. * probably not work in Tor, because waitpid() is called in main.c to reap any
  3777. * terminated child processes.*/
  3778. int
  3779. tor_get_exit_code(process_handle_t *process_handle,
  3780. int block, int *exit_code)
  3781. {
  3782. #ifdef _WIN32
  3783. DWORD retval;
  3784. BOOL success;
  3785. if (block) {
  3786. /* Wait for the process to exit */
  3787. retval = WaitForSingleObject(process_handle->pid.hProcess, INFINITE);
  3788. if (retval != WAIT_OBJECT_0) {
  3789. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3790. (int)retval, format_win32_error(GetLastError()));
  3791. return PROCESS_EXIT_ERROR;
  3792. }
  3793. } else {
  3794. retval = WaitForSingleObject(process_handle->pid.hProcess, 0);
  3795. if (WAIT_TIMEOUT == retval) {
  3796. /* Process has not exited */
  3797. return PROCESS_EXIT_RUNNING;
  3798. } else if (retval != WAIT_OBJECT_0) {
  3799. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3800. (int)retval, format_win32_error(GetLastError()));
  3801. return PROCESS_EXIT_ERROR;
  3802. }
  3803. }
  3804. if (exit_code != NULL) {
  3805. success = GetExitCodeProcess(process_handle->pid.hProcess,
  3806. (PDWORD)exit_code);
  3807. if (!success) {
  3808. log_warn(LD_GENERAL, "GetExitCodeProcess() failed: %s",
  3809. format_win32_error(GetLastError()));
  3810. return PROCESS_EXIT_ERROR;
  3811. }
  3812. }
  3813. #else
  3814. int stat_loc;
  3815. int retval;
  3816. if (process_handle->waitpid_cb) {
  3817. /* We haven't processed a SIGCHLD yet. */
  3818. retval = waitpid(process_handle->pid, &stat_loc, block?0:WNOHANG);
  3819. if (retval == process_handle->pid) {
  3820. clear_waitpid_callback(process_handle->waitpid_cb);
  3821. process_handle->waitpid_cb = NULL;
  3822. process_handle->waitpid_exit_status = stat_loc;
  3823. }
  3824. } else {
  3825. /* We already got a SIGCHLD for this process, and handled it. */
  3826. retval = process_handle->pid;
  3827. stat_loc = process_handle->waitpid_exit_status;
  3828. }
  3829. if (!block && 0 == retval) {
  3830. /* Process has not exited */
  3831. return PROCESS_EXIT_RUNNING;
  3832. } else if (retval != process_handle->pid) {
  3833. log_warn(LD_GENERAL, "waitpid() failed for PID %d: %s",
  3834. process_handle->pid, strerror(errno));
  3835. return PROCESS_EXIT_ERROR;
  3836. }
  3837. if (!WIFEXITED(stat_loc)) {
  3838. log_warn(LD_GENERAL, "Process %d did not exit normally",
  3839. process_handle->pid);
  3840. return PROCESS_EXIT_ERROR;
  3841. }
  3842. if (exit_code != NULL)
  3843. *exit_code = WEXITSTATUS(stat_loc);
  3844. #endif // _WIN32
  3845. return PROCESS_EXIT_EXITED;
  3846. }
  3847. /** Helper: return the number of characters in <b>s</b> preceding the first
  3848. * occurrence of <b>ch</b>. If <b>ch</b> does not occur in <b>s</b>, return
  3849. * the length of <b>s</b>. Should be equivalent to strspn(s, "ch"). */
  3850. static INLINE size_t
  3851. str_num_before(const char *s, char ch)
  3852. {
  3853. const char *cp = strchr(s, ch);
  3854. if (cp)
  3855. return cp - s;
  3856. else
  3857. return strlen(s);
  3858. }
  3859. /** Return non-zero iff getenv would consider <b>s1</b> and <b>s2</b>
  3860. * to have the same name as strings in a process's environment. */
  3861. int
  3862. environment_variable_names_equal(const char *s1, const char *s2)
  3863. {
  3864. size_t s1_name_len = str_num_before(s1, '=');
  3865. size_t s2_name_len = str_num_before(s2, '=');
  3866. return (s1_name_len == s2_name_len &&
  3867. tor_memeq(s1, s2, s1_name_len));
  3868. }
  3869. /** Free <b>env</b> (assuming it was produced by
  3870. * process_environment_make). */
  3871. void
  3872. process_environment_free(process_environment_t *env)
  3873. {
  3874. if (env == NULL) return;
  3875. /* As both an optimization hack to reduce consing on Unixoid systems
  3876. * and a nice way to ensure that some otherwise-Windows-specific
  3877. * code will always get tested before changes to it get merged, the
  3878. * strings which env->unixoid_environment_block points to are packed
  3879. * into env->windows_environment_block. */
  3880. tor_free(env->unixoid_environment_block);
  3881. tor_free(env->windows_environment_block);
  3882. tor_free(env);
  3883. }
  3884. /** Make a process_environment_t containing the environment variables
  3885. * specified in <b>env_vars</b> (as C strings of the form
  3886. * "NAME=VALUE"). */
  3887. process_environment_t *
  3888. process_environment_make(struct smartlist_t *env_vars)
  3889. {
  3890. process_environment_t *env = tor_malloc_zero(sizeof(process_environment_t));
  3891. size_t n_env_vars = smartlist_len(env_vars);
  3892. size_t i;
  3893. size_t total_env_length;
  3894. smartlist_t *env_vars_sorted;
  3895. tor_assert(n_env_vars + 1 != 0);
  3896. env->unixoid_environment_block = tor_calloc(n_env_vars + 1, sizeof(char *));
  3897. /* env->unixoid_environment_block is already NULL-terminated,
  3898. * because we assume that NULL == 0 (and check that during compilation). */
  3899. total_env_length = 1; /* terminating NUL of terminating empty string */
  3900. for (i = 0; i < n_env_vars; ++i) {
  3901. const char *s = smartlist_get(env_vars, i);
  3902. size_t slen = strlen(s);
  3903. tor_assert(slen + 1 != 0);
  3904. tor_assert(slen + 1 < SIZE_MAX - total_env_length);
  3905. total_env_length += slen + 1;
  3906. }
  3907. env->windows_environment_block = tor_malloc_zero(total_env_length);
  3908. /* env->windows_environment_block is already
  3909. * (NUL-terminated-empty-string)-terminated. */
  3910. /* Some versions of Windows supposedly require that environment
  3911. * blocks be sorted. Or maybe some Windows programs (or their
  3912. * runtime libraries) fail to look up strings in non-sorted
  3913. * environment blocks.
  3914. *
  3915. * Also, sorting strings makes it easy to find duplicate environment
  3916. * variables and environment-variable strings without an '=' on all
  3917. * OSes, and they can cause badness. Let's complain about those. */
  3918. env_vars_sorted = smartlist_new();
  3919. smartlist_add_all(env_vars_sorted, env_vars);
  3920. smartlist_sort_strings(env_vars_sorted);
  3921. /* Now copy the strings into the environment blocks. */
  3922. {
  3923. char *cp = env->windows_environment_block;
  3924. const char *prev_env_var = NULL;
  3925. for (i = 0; i < n_env_vars; ++i) {
  3926. const char *s = smartlist_get(env_vars_sorted, i);
  3927. size_t slen = strlen(s);
  3928. size_t s_name_len = str_num_before(s, '=');
  3929. if (s_name_len == slen) {
  3930. log_warn(LD_GENERAL,
  3931. "Preparing an environment containing a variable "
  3932. "without a value: %s",
  3933. s);
  3934. }
  3935. if (prev_env_var != NULL &&
  3936. environment_variable_names_equal(s, prev_env_var)) {
  3937. log_warn(LD_GENERAL,
  3938. "Preparing an environment containing two variables "
  3939. "with the same name: %s and %s",
  3940. prev_env_var, s);
  3941. }
  3942. prev_env_var = s;
  3943. /* Actually copy the string into the environment. */
  3944. memcpy(cp, s, slen+1);
  3945. env->unixoid_environment_block[i] = cp;
  3946. cp += slen+1;
  3947. }
  3948. tor_assert(cp == env->windows_environment_block + total_env_length - 1);
  3949. }
  3950. smartlist_free(env_vars_sorted);
  3951. return env;
  3952. }
  3953. /** Return a newly allocated smartlist containing every variable in
  3954. * this process's environment, as a NUL-terminated string of the form
  3955. * "NAME=VALUE". Note that on some/many/most/all OSes, the parent
  3956. * process can put strings not of that form in our environment;
  3957. * callers should try to not get crashed by that.
  3958. *
  3959. * The returned strings are heap-allocated, and must be freed by the
  3960. * caller. */
  3961. struct smartlist_t *
  3962. get_current_process_environment_variables(void)
  3963. {
  3964. smartlist_t *sl = smartlist_new();
  3965. char **environ_tmp; /* Not const char ** ? Really? */
  3966. for (environ_tmp = get_environment(); *environ_tmp; ++environ_tmp) {
  3967. smartlist_add(sl, tor_strdup(*environ_tmp));
  3968. }
  3969. return sl;
  3970. }
  3971. /** For each string s in <b>env_vars</b> such that
  3972. * environment_variable_names_equal(s, <b>new_var</b>), remove it; if
  3973. * <b>free_p</b> is non-zero, call <b>free_old</b>(s). If
  3974. * <b>new_var</b> contains '=', insert it into <b>env_vars</b>. */
  3975. void
  3976. set_environment_variable_in_smartlist(struct smartlist_t *env_vars,
  3977. const char *new_var,
  3978. void (*free_old)(void*),
  3979. int free_p)
  3980. {
  3981. SMARTLIST_FOREACH_BEGIN(env_vars, const char *, s) {
  3982. if (environment_variable_names_equal(s, new_var)) {
  3983. SMARTLIST_DEL_CURRENT(env_vars, s);
  3984. if (free_p) {
  3985. free_old((void *)s);
  3986. }
  3987. }
  3988. } SMARTLIST_FOREACH_END(s);
  3989. if (strchr(new_var, '=') != NULL) {
  3990. smartlist_add(env_vars, (void *)new_var);
  3991. }
  3992. }
  3993. #ifdef _WIN32
  3994. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3995. * <b>hProcess</b> is NULL, the function will return immediately if there is
  3996. * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
  3997. * to the process owning the <b>h</b>. In this case, the function will exit
  3998. * only once the process has exited, or <b>count</b> bytes are read. Returns
  3999. * the number of bytes read, or -1 on error. */
  4000. ssize_t
  4001. tor_read_all_handle(HANDLE h, char *buf, size_t count,
  4002. const process_handle_t *process)
  4003. {
  4004. size_t numread = 0;
  4005. BOOL retval;
  4006. DWORD byte_count;
  4007. BOOL process_exited = FALSE;
  4008. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  4009. return -1;
  4010. while (numread != count) {
  4011. /* Check if there is anything to read */
  4012. retval = PeekNamedPipe(h, NULL, 0, NULL, &byte_count, NULL);
  4013. if (!retval) {
  4014. log_warn(LD_GENERAL,
  4015. "Failed to peek from handle: %s",
  4016. format_win32_error(GetLastError()));
  4017. return -1;
  4018. } else if (0 == byte_count) {
  4019. /* Nothing available: process exited or it is busy */
  4020. /* Exit if we don't know whether the process is running */
  4021. if (NULL == process)
  4022. break;
  4023. /* The process exited and there's nothing left to read from it */
  4024. if (process_exited)
  4025. break;
  4026. /* If process is not running, check for output one more time in case
  4027. it wrote something after the peek was performed. Otherwise keep on
  4028. waiting for output */
  4029. tor_assert(process != NULL);
  4030. byte_count = WaitForSingleObject(process->pid.hProcess, 0);
  4031. if (WAIT_TIMEOUT != byte_count)
  4032. process_exited = TRUE;
  4033. continue;
  4034. }
  4035. /* There is data to read; read it */
  4036. retval = ReadFile(h, buf+numread, count-numread, &byte_count, NULL);
  4037. tor_assert(byte_count + numread <= count);
  4038. if (!retval) {
  4039. log_warn(LD_GENERAL, "Failed to read from handle: %s",
  4040. format_win32_error(GetLastError()));
  4041. return -1;
  4042. } else if (0 == byte_count) {
  4043. /* End of file */
  4044. break;
  4045. }
  4046. numread += byte_count;
  4047. }
  4048. return (ssize_t)numread;
  4049. }
  4050. #else
  4051. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  4052. * <b>process</b> is NULL, the function will return immediately if there is
  4053. * nothing more to read. Otherwise data will be read until end of file, or
  4054. * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
  4055. * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
  4056. * file has been reached. */
  4057. ssize_t
  4058. tor_read_all_handle(FILE *h, char *buf, size_t count,
  4059. const process_handle_t *process,
  4060. int *eof)
  4061. {
  4062. size_t numread = 0;
  4063. char *retval;
  4064. if (eof)
  4065. *eof = 0;
  4066. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  4067. return -1;
  4068. while (numread != count) {
  4069. /* Use fgets because that is what we use in log_from_pipe() */
  4070. retval = fgets(buf+numread, (int)(count-numread), h);
  4071. if (NULL == retval) {
  4072. if (feof(h)) {
  4073. log_debug(LD_GENERAL, "fgets() reached end of file");
  4074. if (eof)
  4075. *eof = 1;
  4076. break;
  4077. } else {
  4078. if (EAGAIN == errno) {
  4079. if (process)
  4080. continue;
  4081. else
  4082. break;
  4083. } else {
  4084. log_warn(LD_GENERAL, "fgets() from handle failed: %s",
  4085. strerror(errno));
  4086. return -1;
  4087. }
  4088. }
  4089. }
  4090. tor_assert(retval != NULL);
  4091. tor_assert(strlen(retval) + numread <= count);
  4092. numread += strlen(retval);
  4093. }
  4094. log_debug(LD_GENERAL, "fgets() read %d bytes from handle", (int)numread);
  4095. return (ssize_t)numread;
  4096. }
  4097. #endif
  4098. /** Read from stdout of a process until the process exits. */
  4099. ssize_t
  4100. tor_read_all_from_process_stdout(const process_handle_t *process_handle,
  4101. char *buf, size_t count)
  4102. {
  4103. #ifdef _WIN32
  4104. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  4105. process_handle);
  4106. #else
  4107. return tor_read_all_handle(process_handle->stdout_handle, buf, count,
  4108. process_handle, NULL);
  4109. #endif
  4110. }
  4111. /** Read from stdout of a process until the process exits. */
  4112. ssize_t
  4113. tor_read_all_from_process_stderr(const process_handle_t *process_handle,
  4114. char *buf, size_t count)
  4115. {
  4116. #ifdef _WIN32
  4117. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  4118. process_handle);
  4119. #else
  4120. return tor_read_all_handle(process_handle->stderr_handle, buf, count,
  4121. process_handle, NULL);
  4122. #endif
  4123. }
  4124. /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
  4125. * modified. The resulting smartlist will consist of pointers to buf, so there
  4126. * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
  4127. * string. <b>len</b> should be set to the length of the buffer excluding the
  4128. * NUL. Non-printable characters (including NUL) will be replaced with "." */
  4129. int
  4130. tor_split_lines(smartlist_t *sl, char *buf, int len)
  4131. {
  4132. /* Index in buf of the start of the current line */
  4133. int start = 0;
  4134. /* Index in buf of the current character being processed */
  4135. int cur = 0;
  4136. /* Are we currently in a line */
  4137. char in_line = 0;
  4138. /* Loop over string */
  4139. while (cur < len) {
  4140. /* Loop until end of line or end of string */
  4141. for (; cur < len; cur++) {
  4142. if (in_line) {
  4143. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  4144. /* End of line */
  4145. buf[cur] = '\0';
  4146. /* Point cur to the next line */
  4147. cur++;
  4148. /* Line starts at start and ends with a nul */
  4149. break;
  4150. } else {
  4151. if (!TOR_ISPRINT(buf[cur]))
  4152. buf[cur] = '.';
  4153. }
  4154. } else {
  4155. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  4156. /* Skip leading vertical space */
  4157. ;
  4158. } else {
  4159. in_line = 1;
  4160. start = cur;
  4161. if (!TOR_ISPRINT(buf[cur]))
  4162. buf[cur] = '.';
  4163. }
  4164. }
  4165. }
  4166. /* We are at the end of the line or end of string. If in_line is true there
  4167. * is a line which starts at buf+start and ends at a NUL. cur points to
  4168. * the character after the NUL. */
  4169. if (in_line)
  4170. smartlist_add(sl, (void *)(buf+start));
  4171. in_line = 0;
  4172. }
  4173. return smartlist_len(sl);
  4174. }
  4175. /** Return a string corresponding to <b>stream_status</b>. */
  4176. const char *
  4177. stream_status_to_string(enum stream_status stream_status)
  4178. {
  4179. switch (stream_status) {
  4180. case IO_STREAM_OKAY:
  4181. return "okay";
  4182. case IO_STREAM_EAGAIN:
  4183. return "temporarily unavailable";
  4184. case IO_STREAM_TERM:
  4185. return "terminated";
  4186. case IO_STREAM_CLOSED:
  4187. return "closed";
  4188. default:
  4189. tor_fragile_assert();
  4190. return "unknown";
  4191. }
  4192. }
  4193. /* DOCDOC */
  4194. static void
  4195. log_portfw_spawn_error_message(const char *buf,
  4196. const char *executable, int *child_status)
  4197. {
  4198. /* Parse error message */
  4199. int retval, child_state, saved_errno;
  4200. retval = tor_sscanf(buf, SPAWN_ERROR_MESSAGE "%x/%x",
  4201. &child_state, &saved_errno);
  4202. if (retval == 2) {
  4203. log_warn(LD_GENERAL,
  4204. "Failed to start child process \"%s\" in state %d: %s",
  4205. executable, child_state, strerror(saved_errno));
  4206. if (child_status)
  4207. *child_status = 1;
  4208. } else {
  4209. /* Failed to parse message from child process, log it as a
  4210. warning */
  4211. log_warn(LD_GENERAL,
  4212. "Unexpected message from port forwarding helper \"%s\": %s",
  4213. executable, buf);
  4214. }
  4215. }
  4216. #ifdef _WIN32
  4217. /** Return a smartlist containing lines outputted from
  4218. * <b>handle</b>. Return NULL on error, and set
  4219. * <b>stream_status_out</b> appropriately. */
  4220. MOCK_IMPL(smartlist_t *,
  4221. tor_get_lines_from_handle, (HANDLE *handle,
  4222. enum stream_status *stream_status_out))
  4223. {
  4224. int pos;
  4225. char stdout_buf[600] = {0};
  4226. smartlist_t *lines = NULL;
  4227. tor_assert(stream_status_out);
  4228. *stream_status_out = IO_STREAM_TERM;
  4229. pos = tor_read_all_handle(handle, stdout_buf, sizeof(stdout_buf) - 1, NULL);
  4230. if (pos < 0) {
  4231. *stream_status_out = IO_STREAM_TERM;
  4232. return NULL;
  4233. }
  4234. if (pos == 0) {
  4235. *stream_status_out = IO_STREAM_EAGAIN;
  4236. return NULL;
  4237. }
  4238. /* End with a null even if there isn't a \r\n at the end */
  4239. /* TODO: What if this is a partial line? */
  4240. stdout_buf[pos] = '\0';
  4241. /* Split up the buffer */
  4242. lines = smartlist_new();
  4243. tor_split_lines(lines, stdout_buf, pos);
  4244. /* Currently 'lines' is populated with strings residing on the
  4245. stack. Replace them with their exact copies on the heap: */
  4246. SMARTLIST_FOREACH(lines, char *, line,
  4247. SMARTLIST_REPLACE_CURRENT(lines, line, tor_strdup(line)));
  4248. *stream_status_out = IO_STREAM_OKAY;
  4249. return lines;
  4250. }
  4251. /** Read from stream, and send lines to log at the specified log level.
  4252. * Returns -1 if there is a error reading, and 0 otherwise.
  4253. * If the generated stream is flushed more often than on new lines, or
  4254. * a read exceeds 256 bytes, lines will be truncated. This should be fixed,
  4255. * along with the corresponding problem on *nix (see bug #2045).
  4256. */
  4257. static int
  4258. log_from_handle(HANDLE *pipe, int severity)
  4259. {
  4260. char buf[256];
  4261. int pos;
  4262. smartlist_t *lines;
  4263. pos = tor_read_all_handle(pipe, buf, sizeof(buf) - 1, NULL);
  4264. if (pos < 0) {
  4265. /* Error */
  4266. log_warn(LD_GENERAL, "Failed to read data from subprocess");
  4267. return -1;
  4268. }
  4269. if (0 == pos) {
  4270. /* There's nothing to read (process is busy or has exited) */
  4271. log_debug(LD_GENERAL, "Subprocess had nothing to say");
  4272. return 0;
  4273. }
  4274. /* End with a null even if there isn't a \r\n at the end */
  4275. /* TODO: What if this is a partial line? */
  4276. buf[pos] = '\0';
  4277. log_debug(LD_GENERAL, "Subprocess had %d bytes to say", pos);
  4278. /* Split up the buffer */
  4279. lines = smartlist_new();
  4280. tor_split_lines(lines, buf, pos);
  4281. /* Log each line */
  4282. SMARTLIST_FOREACH(lines, char *, line,
  4283. {
  4284. log_fn(severity, LD_GENERAL, "Port forwarding helper says: %s", line);
  4285. });
  4286. smartlist_free(lines);
  4287. return 0;
  4288. }
  4289. #else
  4290. /** Return a smartlist containing lines outputted from
  4291. * <b>handle</b>. Return NULL on error, and set
  4292. * <b>stream_status_out</b> appropriately. */
  4293. MOCK_IMPL(smartlist_t *,
  4294. tor_get_lines_from_handle, (FILE *handle,
  4295. enum stream_status *stream_status_out))
  4296. {
  4297. enum stream_status stream_status;
  4298. char stdout_buf[400];
  4299. smartlist_t *lines = NULL;
  4300. while (1) {
  4301. memset(stdout_buf, 0, sizeof(stdout_buf));
  4302. stream_status = get_string_from_pipe(handle,
  4303. stdout_buf, sizeof(stdout_buf) - 1);
  4304. if (stream_status != IO_STREAM_OKAY)
  4305. goto done;
  4306. if (!lines) lines = smartlist_new();
  4307. smartlist_add(lines, tor_strdup(stdout_buf));
  4308. }
  4309. done:
  4310. *stream_status_out = stream_status;
  4311. return lines;
  4312. }
  4313. /** Read from stream, and send lines to log at the specified log level.
  4314. * Returns 1 if stream is closed normally, -1 if there is a error reading, and
  4315. * 0 otherwise. Handles lines from tor-fw-helper and
  4316. * tor_spawn_background() specially.
  4317. */
  4318. static int
  4319. log_from_pipe(FILE *stream, int severity, const char *executable,
  4320. int *child_status)
  4321. {
  4322. char buf[256];
  4323. enum stream_status r;
  4324. for (;;) {
  4325. r = get_string_from_pipe(stream, buf, sizeof(buf) - 1);
  4326. if (r == IO_STREAM_CLOSED) {
  4327. return 1;
  4328. } else if (r == IO_STREAM_EAGAIN) {
  4329. return 0;
  4330. } else if (r == IO_STREAM_TERM) {
  4331. return -1;
  4332. }
  4333. tor_assert(r == IO_STREAM_OKAY);
  4334. /* Check if buf starts with SPAWN_ERROR_MESSAGE */
  4335. if (strcmpstart(buf, SPAWN_ERROR_MESSAGE) == 0) {
  4336. log_portfw_spawn_error_message(buf, executable, child_status);
  4337. } else {
  4338. log_fn(severity, LD_GENERAL, "Port forwarding helper says: %s", buf);
  4339. }
  4340. }
  4341. /* We should never get here */
  4342. return -1;
  4343. }
  4344. #endif
  4345. /** Reads from <b>stream</b> and stores input in <b>buf_out</b> making
  4346. * sure it's below <b>count</b> bytes.
  4347. * If the string has a trailing newline, we strip it off.
  4348. *
  4349. * This function is specifically created to handle input from managed
  4350. * proxies, according to the pluggable transports spec. Make sure it
  4351. * fits your needs before using it.
  4352. *
  4353. * Returns:
  4354. * IO_STREAM_CLOSED: If the stream is closed.
  4355. * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
  4356. * later.
  4357. * IO_STREAM_TERM: If something is wrong with the stream.
  4358. * IO_STREAM_OKAY: If everything went okay and we got a string
  4359. * in <b>buf_out</b>. */
  4360. enum stream_status
  4361. get_string_from_pipe(FILE *stream, char *buf_out, size_t count)
  4362. {
  4363. char *retval;
  4364. size_t len;
  4365. tor_assert(count <= INT_MAX);
  4366. retval = fgets(buf_out, (int)count, stream);
  4367. if (!retval) {
  4368. if (feof(stream)) {
  4369. /* Program has closed stream (probably it exited) */
  4370. /* TODO: check error */
  4371. return IO_STREAM_CLOSED;
  4372. } else {
  4373. if (EAGAIN == errno) {
  4374. /* Nothing more to read, try again next time */
  4375. return IO_STREAM_EAGAIN;
  4376. } else {
  4377. /* There was a problem, abandon this child process */
  4378. return IO_STREAM_TERM;
  4379. }
  4380. }
  4381. } else {
  4382. len = strlen(buf_out);
  4383. if (len == 0) {
  4384. /* this probably means we got a NUL at the start of the string. */
  4385. return IO_STREAM_EAGAIN;
  4386. }
  4387. if (buf_out[len - 1] == '\n') {
  4388. /* Remove the trailing newline */
  4389. buf_out[len - 1] = '\0';
  4390. } else {
  4391. /* No newline; check whether we overflowed the buffer */
  4392. if (!feof(stream))
  4393. log_info(LD_GENERAL,
  4394. "Line from stream was truncated: %s", buf_out);
  4395. /* TODO: What to do with this error? */
  4396. }
  4397. return IO_STREAM_OKAY;
  4398. }
  4399. /* We should never get here */
  4400. return IO_STREAM_TERM;
  4401. }
  4402. /** Parse a <b>line</b> from tor-fw-helper and issue an appropriate
  4403. * log message to our user. */
  4404. static void
  4405. handle_fw_helper_line(const char *executable, const char *line)
  4406. {
  4407. smartlist_t *tokens = smartlist_new();
  4408. char *message = NULL;
  4409. char *message_for_log = NULL;
  4410. const char *external_port = NULL;
  4411. const char *internal_port = NULL;
  4412. const char *result = NULL;
  4413. int port = 0;
  4414. int success = 0;
  4415. if (strcmpstart(line, SPAWN_ERROR_MESSAGE) == 0) {
  4416. /* We need to check for SPAWN_ERROR_MESSAGE again here, since it's
  4417. * possible that it got sent after we tried to read it in log_from_pipe.
  4418. *
  4419. * XXX Ideally, we should be using one of stdout/stderr for the real
  4420. * output, and one for the output of the startup code. We used to do that
  4421. * before cd05f35d2c.
  4422. */
  4423. int child_status;
  4424. log_portfw_spawn_error_message(line, executable, &child_status);
  4425. goto done;
  4426. }
  4427. smartlist_split_string(tokens, line, NULL,
  4428. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4429. if (smartlist_len(tokens) < 5)
  4430. goto err;
  4431. if (strcmp(smartlist_get(tokens, 0), "tor-fw-helper") ||
  4432. strcmp(smartlist_get(tokens, 1), "tcp-forward"))
  4433. goto err;
  4434. external_port = smartlist_get(tokens, 2);
  4435. internal_port = smartlist_get(tokens, 3);
  4436. result = smartlist_get(tokens, 4);
  4437. if (smartlist_len(tokens) > 5) {
  4438. /* If there are more than 5 tokens, they are part of [<message>].
  4439. Let's use a second smartlist to form the whole message;
  4440. strncat loops suck. */
  4441. int i;
  4442. int message_words_n = smartlist_len(tokens) - 5;
  4443. smartlist_t *message_sl = smartlist_new();
  4444. for (i = 0; i < message_words_n; i++)
  4445. smartlist_add(message_sl, smartlist_get(tokens, 5+i));
  4446. tor_assert(smartlist_len(message_sl) > 0);
  4447. message = smartlist_join_strings(message_sl, " ", 0, NULL);
  4448. /* wrap the message in log-friendly wrapping */
  4449. tor_asprintf(&message_for_log, " ('%s')", message);
  4450. smartlist_free(message_sl);
  4451. }
  4452. port = atoi(external_port);
  4453. if (port < 1 || port > 65535)
  4454. goto err;
  4455. port = atoi(internal_port);
  4456. if (port < 1 || port > 65535)
  4457. goto err;
  4458. if (!strcmp(result, "SUCCESS"))
  4459. success = 1;
  4460. else if (!strcmp(result, "FAIL"))
  4461. success = 0;
  4462. else
  4463. goto err;
  4464. if (!success) {
  4465. log_warn(LD_GENERAL, "Tor was unable to forward TCP port '%s' to '%s'%s. "
  4466. "Please make sure that your router supports port "
  4467. "forwarding protocols (like NAT-PMP). Note that if '%s' is "
  4468. "your ORPort, your relay will be unable to receive inbound "
  4469. "traffic.", external_port, internal_port,
  4470. message_for_log ? message_for_log : "",
  4471. internal_port);
  4472. } else {
  4473. log_info(LD_GENERAL,
  4474. "Tor successfully forwarded TCP port '%s' to '%s'%s.",
  4475. external_port, internal_port,
  4476. message_for_log ? message_for_log : "");
  4477. }
  4478. goto done;
  4479. err:
  4480. log_warn(LD_GENERAL, "tor-fw-helper sent us a string we could not "
  4481. "parse (%s).", line);
  4482. done:
  4483. SMARTLIST_FOREACH(tokens, char *, cp, tor_free(cp));
  4484. smartlist_free(tokens);
  4485. tor_free(message);
  4486. tor_free(message_for_log);
  4487. }
  4488. /** Read what tor-fw-helper has to say in its stdout and handle it
  4489. * appropriately */
  4490. static int
  4491. handle_fw_helper_output(const char *executable,
  4492. process_handle_t *process_handle)
  4493. {
  4494. smartlist_t *fw_helper_output = NULL;
  4495. enum stream_status stream_status = 0;
  4496. fw_helper_output =
  4497. tor_get_lines_from_handle(tor_process_get_stdout_pipe(process_handle),
  4498. &stream_status);
  4499. if (!fw_helper_output) { /* didn't get any output from tor-fw-helper */
  4500. /* if EAGAIN we should retry in the future */
  4501. return (stream_status == IO_STREAM_EAGAIN) ? 0 : -1;
  4502. }
  4503. /* Handle the lines we got: */
  4504. SMARTLIST_FOREACH_BEGIN(fw_helper_output, char *, line) {
  4505. handle_fw_helper_line(executable, line);
  4506. tor_free(line);
  4507. } SMARTLIST_FOREACH_END(line);
  4508. smartlist_free(fw_helper_output);
  4509. return 0;
  4510. }
  4511. /** Spawn tor-fw-helper and ask it to forward the ports in
  4512. * <b>ports_to_forward</b>. <b>ports_to_forward</b> contains strings
  4513. * of the form "<external port>:<internal port>", which is the format
  4514. * that tor-fw-helper expects. */
  4515. void
  4516. tor_check_port_forwarding(const char *filename,
  4517. smartlist_t *ports_to_forward,
  4518. time_t now)
  4519. {
  4520. /* When fw-helper succeeds, how long do we wait until running it again */
  4521. #define TIME_TO_EXEC_FWHELPER_SUCCESS 300
  4522. /* When fw-helper failed to start, how long do we wait until running it again
  4523. */
  4524. #define TIME_TO_EXEC_FWHELPER_FAIL 60
  4525. /* Static variables are initialized to zero, so child_handle.status=0
  4526. * which corresponds to it not running on startup */
  4527. static process_handle_t *child_handle=NULL;
  4528. static time_t time_to_run_helper = 0;
  4529. int stderr_status, retval;
  4530. int stdout_status = 0;
  4531. tor_assert(filename);
  4532. /* Start the child, if it is not already running */
  4533. if ((!child_handle || child_handle->status != PROCESS_STATUS_RUNNING) &&
  4534. time_to_run_helper < now) {
  4535. /*tor-fw-helper cli looks like this: tor_fw_helper -p :5555 -p 4555:1111 */
  4536. const char **argv; /* cli arguments */
  4537. int args_n, status;
  4538. int argv_index = 0; /* index inside 'argv' */
  4539. tor_assert(smartlist_len(ports_to_forward) > 0);
  4540. /* check for overflow during 'argv' allocation:
  4541. (len(ports_to_forward)*2 + 2)*sizeof(char*) > SIZE_MAX ==
  4542. len(ports_to_forward) > (((SIZE_MAX/sizeof(char*)) - 2)/2) */
  4543. if ((size_t) smartlist_len(ports_to_forward) >
  4544. (((SIZE_MAX/sizeof(char*)) - 2)/2)) {
  4545. log_warn(LD_GENERAL,
  4546. "Overflow during argv allocation. This shouldn't happen.");
  4547. return;
  4548. }
  4549. /* check for overflow during 'argv_index' increase:
  4550. ((len(ports_to_forward)*2 + 2) > INT_MAX) ==
  4551. len(ports_to_forward) > (INT_MAX - 2)/2 */
  4552. if (smartlist_len(ports_to_forward) > (INT_MAX - 2)/2) {
  4553. log_warn(LD_GENERAL,
  4554. "Overflow during argv_index increase. This shouldn't happen.");
  4555. return;
  4556. }
  4557. /* Calculate number of cli arguments: one for the filename, two
  4558. for each smartlist element (one for "-p" and one for the
  4559. ports), and one for the final NULL. */
  4560. args_n = 1 + 2*smartlist_len(ports_to_forward) + 1;
  4561. argv = tor_calloc(sizeof(char *), args_n);
  4562. argv[argv_index++] = filename;
  4563. SMARTLIST_FOREACH_BEGIN(ports_to_forward, const char *, port) {
  4564. argv[argv_index++] = "-p";
  4565. argv[argv_index++] = port;
  4566. } SMARTLIST_FOREACH_END(port);
  4567. argv[argv_index] = NULL;
  4568. /* Assume tor-fw-helper will succeed, start it later*/
  4569. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_SUCCESS;
  4570. if (child_handle) {
  4571. tor_process_handle_destroy(child_handle, 1);
  4572. child_handle = NULL;
  4573. }
  4574. #ifdef _WIN32
  4575. /* Passing NULL as lpApplicationName makes Windows search for the .exe */
  4576. status = tor_spawn_background(NULL, argv, NULL, &child_handle);
  4577. #else
  4578. status = tor_spawn_background(filename, argv, NULL, &child_handle);
  4579. #endif
  4580. tor_free_((void*)argv);
  4581. argv=NULL;
  4582. if (PROCESS_STATUS_ERROR == status) {
  4583. log_warn(LD_GENERAL, "Failed to start port forwarding helper %s",
  4584. filename);
  4585. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_FAIL;
  4586. return;
  4587. }
  4588. log_info(LD_GENERAL,
  4589. "Started port forwarding helper (%s) with pid '%d'",
  4590. filename, tor_process_get_pid(child_handle));
  4591. }
  4592. /* If child is running, read from its stdout and stderr) */
  4593. if (child_handle && PROCESS_STATUS_RUNNING == child_handle->status) {
  4594. /* Read from stdout/stderr and log result */
  4595. retval = 0;
  4596. #ifdef _WIN32
  4597. stderr_status = log_from_handle(child_handle->stderr_pipe, LOG_INFO);
  4598. #else
  4599. stderr_status = log_from_pipe(child_handle->stderr_handle,
  4600. LOG_INFO, filename, &retval);
  4601. #endif
  4602. if (handle_fw_helper_output(filename, child_handle) < 0) {
  4603. log_warn(LD_GENERAL, "Failed to handle fw helper output.");
  4604. stdout_status = -1;
  4605. retval = -1;
  4606. }
  4607. if (retval) {
  4608. /* There was a problem in the child process */
  4609. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_FAIL;
  4610. }
  4611. /* Combine the two statuses in order of severity */
  4612. if (-1 == stdout_status || -1 == stderr_status)
  4613. /* There was a failure */
  4614. retval = -1;
  4615. #ifdef _WIN32
  4616. else if (!child_handle || tor_get_exit_code(child_handle, 0, NULL) !=
  4617. PROCESS_EXIT_RUNNING) {
  4618. /* process has exited or there was an error */
  4619. /* TODO: Do something with the process return value */
  4620. /* TODO: What if the process output something since
  4621. * between log_from_handle and tor_get_exit_code? */
  4622. retval = 1;
  4623. }
  4624. #else
  4625. else if (1 == stdout_status || 1 == stderr_status)
  4626. /* stdout or stderr was closed, the process probably
  4627. * exited. It will be reaped by waitpid() in main.c */
  4628. /* TODO: Do something with the process return value */
  4629. retval = 1;
  4630. #endif
  4631. else
  4632. /* Both are fine */
  4633. retval = 0;
  4634. /* If either pipe indicates a failure, act on it */
  4635. if (0 != retval) {
  4636. if (1 == retval) {
  4637. log_info(LD_GENERAL, "Port forwarding helper terminated");
  4638. child_handle->status = PROCESS_STATUS_NOTRUNNING;
  4639. } else {
  4640. log_warn(LD_GENERAL, "Failed to read from port forwarding helper");
  4641. child_handle->status = PROCESS_STATUS_ERROR;
  4642. }
  4643. /* TODO: The child might not actually be finished (maybe it failed or
  4644. closed stdout/stderr), so maybe we shouldn't start another? */
  4645. }
  4646. }
  4647. }
  4648. /** Initialize the insecure RNG <b>rng</b> from a seed value <b>seed</b>. */
  4649. void
  4650. tor_init_weak_random(tor_weak_rng_t *rng, unsigned seed)
  4651. {
  4652. rng->state = (uint32_t)(seed & 0x7fffffff);
  4653. }
  4654. /** Return a randomly chosen value in the range 0..TOR_WEAK_RANDOM_MAX based
  4655. * on the RNG state of <b>rng</b>. This entropy will not be cryptographically
  4656. * strong; do not rely on it for anything an adversary should not be able to
  4657. * predict. */
  4658. int32_t
  4659. tor_weak_random(tor_weak_rng_t *rng)
  4660. {
  4661. /* Here's a linear congruential generator. OpenBSD and glibc use these
  4662. * parameters; they aren't too bad, and should have maximal period over the
  4663. * range 0..INT32_MAX. We don't want to use the platform rand() or random(),
  4664. * since some platforms have bad weak RNGs that only return values in the
  4665. * range 0..INT16_MAX, which just isn't enough. */
  4666. rng->state = (rng->state * 1103515245 + 12345) & 0x7fffffff;
  4667. return (int32_t) rng->state;
  4668. }
  4669. /** Return a random number in the range [0 , <b>top</b>). {That is, the range
  4670. * of integers i such that 0 <= i < top.} Chooses uniformly. Requires that
  4671. * top is greater than 0. This randomness is not cryptographically strong; do
  4672. * not rely on it for anything an adversary should not be able to predict. */
  4673. int32_t
  4674. tor_weak_random_range(tor_weak_rng_t *rng, int32_t top)
  4675. {
  4676. /* We don't want to just do tor_weak_random() % top, since random() is often
  4677. * implemented with an LCG whose modulus is a power of 2, and those are
  4678. * cyclic in their low-order bits. */
  4679. int divisor, result;
  4680. tor_assert(top > 0);
  4681. divisor = TOR_WEAK_RANDOM_MAX / top;
  4682. do {
  4683. result = (int32_t)(tor_weak_random(rng) / divisor);
  4684. } while (result >= top);
  4685. return result;
  4686. }