util.c 139 KB

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