util.c 149 KB

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