util.c 155 KB

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