util.c 161 KB

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