util.c 157 KB

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