util.c 162 KB

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