util.c 162 KB

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