util.c 161 KB

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