util.c 134 KB

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