util.c 151 KB

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