util.c 163 KB

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