util.c 145 KB

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