util.c 162 KB

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