util.c 150 KB

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