util.c 150 KB

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