util.c 156 KB

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