util.c 162 KB

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