util.c 139 KB

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