util.c 150 KB

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