util.c 148 KB

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