util.c 137 KB

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