util.c 160 KB

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