util.c 148 KB

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