util.c 151 KB

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