util.c 162 KB

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