util.c 162 KB

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