util.c 161 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740
  1. /* Copyright (c) 2003, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2016, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file util.c
  7. * \brief Common functions for strings, IO, network, data structures,
  8. * process control.
  9. **/
  10. #include "orconfig.h"
  11. #ifdef HAVE_FCNTL_H
  12. #include <fcntl.h>
  13. #endif
  14. #define UTIL_PRIVATE
  15. #include "util.h"
  16. #include "torlog.h"
  17. #include "crypto.h"
  18. #include "torint.h"
  19. #include "container.h"
  20. #include "address.h"
  21. #include "sandbox.h"
  22. #include "backtrace.h"
  23. #include "util_process.h"
  24. #include "util_format.h"
  25. #ifdef _WIN32
  26. #include <io.h>
  27. #include <direct.h>
  28. #include <process.h>
  29. #include <tchar.h>
  30. #include <winbase.h>
  31. #else
  32. #include <dirent.h>
  33. #include <pwd.h>
  34. #include <grp.h>
  35. #endif
  36. /* math.h needs this on Linux */
  37. #ifndef _USE_ISOC99_
  38. #define _USE_ISOC99_ 1
  39. #endif
  40. #include <math.h>
  41. #include <stdlib.h>
  42. #include <stdio.h>
  43. #include <string.h>
  44. #include <assert.h>
  45. #include <signal.h>
  46. #ifdef HAVE_NETINET_IN_H
  47. #include <netinet/in.h>
  48. #endif
  49. #ifdef HAVE_ARPA_INET_H
  50. #include <arpa/inet.h>
  51. #endif
  52. #ifdef HAVE_ERRNO_H
  53. #include <errno.h>
  54. #endif
  55. #ifdef HAVE_SYS_SOCKET_H
  56. #include <sys/socket.h>
  57. #endif
  58. #ifdef HAVE_SYS_TIME_H
  59. #include <sys/time.h>
  60. #endif
  61. #ifdef HAVE_UNISTD_H
  62. #include <unistd.h>
  63. #endif
  64. #ifdef HAVE_SYS_STAT_H
  65. #include <sys/stat.h>
  66. #endif
  67. #ifdef HAVE_SYS_FCNTL_H
  68. #include <sys/fcntl.h>
  69. #endif
  70. #ifdef HAVE_TIME_H
  71. #include <time.h>
  72. #endif
  73. #ifdef HAVE_MALLOC_MALLOC_H
  74. #include <malloc/malloc.h>
  75. #endif
  76. #ifdef HAVE_MALLOC_H
  77. #if !defined(OPENBSD) && !defined(__FreeBSD__)
  78. /* OpenBSD has a malloc.h, but for our purposes, it only exists in order to
  79. * scold us for being so stupid as to autodetect its presence. To be fair,
  80. * they've done this since 1996, when autoconf was only 5 years old. */
  81. #include <malloc.h>
  82. #endif
  83. #endif
  84. #ifdef HAVE_MALLOC_NP_H
  85. #include <malloc_np.h>
  86. #endif
  87. #ifdef HAVE_SYS_WAIT_H
  88. #include <sys/wait.h>
  89. #endif
  90. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  91. #include <sys/prctl.h>
  92. #endif
  93. #ifdef __clang_analyzer__
  94. #undef MALLOC_ZERO_WORKS
  95. #endif
  96. /* =====
  97. * Memory management
  98. * ===== */
  99. #ifdef USE_DMALLOC
  100. #undef strndup
  101. #include <dmalloc.h>
  102. /* Macro to pass the extra dmalloc args to another function. */
  103. #define DMALLOC_FN_ARGS , file, line
  104. #if defined(HAVE_DMALLOC_STRDUP)
  105. /* the dmalloc_strdup should be fine as defined */
  106. #elif defined(HAVE_DMALLOC_STRNDUP)
  107. #define dmalloc_strdup(file, line, string, xalloc_b) \
  108. dmalloc_strndup(file, line, (string), -1, xalloc_b)
  109. #else
  110. #error "No dmalloc_strdup or equivalent"
  111. #endif
  112. #else /* not using dmalloc */
  113. #define DMALLOC_FN_ARGS
  114. #endif
  115. /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
  116. * result. On error, log and terminate the process. (Same as malloc(size),
  117. * but never returns NULL.)
  118. *
  119. * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
  120. * ignored otherwise.
  121. */
  122. void *
  123. tor_malloc_(size_t size DMALLOC_PARAMS)
  124. {
  125. void *result;
  126. tor_assert(size < SIZE_T_CEILING);
  127. #ifndef MALLOC_ZERO_WORKS
  128. /* Some libc mallocs don't work when size==0. Override them. */
  129. if (size==0) {
  130. size=1;
  131. }
  132. #endif
  133. #ifdef USE_DMALLOC
  134. result = dmalloc_malloc(file, line, size, DMALLOC_FUNC_MALLOC, 0, 0);
  135. #else
  136. result = malloc(size);
  137. #endif
  138. if (PREDICT_UNLIKELY(result == NULL)) {
  139. /* LCOV_EXCL_START */
  140. log_err(LD_MM,"Out of memory on malloc(). Dying.");
  141. /* If these functions die within a worker process, they won't call
  142. * spawn_exit, but that's ok, since the parent will run out of memory soon
  143. * anyway. */
  144. exit(1);
  145. /* LCOV_EXCL_STOP */
  146. }
  147. return result;
  148. }
  149. /** Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
  150. * zero bytes, and return a pointer to the result. Log and terminate
  151. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  152. */
  153. void *
  154. tor_malloc_zero_(size_t size DMALLOC_PARAMS)
  155. {
  156. /* You may ask yourself, "wouldn't it be smart to use calloc instead of
  157. * malloc+memset? Perhaps libc's calloc knows some nifty optimization trick
  158. * we don't!" Indeed it does, but its optimizations are only a big win when
  159. * we're allocating something very big (it knows if it just got the memory
  160. * from the OS in a pre-zeroed state). We don't want to use tor_malloc_zero
  161. * for big stuff, so we don't bother with calloc. */
  162. void *result = tor_malloc_(size DMALLOC_FN_ARGS);
  163. memset(result, 0, size);
  164. return result;
  165. }
  166. /* The square root of SIZE_MAX + 1. If a is less than this, and b is less
  167. * than this, then a*b is less than SIZE_MAX. (For example, if size_t is
  168. * 32 bits, then SIZE_MAX is 0xffffffff and this value is 0x10000. If a and
  169. * b are less than this, then their product is at most (65535*65535) ==
  170. * 0xfffe0001. */
  171. #define SQRT_SIZE_MAX_P1 (((size_t)1) << (sizeof(size_t)*4))
  172. /** Return non-zero if and only if the product of the arguments is exact. */
  173. static inline int
  174. size_mul_check(const size_t x, const size_t y)
  175. {
  176. /* This first check is equivalent to
  177. (x < SQRT_SIZE_MAX_P1 && y < SQRT_SIZE_MAX_P1)
  178. Rationale: if either one of x or y is >= SQRT_SIZE_MAX_P1, then it
  179. will have some bit set in its most significant half.
  180. */
  181. return ((x|y) < SQRT_SIZE_MAX_P1 ||
  182. y == 0 ||
  183. x <= SIZE_MAX / y);
  184. }
  185. #ifdef TOR_UNIT_TESTS
  186. /** Exposed for unit tests only */
  187. int
  188. size_mul_check__(const size_t x, const size_t y)
  189. {
  190. return size_mul_check(x,y);
  191. }
  192. #endif
  193. /** Allocate a chunk of <b>nmemb</b>*<b>size</b> bytes of memory, fill
  194. * the memory with zero bytes, and return a pointer to the result.
  195. * Log and terminate the process on error. (Same as
  196. * calloc(<b>nmemb</b>,<b>size</b>), but never returns NULL.)
  197. * The second argument (<b>size</b>) should preferably be non-zero
  198. * and a compile-time constant.
  199. */
  200. void *
  201. tor_calloc_(size_t nmemb, size_t size DMALLOC_PARAMS)
  202. {
  203. tor_assert(size_mul_check(nmemb, size));
  204. return tor_malloc_zero_((nmemb * size) DMALLOC_FN_ARGS);
  205. }
  206. /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
  207. * bytes long; return the new memory block. On error, log and
  208. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  209. */
  210. void *
  211. tor_realloc_(void *ptr, size_t size DMALLOC_PARAMS)
  212. {
  213. void *result;
  214. tor_assert(size < SIZE_T_CEILING);
  215. #ifndef MALLOC_ZERO_WORKS
  216. /* Some libc mallocs don't work when size==0. Override them. */
  217. if (size==0) {
  218. size=1;
  219. }
  220. #endif
  221. #ifdef USE_DMALLOC
  222. result = dmalloc_realloc(file, line, ptr, size, DMALLOC_FUNC_REALLOC, 0);
  223. #else
  224. result = realloc(ptr, size);
  225. #endif
  226. if (PREDICT_UNLIKELY(result == NULL)) {
  227. /* LCOV_EXCL_START */
  228. log_err(LD_MM,"Out of memory on realloc(). Dying.");
  229. exit(1);
  230. /* LCOV_EXCL_STOP */
  231. }
  232. return result;
  233. }
  234. /**
  235. * Try to realloc <b>ptr</b> so that it takes up sz1 * sz2 bytes. Check for
  236. * overflow. Unlike other allocation functions, return NULL on overflow.
  237. */
  238. void *
  239. tor_reallocarray_(void *ptr, size_t sz1, size_t sz2 DMALLOC_PARAMS)
  240. {
  241. /* XXXX we can make this return 0, but we would need to check all the
  242. * reallocarray users. */
  243. tor_assert(size_mul_check(sz1, sz2));
  244. return tor_realloc(ptr, (sz1 * sz2) DMALLOC_FN_ARGS);
  245. }
  246. /** Return a newly allocated copy of the NUL-terminated string s. On
  247. * error, log and terminate. (Like strdup(s), but never returns
  248. * NULL.)
  249. */
  250. char *
  251. tor_strdup_(const char *s DMALLOC_PARAMS)
  252. {
  253. char *dup;
  254. tor_assert(s);
  255. #ifdef USE_DMALLOC
  256. dup = dmalloc_strdup(file, line, s, 0);
  257. #else
  258. dup = strdup(s);
  259. #endif
  260. if (PREDICT_UNLIKELY(dup == NULL)) {
  261. /* LCOV_EXCL_START */
  262. log_err(LD_MM,"Out of memory on strdup(). Dying.");
  263. exit(1);
  264. /* LCOV_EXCL_STOP */
  265. }
  266. return dup;
  267. }
  268. /** Allocate and return a new string containing the first <b>n</b>
  269. * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
  270. * characters, only the first <b>n</b> are copied. The result is
  271. * always NUL-terminated. (Like strndup(s,n), but never returns
  272. * NULL.)
  273. */
  274. char *
  275. tor_strndup_(const char *s, size_t n DMALLOC_PARAMS)
  276. {
  277. char *dup;
  278. tor_assert(s);
  279. tor_assert(n < SIZE_T_CEILING);
  280. dup = 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(dup, s, n);
  286. dup[n]='\0';
  287. return dup;
  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 *dup;
  295. tor_assert(len < SIZE_T_CEILING);
  296. tor_assert(mem);
  297. dup = tor_malloc_(len DMALLOC_FN_ARGS);
  298. memcpy(dup, mem, len);
  299. return dup;
  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 *dup;
  307. tor_assert(len < SIZE_T_CEILING+1);
  308. tor_assert(mem);
  309. dup = tor_malloc_(len+1 DMALLOC_FN_ARGS);
  310. memcpy(dup, mem, len);
  311. dup[len] = '\0';
  312. return dup;
  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 *read = s;
  580. while (*read) {
  581. if (strchr(strip, *read)) {
  582. ++read;
  583. } else {
  584. *s++ = *read++;
  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 y1, int y2)
  1395. {
  1396. --y1;
  1397. --y2;
  1398. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  1399. }
  1400. /** Number of days per month in non-leap year; used by tor_timegm and
  1401. * parse_rfc1123_time. */
  1402. static const int days_per_month[] =
  1403. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  1404. /** Compute a time_t given a struct tm. The result is given in UTC, and
  1405. * does not account for leap seconds. Return 0 on success, -1 on failure.
  1406. */
  1407. int
  1408. tor_timegm(const struct tm *tm, time_t *time_out)
  1409. {
  1410. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  1411. * It's way more brute-force than fiddling with tzset().
  1412. *
  1413. * We use int64_t rather than time_t to avoid overflow on multiplication on
  1414. * platforms with 32-bit time_t. Since year is clipped to INT32_MAX, and
  1415. * since 365 * 24 * 60 * 60 is approximately 31 million, it's not possible
  1416. * for INT32_MAX years to overflow int64_t when converted to seconds. */
  1417. int64_t year, days, hours, minutes, seconds;
  1418. int i, invalid_year, dpm;
  1419. /* Initialize time_out to 0 for now, to avoid bad usage in case this function
  1420. fails and the caller ignores the return value. */
  1421. tor_assert(time_out);
  1422. *time_out = 0;
  1423. /* avoid int overflow on addition */
  1424. if (tm->tm_year < INT32_MAX-1900) {
  1425. year = tm->tm_year + 1900;
  1426. } else {
  1427. /* clamp year */
  1428. year = INT32_MAX;
  1429. }
  1430. invalid_year = (year < 1970 || tm->tm_year >= INT32_MAX-1900);
  1431. if (tm->tm_mon >= 0 && tm->tm_mon <= 11) {
  1432. dpm = days_per_month[tm->tm_mon];
  1433. if (tm->tm_mon == 1 && !invalid_year && IS_LEAPYEAR(tm->tm_year)) {
  1434. dpm = 29;
  1435. }
  1436. } else {
  1437. /* invalid month - default to 0 days per month */
  1438. dpm = 0;
  1439. }
  1440. if (invalid_year ||
  1441. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  1442. tm->tm_mday < 1 || tm->tm_mday > dpm ||
  1443. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1444. tm->tm_min < 0 || tm->tm_min > 59 ||
  1445. tm->tm_sec < 0 || tm->tm_sec > 60) {
  1446. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  1447. return -1;
  1448. }
  1449. days = 365 * (year-1970) + n_leapdays(1970,(int)year);
  1450. for (i = 0; i < tm->tm_mon; ++i)
  1451. days += days_per_month[i];
  1452. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  1453. ++days;
  1454. days += tm->tm_mday - 1;
  1455. hours = days*24 + tm->tm_hour;
  1456. minutes = hours*60 + tm->tm_min;
  1457. seconds = minutes*60 + tm->tm_sec;
  1458. /* Check that "seconds" will fit in a time_t. On platforms where time_t is
  1459. * 32-bit, this check will fail for dates in and after 2038.
  1460. *
  1461. * We already know that "seconds" can't be negative because "year" >= 1970 */
  1462. #if SIZEOF_TIME_T < 8
  1463. if (seconds < TIME_MIN || seconds > TIME_MAX) {
  1464. log_warn(LD_BUG, "Result does not fit in tor_timegm");
  1465. return -1;
  1466. }
  1467. #endif
  1468. *time_out = (time_t)seconds;
  1469. return 0;
  1470. }
  1471. /* strftime is locale-specific, so we need to replace those parts */
  1472. /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
  1473. static const char *WEEKDAY_NAMES[] =
  1474. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1475. /** A c-locale array of 3-letter names of months, starting with Jan. */
  1476. static const char *MONTH_NAMES[] =
  1477. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  1478. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1479. /** Set <b>buf</b> to the RFC1123 encoding of the UTC value of <b>t</b>.
  1480. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  1481. *
  1482. * (RFC1123 format is "Fri, 29 Sep 2006 15:54:20 GMT". Note the "GMT"
  1483. * rather than "UTC".)
  1484. */
  1485. void
  1486. format_rfc1123_time(char *buf, time_t t)
  1487. {
  1488. struct tm tm;
  1489. tor_gmtime_r(&t, &tm);
  1490. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  1491. tor_assert(tm.tm_wday >= 0);
  1492. tor_assert(tm.tm_wday <= 6);
  1493. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  1494. tor_assert(tm.tm_mon >= 0);
  1495. tor_assert(tm.tm_mon <= 11);
  1496. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  1497. }
  1498. /** Parse the (a subset of) the RFC1123 encoding of some time (in UTC) from
  1499. * <b>buf</b>, and store the result in *<b>t</b>.
  1500. *
  1501. * Note that we only accept the subset generated by format_rfc1123_time above,
  1502. * not the full range of formats suggested by RFC 1123.
  1503. *
  1504. * Return 0 on success, -1 on failure.
  1505. */
  1506. int
  1507. parse_rfc1123_time(const char *buf, time_t *t)
  1508. {
  1509. struct tm tm;
  1510. char month[4];
  1511. char weekday[4];
  1512. int i, m, invalid_year;
  1513. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1514. unsigned dpm;
  1515. if (strlen(buf) != RFC1123_TIME_LEN)
  1516. return -1;
  1517. memset(&tm, 0, sizeof(tm));
  1518. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  1519. &tm_mday, month, &tm_year, &tm_hour,
  1520. &tm_min, &tm_sec) < 7) {
  1521. char *esc = esc_for_log(buf);
  1522. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1523. tor_free(esc);
  1524. return -1;
  1525. }
  1526. m = -1;
  1527. for (i = 0; i < 12; ++i) {
  1528. if (!strcmp(month, MONTH_NAMES[i])) {
  1529. m = i;
  1530. break;
  1531. }
  1532. }
  1533. if (m<0) {
  1534. char *esc = esc_for_log(buf);
  1535. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  1536. tor_free(esc);
  1537. return -1;
  1538. }
  1539. tm.tm_mon = m;
  1540. invalid_year = (tm_year >= INT32_MAX || tm_year < 1970);
  1541. tor_assert(m >= 0 && m <= 11);
  1542. dpm = days_per_month[m];
  1543. if (m == 1 && !invalid_year && IS_LEAPYEAR(tm_year)) {
  1544. dpm = 29;
  1545. }
  1546. if (invalid_year || tm_mday < 1 || tm_mday > dpm ||
  1547. tm_hour > 23 || tm_min > 59 || tm_sec > 60) {
  1548. char *esc = esc_for_log(buf);
  1549. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1550. tor_free(esc);
  1551. return -1;
  1552. }
  1553. tm.tm_mday = (int)tm_mday;
  1554. tm.tm_year = (int)tm_year;
  1555. tm.tm_hour = (int)tm_hour;
  1556. tm.tm_min = (int)tm_min;
  1557. tm.tm_sec = (int)tm_sec;
  1558. if (tm.tm_year < 1970) {
  1559. /* LCOV_EXCL_START
  1560. * XXXX I think this is dead code; we already checked for
  1561. * invalid_year above. */
  1562. tor_assert_nonfatal_unreached();
  1563. char *esc = esc_for_log(buf);
  1564. log_warn(LD_GENERAL,
  1565. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  1566. tor_free(esc);
  1567. return -1;
  1568. /* LCOV_EXCL_STOP */
  1569. }
  1570. tm.tm_year -= 1900;
  1571. return tor_timegm(&tm, t);
  1572. }
  1573. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  1574. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1575. *
  1576. * (ISO8601 format is 2006-10-29 10:57:20)
  1577. */
  1578. void
  1579. format_local_iso_time(char *buf, time_t t)
  1580. {
  1581. struct tm tm;
  1582. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  1583. }
  1584. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  1585. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1586. */
  1587. void
  1588. format_iso_time(char *buf, time_t t)
  1589. {
  1590. struct tm tm;
  1591. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  1592. }
  1593. /** As format_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  1594. * embedding an internal space. */
  1595. void
  1596. format_iso_time_nospace(char *buf, time_t t)
  1597. {
  1598. format_iso_time(buf, t);
  1599. buf[10] = 'T';
  1600. }
  1601. /** As format_iso_time_nospace, but include microseconds in decimal
  1602. * fixed-point format. Requires that buf be at least ISO_TIME_USEC_LEN+1
  1603. * bytes long. */
  1604. void
  1605. format_iso_time_nospace_usec(char *buf, const struct timeval *tv)
  1606. {
  1607. tor_assert(tv);
  1608. format_iso_time_nospace(buf, (time_t)tv->tv_sec);
  1609. tor_snprintf(buf+ISO_TIME_LEN, 8, ".%06d", (int)tv->tv_usec);
  1610. }
  1611. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  1612. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  1613. * failure. Ignore extraneous stuff in <b>cp</b> after the end of the time
  1614. * string, unless <b>strict</b> is set. */
  1615. int
  1616. parse_iso_time_(const char *cp, time_t *t, int strict)
  1617. {
  1618. struct tm st_tm;
  1619. unsigned int year=0, month=0, day=0, hour=0, minute=0, second=0;
  1620. int n_fields;
  1621. char extra_char;
  1622. n_fields = tor_sscanf(cp, "%u-%2u-%2u %2u:%2u:%2u%c", &year, &month,
  1623. &day, &hour, &minute, &second, &extra_char);
  1624. if (strict ? (n_fields != 6) : (n_fields < 6)) {
  1625. char *esc = esc_for_log(cp);
  1626. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  1627. tor_free(esc);
  1628. return -1;
  1629. }
  1630. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  1631. hour > 23 || minute > 59 || second > 60 || year >= INT32_MAX) {
  1632. char *esc = esc_for_log(cp);
  1633. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  1634. tor_free(esc);
  1635. return -1;
  1636. }
  1637. st_tm.tm_year = (int)year-1900;
  1638. st_tm.tm_mon = month-1;
  1639. st_tm.tm_mday = day;
  1640. st_tm.tm_hour = hour;
  1641. st_tm.tm_min = minute;
  1642. st_tm.tm_sec = second;
  1643. st_tm.tm_wday = 0; /* Should be ignored. */
  1644. if (st_tm.tm_year < 70) {
  1645. /* LCOV_EXCL_START
  1646. * XXXX I think this is dead code; we already checked for
  1647. * year < 1970 above. */
  1648. tor_assert_nonfatal_unreached();
  1649. char *esc = esc_for_log(cp);
  1650. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  1651. tor_free(esc);
  1652. return -1;
  1653. /* LCOV_EXCL_STOP */
  1654. }
  1655. return tor_timegm(&st_tm, t);
  1656. }
  1657. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  1658. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  1659. * failure. Reject the string if any characters are present after the time.
  1660. */
  1661. int
  1662. parse_iso_time(const char *cp, time_t *t)
  1663. {
  1664. return parse_iso_time_(cp, t, 1);
  1665. }
  1666. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  1667. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  1668. int
  1669. parse_http_time(const char *date, struct tm *tm)
  1670. {
  1671. const char *cp;
  1672. char month[4];
  1673. char wkday[4];
  1674. int i;
  1675. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1676. tor_assert(tm);
  1677. memset(tm, 0, sizeof(*tm));
  1678. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  1679. if ((cp = strchr(date, ','))) {
  1680. ++cp;
  1681. if (*cp != ' ')
  1682. return -1;
  1683. ++cp;
  1684. if (tor_sscanf(cp, "%2u %3s %4u %2u:%2u:%2u GMT",
  1685. &tm_mday, month, &tm_year,
  1686. &tm_hour, &tm_min, &tm_sec) == 6) {
  1687. /* rfc1123-date */
  1688. tm_year -= 1900;
  1689. } else if (tor_sscanf(cp, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  1690. &tm_mday, month, &tm_year,
  1691. &tm_hour, &tm_min, &tm_sec) == 6) {
  1692. /* rfc850-date */
  1693. } else {
  1694. return -1;
  1695. }
  1696. } else {
  1697. /* No comma; possibly asctime() format. */
  1698. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  1699. wkday, month, &tm_mday,
  1700. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  1701. tm_year -= 1900;
  1702. } else {
  1703. return -1;
  1704. }
  1705. }
  1706. tm->tm_mday = (int)tm_mday;
  1707. tm->tm_year = (int)tm_year;
  1708. tm->tm_hour = (int)tm_hour;
  1709. tm->tm_min = (int)tm_min;
  1710. tm->tm_sec = (int)tm_sec;
  1711. tm->tm_wday = 0; /* Leave this unset. */
  1712. month[3] = '\0';
  1713. /* Okay, now decode the month. */
  1714. /* set tm->tm_mon to dummy value so the check below fails. */
  1715. tm->tm_mon = -1;
  1716. for (i = 0; i < 12; ++i) {
  1717. if (!strcasecmp(MONTH_NAMES[i], month)) {
  1718. tm->tm_mon = i;
  1719. }
  1720. }
  1721. if (tm->tm_year < 0 ||
  1722. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  1723. tm->tm_mday < 1 || tm->tm_mday > 31 ||
  1724. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1725. tm->tm_min < 0 || tm->tm_min > 59 ||
  1726. tm->tm_sec < 0 || tm->tm_sec > 60)
  1727. return -1; /* Out of range, or bad month. */
  1728. return 0;
  1729. }
  1730. /** Given an <b>interval</b> in seconds, try to write it to the
  1731. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  1732. * Return 0 on success, -1 on failure.
  1733. */
  1734. int
  1735. format_time_interval(char *out, size_t out_len, long interval)
  1736. {
  1737. /* We only report seconds if there's no hours. */
  1738. long sec = 0, min = 0, hour = 0, day = 0;
  1739. /* -LONG_MIN is LONG_MAX + 1, which causes signed overflow */
  1740. if (interval < -LONG_MAX)
  1741. interval = LONG_MAX;
  1742. else if (interval < 0)
  1743. interval = -interval;
  1744. if (interval >= 86400) {
  1745. day = interval / 86400;
  1746. interval %= 86400;
  1747. }
  1748. if (interval >= 3600) {
  1749. hour = interval / 3600;
  1750. interval %= 3600;
  1751. }
  1752. if (interval >= 60) {
  1753. min = interval / 60;
  1754. interval %= 60;
  1755. }
  1756. sec = interval;
  1757. if (day) {
  1758. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  1759. day, hour, min);
  1760. } else if (hour) {
  1761. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  1762. } else if (min) {
  1763. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  1764. } else {
  1765. return tor_snprintf(out, out_len, "%ld seconds", sec);
  1766. }
  1767. }
  1768. /* =====
  1769. * Cached time
  1770. * ===== */
  1771. #ifndef TIME_IS_FAST
  1772. /** Cached estimate of the current time. Updated around once per second;
  1773. * may be a few seconds off if we are really busy. This is a hack to avoid
  1774. * calling time(NULL) (which not everybody has optimized) on critical paths.
  1775. */
  1776. static time_t cached_approx_time = 0;
  1777. /** Return a cached estimate of the current time from when
  1778. * update_approx_time() was last called. This is a hack to avoid calling
  1779. * time(NULL) on critical paths: please do not even think of calling it
  1780. * anywhere else. */
  1781. time_t
  1782. approx_time(void)
  1783. {
  1784. return cached_approx_time;
  1785. }
  1786. /** Update the cached estimate of the current time. This function SHOULD be
  1787. * called once per second, and MUST be called before the first call to
  1788. * get_approx_time. */
  1789. void
  1790. update_approx_time(time_t now)
  1791. {
  1792. cached_approx_time = now;
  1793. }
  1794. #endif
  1795. /* =====
  1796. * Rate limiting
  1797. * ===== */
  1798. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return the number
  1799. * of calls to rate_limit_is_ready (including this one!) since the last time
  1800. * rate_limit_is_ready returned nonzero. Otherwise return 0.
  1801. * If the call number hits <b>RATELIM_TOOMANY</b> limit, drop a warning
  1802. * about this event and stop counting. */
  1803. static int
  1804. rate_limit_is_ready(ratelim_t *lim, time_t now)
  1805. {
  1806. if (lim->rate + lim->last_allowed <= now) {
  1807. int res = lim->n_calls_since_last_time + 1;
  1808. lim->last_allowed = now;
  1809. lim->n_calls_since_last_time = 0;
  1810. return res;
  1811. } else {
  1812. if (lim->n_calls_since_last_time <= RATELIM_TOOMANY) {
  1813. ++lim->n_calls_since_last_time;
  1814. }
  1815. return 0;
  1816. }
  1817. }
  1818. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return a newly
  1819. * allocated string indicating how many messages were suppressed, suitable to
  1820. * append to a log message. Otherwise return NULL. */
  1821. char *
  1822. rate_limit_log(ratelim_t *lim, time_t now)
  1823. {
  1824. int n;
  1825. if ((n = rate_limit_is_ready(lim, now))) {
  1826. if (n == 1) {
  1827. return tor_strdup("");
  1828. } else {
  1829. char *cp=NULL;
  1830. const char *opt_over = (n >= RATELIM_TOOMANY) ? "over " : "";
  1831. /* XXXX this is not exactly correct: the messages could have occurred
  1832. * any time between the old value of lim->allowed and now. */
  1833. tor_asprintf(&cp,
  1834. " [%s%d similar message(s) suppressed in last %d seconds]",
  1835. opt_over, n-1, lim->rate);
  1836. return cp;
  1837. }
  1838. } else {
  1839. return NULL;
  1840. }
  1841. }
  1842. /* =====
  1843. * File helpers
  1844. * ===== */
  1845. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1846. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1847. * was returned by open(). Return the number of bytes written, or -1
  1848. * on error. Only use if fd is a blocking fd. */
  1849. ssize_t
  1850. write_all(tor_socket_t fd, const char *buf, size_t count, int isSocket)
  1851. {
  1852. size_t written = 0;
  1853. ssize_t result;
  1854. tor_assert(count < SSIZE_MAX);
  1855. while (written != count) {
  1856. if (isSocket)
  1857. result = tor_socket_send(fd, buf+written, count-written, 0);
  1858. else
  1859. result = write((int)fd, buf+written, count-written);
  1860. if (result<0)
  1861. return -1;
  1862. written += result;
  1863. }
  1864. return (ssize_t)count;
  1865. }
  1866. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1867. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1868. * was returned by socket() or accept(), and 0 if fd was returned by
  1869. * open(). Return the number of bytes read, or -1 on error. Only use
  1870. * if fd is a blocking fd. */
  1871. ssize_t
  1872. read_all(tor_socket_t fd, char *buf, size_t count, int isSocket)
  1873. {
  1874. size_t numread = 0;
  1875. ssize_t result;
  1876. if (count > SIZE_T_CEILING || count > SSIZE_MAX) {
  1877. errno = EINVAL;
  1878. return -1;
  1879. }
  1880. while (numread != count) {
  1881. if (isSocket)
  1882. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1883. else
  1884. result = read((int)fd, buf+numread, count-numread);
  1885. if (result<0)
  1886. return -1;
  1887. else if (result == 0)
  1888. break;
  1889. numread += result;
  1890. }
  1891. return (ssize_t)numread;
  1892. }
  1893. /*
  1894. * Filesystem operations.
  1895. */
  1896. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1897. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1898. * the root of a disk. */
  1899. static void
  1900. clean_name_for_stat(char *name)
  1901. {
  1902. #ifdef _WIN32
  1903. size_t len = strlen(name);
  1904. if (!len)
  1905. return;
  1906. if (name[len-1]=='\\' || name[len-1]=='/') {
  1907. if (len == 1 || (len==3 && name[1]==':'))
  1908. return;
  1909. name[len-1]='\0';
  1910. }
  1911. #else
  1912. (void)name;
  1913. #endif
  1914. }
  1915. /** Wrapper for unlink() to make it mockable for the test suite; returns 0
  1916. * if unlinking the file succeeded, -1 and sets errno if unlinking fails.
  1917. */
  1918. MOCK_IMPL(int,
  1919. tor_unlink,(const char *pathname))
  1920. {
  1921. return unlink(pathname);
  1922. }
  1923. /** Return:
  1924. * FN_ERROR if filename can't be read, is NULL, or is zero-length,
  1925. * FN_NOENT if it doesn't exist,
  1926. * FN_FILE if it is a non-empty regular file, or a FIFO on unix-like systems,
  1927. * FN_EMPTY for zero-byte regular files,
  1928. * FN_DIR if it's a directory, and
  1929. * FN_ERROR for any other file type.
  1930. * On FN_ERROR and FN_NOENT, sets errno. (errno is not set when FN_ERROR
  1931. * is returned due to an unhandled file type.) */
  1932. file_status_t
  1933. file_status(const char *fname)
  1934. {
  1935. struct stat st;
  1936. char *f;
  1937. int r;
  1938. if (!fname || strlen(fname) == 0) {
  1939. return FN_ERROR;
  1940. }
  1941. f = tor_strdup(fname);
  1942. clean_name_for_stat(f);
  1943. log_debug(LD_FS, "stat()ing %s", f);
  1944. r = stat(sandbox_intern_string(f), &st);
  1945. tor_free(f);
  1946. if (r) {
  1947. if (errno == ENOENT) {
  1948. return FN_NOENT;
  1949. }
  1950. return FN_ERROR;
  1951. }
  1952. if (st.st_mode & S_IFDIR) {
  1953. return FN_DIR;
  1954. } else if (st.st_mode & S_IFREG) {
  1955. if (st.st_size > 0) {
  1956. return FN_FILE;
  1957. } else if (st.st_size == 0) {
  1958. return FN_EMPTY;
  1959. } else {
  1960. return FN_ERROR;
  1961. }
  1962. #ifndef _WIN32
  1963. } else if (st.st_mode & S_IFIFO) {
  1964. return FN_FILE;
  1965. #endif
  1966. } else {
  1967. return FN_ERROR;
  1968. }
  1969. }
  1970. /** Check whether <b>dirname</b> exists and is private. If yes return 0. If
  1971. * it does not exist, and <b>check</b>&CPD_CREATE is set, try to create it
  1972. * and return 0 on success. If it does not exist, and
  1973. * <b>check</b>&CPD_CHECK, and we think we can create it, return 0. Else
  1974. * return -1. If CPD_GROUP_OK is set, then it's okay if the directory
  1975. * is group-readable, but in all cases we create the directory mode 0700.
  1976. * If CPD_GROUP_READ is set, existing directory behaves as CPD_GROUP_OK and
  1977. * if the directory is created it will use mode 0750 with group read
  1978. * permission. Group read privileges also assume execute permission
  1979. * as norm for directories. If CPD_CHECK_MODE_ONLY is set, then we don't
  1980. * alter the directory permissions if they are too permissive:
  1981. * we just return -1.
  1982. * When effective_user is not NULL, check permissions against the given user
  1983. * and its primary group.
  1984. */
  1985. MOCK_IMPL(int,
  1986. check_private_dir,(const char *dirname, cpd_check_t check,
  1987. const char *effective_user))
  1988. {
  1989. int r;
  1990. struct stat st;
  1991. tor_assert(dirname);
  1992. #ifndef _WIN32
  1993. int fd;
  1994. const struct passwd *pw = NULL;
  1995. uid_t running_uid;
  1996. gid_t running_gid;
  1997. /*
  1998. * Goal is to harden the implementation by removing any
  1999. * potential for race between stat() and chmod().
  2000. * chmod() accepts filename as argument. If an attacker can move
  2001. * the file between stat() and chmod(), a potential race exists.
  2002. *
  2003. * Several suggestions taken from:
  2004. * https://developer.apple.com/library/mac/documentation/
  2005. * Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html
  2006. */
  2007. /* Open directory.
  2008. * O_NOFOLLOW to ensure that it does not follow symbolic links */
  2009. fd = open(sandbox_intern_string(dirname), O_NOFOLLOW);
  2010. /* Was there an error? Maybe the directory does not exist? */
  2011. if (fd == -1) {
  2012. if (errno != ENOENT) {
  2013. /* Other directory error */
  2014. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  2015. strerror(errno));
  2016. return -1;
  2017. }
  2018. /* Received ENOENT: Directory does not exist */
  2019. /* Should we create the directory? */
  2020. if (check & CPD_CREATE) {
  2021. log_info(LD_GENERAL, "Creating directory %s", dirname);
  2022. if (check & CPD_GROUP_READ) {
  2023. r = mkdir(dirname, 0750);
  2024. } else {
  2025. r = mkdir(dirname, 0700);
  2026. }
  2027. /* check for mkdir() error */
  2028. if (r) {
  2029. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  2030. strerror(errno));
  2031. return -1;
  2032. }
  2033. /* we just created the directory. try to open it again.
  2034. * permissions on the directory will be checked again below.*/
  2035. fd = open(sandbox_intern_string(dirname), O_NOFOLLOW);
  2036. if (fd == -1)
  2037. return -1;
  2038. else
  2039. close(fd);
  2040. } else if (!(check & CPD_CHECK)) {
  2041. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  2042. return -1;
  2043. }
  2044. /* XXXX In the case where check==CPD_CHECK, we should look at the
  2045. * parent directory a little harder. */
  2046. return 0;
  2047. }
  2048. tor_assert(fd >= 0);
  2049. //f = tor_strdup(dirname);
  2050. //clean_name_for_stat(f);
  2051. log_debug(LD_FS, "stat()ing %s", dirname);
  2052. //r = stat(sandbox_intern_string(f), &st);
  2053. r = fstat(fd, &st);
  2054. if (r == -1) {
  2055. log_warn(LD_FS, "fstat() on directory %s failed.", dirname);
  2056. close(fd);
  2057. return -1;
  2058. }
  2059. //tor_free(f);
  2060. /* check that dirname is a directory */
  2061. if (!(st.st_mode & S_IFDIR)) {
  2062. log_warn(LD_FS, "%s is not a directory", dirname);
  2063. close(fd);
  2064. return -1;
  2065. }
  2066. if (effective_user) {
  2067. /* Look up the user and group information.
  2068. * If we have a problem, bail out. */
  2069. pw = tor_getpwnam(effective_user);
  2070. if (pw == NULL) {
  2071. log_warn(LD_CONFIG, "Error setting configured user: %s not found",
  2072. effective_user);
  2073. close(fd);
  2074. return -1;
  2075. }
  2076. running_uid = pw->pw_uid;
  2077. running_gid = pw->pw_gid;
  2078. } else {
  2079. running_uid = getuid();
  2080. running_gid = getgid();
  2081. }
  2082. if (st.st_uid != running_uid) {
  2083. const struct passwd *pw_uid = NULL;
  2084. char *process_ownername = NULL;
  2085. pw_uid = tor_getpwuid(running_uid);
  2086. process_ownername = pw_uid ? tor_strdup(pw_uid->pw_name) :
  2087. tor_strdup("<unknown>");
  2088. pw_uid = tor_getpwuid(st.st_uid);
  2089. log_warn(LD_FS, "%s is not owned by this user (%s, %d) but by "
  2090. "%s (%d). Perhaps you are running Tor as the wrong user?",
  2091. dirname, process_ownername, (int)running_uid,
  2092. pw ? pw->pw_name : "<unknown>", (int)st.st_uid);
  2093. tor_free(process_ownername);
  2094. close(fd);
  2095. return -1;
  2096. }
  2097. if ( (check & (CPD_GROUP_OK|CPD_GROUP_READ))
  2098. && (st.st_gid != running_gid) && (st.st_gid != 0)) {
  2099. struct group *gr;
  2100. char *process_groupname = NULL;
  2101. gr = getgrgid(running_gid);
  2102. process_groupname = gr ? tor_strdup(gr->gr_name) : tor_strdup("<unknown>");
  2103. gr = getgrgid(st.st_gid);
  2104. log_warn(LD_FS, "%s is not owned by this group (%s, %d) but by group "
  2105. "%s (%d). Are you running Tor as the wrong user?",
  2106. dirname, process_groupname, (int)running_gid,
  2107. gr ? gr->gr_name : "<unknown>", (int)st.st_gid);
  2108. tor_free(process_groupname);
  2109. close(fd);
  2110. return -1;
  2111. }
  2112. unsigned unwanted_bits = 0;
  2113. if (check & (CPD_GROUP_OK|CPD_GROUP_READ)) {
  2114. unwanted_bits = 0027;
  2115. } else {
  2116. unwanted_bits = 0077;
  2117. }
  2118. unsigned check_bits_filter = ~0;
  2119. if (check & CPD_RELAX_DIRMODE_CHECK) {
  2120. check_bits_filter = 0022;
  2121. }
  2122. if ((st.st_mode & unwanted_bits & check_bits_filter) != 0) {
  2123. unsigned new_mode;
  2124. if (check & CPD_CHECK_MODE_ONLY) {
  2125. log_warn(LD_FS, "Permissions on directory %s are too permissive.",
  2126. dirname);
  2127. close(fd);
  2128. return -1;
  2129. }
  2130. log_warn(LD_FS, "Fixing permissions on directory %s", dirname);
  2131. new_mode = st.st_mode;
  2132. new_mode |= 0700; /* Owner should have rwx */
  2133. if (check & CPD_GROUP_READ) {
  2134. new_mode |= 0050; /* Group should have rx */
  2135. }
  2136. new_mode &= ~unwanted_bits; /* Clear the bits that we didn't want set...*/
  2137. if (fchmod(fd, new_mode)) {
  2138. log_warn(LD_FS, "Could not chmod directory %s: %s", dirname,
  2139. strerror(errno));
  2140. close(fd);
  2141. return -1;
  2142. } else {
  2143. close(fd);
  2144. return 0;
  2145. }
  2146. }
  2147. close(fd);
  2148. #else
  2149. /* Win32 case: we can't open() a directory. */
  2150. (void)effective_user;
  2151. char *f = tor_strdup(dirname);
  2152. clean_name_for_stat(f);
  2153. log_debug(LD_FS, "stat()ing %s", f);
  2154. r = stat(sandbox_intern_string(f), &st);
  2155. tor_free(f);
  2156. if (r) {
  2157. if (errno != ENOENT) {
  2158. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  2159. strerror(errno));
  2160. return -1;
  2161. }
  2162. if (check & CPD_CREATE) {
  2163. log_info(LD_GENERAL, "Creating directory %s", dirname);
  2164. r = mkdir(dirname);
  2165. if (r) {
  2166. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  2167. strerror(errno));
  2168. return -1;
  2169. }
  2170. } else if (!(check & CPD_CHECK)) {
  2171. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  2172. return -1;
  2173. }
  2174. return 0;
  2175. }
  2176. if (!(st.st_mode & S_IFDIR)) {
  2177. log_warn(LD_FS, "%s is not a directory", dirname);
  2178. return -1;
  2179. }
  2180. #endif
  2181. return 0;
  2182. }
  2183. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  2184. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  2185. *
  2186. * This function replaces the old file atomically, if possible. This
  2187. * function, and all other functions in util.c that create files, create them
  2188. * with mode 0600.
  2189. */
  2190. MOCK_IMPL(int,
  2191. write_str_to_file,(const char *fname, const char *str, int bin))
  2192. {
  2193. #ifdef _WIN32
  2194. if (!bin && strchr(str, '\r')) {
  2195. log_warn(LD_BUG,
  2196. "We're writing a text string that already contains a CR to %s",
  2197. escaped(fname));
  2198. }
  2199. #endif
  2200. return write_bytes_to_file(fname, str, strlen(str), bin);
  2201. }
  2202. /** Represents a file that we're writing to, with support for atomic commit:
  2203. * we can write into a temporary file, and either remove the file on
  2204. * failure, or replace the original file on success. */
  2205. struct open_file_t {
  2206. char *tempname; /**< Name of the temporary file. */
  2207. char *filename; /**< Name of the original file. */
  2208. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  2209. unsigned binary:1; /**< Did we open in binary mode? */
  2210. int fd; /**< fd for the open file. */
  2211. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  2212. };
  2213. /** Try to start writing to the file in <b>fname</b>, passing the flags
  2214. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  2215. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  2216. * original file. Otherwise, we open a new temporary file in the same
  2217. * directory, and either replace the original or remove the temporary file
  2218. * when we're done.
  2219. *
  2220. * Return the fd for the newly opened file, and store working data in
  2221. * *<b>data_out</b>. The caller should not close the fd manually:
  2222. * instead, call finish_writing_to_file() or abort_writing_to_file().
  2223. * Returns -1 on failure.
  2224. *
  2225. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  2226. * as true and the flag O_EXCL is treated as false.
  2227. *
  2228. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  2229. * write()". We don't do that.
  2230. */
  2231. int
  2232. start_writing_to_file(const char *fname, int open_flags, int mode,
  2233. open_file_t **data_out)
  2234. {
  2235. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  2236. const char *open_name;
  2237. int append = 0;
  2238. tor_assert(fname);
  2239. tor_assert(data_out);
  2240. #if (O_BINARY != 0 && O_TEXT != 0)
  2241. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  2242. #endif
  2243. new_file->fd = -1;
  2244. new_file->filename = tor_strdup(fname);
  2245. if (open_flags & O_APPEND) {
  2246. open_name = fname;
  2247. new_file->rename_on_close = 0;
  2248. append = 1;
  2249. open_flags &= ~O_APPEND;
  2250. } else {
  2251. tor_asprintf(&new_file->tempname, "%s.tmp", fname);
  2252. open_name = new_file->tempname;
  2253. /* We always replace an existing temporary file if there is one. */
  2254. open_flags |= O_CREAT|O_TRUNC;
  2255. open_flags &= ~O_EXCL;
  2256. new_file->rename_on_close = 1;
  2257. }
  2258. #if O_BINARY != 0
  2259. if (open_flags & O_BINARY)
  2260. new_file->binary = 1;
  2261. #endif
  2262. new_file->fd = tor_open_cloexec(open_name, open_flags, mode);
  2263. if (new_file->fd < 0) {
  2264. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  2265. open_name, fname, strerror(errno));
  2266. goto err;
  2267. }
  2268. if (append) {
  2269. if (tor_fd_seekend(new_file->fd) < 0) {
  2270. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  2271. strerror(errno));
  2272. goto err;
  2273. }
  2274. }
  2275. *data_out = new_file;
  2276. return new_file->fd;
  2277. err:
  2278. if (new_file->fd >= 0)
  2279. close(new_file->fd);
  2280. *data_out = NULL;
  2281. tor_free(new_file->filename);
  2282. tor_free(new_file->tempname);
  2283. tor_free(new_file);
  2284. return -1;
  2285. }
  2286. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  2287. * that can be used to write to the same file. The caller should not mix
  2288. * stdio calls with non-stdio calls. */
  2289. FILE *
  2290. fdopen_file(open_file_t *file_data)
  2291. {
  2292. tor_assert(file_data);
  2293. if (file_data->stdio_file)
  2294. return file_data->stdio_file;
  2295. tor_assert(file_data->fd >= 0);
  2296. if (!(file_data->stdio_file = fdopen(file_data->fd,
  2297. file_data->binary?"ab":"a"))) {
  2298. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  2299. file_data->fd, strerror(errno));
  2300. }
  2301. return file_data->stdio_file;
  2302. }
  2303. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  2304. * for start_writing_to_file, but */
  2305. FILE *
  2306. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  2307. open_file_t **data_out)
  2308. {
  2309. FILE *res;
  2310. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  2311. return NULL;
  2312. if (!(res = fdopen_file(*data_out))) {
  2313. abort_writing_to_file(*data_out);
  2314. *data_out = NULL;
  2315. }
  2316. return res;
  2317. }
  2318. /** Helper function: close and free the underlying file and memory in
  2319. * <b>file_data</b>. If we were writing into a temporary file, then delete
  2320. * that file (if abort_write is true) or replaces the target file with
  2321. * the temporary file (if abort_write is false). */
  2322. static int
  2323. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  2324. {
  2325. int r = 0;
  2326. tor_assert(file_data && file_data->filename);
  2327. if (file_data->stdio_file) {
  2328. if (fclose(file_data->stdio_file)) {
  2329. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  2330. strerror(errno));
  2331. abort_write = r = -1;
  2332. }
  2333. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  2334. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  2335. strerror(errno));
  2336. abort_write = r = -1;
  2337. }
  2338. if (file_data->rename_on_close) {
  2339. tor_assert(file_data->tempname && file_data->filename);
  2340. if (abort_write) {
  2341. int res = unlink(file_data->tempname);
  2342. if (res != 0) {
  2343. /* We couldn't unlink and we'll leave a mess behind */
  2344. log_warn(LD_FS, "Failed to unlink %s: %s",
  2345. file_data->tempname, strerror(errno));
  2346. r = -1;
  2347. }
  2348. } else {
  2349. tor_assert(strcmp(file_data->filename, file_data->tempname));
  2350. if (replace_file(file_data->tempname, file_data->filename)) {
  2351. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  2352. strerror(errno));
  2353. r = -1;
  2354. }
  2355. }
  2356. }
  2357. tor_free(file_data->filename);
  2358. tor_free(file_data->tempname);
  2359. tor_free(file_data);
  2360. return r;
  2361. }
  2362. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  2363. * needed, and if using a temporary file, replace the original file with
  2364. * the temporary file. */
  2365. int
  2366. finish_writing_to_file(open_file_t *file_data)
  2367. {
  2368. return finish_writing_to_file_impl(file_data, 0);
  2369. }
  2370. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  2371. * needed, and if using a temporary file, delete it. */
  2372. int
  2373. abort_writing_to_file(open_file_t *file_data)
  2374. {
  2375. return finish_writing_to_file_impl(file_data, 1);
  2376. }
  2377. /** Helper: given a set of flags as passed to open(2), open the file
  2378. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  2379. * the file. Do so as atomically as possible e.g. by opening temp files and
  2380. * renaming. */
  2381. static int
  2382. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  2383. int open_flags)
  2384. {
  2385. open_file_t *file = NULL;
  2386. int fd;
  2387. ssize_t result;
  2388. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  2389. if (fd<0)
  2390. return -1;
  2391. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  2392. {
  2393. result = write_all(fd, chunk->bytes, chunk->len, 0);
  2394. if (result < 0) {
  2395. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  2396. strerror(errno));
  2397. goto err;
  2398. }
  2399. tor_assert((size_t)result == chunk->len);
  2400. });
  2401. return finish_writing_to_file(file);
  2402. err:
  2403. abort_writing_to_file(file);
  2404. return -1;
  2405. }
  2406. /** Given a smartlist of sized_chunk_t, write them to a file
  2407. * <b>fname</b>, overwriting or creating the file as necessary.
  2408. * If <b>no_tempfile</b> is 0 then the file will be written
  2409. * atomically. */
  2410. int
  2411. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin,
  2412. int no_tempfile)
  2413. {
  2414. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  2415. if (no_tempfile) {
  2416. /* O_APPEND stops write_chunks_to_file from using tempfiles */
  2417. flags |= O_APPEND;
  2418. }
  2419. return write_chunks_to_file_impl(fname, chunks, flags);
  2420. }
  2421. /** Write <b>len</b> bytes, starting at <b>str</b>, to <b>fname</b>
  2422. using the open() flags passed in <b>flags</b>. */
  2423. static int
  2424. write_bytes_to_file_impl(const char *fname, const char *str, size_t len,
  2425. int flags)
  2426. {
  2427. int r;
  2428. sized_chunk_t c = { str, len };
  2429. smartlist_t *chunks = smartlist_new();
  2430. smartlist_add(chunks, &c);
  2431. r = write_chunks_to_file_impl(fname, chunks, flags);
  2432. smartlist_free(chunks);
  2433. return r;
  2434. }
  2435. /** As write_str_to_file, but does not assume a NUL-terminated
  2436. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  2437. MOCK_IMPL(int,
  2438. write_bytes_to_file,(const char *fname, const char *str, size_t len,
  2439. int bin))
  2440. {
  2441. return write_bytes_to_file_impl(fname, str, len,
  2442. OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT));
  2443. }
  2444. /** As write_bytes_to_file, but if the file already exists, append the bytes
  2445. * to the end of the file instead of overwriting it. */
  2446. int
  2447. append_bytes_to_file(const char *fname, const char *str, size_t len,
  2448. int bin)
  2449. {
  2450. return write_bytes_to_file_impl(fname, str, len,
  2451. OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT));
  2452. }
  2453. /** Like write_str_to_file(), but also return -1 if there was a file
  2454. already residing in <b>fname</b>. */
  2455. int
  2456. write_bytes_to_new_file(const char *fname, const char *str, size_t len,
  2457. int bin)
  2458. {
  2459. return write_bytes_to_file_impl(fname, str, len,
  2460. OPEN_FLAGS_DONT_REPLACE|
  2461. (bin?O_BINARY:O_TEXT));
  2462. }
  2463. /**
  2464. * Read the contents of the open file <b>fd</b> presuming it is a FIFO
  2465. * (or similar) file descriptor for which the size of the file isn't
  2466. * known ahead of time. Return NULL on failure, and a NUL-terminated
  2467. * string on success. On success, set <b>sz_out</b> to the number of
  2468. * bytes read.
  2469. */
  2470. char *
  2471. read_file_to_str_until_eof(int fd, size_t max_bytes_to_read, size_t *sz_out)
  2472. {
  2473. ssize_t r;
  2474. size_t pos = 0;
  2475. char *string = NULL;
  2476. size_t string_max = 0;
  2477. if (max_bytes_to_read+1 >= SIZE_T_CEILING) {
  2478. errno = EINVAL;
  2479. return NULL;
  2480. }
  2481. do {
  2482. /* XXXX This "add 1K" approach is a little goofy; if we care about
  2483. * performance here, we should be doubling. But in practice we shouldn't
  2484. * be using this function on big files anyway. */
  2485. string_max = pos + 1024;
  2486. if (string_max > max_bytes_to_read)
  2487. string_max = max_bytes_to_read + 1;
  2488. string = tor_realloc(string, string_max);
  2489. r = read(fd, string + pos, string_max - pos - 1);
  2490. if (r < 0) {
  2491. int save_errno = errno;
  2492. tor_free(string);
  2493. errno = save_errno;
  2494. return NULL;
  2495. }
  2496. pos += r;
  2497. } while (r > 0 && pos < max_bytes_to_read);
  2498. tor_assert(pos < string_max);
  2499. *sz_out = pos;
  2500. string[pos] = '\0';
  2501. return string;
  2502. }
  2503. /** Read the contents of <b>filename</b> into a newly allocated
  2504. * string; return the string on success or NULL on failure.
  2505. *
  2506. * If <b>stat_out</b> is provided, store the result of stat()ing the
  2507. * file into <b>stat_out</b>.
  2508. *
  2509. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  2510. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  2511. * doesn't exist.
  2512. */
  2513. /*
  2514. * This function <em>may</em> return an erroneous result if the file
  2515. * is modified while it is running, but must not crash or overflow.
  2516. * Right now, the error case occurs when the file length grows between
  2517. * the call to stat and the call to read_all: the resulting string will
  2518. * be truncated.
  2519. */
  2520. MOCK_IMPL(char *,
  2521. read_file_to_str, (const char *filename, int flags, struct stat *stat_out))
  2522. {
  2523. int fd; /* router file */
  2524. struct stat statbuf;
  2525. char *string;
  2526. ssize_t r;
  2527. int bin = flags & RFTS_BIN;
  2528. tor_assert(filename);
  2529. fd = tor_open_cloexec(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  2530. if (fd<0) {
  2531. int severity = LOG_WARN;
  2532. int save_errno = errno;
  2533. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  2534. severity = LOG_INFO;
  2535. log_fn(severity, LD_FS,"Could not open \"%s\": %s",filename,
  2536. strerror(errno));
  2537. errno = save_errno;
  2538. return NULL;
  2539. }
  2540. if (fstat(fd, &statbuf)<0) {
  2541. int save_errno = errno;
  2542. close(fd);
  2543. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  2544. errno = save_errno;
  2545. return NULL;
  2546. }
  2547. #ifndef _WIN32
  2548. /** When we detect that we're reading from a FIFO, don't read more than
  2549. * this many bytes. It's insane overkill for most uses. */
  2550. #define FIFO_READ_MAX (1024*1024)
  2551. if (S_ISFIFO(statbuf.st_mode)) {
  2552. size_t sz = 0;
  2553. string = read_file_to_str_until_eof(fd, FIFO_READ_MAX, &sz);
  2554. int save_errno = errno;
  2555. if (string && stat_out) {
  2556. statbuf.st_size = sz;
  2557. memcpy(stat_out, &statbuf, sizeof(struct stat));
  2558. }
  2559. close(fd);
  2560. if (!string)
  2561. errno = save_errno;
  2562. return string;
  2563. }
  2564. #endif
  2565. if ((uint64_t)(statbuf.st_size)+1 >= SIZE_T_CEILING) {
  2566. close(fd);
  2567. errno = EINVAL;
  2568. return NULL;
  2569. }
  2570. string = tor_malloc((size_t)(statbuf.st_size+1));
  2571. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  2572. if (r<0) {
  2573. int save_errno = errno;
  2574. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  2575. strerror(errno));
  2576. tor_free(string);
  2577. close(fd);
  2578. errno = save_errno;
  2579. return NULL;
  2580. }
  2581. string[r] = '\0'; /* NUL-terminate the result. */
  2582. #if defined(_WIN32) || defined(__CYGWIN__)
  2583. if (!bin && strchr(string, '\r')) {
  2584. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  2585. "when reading %s. Coping.",
  2586. filename);
  2587. tor_strstrip(string, "\r");
  2588. r = strlen(string);
  2589. }
  2590. if (!bin) {
  2591. statbuf.st_size = (size_t) r;
  2592. } else
  2593. #endif
  2594. if (r != statbuf.st_size) {
  2595. /* Unless we're using text mode on win32, we'd better have an exact
  2596. * match for size. */
  2597. int save_errno = errno;
  2598. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  2599. (int)r, (long)statbuf.st_size,filename);
  2600. tor_free(string);
  2601. close(fd);
  2602. errno = save_errno;
  2603. return NULL;
  2604. }
  2605. close(fd);
  2606. if (stat_out) {
  2607. memcpy(stat_out, &statbuf, sizeof(struct stat));
  2608. }
  2609. return string;
  2610. }
  2611. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  2612. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  2613. * decode its contents into a newly allocated string. On success, assign this
  2614. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  2615. * provided), and return a pointer to the position in <b>s</b> immediately
  2616. * after the string. On failure, return NULL.
  2617. */
  2618. static const char *
  2619. unescape_string(const char *s, char **result, size_t *size_out)
  2620. {
  2621. const char *cp;
  2622. char *out;
  2623. if (s[0] != '\"')
  2624. return NULL;
  2625. cp = s+1;
  2626. while (1) {
  2627. switch (*cp) {
  2628. case '\0':
  2629. case '\n':
  2630. return NULL;
  2631. case '\"':
  2632. goto end_of_loop;
  2633. case '\\':
  2634. if (cp[1] == 'x' || cp[1] == 'X') {
  2635. if (!(TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])))
  2636. return NULL;
  2637. cp += 4;
  2638. } else if (TOR_ISODIGIT(cp[1])) {
  2639. cp += 2;
  2640. if (TOR_ISODIGIT(*cp)) ++cp;
  2641. if (TOR_ISODIGIT(*cp)) ++cp;
  2642. } else if (cp[1] == 'n' || cp[1] == 'r' || cp[1] == 't' || cp[1] == '"'
  2643. || cp[1] == '\\' || cp[1] == '\'') {
  2644. cp += 2;
  2645. } else {
  2646. return NULL;
  2647. }
  2648. break;
  2649. default:
  2650. ++cp;
  2651. break;
  2652. }
  2653. }
  2654. end_of_loop:
  2655. out = *result = tor_malloc(cp-s + 1);
  2656. cp = s+1;
  2657. while (1) {
  2658. switch (*cp)
  2659. {
  2660. case '\"':
  2661. *out = '\0';
  2662. if (size_out) *size_out = out - *result;
  2663. return cp+1;
  2664. case '\0':
  2665. /* LCOV_EXCL_START -- we caught this in parse_config_from_line. */
  2666. tor_fragile_assert();
  2667. tor_free(*result);
  2668. return NULL;
  2669. /* LCOV_EXCL_STOP */
  2670. case '\\':
  2671. switch (cp[1])
  2672. {
  2673. case 'n': *out++ = '\n'; cp += 2; break;
  2674. case 'r': *out++ = '\r'; cp += 2; break;
  2675. case 't': *out++ = '\t'; cp += 2; break;
  2676. case 'x': case 'X':
  2677. {
  2678. int x1, x2;
  2679. x1 = hex_decode_digit(cp[2]);
  2680. x2 = hex_decode_digit(cp[3]);
  2681. if (x1 == -1 || x2 == -1) {
  2682. /* LCOV_EXCL_START */
  2683. /* we caught this above in the initial loop. */
  2684. tor_assert_nonfatal_unreached();
  2685. tor_free(*result);
  2686. return NULL;
  2687. /* LCOV_EXCL_STOP */
  2688. }
  2689. *out++ = ((x1<<4) + x2);
  2690. cp += 4;
  2691. }
  2692. break;
  2693. case '0': case '1': case '2': case '3': case '4': case '5':
  2694. case '6': case '7':
  2695. {
  2696. int n = cp[1]-'0';
  2697. cp += 2;
  2698. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2699. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2700. if (n > 255) { tor_free(*result); return NULL; }
  2701. *out++ = (char)n;
  2702. }
  2703. break;
  2704. case '\'':
  2705. case '\"':
  2706. case '\\':
  2707. case '\?':
  2708. *out++ = cp[1];
  2709. cp += 2;
  2710. break;
  2711. default:
  2712. /* LCOV_EXCL_START */
  2713. /* we caught this above in the initial loop. */
  2714. tor_assert_nonfatal_unreached();
  2715. tor_free(*result); return NULL;
  2716. /* LCOV_EXCL_STOP */
  2717. }
  2718. break;
  2719. default:
  2720. *out++ = *cp++;
  2721. }
  2722. }
  2723. }
  2724. /** Given a string containing part of a configuration file or similar format,
  2725. * advance past comments and whitespace and try to parse a single line. If we
  2726. * parse a line successfully, set *<b>key_out</b> to a new string holding the
  2727. * key portion and *<b>value_out</b> to a new string holding the value portion
  2728. * of the line, and return a pointer to the start of the next line. If we run
  2729. * out of data, return a pointer to the end of the string. If we encounter an
  2730. * error, return NULL and set *<b>err_out</b> (if provided) to an error
  2731. * message.
  2732. */
  2733. const char *
  2734. parse_config_line_from_str_verbose(const char *line, char **key_out,
  2735. char **value_out,
  2736. const char **err_out)
  2737. {
  2738. /*
  2739. See torrc_format.txt for a description of the (silly) format this parses.
  2740. */
  2741. const char *key, *val, *cp;
  2742. int continuation = 0;
  2743. tor_assert(key_out);
  2744. tor_assert(value_out);
  2745. *key_out = *value_out = NULL;
  2746. key = val = NULL;
  2747. /* Skip until the first keyword. */
  2748. while (1) {
  2749. while (TOR_ISSPACE(*line))
  2750. ++line;
  2751. if (*line == '#') {
  2752. while (*line && *line != '\n')
  2753. ++line;
  2754. } else {
  2755. break;
  2756. }
  2757. }
  2758. if (!*line) { /* End of string? */
  2759. *key_out = *value_out = NULL;
  2760. return line;
  2761. }
  2762. /* Skip until the next space or \ followed by newline. */
  2763. key = line;
  2764. while (*line && !TOR_ISSPACE(*line) && *line != '#' &&
  2765. ! (line[0] == '\\' && line[1] == '\n'))
  2766. ++line;
  2767. *key_out = tor_strndup(key, line-key);
  2768. /* Skip until the value. */
  2769. while (*line == ' ' || *line == '\t')
  2770. ++line;
  2771. val = line;
  2772. /* Find the end of the line. */
  2773. if (*line == '\"') { // XXX No continuation handling is done here
  2774. if (!(line = unescape_string(line, value_out, NULL))) {
  2775. if (err_out)
  2776. *err_out = "Invalid escape sequence in quoted string";
  2777. return NULL;
  2778. }
  2779. while (*line == ' ' || *line == '\t')
  2780. ++line;
  2781. if (*line && *line != '#' && *line != '\n') {
  2782. if (err_out)
  2783. *err_out = "Excess data after quoted string";
  2784. return NULL;
  2785. }
  2786. } else {
  2787. /* Look for the end of the line. */
  2788. while (*line && *line != '\n' && (*line != '#' || continuation)) {
  2789. if (*line == '\\' && line[1] == '\n') {
  2790. continuation = 1;
  2791. line += 2;
  2792. } else if (*line == '#') {
  2793. do {
  2794. ++line;
  2795. } while (*line && *line != '\n');
  2796. if (*line == '\n')
  2797. ++line;
  2798. } else {
  2799. ++line;
  2800. }
  2801. }
  2802. if (*line == '\n') {
  2803. cp = line++;
  2804. } else {
  2805. cp = line;
  2806. }
  2807. /* Now back cp up to be the last nonspace character */
  2808. while (cp>val && TOR_ISSPACE(*(cp-1)))
  2809. --cp;
  2810. tor_assert(cp >= val);
  2811. /* Now copy out and decode the value. */
  2812. *value_out = tor_strndup(val, cp-val);
  2813. if (continuation) {
  2814. char *v_out, *v_in;
  2815. v_out = v_in = *value_out;
  2816. while (*v_in) {
  2817. if (*v_in == '#') {
  2818. do {
  2819. ++v_in;
  2820. } while (*v_in && *v_in != '\n');
  2821. if (*v_in == '\n')
  2822. ++v_in;
  2823. } else if (v_in[0] == '\\' && v_in[1] == '\n') {
  2824. v_in += 2;
  2825. } else {
  2826. *v_out++ = *v_in++;
  2827. }
  2828. }
  2829. *v_out = '\0';
  2830. }
  2831. }
  2832. if (*line == '#') {
  2833. do {
  2834. ++line;
  2835. } while (*line && *line != '\n');
  2836. }
  2837. while (TOR_ISSPACE(*line)) ++line;
  2838. return line;
  2839. }
  2840. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  2841. * string. */
  2842. char *
  2843. expand_filename(const char *filename)
  2844. {
  2845. tor_assert(filename);
  2846. #ifdef _WIN32
  2847. /* Might consider using GetFullPathName() as described here:
  2848. * http://etutorials.org/Programming/secure+programming/
  2849. * Chapter+3.+Input+Validation/3.7+Validating+Filenames+and+Paths/
  2850. */
  2851. return tor_strdup(filename);
  2852. #else
  2853. if (*filename == '~') {
  2854. char *home, *result=NULL;
  2855. const char *rest;
  2856. if (filename[1] == '/' || filename[1] == '\0') {
  2857. home = getenv("HOME");
  2858. if (!home) {
  2859. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  2860. "expanding \"%s\"; defaulting to \"\".", filename);
  2861. home = tor_strdup("");
  2862. } else {
  2863. home = tor_strdup(home);
  2864. }
  2865. rest = strlen(filename)>=2?(filename+2):"";
  2866. } else {
  2867. #ifdef HAVE_PWD_H
  2868. char *username, *slash;
  2869. slash = strchr(filename, '/');
  2870. if (slash)
  2871. username = tor_strndup(filename+1,slash-filename-1);
  2872. else
  2873. username = tor_strdup(filename+1);
  2874. if (!(home = get_user_homedir(username))) {
  2875. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2876. tor_free(username);
  2877. return NULL;
  2878. }
  2879. tor_free(username);
  2880. rest = slash ? (slash+1) : "";
  2881. #else
  2882. log_warn(LD_CONFIG, "Couldn't expand homedir on system without pwd.h");
  2883. return tor_strdup(filename);
  2884. #endif
  2885. }
  2886. tor_assert(home);
  2887. /* Remove trailing slash. */
  2888. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2889. home[strlen(home)-1] = '\0';
  2890. }
  2891. tor_asprintf(&result,"%s"PATH_SEPARATOR"%s",home,rest);
  2892. tor_free(home);
  2893. return result;
  2894. } else {
  2895. return tor_strdup(filename);
  2896. }
  2897. #endif
  2898. }
  2899. #define MAX_SCANF_WIDTH 9999
  2900. /** Helper: given an ASCII-encoded decimal digit, return its numeric value.
  2901. * NOTE: requires that its input be in-bounds. */
  2902. static int
  2903. digit_to_num(char d)
  2904. {
  2905. int num = ((int)d) - (int)'0';
  2906. tor_assert(num <= 9 && num >= 0);
  2907. return num;
  2908. }
  2909. /** Helper: Read an unsigned int from *<b>bufp</b> of up to <b>width</b>
  2910. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2911. * success, store the result in <b>out</b>, advance bufp to the next
  2912. * character, and return 0. On failure, return -1. */
  2913. static int
  2914. scan_unsigned(const char **bufp, unsigned long *out, int width, unsigned base)
  2915. {
  2916. unsigned long result = 0;
  2917. int scanned_so_far = 0;
  2918. const int hex = base==16;
  2919. tor_assert(base == 10 || base == 16);
  2920. if (!bufp || !*bufp || !out)
  2921. return -1;
  2922. if (width<0)
  2923. width=MAX_SCANF_WIDTH;
  2924. while (**bufp && (hex?TOR_ISXDIGIT(**bufp):TOR_ISDIGIT(**bufp))
  2925. && scanned_so_far < width) {
  2926. unsigned digit = hex?hex_decode_digit(*(*bufp)++):digit_to_num(*(*bufp)++);
  2927. // Check for overflow beforehand, without actually causing any overflow
  2928. // This preserves functionality on compilers that don't wrap overflow
  2929. // (i.e. that trap or optimise away overflow)
  2930. // result * base + digit > ULONG_MAX
  2931. // result * base > ULONG_MAX - digit
  2932. if (result > (ULONG_MAX - digit)/base)
  2933. return -1; /* Processing this digit would overflow */
  2934. result = result * base + digit;
  2935. ++scanned_so_far;
  2936. }
  2937. if (!scanned_so_far) /* No actual digits scanned */
  2938. return -1;
  2939. *out = result;
  2940. return 0;
  2941. }
  2942. /** Helper: Read an signed int from *<b>bufp</b> of up to <b>width</b>
  2943. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2944. * success, store the result in <b>out</b>, advance bufp to the next
  2945. * character, and return 0. On failure, return -1. */
  2946. static int
  2947. scan_signed(const char **bufp, long *out, int width)
  2948. {
  2949. int neg = 0;
  2950. unsigned long result = 0;
  2951. if (!bufp || !*bufp || !out)
  2952. return -1;
  2953. if (width<0)
  2954. width=MAX_SCANF_WIDTH;
  2955. if (**bufp == '-') {
  2956. neg = 1;
  2957. ++*bufp;
  2958. --width;
  2959. }
  2960. if (scan_unsigned(bufp, &result, width, 10) < 0)
  2961. return -1;
  2962. if (neg && result > 0) {
  2963. if (result > ((unsigned long)LONG_MAX) + 1)
  2964. return -1; /* Underflow */
  2965. else if (result == ((unsigned long)LONG_MAX) + 1)
  2966. *out = LONG_MIN;
  2967. else {
  2968. /* We once had a far more clever no-overflow conversion here, but
  2969. * some versions of GCC apparently ran it into the ground. Now
  2970. * we just check for LONG_MIN explicitly.
  2971. */
  2972. *out = -(long)result;
  2973. }
  2974. } else {
  2975. if (result > LONG_MAX)
  2976. return -1; /* Overflow */
  2977. *out = (long)result;
  2978. }
  2979. return 0;
  2980. }
  2981. /** Helper: Read a decimal-formatted double from *<b>bufp</b> of up to
  2982. * <b>width</b> characters. (Handle arbitrary width if <b>width</b> is less
  2983. * than 0.) On success, store the result in <b>out</b>, advance bufp to the
  2984. * next character, and return 0. On failure, return -1. */
  2985. static int
  2986. scan_double(const char **bufp, double *out, int width)
  2987. {
  2988. int neg = 0;
  2989. double result = 0;
  2990. int scanned_so_far = 0;
  2991. if (!bufp || !*bufp || !out)
  2992. return -1;
  2993. if (width<0)
  2994. width=MAX_SCANF_WIDTH;
  2995. if (**bufp == '-') {
  2996. neg = 1;
  2997. ++*bufp;
  2998. }
  2999. while (**bufp && TOR_ISDIGIT(**bufp) && scanned_so_far < width) {
  3000. const int digit = digit_to_num(*(*bufp)++);
  3001. result = result * 10 + digit;
  3002. ++scanned_so_far;
  3003. }
  3004. if (**bufp == '.') {
  3005. double fracval = 0, denominator = 1;
  3006. ++*bufp;
  3007. ++scanned_so_far;
  3008. while (**bufp && TOR_ISDIGIT(**bufp) && scanned_so_far < width) {
  3009. const int digit = digit_to_num(*(*bufp)++);
  3010. fracval = fracval * 10 + digit;
  3011. denominator *= 10;
  3012. ++scanned_so_far;
  3013. }
  3014. result += fracval / denominator;
  3015. }
  3016. if (!scanned_so_far) /* No actual digits scanned */
  3017. return -1;
  3018. *out = neg ? -result : result;
  3019. return 0;
  3020. }
  3021. /** Helper: copy up to <b>width</b> non-space characters from <b>bufp</b> to
  3022. * <b>out</b>. Make sure <b>out</b> is nul-terminated. Advance <b>bufp</b>
  3023. * to the next non-space character or the EOS. */
  3024. static int
  3025. scan_string(const char **bufp, char *out, int width)
  3026. {
  3027. int scanned_so_far = 0;
  3028. if (!bufp || !out || width < 0)
  3029. return -1;
  3030. while (**bufp && ! TOR_ISSPACE(**bufp) && scanned_so_far < width) {
  3031. *out++ = *(*bufp)++;
  3032. ++scanned_so_far;
  3033. }
  3034. *out = '\0';
  3035. return 0;
  3036. }
  3037. /** Locale-independent, minimal, no-surprises scanf variant, accepting only a
  3038. * restricted pattern format. For more info on what it supports, see
  3039. * tor_sscanf() documentation. */
  3040. int
  3041. tor_vsscanf(const char *buf, const char *pattern, va_list ap)
  3042. {
  3043. int n_matched = 0;
  3044. while (*pattern) {
  3045. if (*pattern != '%') {
  3046. if (*buf == *pattern) {
  3047. ++buf;
  3048. ++pattern;
  3049. continue;
  3050. } else {
  3051. return n_matched;
  3052. }
  3053. } else {
  3054. int width = -1;
  3055. int longmod = 0;
  3056. ++pattern;
  3057. if (TOR_ISDIGIT(*pattern)) {
  3058. width = digit_to_num(*pattern++);
  3059. while (TOR_ISDIGIT(*pattern)) {
  3060. width *= 10;
  3061. width += digit_to_num(*pattern++);
  3062. if (width > MAX_SCANF_WIDTH)
  3063. return -1;
  3064. }
  3065. if (!width) /* No zero-width things. */
  3066. return -1;
  3067. }
  3068. if (*pattern == 'l') {
  3069. longmod = 1;
  3070. ++pattern;
  3071. }
  3072. if (*pattern == 'u' || *pattern == 'x') {
  3073. unsigned long u;
  3074. const int base = (*pattern == 'u') ? 10 : 16;
  3075. if (!*buf)
  3076. return n_matched;
  3077. if (scan_unsigned(&buf, &u, width, base)<0)
  3078. return n_matched;
  3079. if (longmod) {
  3080. unsigned long *out = va_arg(ap, unsigned long *);
  3081. *out = u;
  3082. } else {
  3083. unsigned *out = va_arg(ap, unsigned *);
  3084. if (u > UINT_MAX)
  3085. return n_matched;
  3086. *out = (unsigned) u;
  3087. }
  3088. ++pattern;
  3089. ++n_matched;
  3090. } else if (*pattern == 'f') {
  3091. double *d = va_arg(ap, double *);
  3092. if (!longmod)
  3093. return -1; /* float not supported */
  3094. if (!*buf)
  3095. return n_matched;
  3096. if (scan_double(&buf, d, width)<0)
  3097. return n_matched;
  3098. ++pattern;
  3099. ++n_matched;
  3100. } else if (*pattern == 'd') {
  3101. long lng=0;
  3102. if (scan_signed(&buf, &lng, width)<0)
  3103. return n_matched;
  3104. if (longmod) {
  3105. long *out = va_arg(ap, long *);
  3106. *out = lng;
  3107. } else {
  3108. int *out = va_arg(ap, int *);
  3109. #if LONG_MAX > INT_MAX
  3110. if (lng < INT_MIN || lng > INT_MAX)
  3111. return n_matched;
  3112. #endif
  3113. *out = (int)lng;
  3114. }
  3115. ++pattern;
  3116. ++n_matched;
  3117. } else if (*pattern == 's') {
  3118. char *s = va_arg(ap, char *);
  3119. if (longmod)
  3120. return -1;
  3121. if (width < 0)
  3122. return -1;
  3123. if (scan_string(&buf, s, width)<0)
  3124. return n_matched;
  3125. ++pattern;
  3126. ++n_matched;
  3127. } else if (*pattern == 'c') {
  3128. char *ch = va_arg(ap, char *);
  3129. if (longmod)
  3130. return -1;
  3131. if (width != -1)
  3132. return -1;
  3133. if (!*buf)
  3134. return n_matched;
  3135. *ch = *buf++;
  3136. ++pattern;
  3137. ++n_matched;
  3138. } else if (*pattern == '%') {
  3139. if (*buf != '%')
  3140. return n_matched;
  3141. if (longmod)
  3142. return -1;
  3143. ++buf;
  3144. ++pattern;
  3145. } else {
  3146. return -1; /* Unrecognized pattern component. */
  3147. }
  3148. }
  3149. }
  3150. return n_matched;
  3151. }
  3152. /** Minimal sscanf replacement: parse <b>buf</b> according to <b>pattern</b>
  3153. * and store the results in the corresponding argument fields. Differs from
  3154. * sscanf in that:
  3155. * <ul><li>It only handles %u, %lu, %x, %lx, %[NUM]s, %d, %ld, %lf, and %c.
  3156. * <li>It only handles decimal inputs for %lf. (12.3, not 1.23e1)
  3157. * <li>It does not handle arbitrarily long widths.
  3158. * <li>Numbers do not consume any space characters.
  3159. * <li>It is locale-independent.
  3160. * <li>%u and %x do not consume any space.
  3161. * <li>It returns -1 on malformed patterns.</ul>
  3162. *
  3163. * (As with other locale-independent functions, we need this to parse data that
  3164. * is in ASCII without worrying that the C library's locale-handling will make
  3165. * miscellaneous characters look like numbers, spaces, and so on.)
  3166. */
  3167. int
  3168. tor_sscanf(const char *buf, const char *pattern, ...)
  3169. {
  3170. int r;
  3171. va_list ap;
  3172. va_start(ap, pattern);
  3173. r = tor_vsscanf(buf, pattern, ap);
  3174. va_end(ap);
  3175. return r;
  3176. }
  3177. /** Append the string produced by tor_asprintf(<b>pattern</b>, <b>...</b>)
  3178. * to <b>sl</b>. */
  3179. void
  3180. smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern, ...)
  3181. {
  3182. va_list ap;
  3183. va_start(ap, pattern);
  3184. smartlist_add_vasprintf(sl, pattern, ap);
  3185. va_end(ap);
  3186. }
  3187. /** va_list-based backend of smartlist_add_asprintf. */
  3188. void
  3189. smartlist_add_vasprintf(struct smartlist_t *sl, const char *pattern,
  3190. va_list args)
  3191. {
  3192. char *str = NULL;
  3193. tor_vasprintf(&str, pattern, args);
  3194. tor_assert(str != NULL);
  3195. smartlist_add(sl, str);
  3196. }
  3197. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  3198. * Return NULL on error or if <b>dirname</b> is not a directory.
  3199. */
  3200. MOCK_IMPL(smartlist_t *,
  3201. tor_listdir, (const char *dirname))
  3202. {
  3203. smartlist_t *result;
  3204. #ifdef _WIN32
  3205. char *pattern=NULL;
  3206. TCHAR tpattern[MAX_PATH] = {0};
  3207. char name[MAX_PATH*2+1] = {0};
  3208. HANDLE handle;
  3209. WIN32_FIND_DATA findData;
  3210. tor_asprintf(&pattern, "%s\\*", dirname);
  3211. #ifdef UNICODE
  3212. mbstowcs(tpattern,pattern,MAX_PATH);
  3213. #else
  3214. strlcpy(tpattern, pattern, MAX_PATH);
  3215. #endif
  3216. if (INVALID_HANDLE_VALUE == (handle = FindFirstFile(tpattern, &findData))) {
  3217. tor_free(pattern);
  3218. return NULL;
  3219. }
  3220. result = smartlist_new();
  3221. while (1) {
  3222. #ifdef UNICODE
  3223. wcstombs(name,findData.cFileName,MAX_PATH);
  3224. name[sizeof(name)-1] = '\0';
  3225. #else
  3226. strlcpy(name,findData.cFileName,sizeof(name));
  3227. #endif
  3228. if (strcmp(name, ".") &&
  3229. strcmp(name, "..")) {
  3230. smartlist_add(result, tor_strdup(name));
  3231. }
  3232. if (!FindNextFile(handle, &findData)) {
  3233. DWORD err;
  3234. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  3235. char *errstr = format_win32_error(err);
  3236. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  3237. tor_free(errstr);
  3238. }
  3239. break;
  3240. }
  3241. }
  3242. FindClose(handle);
  3243. tor_free(pattern);
  3244. #else
  3245. const char *prot_dname = sandbox_intern_string(dirname);
  3246. DIR *d;
  3247. struct dirent *de;
  3248. if (!(d = opendir(prot_dname)))
  3249. return NULL;
  3250. result = smartlist_new();
  3251. while ((de = readdir(d))) {
  3252. if (!strcmp(de->d_name, ".") ||
  3253. !strcmp(de->d_name, ".."))
  3254. continue;
  3255. smartlist_add(result, tor_strdup(de->d_name));
  3256. }
  3257. closedir(d);
  3258. #endif
  3259. return result;
  3260. }
  3261. /** Return true iff <b>filename</b> is a relative path. */
  3262. int
  3263. path_is_relative(const char *filename)
  3264. {
  3265. if (filename && filename[0] == '/')
  3266. return 0;
  3267. #ifdef _WIN32
  3268. else if (filename && filename[0] == '\\')
  3269. return 0;
  3270. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  3271. filename[1] == ':' && filename[2] == '\\')
  3272. return 0;
  3273. #endif
  3274. else
  3275. return 1;
  3276. }
  3277. /* =====
  3278. * Process helpers
  3279. * ===== */
  3280. #ifndef _WIN32
  3281. /* Based on code contributed by christian grothoff */
  3282. /** True iff we've called start_daemon(). */
  3283. static int start_daemon_called = 0;
  3284. /** True iff we've called finish_daemon(). */
  3285. static int finish_daemon_called = 0;
  3286. /** Socketpair used to communicate between parent and child process while
  3287. * daemonizing. */
  3288. static int daemon_filedes[2];
  3289. /** Start putting the process into daemon mode: fork and drop all resources
  3290. * except standard fds. The parent process never returns, but stays around
  3291. * until finish_daemon is called. (Note: it's safe to call this more
  3292. * than once: calls after the first are ignored.)
  3293. */
  3294. void
  3295. start_daemon(void)
  3296. {
  3297. pid_t pid;
  3298. if (start_daemon_called)
  3299. return;
  3300. start_daemon_called = 1;
  3301. if (pipe(daemon_filedes)) {
  3302. /* LCOV_EXCL_START */
  3303. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  3304. exit(1);
  3305. /* LCOV_EXCL_STOP */
  3306. }
  3307. pid = fork();
  3308. if (pid < 0) {
  3309. /* LCOV_EXCL_START */
  3310. log_err(LD_GENERAL,"fork failed. Exiting.");
  3311. exit(1);
  3312. /* LCOV_EXCL_STOP */
  3313. }
  3314. if (pid) { /* Parent */
  3315. int ok;
  3316. char c;
  3317. close(daemon_filedes[1]); /* we only read */
  3318. ok = -1;
  3319. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  3320. if (c == '.')
  3321. ok = 1;
  3322. }
  3323. fflush(stdout);
  3324. if (ok == 1)
  3325. exit(0);
  3326. else
  3327. exit(1); /* child reported error */
  3328. } else { /* Child */
  3329. close(daemon_filedes[0]); /* we only write */
  3330. pid = setsid(); /* Detach from controlling terminal */
  3331. /*
  3332. * Fork one more time, so the parent (the session group leader) can exit.
  3333. * This means that we, as a non-session group leader, can never regain a
  3334. * controlling terminal. This part is recommended by Stevens's
  3335. * _Advanced Programming in the Unix Environment_.
  3336. */
  3337. if (fork() != 0) {
  3338. exit(0);
  3339. }
  3340. set_main_thread(); /* We are now the main thread. */
  3341. return;
  3342. }
  3343. }
  3344. /** Finish putting the process into daemon mode: drop standard fds, and tell
  3345. * the parent process to exit. (Note: it's safe to call this more than once:
  3346. * calls after the first are ignored. Calls start_daemon first if it hasn't
  3347. * been called already.)
  3348. */
  3349. void
  3350. finish_daemon(const char *desired_cwd)
  3351. {
  3352. int nullfd;
  3353. char c = '.';
  3354. if (finish_daemon_called)
  3355. return;
  3356. if (!start_daemon_called)
  3357. start_daemon();
  3358. finish_daemon_called = 1;
  3359. if (!desired_cwd)
  3360. desired_cwd = "/";
  3361. /* Don't hold the wrong FS mounted */
  3362. if (chdir(desired_cwd) < 0) {
  3363. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  3364. exit(1);
  3365. }
  3366. nullfd = tor_open_cloexec("/dev/null", O_RDWR, 0);
  3367. if (nullfd < 0) {
  3368. /* LCOV_EXCL_START */
  3369. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  3370. exit(1);
  3371. /* LCOV_EXCL_STOP */
  3372. }
  3373. /* close fds linking to invoking terminal, but
  3374. * close usual incoming fds, but redirect them somewhere
  3375. * useful so the fds don't get reallocated elsewhere.
  3376. */
  3377. if (dup2(nullfd,0) < 0 ||
  3378. dup2(nullfd,1) < 0 ||
  3379. dup2(nullfd,2) < 0) {
  3380. /* LCOV_EXCL_START */
  3381. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  3382. exit(1);
  3383. /* LCOV_EXCL_STOP */
  3384. }
  3385. if (nullfd > 2)
  3386. close(nullfd);
  3387. /* signal success */
  3388. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  3389. log_err(LD_GENERAL,"write failed. Exiting.");
  3390. }
  3391. close(daemon_filedes[1]);
  3392. }
  3393. #else
  3394. /* defined(_WIN32) */
  3395. void
  3396. start_daemon(void)
  3397. {
  3398. }
  3399. void
  3400. finish_daemon(const char *cp)
  3401. {
  3402. (void)cp;
  3403. }
  3404. #endif
  3405. /** Write the current process ID, followed by NL, into <b>filename</b>.
  3406. */
  3407. void
  3408. write_pidfile(const char *filename)
  3409. {
  3410. FILE *pidfile;
  3411. if ((pidfile = fopen(filename, "w")) == NULL) {
  3412. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  3413. strerror(errno));
  3414. } else {
  3415. #ifdef _WIN32
  3416. fprintf(pidfile, "%d\n", (int)_getpid());
  3417. #else
  3418. fprintf(pidfile, "%d\n", (int)getpid());
  3419. #endif
  3420. fclose(pidfile);
  3421. }
  3422. }
  3423. #ifdef _WIN32
  3424. HANDLE
  3425. load_windows_system_library(const TCHAR *library_name)
  3426. {
  3427. TCHAR path[MAX_PATH];
  3428. unsigned n;
  3429. n = GetSystemDirectory(path, MAX_PATH);
  3430. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  3431. return 0;
  3432. _tcscat(path, TEXT("\\"));
  3433. _tcscat(path, library_name);
  3434. return LoadLibrary(path);
  3435. }
  3436. #endif
  3437. /** Format a single argument for being put on a Windows command line.
  3438. * Returns a newly allocated string */
  3439. static char *
  3440. format_win_cmdline_argument(const char *arg)
  3441. {
  3442. char *formatted_arg;
  3443. char need_quotes;
  3444. const char *c;
  3445. int i;
  3446. int bs_counter = 0;
  3447. /* Backslash we can point to when one is inserted into the string */
  3448. const char backslash = '\\';
  3449. /* Smartlist of *char */
  3450. smartlist_t *arg_chars;
  3451. arg_chars = smartlist_new();
  3452. /* Quote string if it contains whitespace or is empty */
  3453. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  3454. /* Build up smartlist of *chars */
  3455. for (c=arg; *c != '\0'; c++) {
  3456. if ('"' == *c) {
  3457. /* Double up backslashes preceding a quote */
  3458. for (i=0; i<(bs_counter*2); i++)
  3459. smartlist_add(arg_chars, (void*)&backslash);
  3460. bs_counter = 0;
  3461. /* Escape the quote */
  3462. smartlist_add(arg_chars, (void*)&backslash);
  3463. smartlist_add(arg_chars, (void*)c);
  3464. } else if ('\\' == *c) {
  3465. /* Count backslashes until we know whether to double up */
  3466. bs_counter++;
  3467. } else {
  3468. /* Don't double up slashes preceding a non-quote */
  3469. for (i=0; i<bs_counter; i++)
  3470. smartlist_add(arg_chars, (void*)&backslash);
  3471. bs_counter = 0;
  3472. smartlist_add(arg_chars, (void*)c);
  3473. }
  3474. }
  3475. /* Don't double up trailing backslashes */
  3476. for (i=0; i<bs_counter; i++)
  3477. smartlist_add(arg_chars, (void*)&backslash);
  3478. /* Allocate space for argument, quotes (if needed), and terminator */
  3479. const size_t formatted_arg_len = smartlist_len(arg_chars) +
  3480. (need_quotes ? 2 : 0) + 1;
  3481. formatted_arg = tor_malloc_zero(formatted_arg_len);
  3482. /* Add leading quote */
  3483. i=0;
  3484. if (need_quotes)
  3485. formatted_arg[i++] = '"';
  3486. /* Add characters */
  3487. SMARTLIST_FOREACH(arg_chars, char*, ch,
  3488. {
  3489. formatted_arg[i++] = *ch;
  3490. });
  3491. /* Add trailing quote */
  3492. if (need_quotes)
  3493. formatted_arg[i++] = '"';
  3494. formatted_arg[i] = '\0';
  3495. smartlist_free(arg_chars);
  3496. return formatted_arg;
  3497. }
  3498. /** Format a command line for use on Windows, which takes the command as a
  3499. * string rather than string array. Follows the rules from "Parsing C++
  3500. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  3501. * Python subprocess module. Returns a newly allocated string */
  3502. char *
  3503. tor_join_win_cmdline(const char *argv[])
  3504. {
  3505. smartlist_t *argv_list;
  3506. char *joined_argv;
  3507. int i;
  3508. /* Format each argument and put the result in a smartlist */
  3509. argv_list = smartlist_new();
  3510. for (i=0; argv[i] != NULL; i++) {
  3511. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  3512. }
  3513. /* Join the arguments with whitespace */
  3514. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  3515. /* Free the newly allocated arguments, and the smartlist */
  3516. SMARTLIST_FOREACH(argv_list, char *, arg,
  3517. {
  3518. tor_free(arg);
  3519. });
  3520. smartlist_free(argv_list);
  3521. return joined_argv;
  3522. }
  3523. /* As format_{hex,dex}_number_sigsafe, but takes a <b>radix</b> argument
  3524. * in range 2..16 inclusive. */
  3525. static int
  3526. format_number_sigsafe(unsigned long x, char *buf, int buf_len,
  3527. unsigned int radix)
  3528. {
  3529. unsigned long tmp;
  3530. int len;
  3531. char *cp;
  3532. /* NOT tor_assert. This needs to be safe to run from within a signal handler,
  3533. * and from within the 'tor_assert() has failed' code. */
  3534. if (radix < 2 || radix > 16)
  3535. return 0;
  3536. /* Count how many digits we need. */
  3537. tmp = x;
  3538. len = 1;
  3539. while (tmp >= radix) {
  3540. tmp /= radix;
  3541. ++len;
  3542. }
  3543. /* Not long enough */
  3544. if (!buf || len >= buf_len)
  3545. return 0;
  3546. cp = buf + len;
  3547. *cp = '\0';
  3548. do {
  3549. unsigned digit = (unsigned) (x % radix);
  3550. tor_assert(cp > buf);
  3551. --cp;
  3552. *cp = "0123456789ABCDEF"[digit];
  3553. x /= radix;
  3554. } while (x);
  3555. /* NOT tor_assert; see above. */
  3556. if (cp != buf) {
  3557. abort(); // LCOV_EXCL_LINE
  3558. }
  3559. return len;
  3560. }
  3561. /**
  3562. * Helper function to output hex numbers from within a signal handler.
  3563. *
  3564. * Writes the nul-terminated hexadecimal digits of <b>x</b> into a buffer
  3565. * <b>buf</b> of size <b>buf_len</b>, and return the actual number of digits
  3566. * written, not counting the terminal NUL.
  3567. *
  3568. * If there is insufficient space, write nothing and return 0.
  3569. *
  3570. * This accepts an unsigned int because format_helper_exit_status() needs to
  3571. * call it with a signed int and an unsigned char, and since the C standard
  3572. * does not guarantee that an int is wider than a char (an int must be at
  3573. * least 16 bits but it is permitted for a char to be that wide as well), we
  3574. * can't assume a signed int is sufficient to accomodate an unsigned char.
  3575. * Thus, format_helper_exit_status() will still need to emit any require '-'
  3576. * on its own.
  3577. *
  3578. * For most purposes, you'd want to use tor_snprintf("%x") instead of this
  3579. * function; it's designed to be used in code paths where you can't call
  3580. * arbitrary C functions.
  3581. */
  3582. int
  3583. format_hex_number_sigsafe(unsigned long x, char *buf, int buf_len)
  3584. {
  3585. return format_number_sigsafe(x, buf, buf_len, 16);
  3586. }
  3587. /** As format_hex_number_sigsafe, but format the number in base 10. */
  3588. int
  3589. format_dec_number_sigsafe(unsigned long x, char *buf, int buf_len)
  3590. {
  3591. return format_number_sigsafe(x, buf, buf_len, 10);
  3592. }
  3593. #ifndef _WIN32
  3594. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  3595. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  3596. * safe.
  3597. *
  3598. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE+1 bytes available.
  3599. *
  3600. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  3601. * with spaces. CHILD_STATE indicates where
  3602. * in the processs of starting the child process did the failure occur (see
  3603. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  3604. * errno when the failure occurred.
  3605. *
  3606. * On success return the number of characters added to hex_errno, not counting
  3607. * the terminating NUL; return -1 on error.
  3608. */
  3609. STATIC int
  3610. format_helper_exit_status(unsigned char child_state, int saved_errno,
  3611. char *hex_errno)
  3612. {
  3613. unsigned int unsigned_errno;
  3614. int written, left;
  3615. char *cur;
  3616. size_t i;
  3617. int res = -1;
  3618. /* Fill hex_errno with spaces, and a trailing newline (memset may
  3619. not be signal handler safe, so we can't use it) */
  3620. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  3621. hex_errno[i] = ' ';
  3622. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  3623. /* Convert errno to be unsigned for hex conversion */
  3624. if (saved_errno < 0) {
  3625. // Avoid overflow on the cast to unsigned int when result is INT_MIN
  3626. // by adding 1 to the signed int negative value,
  3627. // then, after it has been negated and cast to unsigned,
  3628. // adding the original 1 back (the double-addition is intentional).
  3629. // Otherwise, the cast to signed could cause a temporary int
  3630. // to equal INT_MAX + 1, which is undefined.
  3631. unsigned_errno = ((unsigned int) -(saved_errno + 1)) + 1;
  3632. } else {
  3633. unsigned_errno = (unsigned int) saved_errno;
  3634. }
  3635. /*
  3636. * Count how many chars of space we have left, and keep a pointer into the
  3637. * current point in the buffer.
  3638. */
  3639. left = HEX_ERRNO_SIZE+1;
  3640. cur = hex_errno;
  3641. /* Emit child_state */
  3642. written = format_hex_number_sigsafe(child_state, cur, left);
  3643. if (written <= 0)
  3644. goto err;
  3645. /* Adjust left and cur */
  3646. left -= written;
  3647. cur += written;
  3648. if (left <= 0)
  3649. goto err;
  3650. /* Now the '/' */
  3651. *cur = '/';
  3652. /* Adjust left and cur */
  3653. ++cur;
  3654. --left;
  3655. if (left <= 0)
  3656. goto err;
  3657. /* Need minus? */
  3658. if (saved_errno < 0) {
  3659. *cur = '-';
  3660. ++cur;
  3661. --left;
  3662. if (left <= 0)
  3663. goto err;
  3664. }
  3665. /* Emit unsigned_errno */
  3666. written = format_hex_number_sigsafe(unsigned_errno, cur, left);
  3667. if (written <= 0)
  3668. goto err;
  3669. /* Adjust left and cur */
  3670. left -= written;
  3671. cur += written;
  3672. /* Check that we have enough space left for a newline and a NUL */
  3673. if (left <= 1)
  3674. goto err;
  3675. /* Emit the newline and NUL */
  3676. *cur++ = '\n';
  3677. *cur++ = '\0';
  3678. res = (int)(cur - hex_errno - 1);
  3679. goto done;
  3680. err:
  3681. /*
  3682. * In error exit, just write a '\0' in the first char so whatever called
  3683. * this at least won't fall off the end.
  3684. */
  3685. *hex_errno = '\0';
  3686. done:
  3687. return res;
  3688. }
  3689. #endif
  3690. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  3691. #define DEFAULT_MAX_FD 256
  3692. /** Terminate the process of <b>process_handle</b>, if that process has not
  3693. * already exited.
  3694. *
  3695. * Return 0 if we succeeded in terminating the process (or if the process
  3696. * already exited), and -1 if we tried to kill the process but failed.
  3697. *
  3698. * Based on code originally borrowed from Python's os.kill. */
  3699. int
  3700. tor_terminate_process(process_handle_t *process_handle)
  3701. {
  3702. #ifdef _WIN32
  3703. if (tor_get_exit_code(process_handle, 0, NULL) == PROCESS_EXIT_RUNNING) {
  3704. HANDLE handle = process_handle->pid.hProcess;
  3705. if (!TerminateProcess(handle, 0))
  3706. return -1;
  3707. else
  3708. return 0;
  3709. }
  3710. #else /* Unix */
  3711. if (process_handle->waitpid_cb) {
  3712. /* We haven't got a waitpid yet, so we can just kill off the process. */
  3713. return kill(process_handle->pid, SIGTERM);
  3714. }
  3715. #endif
  3716. return 0; /* We didn't need to kill the process, so report success */
  3717. }
  3718. /** Return the Process ID of <b>process_handle</b>. */
  3719. int
  3720. tor_process_get_pid(process_handle_t *process_handle)
  3721. {
  3722. #ifdef _WIN32
  3723. return (int) process_handle->pid.dwProcessId;
  3724. #else
  3725. return (int) process_handle->pid;
  3726. #endif
  3727. }
  3728. #ifdef _WIN32
  3729. HANDLE
  3730. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  3731. {
  3732. return process_handle->stdout_pipe;
  3733. }
  3734. #else
  3735. /* DOCDOC tor_process_get_stdout_pipe */
  3736. FILE *
  3737. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  3738. {
  3739. return process_handle->stdout_handle;
  3740. }
  3741. #endif
  3742. /* DOCDOC process_handle_new */
  3743. static process_handle_t *
  3744. process_handle_new(void)
  3745. {
  3746. process_handle_t *out = tor_malloc_zero(sizeof(process_handle_t));
  3747. #ifdef _WIN32
  3748. out->stdin_pipe = INVALID_HANDLE_VALUE;
  3749. out->stdout_pipe = INVALID_HANDLE_VALUE;
  3750. out->stderr_pipe = INVALID_HANDLE_VALUE;
  3751. #else
  3752. out->stdin_pipe = -1;
  3753. out->stdout_pipe = -1;
  3754. out->stderr_pipe = -1;
  3755. #endif
  3756. return out;
  3757. }
  3758. #ifndef _WIN32
  3759. /** Invoked when a process that we've launched via tor_spawn_background() has
  3760. * been found to have terminated.
  3761. */
  3762. static void
  3763. process_handle_waitpid_cb(int status, void *arg)
  3764. {
  3765. process_handle_t *process_handle = arg;
  3766. process_handle->waitpid_exit_status = status;
  3767. clear_waitpid_callback(process_handle->waitpid_cb);
  3768. if (process_handle->status == PROCESS_STATUS_RUNNING)
  3769. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  3770. process_handle->waitpid_cb = 0;
  3771. }
  3772. #endif
  3773. /**
  3774. * @name child-process states
  3775. *
  3776. * Each of these values represents a possible state that a child process can
  3777. * be in. They're used to determine what to say when telling the parent how
  3778. * far along we were before failure.
  3779. *
  3780. * @{
  3781. */
  3782. #define CHILD_STATE_INIT 0
  3783. #define CHILD_STATE_PIPE 1
  3784. #define CHILD_STATE_MAXFD 2
  3785. #define CHILD_STATE_FORK 3
  3786. #define CHILD_STATE_DUPOUT 4
  3787. #define CHILD_STATE_DUPERR 5
  3788. #define CHILD_STATE_DUPIN 6
  3789. #define CHILD_STATE_CLOSEFD 7
  3790. #define CHILD_STATE_EXEC 8
  3791. #define CHILD_STATE_FAILEXEC 9
  3792. /** @} */
  3793. /** Start a program in the background. If <b>filename</b> contains a '/', then
  3794. * it will be treated as an absolute or relative path. Otherwise, on
  3795. * non-Windows systems, the system path will be searched for <b>filename</b>.
  3796. * On Windows, only the current directory will be searched. Here, to search the
  3797. * system path (as well as the application directory, current working
  3798. * directory, and system directories), set filename to NULL.
  3799. *
  3800. * The strings in <b>argv</b> will be passed as the command line arguments of
  3801. * the child program (following convention, argv[0] should normally be the
  3802. * filename of the executable, and this must be the case if <b>filename</b> is
  3803. * NULL). The last element of argv must be NULL. A handle to the child process
  3804. * will be returned in process_handle (which must be non-NULL). Read
  3805. * process_handle.status to find out if the process was successfully launched.
  3806. * For convenience, process_handle.status is returned by this function.
  3807. *
  3808. * Some parts of this code are based on the POSIX subprocess module from
  3809. * Python, and example code from
  3810. * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
  3811. */
  3812. int
  3813. tor_spawn_background(const char *const filename, const char **argv,
  3814. process_environment_t *env,
  3815. process_handle_t **process_handle_out)
  3816. {
  3817. #ifdef _WIN32
  3818. HANDLE stdout_pipe_read = NULL;
  3819. HANDLE stdout_pipe_write = NULL;
  3820. HANDLE stderr_pipe_read = NULL;
  3821. HANDLE stderr_pipe_write = NULL;
  3822. HANDLE stdin_pipe_read = NULL;
  3823. HANDLE stdin_pipe_write = NULL;
  3824. process_handle_t *process_handle;
  3825. int status;
  3826. STARTUPINFOA siStartInfo;
  3827. BOOL retval = FALSE;
  3828. SECURITY_ATTRIBUTES saAttr;
  3829. char *joined_argv;
  3830. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  3831. saAttr.bInheritHandle = TRUE;
  3832. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3833. saAttr.lpSecurityDescriptor = NULL;
  3834. /* Assume failure to start process */
  3835. status = PROCESS_STATUS_ERROR;
  3836. /* Set up pipe for stdout */
  3837. if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, &saAttr, 0)) {
  3838. log_warn(LD_GENERAL,
  3839. "Failed to create pipe for stdout communication with child process: %s",
  3840. format_win32_error(GetLastError()));
  3841. return status;
  3842. }
  3843. if (!SetHandleInformation(stdout_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3844. log_warn(LD_GENERAL,
  3845. "Failed to configure pipe for stdout communication with child "
  3846. "process: %s", format_win32_error(GetLastError()));
  3847. return status;
  3848. }
  3849. /* Set up pipe for stderr */
  3850. if (!CreatePipe(&stderr_pipe_read, &stderr_pipe_write, &saAttr, 0)) {
  3851. log_warn(LD_GENERAL,
  3852. "Failed to create pipe for stderr communication with child process: %s",
  3853. format_win32_error(GetLastError()));
  3854. return status;
  3855. }
  3856. if (!SetHandleInformation(stderr_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3857. log_warn(LD_GENERAL,
  3858. "Failed to configure pipe for stderr communication with child "
  3859. "process: %s", format_win32_error(GetLastError()));
  3860. return status;
  3861. }
  3862. /* Set up pipe for stdin */
  3863. if (!CreatePipe(&stdin_pipe_read, &stdin_pipe_write, &saAttr, 0)) {
  3864. log_warn(LD_GENERAL,
  3865. "Failed to create pipe for stdin communication with child process: %s",
  3866. format_win32_error(GetLastError()));
  3867. return status;
  3868. }
  3869. if (!SetHandleInformation(stdin_pipe_write, HANDLE_FLAG_INHERIT, 0)) {
  3870. log_warn(LD_GENERAL,
  3871. "Failed to configure pipe for stdin communication with child "
  3872. "process: %s", format_win32_error(GetLastError()));
  3873. return status;
  3874. }
  3875. /* Create the child process */
  3876. /* Windows expects argv to be a whitespace delimited string, so join argv up
  3877. */
  3878. joined_argv = tor_join_win_cmdline(argv);
  3879. process_handle = process_handle_new();
  3880. process_handle->status = status;
  3881. ZeroMemory(&(process_handle->pid), sizeof(PROCESS_INFORMATION));
  3882. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  3883. siStartInfo.cb = sizeof(STARTUPINFO);
  3884. siStartInfo.hStdError = stderr_pipe_write;
  3885. siStartInfo.hStdOutput = stdout_pipe_write;
  3886. siStartInfo.hStdInput = stdin_pipe_read;
  3887. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  3888. /* Create the child process */
  3889. retval = CreateProcessA(filename, // module name
  3890. joined_argv, // command line
  3891. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3892. NULL, // process security attributes
  3893. NULL, // primary thread security attributes
  3894. TRUE, // handles are inherited
  3895. /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
  3896. * work?) */
  3897. CREATE_NO_WINDOW, // creation flags
  3898. (env==NULL) ? NULL : env->windows_environment_block,
  3899. NULL, // use parent's current directory
  3900. &siStartInfo, // STARTUPINFO pointer
  3901. &(process_handle->pid)); // receives PROCESS_INFORMATION
  3902. tor_free(joined_argv);
  3903. if (!retval) {
  3904. log_warn(LD_GENERAL,
  3905. "Failed to create child process %s: %s", filename?filename:argv[0],
  3906. format_win32_error(GetLastError()));
  3907. tor_free(process_handle);
  3908. } else {
  3909. /* TODO: Close hProcess and hThread in process_handle->pid? */
  3910. process_handle->stdout_pipe = stdout_pipe_read;
  3911. process_handle->stderr_pipe = stderr_pipe_read;
  3912. process_handle->stdin_pipe = stdin_pipe_write;
  3913. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3914. }
  3915. /* TODO: Close pipes on exit */
  3916. *process_handle_out = process_handle;
  3917. return status;
  3918. #else // _WIN32
  3919. pid_t pid;
  3920. int stdout_pipe[2];
  3921. int stderr_pipe[2];
  3922. int stdin_pipe[2];
  3923. int fd, retval;
  3924. ssize_t nbytes;
  3925. process_handle_t *process_handle;
  3926. int status;
  3927. const char *error_message = SPAWN_ERROR_MESSAGE;
  3928. size_t error_message_length;
  3929. /* Represents where in the process of spawning the program is;
  3930. this is used for printing out the error message */
  3931. unsigned char child_state = CHILD_STATE_INIT;
  3932. char hex_errno[HEX_ERRNO_SIZE + 2]; /* + 1 should be sufficient actually */
  3933. static int max_fd = -1;
  3934. status = PROCESS_STATUS_ERROR;
  3935. /* We do the strlen here because strlen() is not signal handler safe,
  3936. and we are not allowed to use unsafe functions between fork and exec */
  3937. error_message_length = strlen(error_message);
  3938. child_state = CHILD_STATE_PIPE;
  3939. /* Set up pipe for redirecting stdout, stderr, and stdin of child */
  3940. retval = pipe(stdout_pipe);
  3941. if (-1 == retval) {
  3942. log_warn(LD_GENERAL,
  3943. "Failed to set up pipe for stdout communication with child process: %s",
  3944. strerror(errno));
  3945. return status;
  3946. }
  3947. retval = pipe(stderr_pipe);
  3948. if (-1 == retval) {
  3949. log_warn(LD_GENERAL,
  3950. "Failed to set up pipe for stderr communication with child process: %s",
  3951. strerror(errno));
  3952. close(stdout_pipe[0]);
  3953. close(stdout_pipe[1]);
  3954. return status;
  3955. }
  3956. retval = pipe(stdin_pipe);
  3957. if (-1 == retval) {
  3958. log_warn(LD_GENERAL,
  3959. "Failed to set up pipe for stdin communication with child process: %s",
  3960. strerror(errno));
  3961. close(stdout_pipe[0]);
  3962. close(stdout_pipe[1]);
  3963. close(stderr_pipe[0]);
  3964. close(stderr_pipe[1]);
  3965. return status;
  3966. }
  3967. child_state = CHILD_STATE_MAXFD;
  3968. #ifdef _SC_OPEN_MAX
  3969. if (-1 == max_fd) {
  3970. max_fd = (int) sysconf(_SC_OPEN_MAX);
  3971. if (max_fd == -1) {
  3972. max_fd = DEFAULT_MAX_FD;
  3973. log_warn(LD_GENERAL,
  3974. "Cannot find maximum file descriptor, assuming %d", max_fd);
  3975. }
  3976. }
  3977. #else
  3978. max_fd = DEFAULT_MAX_FD;
  3979. #endif
  3980. child_state = CHILD_STATE_FORK;
  3981. pid = fork();
  3982. if (0 == pid) {
  3983. /* In child */
  3984. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  3985. /* Attempt to have the kernel issue a SIGTERM if the parent
  3986. * goes away. Certain attributes of the binary being execve()ed
  3987. * will clear this during the execve() call, but it's better
  3988. * than nothing.
  3989. */
  3990. prctl(PR_SET_PDEATHSIG, SIGTERM);
  3991. #endif
  3992. child_state = CHILD_STATE_DUPOUT;
  3993. /* Link child stdout to the write end of the pipe */
  3994. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  3995. if (-1 == retval)
  3996. goto error;
  3997. child_state = CHILD_STATE_DUPERR;
  3998. /* Link child stderr to the write end of the pipe */
  3999. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  4000. if (-1 == retval)
  4001. goto error;
  4002. child_state = CHILD_STATE_DUPIN;
  4003. /* Link child stdin to the read end of the pipe */
  4004. retval = dup2(stdin_pipe[0], STDIN_FILENO);
  4005. if (-1 == retval)
  4006. goto error;
  4007. child_state = CHILD_STATE_CLOSEFD;
  4008. close(stderr_pipe[0]);
  4009. close(stderr_pipe[1]);
  4010. close(stdout_pipe[0]);
  4011. close(stdout_pipe[1]);
  4012. close(stdin_pipe[0]);
  4013. close(stdin_pipe[1]);
  4014. /* Close all other fds, including the read end of the pipe */
  4015. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  4016. * this needless. */
  4017. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  4018. close(fd);
  4019. }
  4020. child_state = CHILD_STATE_EXEC;
  4021. /* Call the requested program. We need the cast because
  4022. execvp doesn't define argv as const, even though it
  4023. does not modify the arguments */
  4024. if (env)
  4025. execve(filename, (char *const *) argv, env->unixoid_environment_block);
  4026. else {
  4027. static char *new_env[] = { NULL };
  4028. execve(filename, (char *const *) argv, new_env);
  4029. }
  4030. /* If we got here, the exec or open(/dev/null) failed */
  4031. child_state = CHILD_STATE_FAILEXEC;
  4032. error:
  4033. {
  4034. /* XXX: are we leaking fds from the pipe? */
  4035. int n;
  4036. n = format_helper_exit_status(child_state, errno, hex_errno);
  4037. if (n >= 0) {
  4038. /* Write the error message. GCC requires that we check the return
  4039. value, but there is nothing we can do if it fails */
  4040. /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
  4041. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  4042. nbytes = write(STDOUT_FILENO, hex_errno, n);
  4043. }
  4044. }
  4045. (void) nbytes;
  4046. _exit(255);
  4047. /* Never reached, but avoids compiler warning */
  4048. return status; // LCOV_EXCL_LINE
  4049. }
  4050. /* In parent */
  4051. if (-1 == pid) {
  4052. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  4053. close(stdin_pipe[0]);
  4054. close(stdin_pipe[1]);
  4055. close(stdout_pipe[0]);
  4056. close(stdout_pipe[1]);
  4057. close(stderr_pipe[0]);
  4058. close(stderr_pipe[1]);
  4059. return status;
  4060. }
  4061. process_handle = process_handle_new();
  4062. process_handle->status = status;
  4063. process_handle->pid = pid;
  4064. /* TODO: If the child process forked but failed to exec, waitpid it */
  4065. /* Return read end of the pipes to caller, and close write end */
  4066. process_handle->stdout_pipe = stdout_pipe[0];
  4067. retval = close(stdout_pipe[1]);
  4068. if (-1 == retval) {
  4069. log_warn(LD_GENERAL,
  4070. "Failed to close write end of stdout pipe in parent process: %s",
  4071. strerror(errno));
  4072. }
  4073. process_handle->waitpid_cb = set_waitpid_callback(pid,
  4074. process_handle_waitpid_cb,
  4075. process_handle);
  4076. process_handle->stderr_pipe = stderr_pipe[0];
  4077. retval = close(stderr_pipe[1]);
  4078. if (-1 == retval) {
  4079. log_warn(LD_GENERAL,
  4080. "Failed to close write end of stderr pipe in parent process: %s",
  4081. strerror(errno));
  4082. }
  4083. /* Return write end of the stdin pipe to caller, and close the read end */
  4084. process_handle->stdin_pipe = stdin_pipe[1];
  4085. retval = close(stdin_pipe[0]);
  4086. if (-1 == retval) {
  4087. log_warn(LD_GENERAL,
  4088. "Failed to close read end of stdin pipe in parent process: %s",
  4089. strerror(errno));
  4090. }
  4091. status = process_handle->status = PROCESS_STATUS_RUNNING;
  4092. /* Set stdin/stdout/stderr pipes to be non-blocking */
  4093. if (fcntl(process_handle->stdout_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  4094. fcntl(process_handle->stderr_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  4095. fcntl(process_handle->stdin_pipe, F_SETFL, O_NONBLOCK) < 0) {
  4096. log_warn(LD_GENERAL, "Failed to set stderror/stdout/stdin pipes "
  4097. "nonblocking in parent process: %s", strerror(errno));
  4098. }
  4099. /* Open the buffered IO streams */
  4100. process_handle->stdout_handle = fdopen(process_handle->stdout_pipe, "r");
  4101. process_handle->stderr_handle = fdopen(process_handle->stderr_pipe, "r");
  4102. process_handle->stdin_handle = fdopen(process_handle->stdin_pipe, "r");
  4103. *process_handle_out = process_handle;
  4104. return process_handle->status;
  4105. #endif // _WIN32
  4106. }
  4107. /** Destroy all resources allocated by the process handle in
  4108. * <b>process_handle</b>.
  4109. * If <b>also_terminate_process</b> is true, also terminate the
  4110. * process of the process handle. */
  4111. MOCK_IMPL(void,
  4112. tor_process_handle_destroy,(process_handle_t *process_handle,
  4113. int also_terminate_process))
  4114. {
  4115. if (!process_handle)
  4116. return;
  4117. if (also_terminate_process) {
  4118. if (tor_terminate_process(process_handle) < 0) {
  4119. const char *errstr =
  4120. #ifdef _WIN32
  4121. format_win32_error(GetLastError());
  4122. #else
  4123. strerror(errno);
  4124. #endif
  4125. log_notice(LD_GENERAL, "Failed to terminate process with "
  4126. "PID '%d' ('%s').", tor_process_get_pid(process_handle),
  4127. errstr);
  4128. } else {
  4129. log_info(LD_GENERAL, "Terminated process with PID '%d'.",
  4130. tor_process_get_pid(process_handle));
  4131. }
  4132. }
  4133. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  4134. #ifdef _WIN32
  4135. if (process_handle->stdout_pipe)
  4136. CloseHandle(process_handle->stdout_pipe);
  4137. if (process_handle->stderr_pipe)
  4138. CloseHandle(process_handle->stderr_pipe);
  4139. if (process_handle->stdin_pipe)
  4140. CloseHandle(process_handle->stdin_pipe);
  4141. #else
  4142. if (process_handle->stdout_handle)
  4143. fclose(process_handle->stdout_handle);
  4144. if (process_handle->stderr_handle)
  4145. fclose(process_handle->stderr_handle);
  4146. if (process_handle->stdin_handle)
  4147. fclose(process_handle->stdin_handle);
  4148. clear_waitpid_callback(process_handle->waitpid_cb);
  4149. #endif
  4150. memset(process_handle, 0x0f, sizeof(process_handle_t));
  4151. tor_free(process_handle);
  4152. }
  4153. /** Get the exit code of a process specified by <b>process_handle</b> and store
  4154. * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
  4155. * to true, the call will block until the process has exited. Otherwise if
  4156. * the process is still running, the function will return
  4157. * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
  4158. * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
  4159. * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
  4160. * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
  4161. * probably not work in Tor, because waitpid() is called in main.c to reap any
  4162. * terminated child processes.*/
  4163. int
  4164. tor_get_exit_code(process_handle_t *process_handle,
  4165. int block, int *exit_code)
  4166. {
  4167. #ifdef _WIN32
  4168. DWORD retval;
  4169. BOOL success;
  4170. if (block) {
  4171. /* Wait for the process to exit */
  4172. retval = WaitForSingleObject(process_handle->pid.hProcess, INFINITE);
  4173. if (retval != WAIT_OBJECT_0) {
  4174. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  4175. (int)retval, format_win32_error(GetLastError()));
  4176. return PROCESS_EXIT_ERROR;
  4177. }
  4178. } else {
  4179. retval = WaitForSingleObject(process_handle->pid.hProcess, 0);
  4180. if (WAIT_TIMEOUT == retval) {
  4181. /* Process has not exited */
  4182. return PROCESS_EXIT_RUNNING;
  4183. } else if (retval != WAIT_OBJECT_0) {
  4184. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  4185. (int)retval, format_win32_error(GetLastError()));
  4186. return PROCESS_EXIT_ERROR;
  4187. }
  4188. }
  4189. if (exit_code != NULL) {
  4190. success = GetExitCodeProcess(process_handle->pid.hProcess,
  4191. (PDWORD)exit_code);
  4192. if (!success) {
  4193. log_warn(LD_GENERAL, "GetExitCodeProcess() failed: %s",
  4194. format_win32_error(GetLastError()));
  4195. return PROCESS_EXIT_ERROR;
  4196. }
  4197. }
  4198. #else
  4199. int stat_loc;
  4200. int retval;
  4201. if (process_handle->waitpid_cb) {
  4202. /* We haven't processed a SIGCHLD yet. */
  4203. retval = waitpid(process_handle->pid, &stat_loc, block?0:WNOHANG);
  4204. if (retval == process_handle->pid) {
  4205. clear_waitpid_callback(process_handle->waitpid_cb);
  4206. process_handle->waitpid_cb = NULL;
  4207. process_handle->waitpid_exit_status = stat_loc;
  4208. }
  4209. } else {
  4210. /* We already got a SIGCHLD for this process, and handled it. */
  4211. retval = process_handle->pid;
  4212. stat_loc = process_handle->waitpid_exit_status;
  4213. }
  4214. if (!block && 0 == retval) {
  4215. /* Process has not exited */
  4216. return PROCESS_EXIT_RUNNING;
  4217. } else if (retval != process_handle->pid) {
  4218. log_warn(LD_GENERAL, "waitpid() failed for PID %d: %s",
  4219. process_handle->pid, strerror(errno));
  4220. return PROCESS_EXIT_ERROR;
  4221. }
  4222. if (!WIFEXITED(stat_loc)) {
  4223. log_warn(LD_GENERAL, "Process %d did not exit normally",
  4224. process_handle->pid);
  4225. return PROCESS_EXIT_ERROR;
  4226. }
  4227. if (exit_code != NULL)
  4228. *exit_code = WEXITSTATUS(stat_loc);
  4229. #endif // _WIN32
  4230. return PROCESS_EXIT_EXITED;
  4231. }
  4232. /** Helper: return the number of characters in <b>s</b> preceding the first
  4233. * occurrence of <b>ch</b>. If <b>ch</b> does not occur in <b>s</b>, return
  4234. * the length of <b>s</b>. Should be equivalent to strspn(s, "ch"). */
  4235. static inline size_t
  4236. str_num_before(const char *s, char ch)
  4237. {
  4238. const char *cp = strchr(s, ch);
  4239. if (cp)
  4240. return cp - s;
  4241. else
  4242. return strlen(s);
  4243. }
  4244. /** Return non-zero iff getenv would consider <b>s1</b> and <b>s2</b>
  4245. * to have the same name as strings in a process's environment. */
  4246. int
  4247. environment_variable_names_equal(const char *s1, const char *s2)
  4248. {
  4249. size_t s1_name_len = str_num_before(s1, '=');
  4250. size_t s2_name_len = str_num_before(s2, '=');
  4251. return (s1_name_len == s2_name_len &&
  4252. tor_memeq(s1, s2, s1_name_len));
  4253. }
  4254. /** Free <b>env</b> (assuming it was produced by
  4255. * process_environment_make). */
  4256. void
  4257. process_environment_free(process_environment_t *env)
  4258. {
  4259. if (env == NULL) return;
  4260. /* As both an optimization hack to reduce consing on Unixoid systems
  4261. * and a nice way to ensure that some otherwise-Windows-specific
  4262. * code will always get tested before changes to it get merged, the
  4263. * strings which env->unixoid_environment_block points to are packed
  4264. * into env->windows_environment_block. */
  4265. tor_free(env->unixoid_environment_block);
  4266. tor_free(env->windows_environment_block);
  4267. tor_free(env);
  4268. }
  4269. /** Make a process_environment_t containing the environment variables
  4270. * specified in <b>env_vars</b> (as C strings of the form
  4271. * "NAME=VALUE"). */
  4272. process_environment_t *
  4273. process_environment_make(struct smartlist_t *env_vars)
  4274. {
  4275. process_environment_t *env = tor_malloc_zero(sizeof(process_environment_t));
  4276. size_t n_env_vars = smartlist_len(env_vars);
  4277. size_t i;
  4278. size_t total_env_length;
  4279. smartlist_t *env_vars_sorted;
  4280. tor_assert(n_env_vars + 1 != 0);
  4281. env->unixoid_environment_block = tor_calloc(n_env_vars + 1, sizeof(char *));
  4282. /* env->unixoid_environment_block is already NULL-terminated,
  4283. * because we assume that NULL == 0 (and check that during compilation). */
  4284. total_env_length = 1; /* terminating NUL of terminating empty string */
  4285. for (i = 0; i < n_env_vars; ++i) {
  4286. const char *s = smartlist_get(env_vars, i);
  4287. size_t slen = strlen(s);
  4288. tor_assert(slen + 1 != 0);
  4289. tor_assert(slen + 1 < SIZE_MAX - total_env_length);
  4290. total_env_length += slen + 1;
  4291. }
  4292. env->windows_environment_block = tor_malloc_zero(total_env_length);
  4293. /* env->windows_environment_block is already
  4294. * (NUL-terminated-empty-string)-terminated. */
  4295. /* Some versions of Windows supposedly require that environment
  4296. * blocks be sorted. Or maybe some Windows programs (or their
  4297. * runtime libraries) fail to look up strings in non-sorted
  4298. * environment blocks.
  4299. *
  4300. * Also, sorting strings makes it easy to find duplicate environment
  4301. * variables and environment-variable strings without an '=' on all
  4302. * OSes, and they can cause badness. Let's complain about those. */
  4303. env_vars_sorted = smartlist_new();
  4304. smartlist_add_all(env_vars_sorted, env_vars);
  4305. smartlist_sort_strings(env_vars_sorted);
  4306. /* Now copy the strings into the environment blocks. */
  4307. {
  4308. char *cp = env->windows_environment_block;
  4309. const char *prev_env_var = NULL;
  4310. for (i = 0; i < n_env_vars; ++i) {
  4311. const char *s = smartlist_get(env_vars_sorted, i);
  4312. size_t slen = strlen(s);
  4313. size_t s_name_len = str_num_before(s, '=');
  4314. if (s_name_len == slen) {
  4315. log_warn(LD_GENERAL,
  4316. "Preparing an environment containing a variable "
  4317. "without a value: %s",
  4318. s);
  4319. }
  4320. if (prev_env_var != NULL &&
  4321. environment_variable_names_equal(s, prev_env_var)) {
  4322. log_warn(LD_GENERAL,
  4323. "Preparing an environment containing two variables "
  4324. "with the same name: %s and %s",
  4325. prev_env_var, s);
  4326. }
  4327. prev_env_var = s;
  4328. /* Actually copy the string into the environment. */
  4329. memcpy(cp, s, slen+1);
  4330. env->unixoid_environment_block[i] = cp;
  4331. cp += slen+1;
  4332. }
  4333. tor_assert(cp == env->windows_environment_block + total_env_length - 1);
  4334. }
  4335. smartlist_free(env_vars_sorted);
  4336. return env;
  4337. }
  4338. /** Return a newly allocated smartlist containing every variable in
  4339. * this process's environment, as a NUL-terminated string of the form
  4340. * "NAME=VALUE". Note that on some/many/most/all OSes, the parent
  4341. * process can put strings not of that form in our environment;
  4342. * callers should try to not get crashed by that.
  4343. *
  4344. * The returned strings are heap-allocated, and must be freed by the
  4345. * caller. */
  4346. struct smartlist_t *
  4347. get_current_process_environment_variables(void)
  4348. {
  4349. smartlist_t *sl = smartlist_new();
  4350. char **environ_tmp; /* Not const char ** ? Really? */
  4351. for (environ_tmp = get_environment(); *environ_tmp; ++environ_tmp) {
  4352. smartlist_add(sl, tor_strdup(*environ_tmp));
  4353. }
  4354. return sl;
  4355. }
  4356. /** For each string s in <b>env_vars</b> such that
  4357. * environment_variable_names_equal(s, <b>new_var</b>), remove it; if
  4358. * <b>free_p</b> is non-zero, call <b>free_old</b>(s). If
  4359. * <b>new_var</b> contains '=', insert it into <b>env_vars</b>. */
  4360. void
  4361. set_environment_variable_in_smartlist(struct smartlist_t *env_vars,
  4362. const char *new_var,
  4363. void (*free_old)(void*),
  4364. int free_p)
  4365. {
  4366. SMARTLIST_FOREACH_BEGIN(env_vars, const char *, s) {
  4367. if (environment_variable_names_equal(s, new_var)) {
  4368. SMARTLIST_DEL_CURRENT(env_vars, s);
  4369. if (free_p) {
  4370. free_old((void *)s);
  4371. }
  4372. }
  4373. } SMARTLIST_FOREACH_END(s);
  4374. if (strchr(new_var, '=') != NULL) {
  4375. smartlist_add(env_vars, (void *)new_var);
  4376. }
  4377. }
  4378. #ifdef _WIN32
  4379. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  4380. * <b>hProcess</b> is NULL, the function will return immediately if there is
  4381. * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
  4382. * to the process owning the <b>h</b>. In this case, the function will exit
  4383. * only once the process has exited, or <b>count</b> bytes are read. Returns
  4384. * the number of bytes read, or -1 on error. */
  4385. ssize_t
  4386. tor_read_all_handle(HANDLE h, char *buf, size_t count,
  4387. const process_handle_t *process)
  4388. {
  4389. size_t numread = 0;
  4390. BOOL retval;
  4391. DWORD byte_count;
  4392. BOOL process_exited = FALSE;
  4393. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  4394. return -1;
  4395. while (numread != count) {
  4396. /* Check if there is anything to read */
  4397. retval = PeekNamedPipe(h, NULL, 0, NULL, &byte_count, NULL);
  4398. if (!retval) {
  4399. log_warn(LD_GENERAL,
  4400. "Failed to peek from handle: %s",
  4401. format_win32_error(GetLastError()));
  4402. return -1;
  4403. } else if (0 == byte_count) {
  4404. /* Nothing available: process exited or it is busy */
  4405. /* Exit if we don't know whether the process is running */
  4406. if (NULL == process)
  4407. break;
  4408. /* The process exited and there's nothing left to read from it */
  4409. if (process_exited)
  4410. break;
  4411. /* If process is not running, check for output one more time in case
  4412. it wrote something after the peek was performed. Otherwise keep on
  4413. waiting for output */
  4414. tor_assert(process != NULL);
  4415. byte_count = WaitForSingleObject(process->pid.hProcess, 0);
  4416. if (WAIT_TIMEOUT != byte_count)
  4417. process_exited = TRUE;
  4418. continue;
  4419. }
  4420. /* There is data to read; read it */
  4421. retval = ReadFile(h, buf+numread, count-numread, &byte_count, NULL);
  4422. tor_assert(byte_count + numread <= count);
  4423. if (!retval) {
  4424. log_warn(LD_GENERAL, "Failed to read from handle: %s",
  4425. format_win32_error(GetLastError()));
  4426. return -1;
  4427. } else if (0 == byte_count) {
  4428. /* End of file */
  4429. break;
  4430. }
  4431. numread += byte_count;
  4432. }
  4433. return (ssize_t)numread;
  4434. }
  4435. #else
  4436. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  4437. * <b>process</b> is NULL, the function will return immediately if there is
  4438. * nothing more to read. Otherwise data will be read until end of file, or
  4439. * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
  4440. * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
  4441. * file has been reached. */
  4442. ssize_t
  4443. tor_read_all_handle(FILE *h, char *buf, size_t count,
  4444. const process_handle_t *process,
  4445. int *eof)
  4446. {
  4447. size_t numread = 0;
  4448. char *retval;
  4449. if (eof)
  4450. *eof = 0;
  4451. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  4452. return -1;
  4453. while (numread != count) {
  4454. /* Use fgets because that is what we use in log_from_pipe() */
  4455. retval = fgets(buf+numread, (int)(count-numread), h);
  4456. if (NULL == retval) {
  4457. if (feof(h)) {
  4458. log_debug(LD_GENERAL, "fgets() reached end of file");
  4459. if (eof)
  4460. *eof = 1;
  4461. break;
  4462. } else {
  4463. if (EAGAIN == errno) {
  4464. if (process)
  4465. continue;
  4466. else
  4467. break;
  4468. } else {
  4469. log_warn(LD_GENERAL, "fgets() from handle failed: %s",
  4470. strerror(errno));
  4471. return -1;
  4472. }
  4473. }
  4474. }
  4475. tor_assert(retval != NULL);
  4476. tor_assert(strlen(retval) + numread <= count);
  4477. numread += strlen(retval);
  4478. }
  4479. log_debug(LD_GENERAL, "fgets() read %d bytes from handle", (int)numread);
  4480. return (ssize_t)numread;
  4481. }
  4482. #endif
  4483. /** Read from stdout of a process until the process exits. */
  4484. ssize_t
  4485. tor_read_all_from_process_stdout(const process_handle_t *process_handle,
  4486. char *buf, size_t count)
  4487. {
  4488. #ifdef _WIN32
  4489. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  4490. process_handle);
  4491. #else
  4492. return tor_read_all_handle(process_handle->stdout_handle, buf, count,
  4493. process_handle, NULL);
  4494. #endif
  4495. }
  4496. /** Read from stdout of a process until the process exits. */
  4497. ssize_t
  4498. tor_read_all_from_process_stderr(const process_handle_t *process_handle,
  4499. char *buf, size_t count)
  4500. {
  4501. #ifdef _WIN32
  4502. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  4503. process_handle);
  4504. #else
  4505. return tor_read_all_handle(process_handle->stderr_handle, buf, count,
  4506. process_handle, NULL);
  4507. #endif
  4508. }
  4509. /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
  4510. * modified. The resulting smartlist will consist of pointers to buf, so there
  4511. * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
  4512. * string. <b>len</b> should be set to the length of the buffer excluding the
  4513. * NUL. Non-printable characters (including NUL) will be replaced with "." */
  4514. int
  4515. tor_split_lines(smartlist_t *sl, char *buf, int len)
  4516. {
  4517. /* Index in buf of the start of the current line */
  4518. int start = 0;
  4519. /* Index in buf of the current character being processed */
  4520. int cur = 0;
  4521. /* Are we currently in a line */
  4522. char in_line = 0;
  4523. /* Loop over string */
  4524. while (cur < len) {
  4525. /* Loop until end of line or end of string */
  4526. for (; cur < len; cur++) {
  4527. if (in_line) {
  4528. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  4529. /* End of line */
  4530. buf[cur] = '\0';
  4531. /* Point cur to the next line */
  4532. cur++;
  4533. /* Line starts at start and ends with a nul */
  4534. break;
  4535. } else {
  4536. if (!TOR_ISPRINT(buf[cur]))
  4537. buf[cur] = '.';
  4538. }
  4539. } else {
  4540. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  4541. /* Skip leading vertical space */
  4542. ;
  4543. } else {
  4544. in_line = 1;
  4545. start = cur;
  4546. if (!TOR_ISPRINT(buf[cur]))
  4547. buf[cur] = '.';
  4548. }
  4549. }
  4550. }
  4551. /* We are at the end of the line or end of string. If in_line is true there
  4552. * is a line which starts at buf+start and ends at a NUL. cur points to
  4553. * the character after the NUL. */
  4554. if (in_line)
  4555. smartlist_add(sl, (void *)(buf+start));
  4556. in_line = 0;
  4557. }
  4558. return smartlist_len(sl);
  4559. }
  4560. /** Return a string corresponding to <b>stream_status</b>. */
  4561. const char *
  4562. stream_status_to_string(enum stream_status stream_status)
  4563. {
  4564. switch (stream_status) {
  4565. case IO_STREAM_OKAY:
  4566. return "okay";
  4567. case IO_STREAM_EAGAIN:
  4568. return "temporarily unavailable";
  4569. case IO_STREAM_TERM:
  4570. return "terminated";
  4571. case IO_STREAM_CLOSED:
  4572. return "closed";
  4573. default:
  4574. tor_fragile_assert();
  4575. return "unknown";
  4576. }
  4577. }
  4578. /* DOCDOC */
  4579. static void
  4580. log_portfw_spawn_error_message(const char *buf,
  4581. const char *executable, int *child_status)
  4582. {
  4583. /* Parse error message */
  4584. int retval, child_state, saved_errno;
  4585. retval = tor_sscanf(buf, SPAWN_ERROR_MESSAGE "%x/%x",
  4586. &child_state, &saved_errno);
  4587. if (retval == 2) {
  4588. log_warn(LD_GENERAL,
  4589. "Failed to start child process \"%s\" in state %d: %s",
  4590. executable, child_state, strerror(saved_errno));
  4591. if (child_status)
  4592. *child_status = 1;
  4593. } else {
  4594. /* Failed to parse message from child process, log it as a
  4595. warning */
  4596. log_warn(LD_GENERAL,
  4597. "Unexpected message from port forwarding helper \"%s\": %s",
  4598. executable, buf);
  4599. }
  4600. }
  4601. #ifdef _WIN32
  4602. /** Return a smartlist containing lines outputted from
  4603. * <b>handle</b>. Return NULL on error, and set
  4604. * <b>stream_status_out</b> appropriately. */
  4605. MOCK_IMPL(smartlist_t *,
  4606. tor_get_lines_from_handle, (HANDLE *handle,
  4607. enum stream_status *stream_status_out))
  4608. {
  4609. int pos;
  4610. char stdout_buf[600] = {0};
  4611. smartlist_t *lines = NULL;
  4612. tor_assert(stream_status_out);
  4613. *stream_status_out = IO_STREAM_TERM;
  4614. pos = tor_read_all_handle(handle, stdout_buf, sizeof(stdout_buf) - 1, NULL);
  4615. if (pos < 0) {
  4616. *stream_status_out = IO_STREAM_TERM;
  4617. return NULL;
  4618. }
  4619. if (pos == 0) {
  4620. *stream_status_out = IO_STREAM_EAGAIN;
  4621. return NULL;
  4622. }
  4623. /* End with a null even if there isn't a \r\n at the end */
  4624. /* TODO: What if this is a partial line? */
  4625. stdout_buf[pos] = '\0';
  4626. /* Split up the buffer */
  4627. lines = smartlist_new();
  4628. tor_split_lines(lines, stdout_buf, pos);
  4629. /* Currently 'lines' is populated with strings residing on the
  4630. stack. Replace them with their exact copies on the heap: */
  4631. SMARTLIST_FOREACH(lines, char *, line,
  4632. SMARTLIST_REPLACE_CURRENT(lines, line, tor_strdup(line)));
  4633. *stream_status_out = IO_STREAM_OKAY;
  4634. return lines;
  4635. }
  4636. /** Read from stream, and send lines to log at the specified log level.
  4637. * Returns -1 if there is a error reading, and 0 otherwise.
  4638. * If the generated stream is flushed more often than on new lines, or
  4639. * a read exceeds 256 bytes, lines will be truncated. This should be fixed,
  4640. * along with the corresponding problem on *nix (see bug #2045).
  4641. */
  4642. static int
  4643. log_from_handle(HANDLE *pipe, int severity)
  4644. {
  4645. char buf[256];
  4646. int pos;
  4647. smartlist_t *lines;
  4648. pos = tor_read_all_handle(pipe, buf, sizeof(buf) - 1, NULL);
  4649. if (pos < 0) {
  4650. /* Error */
  4651. log_warn(LD_GENERAL, "Failed to read data from subprocess");
  4652. return -1;
  4653. }
  4654. if (0 == pos) {
  4655. /* There's nothing to read (process is busy or has exited) */
  4656. log_debug(LD_GENERAL, "Subprocess had nothing to say");
  4657. return 0;
  4658. }
  4659. /* End with a null even if there isn't a \r\n at the end */
  4660. /* TODO: What if this is a partial line? */
  4661. buf[pos] = '\0';
  4662. log_debug(LD_GENERAL, "Subprocess had %d bytes to say", pos);
  4663. /* Split up the buffer */
  4664. lines = smartlist_new();
  4665. tor_split_lines(lines, buf, pos);
  4666. /* Log each line */
  4667. SMARTLIST_FOREACH(lines, char *, line,
  4668. {
  4669. log_fn(severity, LD_GENERAL, "Port forwarding helper says: %s", line);
  4670. });
  4671. smartlist_free(lines);
  4672. return 0;
  4673. }
  4674. #else
  4675. /** Return a smartlist containing lines outputted from
  4676. * <b>handle</b>. Return NULL on error, and set
  4677. * <b>stream_status_out</b> appropriately. */
  4678. MOCK_IMPL(smartlist_t *,
  4679. tor_get_lines_from_handle, (FILE *handle,
  4680. enum stream_status *stream_status_out))
  4681. {
  4682. enum stream_status stream_status;
  4683. char stdout_buf[400];
  4684. smartlist_t *lines = NULL;
  4685. while (1) {
  4686. memset(stdout_buf, 0, sizeof(stdout_buf));
  4687. stream_status = get_string_from_pipe(handle,
  4688. stdout_buf, sizeof(stdout_buf) - 1);
  4689. if (stream_status != IO_STREAM_OKAY)
  4690. goto done;
  4691. if (!lines) lines = smartlist_new();
  4692. smartlist_add(lines, tor_strdup(stdout_buf));
  4693. }
  4694. done:
  4695. *stream_status_out = stream_status;
  4696. return lines;
  4697. }
  4698. /** Read from stream, and send lines to log at the specified log level.
  4699. * Returns 1 if stream is closed normally, -1 if there is a error reading, and
  4700. * 0 otherwise. Handles lines from tor-fw-helper and
  4701. * tor_spawn_background() specially.
  4702. */
  4703. static int
  4704. log_from_pipe(FILE *stream, int severity, const char *executable,
  4705. int *child_status)
  4706. {
  4707. char buf[256];
  4708. enum stream_status r;
  4709. for (;;) {
  4710. r = get_string_from_pipe(stream, buf, sizeof(buf) - 1);
  4711. if (r == IO_STREAM_CLOSED) {
  4712. return 1;
  4713. } else if (r == IO_STREAM_EAGAIN) {
  4714. return 0;
  4715. } else if (r == IO_STREAM_TERM) {
  4716. return -1;
  4717. }
  4718. tor_assert(r == IO_STREAM_OKAY);
  4719. /* Check if buf starts with SPAWN_ERROR_MESSAGE */
  4720. if (strcmpstart(buf, SPAWN_ERROR_MESSAGE) == 0) {
  4721. log_portfw_spawn_error_message(buf, executable, child_status);
  4722. } else {
  4723. log_fn(severity, LD_GENERAL, "Port forwarding helper says: %s", buf);
  4724. }
  4725. }
  4726. /* We should never get here */
  4727. return -1;
  4728. }
  4729. #endif
  4730. /** Reads from <b>stream</b> and stores input in <b>buf_out</b> making
  4731. * sure it's below <b>count</b> bytes.
  4732. * If the string has a trailing newline, we strip it off.
  4733. *
  4734. * This function is specifically created to handle input from managed
  4735. * proxies, according to the pluggable transports spec. Make sure it
  4736. * fits your needs before using it.
  4737. *
  4738. * Returns:
  4739. * IO_STREAM_CLOSED: If the stream is closed.
  4740. * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
  4741. * later.
  4742. * IO_STREAM_TERM: If something is wrong with the stream.
  4743. * IO_STREAM_OKAY: If everything went okay and we got a string
  4744. * in <b>buf_out</b>. */
  4745. enum stream_status
  4746. get_string_from_pipe(FILE *stream, char *buf_out, size_t count)
  4747. {
  4748. char *retval;
  4749. size_t len;
  4750. tor_assert(count <= INT_MAX);
  4751. retval = fgets(buf_out, (int)count, stream);
  4752. if (!retval) {
  4753. if (feof(stream)) {
  4754. /* Program has closed stream (probably it exited) */
  4755. /* TODO: check error */
  4756. return IO_STREAM_CLOSED;
  4757. } else {
  4758. if (EAGAIN == errno) {
  4759. /* Nothing more to read, try again next time */
  4760. return IO_STREAM_EAGAIN;
  4761. } else {
  4762. /* There was a problem, abandon this child process */
  4763. return IO_STREAM_TERM;
  4764. }
  4765. }
  4766. } else {
  4767. len = strlen(buf_out);
  4768. if (len == 0) {
  4769. /* this probably means we got a NUL at the start of the string. */
  4770. return IO_STREAM_EAGAIN;
  4771. }
  4772. if (buf_out[len - 1] == '\n') {
  4773. /* Remove the trailing newline */
  4774. buf_out[len - 1] = '\0';
  4775. } else {
  4776. /* No newline; check whether we overflowed the buffer */
  4777. if (!feof(stream))
  4778. log_info(LD_GENERAL,
  4779. "Line from stream was truncated: %s", buf_out);
  4780. /* TODO: What to do with this error? */
  4781. }
  4782. return IO_STREAM_OKAY;
  4783. }
  4784. /* We should never get here */
  4785. return IO_STREAM_TERM;
  4786. }
  4787. /** Parse a <b>line</b> from tor-fw-helper and issue an appropriate
  4788. * log message to our user. */
  4789. static void
  4790. handle_fw_helper_line(const char *executable, const char *line)
  4791. {
  4792. smartlist_t *tokens = smartlist_new();
  4793. char *message = NULL;
  4794. char *message_for_log = NULL;
  4795. const char *external_port = NULL;
  4796. const char *internal_port = NULL;
  4797. const char *result = NULL;
  4798. int port = 0;
  4799. int success = 0;
  4800. if (strcmpstart(line, SPAWN_ERROR_MESSAGE) == 0) {
  4801. /* We need to check for SPAWN_ERROR_MESSAGE again here, since it's
  4802. * possible that it got sent after we tried to read it in log_from_pipe.
  4803. *
  4804. * XXX Ideally, we should be using one of stdout/stderr for the real
  4805. * output, and one for the output of the startup code. We used to do that
  4806. * before cd05f35d2c.
  4807. */
  4808. int child_status;
  4809. log_portfw_spawn_error_message(line, executable, &child_status);
  4810. goto done;
  4811. }
  4812. smartlist_split_string(tokens, line, NULL,
  4813. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4814. if (smartlist_len(tokens) < 5)
  4815. goto err;
  4816. if (strcmp(smartlist_get(tokens, 0), "tor-fw-helper") ||
  4817. strcmp(smartlist_get(tokens, 1), "tcp-forward"))
  4818. goto err;
  4819. external_port = smartlist_get(tokens, 2);
  4820. internal_port = smartlist_get(tokens, 3);
  4821. result = smartlist_get(tokens, 4);
  4822. if (smartlist_len(tokens) > 5) {
  4823. /* If there are more than 5 tokens, they are part of [<message>].
  4824. Let's use a second smartlist to form the whole message;
  4825. strncat loops suck. */
  4826. int i;
  4827. int message_words_n = smartlist_len(tokens) - 5;
  4828. smartlist_t *message_sl = smartlist_new();
  4829. for (i = 0; i < message_words_n; i++)
  4830. smartlist_add(message_sl, smartlist_get(tokens, 5+i));
  4831. tor_assert(smartlist_len(message_sl) > 0);
  4832. message = smartlist_join_strings(message_sl, " ", 0, NULL);
  4833. /* wrap the message in log-friendly wrapping */
  4834. tor_asprintf(&message_for_log, " ('%s')", message);
  4835. smartlist_free(message_sl);
  4836. }
  4837. port = atoi(external_port);
  4838. if (port < 1 || port > 65535)
  4839. goto err;
  4840. port = atoi(internal_port);
  4841. if (port < 1 || port > 65535)
  4842. goto err;
  4843. if (!strcmp(result, "SUCCESS"))
  4844. success = 1;
  4845. else if (!strcmp(result, "FAIL"))
  4846. success = 0;
  4847. else
  4848. goto err;
  4849. if (!success) {
  4850. log_warn(LD_GENERAL, "Tor was unable to forward TCP port '%s' to '%s'%s. "
  4851. "Please make sure that your router supports port "
  4852. "forwarding protocols (like NAT-PMP). Note that if '%s' is "
  4853. "your ORPort, your relay will be unable to receive inbound "
  4854. "traffic.", external_port, internal_port,
  4855. message_for_log ? message_for_log : "",
  4856. internal_port);
  4857. } else {
  4858. log_info(LD_GENERAL,
  4859. "Tor successfully forwarded TCP port '%s' to '%s'%s.",
  4860. external_port, internal_port,
  4861. message_for_log ? message_for_log : "");
  4862. }
  4863. goto done;
  4864. err:
  4865. log_warn(LD_GENERAL, "tor-fw-helper sent us a string we could not "
  4866. "parse (%s).", line);
  4867. done:
  4868. SMARTLIST_FOREACH(tokens, char *, cp, tor_free(cp));
  4869. smartlist_free(tokens);
  4870. tor_free(message);
  4871. tor_free(message_for_log);
  4872. }
  4873. /** Read what tor-fw-helper has to say in its stdout and handle it
  4874. * appropriately */
  4875. static int
  4876. handle_fw_helper_output(const char *executable,
  4877. process_handle_t *process_handle)
  4878. {
  4879. smartlist_t *fw_helper_output = NULL;
  4880. enum stream_status stream_status = 0;
  4881. fw_helper_output =
  4882. tor_get_lines_from_handle(tor_process_get_stdout_pipe(process_handle),
  4883. &stream_status);
  4884. if (!fw_helper_output) { /* didn't get any output from tor-fw-helper */
  4885. /* if EAGAIN we should retry in the future */
  4886. return (stream_status == IO_STREAM_EAGAIN) ? 0 : -1;
  4887. }
  4888. /* Handle the lines we got: */
  4889. SMARTLIST_FOREACH_BEGIN(fw_helper_output, char *, line) {
  4890. handle_fw_helper_line(executable, line);
  4891. tor_free(line);
  4892. } SMARTLIST_FOREACH_END(line);
  4893. smartlist_free(fw_helper_output);
  4894. return 0;
  4895. }
  4896. /** Spawn tor-fw-helper and ask it to forward the ports in
  4897. * <b>ports_to_forward</b>. <b>ports_to_forward</b> contains strings
  4898. * of the form "<external port>:<internal port>", which is the format
  4899. * that tor-fw-helper expects. */
  4900. void
  4901. tor_check_port_forwarding(const char *filename,
  4902. smartlist_t *ports_to_forward,
  4903. time_t now)
  4904. {
  4905. /* When fw-helper succeeds, how long do we wait until running it again */
  4906. #define TIME_TO_EXEC_FWHELPER_SUCCESS 300
  4907. /* When fw-helper failed to start, how long do we wait until running it again
  4908. */
  4909. #define TIME_TO_EXEC_FWHELPER_FAIL 60
  4910. /* Static variables are initialized to zero, so child_handle.status=0
  4911. * which corresponds to it not running on startup */
  4912. static process_handle_t *child_handle=NULL;
  4913. static time_t time_to_run_helper = 0;
  4914. int stderr_status, retval;
  4915. int stdout_status = 0;
  4916. tor_assert(filename);
  4917. /* Start the child, if it is not already running */
  4918. if ((!child_handle || child_handle->status != PROCESS_STATUS_RUNNING) &&
  4919. time_to_run_helper < now) {
  4920. /*tor-fw-helper cli looks like this: tor_fw_helper -p :5555 -p 4555:1111 */
  4921. const char **argv; /* cli arguments */
  4922. int args_n, status;
  4923. int argv_index = 0; /* index inside 'argv' */
  4924. tor_assert(smartlist_len(ports_to_forward) > 0);
  4925. /* check for overflow during 'argv' allocation:
  4926. (len(ports_to_forward)*2 + 2)*sizeof(char*) > SIZE_MAX ==
  4927. len(ports_to_forward) > (((SIZE_MAX/sizeof(char*)) - 2)/2) */
  4928. if ((size_t) smartlist_len(ports_to_forward) >
  4929. (((SIZE_MAX/sizeof(char*)) - 2)/2)) {
  4930. log_warn(LD_GENERAL,
  4931. "Overflow during argv allocation. This shouldn't happen.");
  4932. return;
  4933. }
  4934. /* check for overflow during 'argv_index' increase:
  4935. ((len(ports_to_forward)*2 + 2) > INT_MAX) ==
  4936. len(ports_to_forward) > (INT_MAX - 2)/2 */
  4937. if (smartlist_len(ports_to_forward) > (INT_MAX - 2)/2) {
  4938. log_warn(LD_GENERAL,
  4939. "Overflow during argv_index increase. This shouldn't happen.");
  4940. return;
  4941. }
  4942. /* Calculate number of cli arguments: one for the filename, two
  4943. for each smartlist element (one for "-p" and one for the
  4944. ports), and one for the final NULL. */
  4945. args_n = 1 + 2*smartlist_len(ports_to_forward) + 1;
  4946. argv = tor_calloc(args_n, sizeof(char *));
  4947. argv[argv_index++] = filename;
  4948. SMARTLIST_FOREACH_BEGIN(ports_to_forward, const char *, port) {
  4949. argv[argv_index++] = "-p";
  4950. argv[argv_index++] = port;
  4951. } SMARTLIST_FOREACH_END(port);
  4952. argv[argv_index] = NULL;
  4953. /* Assume tor-fw-helper will succeed, start it later*/
  4954. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_SUCCESS;
  4955. if (child_handle) {
  4956. tor_process_handle_destroy(child_handle, 1);
  4957. child_handle = NULL;
  4958. }
  4959. #ifdef _WIN32
  4960. /* Passing NULL as lpApplicationName makes Windows search for the .exe */
  4961. status = tor_spawn_background(NULL, argv, NULL, &child_handle);
  4962. #else
  4963. status = tor_spawn_background(filename, argv, NULL, &child_handle);
  4964. #endif
  4965. tor_free_((void*)argv);
  4966. argv=NULL;
  4967. if (PROCESS_STATUS_ERROR == status) {
  4968. log_warn(LD_GENERAL, "Failed to start port forwarding helper %s",
  4969. filename);
  4970. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_FAIL;
  4971. return;
  4972. }
  4973. log_info(LD_GENERAL,
  4974. "Started port forwarding helper (%s) with pid '%d'",
  4975. filename, tor_process_get_pid(child_handle));
  4976. }
  4977. /* If child is running, read from its stdout and stderr) */
  4978. if (child_handle && PROCESS_STATUS_RUNNING == child_handle->status) {
  4979. /* Read from stdout/stderr and log result */
  4980. retval = 0;
  4981. #ifdef _WIN32
  4982. stderr_status = log_from_handle(child_handle->stderr_pipe, LOG_INFO);
  4983. #else
  4984. stderr_status = log_from_pipe(child_handle->stderr_handle,
  4985. LOG_INFO, filename, &retval);
  4986. #endif
  4987. if (handle_fw_helper_output(filename, child_handle) < 0) {
  4988. log_warn(LD_GENERAL, "Failed to handle fw helper output.");
  4989. stdout_status = -1;
  4990. retval = -1;
  4991. }
  4992. if (retval) {
  4993. /* There was a problem in the child process */
  4994. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_FAIL;
  4995. }
  4996. /* Combine the two statuses in order of severity */
  4997. if (-1 == stdout_status || -1 == stderr_status)
  4998. /* There was a failure */
  4999. retval = -1;
  5000. #ifdef _WIN32
  5001. else if (!child_handle || tor_get_exit_code(child_handle, 0, NULL) !=
  5002. PROCESS_EXIT_RUNNING) {
  5003. /* process has exited or there was an error */
  5004. /* TODO: Do something with the process return value */
  5005. /* TODO: What if the process output something since
  5006. * between log_from_handle and tor_get_exit_code? */
  5007. retval = 1;
  5008. }
  5009. #else
  5010. else if (1 == stdout_status || 1 == stderr_status)
  5011. /* stdout or stderr was closed, the process probably
  5012. * exited. It will be reaped by waitpid() in main.c */
  5013. /* TODO: Do something with the process return value */
  5014. retval = 1;
  5015. #endif
  5016. else
  5017. /* Both are fine */
  5018. retval = 0;
  5019. /* If either pipe indicates a failure, act on it */
  5020. if (0 != retval) {
  5021. if (1 == retval) {
  5022. log_info(LD_GENERAL, "Port forwarding helper terminated");
  5023. child_handle->status = PROCESS_STATUS_NOTRUNNING;
  5024. } else {
  5025. log_warn(LD_GENERAL, "Failed to read from port forwarding helper");
  5026. child_handle->status = PROCESS_STATUS_ERROR;
  5027. }
  5028. /* TODO: The child might not actually be finished (maybe it failed or
  5029. closed stdout/stderr), so maybe we shouldn't start another? */
  5030. }
  5031. }
  5032. }
  5033. /** Initialize the insecure RNG <b>rng</b> from a seed value <b>seed</b>. */
  5034. void
  5035. tor_init_weak_random(tor_weak_rng_t *rng, unsigned seed)
  5036. {
  5037. rng->state = (uint32_t)(seed & 0x7fffffff);
  5038. }
  5039. /** Return a randomly chosen value in the range 0..TOR_WEAK_RANDOM_MAX based
  5040. * on the RNG state of <b>rng</b>. This entropy will not be cryptographically
  5041. * strong; do not rely on it for anything an adversary should not be able to
  5042. * predict. */
  5043. int32_t
  5044. tor_weak_random(tor_weak_rng_t *rng)
  5045. {
  5046. /* Here's a linear congruential generator. OpenBSD and glibc use these
  5047. * parameters; they aren't too bad, and should have maximal period over the
  5048. * range 0..INT32_MAX. We don't want to use the platform rand() or random(),
  5049. * since some platforms have bad weak RNGs that only return values in the
  5050. * range 0..INT16_MAX, which just isn't enough. */
  5051. rng->state = (rng->state * 1103515245 + 12345) & 0x7fffffff;
  5052. return (int32_t) rng->state;
  5053. }
  5054. /** Return a random number in the range [0 , <b>top</b>). {That is, the range
  5055. * of integers i such that 0 <= i < top.} Chooses uniformly. Requires that
  5056. * top is greater than 0. This randomness is not cryptographically strong; do
  5057. * not rely on it for anything an adversary should not be able to predict. */
  5058. int32_t
  5059. tor_weak_random_range(tor_weak_rng_t *rng, int32_t top)
  5060. {
  5061. /* We don't want to just do tor_weak_random() % top, since random() is often
  5062. * implemented with an LCG whose modulus is a power of 2, and those are
  5063. * cyclic in their low-order bits. */
  5064. int divisor, result;
  5065. tor_assert(top > 0);
  5066. divisor = TOR_WEAK_RANDOM_MAX / top;
  5067. do {
  5068. result = (int32_t)(tor_weak_random(rng) / divisor);
  5069. } while (result >= top);
  5070. return result;
  5071. }
  5072. /** Cast a given double value to a int64_t. Return 0 if number is NaN.
  5073. * Returns either INT64_MIN or INT64_MAX if number is outside of the int64_t
  5074. * range. */
  5075. int64_t
  5076. clamp_double_to_int64(double number)
  5077. {
  5078. int exp;
  5079. /* NaN is a special case that can't be used with the logic below. */
  5080. if (isnan(number)) {
  5081. return 0;
  5082. }
  5083. /* Time to validate if result can overflows a int64_t value. Fun with
  5084. * float! Find that exponent exp such that
  5085. * number == x * 2^exp
  5086. * for some x with abs(x) in [0.5, 1.0). Note that this implies that the
  5087. * magnitude of number is strictly less than 2^exp.
  5088. *
  5089. * If number is infinite, the call to frexp is legal but the contents of
  5090. * exp are unspecified. */
  5091. frexp(number, &exp);
  5092. /* If the magnitude of number is strictly less than 2^63, the truncated
  5093. * version of number is guaranteed to be representable. The only
  5094. * representable integer for which this is not the case is INT64_MIN, but
  5095. * it is covered by the logic below. */
  5096. if (isfinite(number) && exp <= 63) {
  5097. return (int64_t)number;
  5098. }
  5099. /* Handle infinities and finite numbers with magnitude >= 2^63. */
  5100. return signbit(number) ? INT64_MIN : INT64_MAX;
  5101. }
  5102. /** Return a uint64_t value from <b>a</b> in network byte order. */
  5103. uint64_t
  5104. tor_htonll(uint64_t a)
  5105. {
  5106. #ifdef WORDS_BIGENDIAN
  5107. /* Big endian. */
  5108. return a;
  5109. #else /* WORDS_BIGENDIAN */
  5110. /* Little endian. The worst... */
  5111. return htonl((uint32_t)(a>>32)) |
  5112. (((uint64_t)htonl((uint32_t)a))<<32);
  5113. #endif /* WORDS_BIGENDIAN */
  5114. }
  5115. /** Return a uint64_t value from <b>a</b> in host byte order. */
  5116. uint64_t
  5117. tor_ntohll(uint64_t a)
  5118. {
  5119. return tor_htonll(a);
  5120. }