util.c 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993
  1. /* Copyright (c) 2003, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2012, 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. * Return 0 on success, -1 on failure.
  1284. */
  1285. int
  1286. parse_rfc1123_time(const char *buf, time_t *t)
  1287. {
  1288. struct tm tm;
  1289. char month[4];
  1290. char weekday[4];
  1291. int i, m;
  1292. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1293. if (strlen(buf) != RFC1123_TIME_LEN)
  1294. return -1;
  1295. memset(&tm, 0, sizeof(tm));
  1296. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  1297. &tm_mday, month, &tm_year, &tm_hour,
  1298. &tm_min, &tm_sec) < 7) {
  1299. char *esc = esc_for_log(buf);
  1300. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1301. tor_free(esc);
  1302. return -1;
  1303. }
  1304. if (tm_mday < 1 || tm_mday > 31 || tm_hour > 23 || tm_min > 59 ||
  1305. tm_sec > 60 || tm_year >= INT32_MAX || tm_year < 1970) {
  1306. char *esc = esc_for_log(buf);
  1307. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1308. tor_free(esc);
  1309. return -1;
  1310. }
  1311. tm.tm_mday = (int)tm_mday;
  1312. tm.tm_year = (int)tm_year;
  1313. tm.tm_hour = (int)tm_hour;
  1314. tm.tm_min = (int)tm_min;
  1315. tm.tm_sec = (int)tm_sec;
  1316. m = -1;
  1317. for (i = 0; i < 12; ++i) {
  1318. if (!strcmp(month, MONTH_NAMES[i])) {
  1319. m = i;
  1320. break;
  1321. }
  1322. }
  1323. if (m<0) {
  1324. char *esc = esc_for_log(buf);
  1325. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  1326. tor_free(esc);
  1327. return -1;
  1328. }
  1329. tm.tm_mon = m;
  1330. if (tm.tm_year < 1970) {
  1331. char *esc = esc_for_log(buf);
  1332. log_warn(LD_GENERAL,
  1333. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  1334. tor_free(esc);
  1335. return -1;
  1336. }
  1337. tm.tm_year -= 1900;
  1338. return tor_timegm(&tm, t);
  1339. }
  1340. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  1341. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1342. *
  1343. * (ISO8601 format is 2006-10-29 10:57:20)
  1344. */
  1345. void
  1346. format_local_iso_time(char *buf, time_t t)
  1347. {
  1348. struct tm tm;
  1349. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  1350. }
  1351. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  1352. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1353. */
  1354. void
  1355. format_iso_time(char *buf, time_t t)
  1356. {
  1357. struct tm tm;
  1358. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  1359. }
  1360. /** As format_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  1361. * embedding an internal space. */
  1362. void
  1363. format_iso_time_nospace(char *buf, time_t t)
  1364. {
  1365. format_iso_time(buf, t);
  1366. buf[10] = 'T';
  1367. }
  1368. /** As format_iso_time_nospace, but include microseconds in decimal
  1369. * fixed-point format. Requires that buf be at least ISO_TIME_USEC_LEN+1
  1370. * bytes long. */
  1371. void
  1372. format_iso_time_nospace_usec(char *buf, const struct timeval *tv)
  1373. {
  1374. tor_assert(tv);
  1375. format_iso_time_nospace(buf, tv->tv_sec);
  1376. tor_snprintf(buf+ISO_TIME_LEN, 8, ".%06d", (int)tv->tv_usec);
  1377. }
  1378. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  1379. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  1380. * failure. Ignore extraneous stuff in <b>cp</b> separated by whitespace from
  1381. * the end of the time string. */
  1382. int
  1383. parse_iso_time(const char *cp, time_t *t)
  1384. {
  1385. struct tm st_tm;
  1386. unsigned int year=0, month=0, day=0, hour=0, minute=0, second=0;
  1387. if (tor_sscanf(cp, "%u-%2u-%2u %2u:%2u:%2u", &year, &month,
  1388. &day, &hour, &minute, &second) < 6) {
  1389. char *esc = esc_for_log(cp);
  1390. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  1391. tor_free(esc);
  1392. return -1;
  1393. }
  1394. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  1395. hour > 23 || minute > 59 || second > 60 || year >= INT32_MAX) {
  1396. char *esc = esc_for_log(cp);
  1397. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  1398. tor_free(esc);
  1399. return -1;
  1400. }
  1401. st_tm.tm_year = (int)year-1900;
  1402. st_tm.tm_mon = month-1;
  1403. st_tm.tm_mday = day;
  1404. st_tm.tm_hour = hour;
  1405. st_tm.tm_min = minute;
  1406. st_tm.tm_sec = second;
  1407. if (st_tm.tm_year < 70) {
  1408. char *esc = esc_for_log(cp);
  1409. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  1410. tor_free(esc);
  1411. return -1;
  1412. }
  1413. return tor_timegm(&st_tm, t);
  1414. }
  1415. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  1416. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  1417. int
  1418. parse_http_time(const char *date, struct tm *tm)
  1419. {
  1420. const char *cp;
  1421. char month[4];
  1422. char wkday[4];
  1423. int i;
  1424. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1425. tor_assert(tm);
  1426. memset(tm, 0, sizeof(*tm));
  1427. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  1428. if ((cp = strchr(date, ','))) {
  1429. ++cp;
  1430. if (*cp != ' ')
  1431. return -1;
  1432. ++cp;
  1433. if (tor_sscanf(cp, "%2u %3s %4u %2u:%2u:%2u GMT",
  1434. &tm_mday, month, &tm_year,
  1435. &tm_hour, &tm_min, &tm_sec) == 6) {
  1436. /* rfc1123-date */
  1437. tm_year -= 1900;
  1438. } else if (tor_sscanf(cp, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  1439. &tm_mday, month, &tm_year,
  1440. &tm_hour, &tm_min, &tm_sec) == 6) {
  1441. /* rfc850-date */
  1442. } else {
  1443. return -1;
  1444. }
  1445. } else {
  1446. /* No comma; possibly asctime() format. */
  1447. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  1448. wkday, month, &tm_mday,
  1449. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  1450. tm_year -= 1900;
  1451. } else {
  1452. return -1;
  1453. }
  1454. }
  1455. tm->tm_mday = (int)tm_mday;
  1456. tm->tm_year = (int)tm_year;
  1457. tm->tm_hour = (int)tm_hour;
  1458. tm->tm_min = (int)tm_min;
  1459. tm->tm_sec = (int)tm_sec;
  1460. month[3] = '\0';
  1461. /* Okay, now decode the month. */
  1462. /* set tm->tm_mon to dummy value so the check below fails. */
  1463. tm->tm_mon = -1;
  1464. for (i = 0; i < 12; ++i) {
  1465. if (!strcasecmp(MONTH_NAMES[i], month)) {
  1466. tm->tm_mon = i;
  1467. }
  1468. }
  1469. if (tm->tm_year < 0 ||
  1470. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  1471. tm->tm_mday < 1 || tm->tm_mday > 31 ||
  1472. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1473. tm->tm_min < 0 || tm->tm_min > 59 ||
  1474. tm->tm_sec < 0 || tm->tm_sec > 60)
  1475. return -1; /* Out of range, or bad month. */
  1476. return 0;
  1477. }
  1478. /** Given an <b>interval</b> in seconds, try to write it to the
  1479. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  1480. * Return 0 on success, -1 on failure.
  1481. */
  1482. int
  1483. format_time_interval(char *out, size_t out_len, long interval)
  1484. {
  1485. /* We only report seconds if there's no hours. */
  1486. long sec = 0, min = 0, hour = 0, day = 0;
  1487. if (interval < 0)
  1488. interval = -interval;
  1489. if (interval >= 86400) {
  1490. day = interval / 86400;
  1491. interval %= 86400;
  1492. }
  1493. if (interval >= 3600) {
  1494. hour = interval / 3600;
  1495. interval %= 3600;
  1496. }
  1497. if (interval >= 60) {
  1498. min = interval / 60;
  1499. interval %= 60;
  1500. }
  1501. sec = interval;
  1502. if (day) {
  1503. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  1504. day, hour, min);
  1505. } else if (hour) {
  1506. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  1507. } else if (min) {
  1508. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  1509. } else {
  1510. return tor_snprintf(out, out_len, "%ld seconds", sec);
  1511. }
  1512. }
  1513. /* =====
  1514. * Cached time
  1515. * ===== */
  1516. #ifndef TIME_IS_FAST
  1517. /** Cached estimate of the current time. Updated around once per second;
  1518. * may be a few seconds off if we are really busy. This is a hack to avoid
  1519. * calling time(NULL) (which not everybody has optimized) on critical paths.
  1520. */
  1521. static time_t cached_approx_time = 0;
  1522. /** Return a cached estimate of the current time from when
  1523. * update_approx_time() was last called. This is a hack to avoid calling
  1524. * time(NULL) on critical paths: please do not even think of calling it
  1525. * anywhere else. */
  1526. time_t
  1527. approx_time(void)
  1528. {
  1529. return cached_approx_time;
  1530. }
  1531. /** Update the cached estimate of the current time. This function SHOULD be
  1532. * called once per second, and MUST be called before the first call to
  1533. * get_approx_time. */
  1534. void
  1535. update_approx_time(time_t now)
  1536. {
  1537. cached_approx_time = now;
  1538. }
  1539. #endif
  1540. /* =====
  1541. * Rate limiting
  1542. * ===== */
  1543. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return the number
  1544. * of calls to rate_limit_is_ready (including this one!) since the last time
  1545. * rate_limit_is_ready returned nonzero. Otherwise return 0. */
  1546. static int
  1547. rate_limit_is_ready(ratelim_t *lim, time_t now)
  1548. {
  1549. if (lim->rate + lim->last_allowed <= now) {
  1550. int res = lim->n_calls_since_last_time + 1;
  1551. lim->last_allowed = now;
  1552. lim->n_calls_since_last_time = 0;
  1553. return res;
  1554. } else {
  1555. ++lim->n_calls_since_last_time;
  1556. return 0;
  1557. }
  1558. }
  1559. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return a newly
  1560. * allocated string indicating how many messages were suppressed, suitable to
  1561. * append to a log message. Otherwise return NULL. */
  1562. char *
  1563. rate_limit_log(ratelim_t *lim, time_t now)
  1564. {
  1565. int n;
  1566. if ((n = rate_limit_is_ready(lim, now))) {
  1567. if (n == 1) {
  1568. return tor_strdup("");
  1569. } else {
  1570. char *cp=NULL;
  1571. tor_asprintf(&cp,
  1572. " [%d similar message(s) suppressed in last %d seconds]",
  1573. n-1, lim->rate);
  1574. return cp;
  1575. }
  1576. } else {
  1577. return NULL;
  1578. }
  1579. }
  1580. /* =====
  1581. * File helpers
  1582. * ===== */
  1583. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1584. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1585. * was returned by open(). Return the number of bytes written, or -1
  1586. * on error. Only use if fd is a blocking fd. */
  1587. ssize_t
  1588. write_all(tor_socket_t fd, const char *buf, size_t count, int isSocket)
  1589. {
  1590. size_t written = 0;
  1591. ssize_t result;
  1592. tor_assert(count < SSIZE_T_MAX);
  1593. while (written != count) {
  1594. if (isSocket)
  1595. result = tor_socket_send(fd, buf+written, count-written, 0);
  1596. else
  1597. result = write((int)fd, buf+written, count-written);
  1598. if (result<0)
  1599. return -1;
  1600. written += result;
  1601. }
  1602. return (ssize_t)count;
  1603. }
  1604. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1605. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1606. * was returned by socket() or accept(), and 0 if fd was returned by
  1607. * open(). Return the number of bytes read, or -1 on error. Only use
  1608. * if fd is a blocking fd. */
  1609. ssize_t
  1610. read_all(tor_socket_t fd, char *buf, size_t count, int isSocket)
  1611. {
  1612. size_t numread = 0;
  1613. ssize_t result;
  1614. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  1615. return -1;
  1616. while (numread != count) {
  1617. if (isSocket)
  1618. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1619. else
  1620. result = read((int)fd, buf+numread, count-numread);
  1621. if (result<0)
  1622. return -1;
  1623. else if (result == 0)
  1624. break;
  1625. numread += result;
  1626. }
  1627. return (ssize_t)numread;
  1628. }
  1629. /*
  1630. * Filesystem operations.
  1631. */
  1632. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1633. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1634. * the root of a disk. */
  1635. static void
  1636. clean_name_for_stat(char *name)
  1637. {
  1638. #ifdef _WIN32
  1639. size_t len = strlen(name);
  1640. if (!len)
  1641. return;
  1642. if (name[len-1]=='\\' || name[len-1]=='/') {
  1643. if (len == 1 || (len==3 && name[1]==':'))
  1644. return;
  1645. name[len-1]='\0';
  1646. }
  1647. #else
  1648. (void)name;
  1649. #endif
  1650. }
  1651. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1652. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1653. * directory. On FN_ERROR, sets errno. */
  1654. file_status_t
  1655. file_status(const char *fname)
  1656. {
  1657. struct stat st;
  1658. char *f;
  1659. int r;
  1660. f = tor_strdup(fname);
  1661. clean_name_for_stat(f);
  1662. r = stat(f, &st);
  1663. tor_free(f);
  1664. if (r) {
  1665. if (errno == ENOENT) {
  1666. return FN_NOENT;
  1667. }
  1668. return FN_ERROR;
  1669. }
  1670. if (st.st_mode & S_IFDIR)
  1671. return FN_DIR;
  1672. else if (st.st_mode & S_IFREG)
  1673. return FN_FILE;
  1674. #ifndef _WIN32
  1675. else if (st.st_mode & S_IFIFO)
  1676. return FN_FILE;
  1677. #endif
  1678. else
  1679. return FN_ERROR;
  1680. }
  1681. /** Check whether <b>dirname</b> exists and is private. If yes return 0. If
  1682. * it does not exist, and <b>check</b>&CPD_CREATE is set, try to create it
  1683. * and return 0 on success. If it does not exist, and
  1684. * <b>check</b>&CPD_CHECK, and we think we can create it, return 0. Else
  1685. * return -1. If CPD_GROUP_OK is set, then it's okay if the directory
  1686. * is group-readable, but in all cases we create the directory mode 0700.
  1687. * If CPD_CHECK_MODE_ONLY is set, then we don't alter the directory permissions
  1688. * if they are too permissive: we just return -1.
  1689. * When effective_user is not NULL, check permissions against the given user
  1690. * and its primary group.
  1691. */
  1692. int
  1693. check_private_dir(const char *dirname, cpd_check_t check,
  1694. const char *effective_user)
  1695. {
  1696. int r;
  1697. struct stat st;
  1698. char *f;
  1699. #ifndef _WIN32
  1700. int mask;
  1701. struct passwd *pw = NULL;
  1702. uid_t running_uid;
  1703. gid_t running_gid;
  1704. #else
  1705. (void)effective_user;
  1706. #endif
  1707. tor_assert(dirname);
  1708. f = tor_strdup(dirname);
  1709. clean_name_for_stat(f);
  1710. r = stat(f, &st);
  1711. tor_free(f);
  1712. if (r) {
  1713. if (errno != ENOENT) {
  1714. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1715. strerror(errno));
  1716. return -1;
  1717. }
  1718. if (check & CPD_CREATE) {
  1719. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1720. #if defined (_WIN32) && !defined (WINCE)
  1721. r = mkdir(dirname);
  1722. #else
  1723. r = mkdir(dirname, 0700);
  1724. #endif
  1725. if (r) {
  1726. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1727. strerror(errno));
  1728. return -1;
  1729. }
  1730. } else if (!(check & CPD_CHECK)) {
  1731. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1732. return -1;
  1733. }
  1734. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1735. * parent directory a little harder. */
  1736. return 0;
  1737. }
  1738. if (!(st.st_mode & S_IFDIR)) {
  1739. log_warn(LD_FS, "%s is not a directory", dirname);
  1740. return -1;
  1741. }
  1742. #ifndef _WIN32
  1743. if (effective_user) {
  1744. /* Look up the user and group information.
  1745. * If we have a problem, bail out. */
  1746. pw = getpwnam(effective_user);
  1747. if (pw == NULL) {
  1748. log_warn(LD_CONFIG, "Error setting configured user: %s not found",
  1749. effective_user);
  1750. return -1;
  1751. }
  1752. running_uid = pw->pw_uid;
  1753. running_gid = pw->pw_gid;
  1754. } else {
  1755. running_uid = getuid();
  1756. running_gid = getgid();
  1757. }
  1758. if (st.st_uid != running_uid) {
  1759. struct passwd *pw = NULL;
  1760. char *process_ownername = NULL;
  1761. pw = getpwuid(running_uid);
  1762. process_ownername = pw ? tor_strdup(pw->pw_name) : tor_strdup("<unknown>");
  1763. pw = getpwuid(st.st_uid);
  1764. log_warn(LD_FS, "%s is not owned by this user (%s, %d) but by "
  1765. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1766. dirname, process_ownername, (int)running_uid,
  1767. pw ? pw->pw_name : "<unknown>", (int)st.st_uid);
  1768. tor_free(process_ownername);
  1769. return -1;
  1770. }
  1771. if ((check & CPD_GROUP_OK) && st.st_gid != running_gid) {
  1772. struct group *gr;
  1773. char *process_groupname = NULL;
  1774. gr = getgrgid(running_gid);
  1775. process_groupname = gr ? tor_strdup(gr->gr_name) : tor_strdup("<unknown>");
  1776. gr = getgrgid(st.st_gid);
  1777. log_warn(LD_FS, "%s is not owned by this group (%s, %d) but by group "
  1778. "%s (%d). Are you running Tor as the wrong user?",
  1779. dirname, process_groupname, (int)running_gid,
  1780. gr ? gr->gr_name : "<unknown>", (int)st.st_gid);
  1781. tor_free(process_groupname);
  1782. return -1;
  1783. }
  1784. if (check & CPD_GROUP_OK) {
  1785. mask = 0027;
  1786. } else {
  1787. mask = 0077;
  1788. }
  1789. if (st.st_mode & mask) {
  1790. unsigned new_mode;
  1791. if (check & CPD_CHECK_MODE_ONLY) {
  1792. log_warn(LD_FS, "Permissions on directory %s are too permissive.",
  1793. dirname);
  1794. return -1;
  1795. }
  1796. log_warn(LD_FS, "Fixing permissions on directory %s", dirname);
  1797. new_mode = st.st_mode;
  1798. new_mode |= 0700; /* Owner should have rwx */
  1799. new_mode &= ~mask; /* Clear the other bits that we didn't want set...*/
  1800. if (chmod(dirname, new_mode)) {
  1801. log_warn(LD_FS, "Could not chmod directory %s: %s", dirname,
  1802. strerror(errno));
  1803. return -1;
  1804. } else {
  1805. return 0;
  1806. }
  1807. }
  1808. #endif
  1809. return 0;
  1810. }
  1811. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1812. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1813. *
  1814. * This function replaces the old file atomically, if possible. This
  1815. * function, and all other functions in util.c that create files, create them
  1816. * with mode 0600.
  1817. */
  1818. int
  1819. write_str_to_file(const char *fname, const char *str, int bin)
  1820. {
  1821. #ifdef _WIN32
  1822. if (!bin && strchr(str, '\r')) {
  1823. log_warn(LD_BUG,
  1824. "We're writing a text string that already contains a CR.");
  1825. }
  1826. #endif
  1827. return write_bytes_to_file(fname, str, strlen(str), bin);
  1828. }
  1829. /** Represents a file that we're writing to, with support for atomic commit:
  1830. * we can write into a temporary file, and either remove the file on
  1831. * failure, or replace the original file on success. */
  1832. struct open_file_t {
  1833. char *tempname; /**< Name of the temporary file. */
  1834. char *filename; /**< Name of the original file. */
  1835. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  1836. unsigned binary:1; /**< Did we open in binary mode? */
  1837. int fd; /**< fd for the open file. */
  1838. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  1839. };
  1840. /** Try to start writing to the file in <b>fname</b>, passing the flags
  1841. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  1842. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  1843. * original file. Otherwise, we open a new temporary file in the same
  1844. * directory, and either replace the original or remove the temporary file
  1845. * when we're done.
  1846. *
  1847. * Return the fd for the newly opened file, and store working data in
  1848. * *<b>data_out</b>. The caller should not close the fd manually:
  1849. * instead, call finish_writing_to_file() or abort_writing_to_file().
  1850. * Returns -1 on failure.
  1851. *
  1852. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  1853. * as true and the flag O_EXCL is treated as false.
  1854. *
  1855. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  1856. * write()". We don't do that.
  1857. */
  1858. int
  1859. start_writing_to_file(const char *fname, int open_flags, int mode,
  1860. open_file_t **data_out)
  1861. {
  1862. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  1863. const char *open_name;
  1864. int append = 0;
  1865. tor_assert(fname);
  1866. tor_assert(data_out);
  1867. #if (O_BINARY != 0 && O_TEXT != 0)
  1868. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  1869. #endif
  1870. new_file->fd = -1;
  1871. new_file->filename = tor_strdup(fname);
  1872. if (open_flags & O_APPEND) {
  1873. open_name = fname;
  1874. new_file->rename_on_close = 0;
  1875. append = 1;
  1876. open_flags &= ~O_APPEND;
  1877. } else {
  1878. tor_asprintf(&new_file->tempname, "%s.tmp", fname);
  1879. open_name = new_file->tempname;
  1880. /* We always replace an existing temporary file if there is one. */
  1881. open_flags |= O_CREAT|O_TRUNC;
  1882. open_flags &= ~O_EXCL;
  1883. new_file->rename_on_close = 1;
  1884. }
  1885. if (open_flags & O_BINARY)
  1886. new_file->binary = 1;
  1887. new_file->fd = tor_open_cloexec(open_name, open_flags, mode);
  1888. if (new_file->fd < 0) {
  1889. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  1890. open_name, fname, strerror(errno));
  1891. goto err;
  1892. }
  1893. if (append) {
  1894. if (tor_fd_seekend(new_file->fd) < 0) {
  1895. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  1896. strerror(errno));
  1897. goto err;
  1898. }
  1899. }
  1900. *data_out = new_file;
  1901. return new_file->fd;
  1902. err:
  1903. if (new_file->fd >= 0)
  1904. close(new_file->fd);
  1905. *data_out = NULL;
  1906. tor_free(new_file->filename);
  1907. tor_free(new_file->tempname);
  1908. tor_free(new_file);
  1909. return -1;
  1910. }
  1911. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  1912. * that can be used to write to the same file. The caller should not mix
  1913. * stdio calls with non-stdio calls. */
  1914. FILE *
  1915. fdopen_file(open_file_t *file_data)
  1916. {
  1917. tor_assert(file_data);
  1918. if (file_data->stdio_file)
  1919. return file_data->stdio_file;
  1920. tor_assert(file_data->fd >= 0);
  1921. if (!(file_data->stdio_file = fdopen(file_data->fd,
  1922. file_data->binary?"ab":"a"))) {
  1923. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  1924. file_data->fd, strerror(errno));
  1925. }
  1926. return file_data->stdio_file;
  1927. }
  1928. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  1929. * for start_writing_to_file, but */
  1930. FILE *
  1931. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  1932. open_file_t **data_out)
  1933. {
  1934. FILE *res;
  1935. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  1936. return NULL;
  1937. if (!(res = fdopen_file(*data_out))) {
  1938. abort_writing_to_file(*data_out);
  1939. *data_out = NULL;
  1940. }
  1941. return res;
  1942. }
  1943. /** Helper function: close and free the underlying file and memory in
  1944. * <b>file_data</b>. If we were writing into a temporary file, then delete
  1945. * that file (if abort_write is true) or replaces the target file with
  1946. * the temporary file (if abort_write is false). */
  1947. static int
  1948. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  1949. {
  1950. int r = 0;
  1951. tor_assert(file_data && file_data->filename);
  1952. if (file_data->stdio_file) {
  1953. if (fclose(file_data->stdio_file)) {
  1954. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  1955. strerror(errno));
  1956. abort_write = r = -1;
  1957. }
  1958. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  1959. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  1960. strerror(errno));
  1961. abort_write = r = -1;
  1962. }
  1963. if (file_data->rename_on_close) {
  1964. tor_assert(file_data->tempname && file_data->filename);
  1965. if (abort_write) {
  1966. unlink(file_data->tempname);
  1967. } else {
  1968. tor_assert(strcmp(file_data->filename, file_data->tempname));
  1969. if (replace_file(file_data->tempname, file_data->filename)) {
  1970. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  1971. strerror(errno));
  1972. r = -1;
  1973. }
  1974. }
  1975. }
  1976. tor_free(file_data->filename);
  1977. tor_free(file_data->tempname);
  1978. tor_free(file_data);
  1979. return r;
  1980. }
  1981. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1982. * needed, and if using a temporary file, replace the original file with
  1983. * the temporary file. */
  1984. int
  1985. finish_writing_to_file(open_file_t *file_data)
  1986. {
  1987. return finish_writing_to_file_impl(file_data, 0);
  1988. }
  1989. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1990. * needed, and if using a temporary file, delete it. */
  1991. int
  1992. abort_writing_to_file(open_file_t *file_data)
  1993. {
  1994. return finish_writing_to_file_impl(file_data, 1);
  1995. }
  1996. /** Helper: given a set of flags as passed to open(2), open the file
  1997. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  1998. * the file. Do so as atomically as possible e.g. by opening temp files and
  1999. * renaming. */
  2000. static int
  2001. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  2002. int open_flags)
  2003. {
  2004. open_file_t *file = NULL;
  2005. int fd;
  2006. ssize_t result;
  2007. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  2008. if (fd<0)
  2009. return -1;
  2010. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  2011. {
  2012. result = write_all(fd, chunk->bytes, chunk->len, 0);
  2013. if (result < 0) {
  2014. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  2015. strerror(errno));
  2016. goto err;
  2017. }
  2018. tor_assert((size_t)result == chunk->len);
  2019. });
  2020. return finish_writing_to_file(file);
  2021. err:
  2022. abort_writing_to_file(file);
  2023. return -1;
  2024. }
  2025. /** Given a smartlist of sized_chunk_t, write them atomically to a file
  2026. * <b>fname</b>, overwriting or creating the file as necessary. */
  2027. int
  2028. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin)
  2029. {
  2030. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  2031. return write_chunks_to_file_impl(fname, chunks, flags);
  2032. }
  2033. /** Write <b>len</b> bytes, starting at <b>str</b>, to <b>fname</b>
  2034. using the open() flags passed in <b>flags</b>. */
  2035. static int
  2036. write_bytes_to_file_impl(const char *fname, const char *str, size_t len,
  2037. int flags)
  2038. {
  2039. int r;
  2040. sized_chunk_t c = { str, len };
  2041. smartlist_t *chunks = smartlist_new();
  2042. smartlist_add(chunks, &c);
  2043. r = write_chunks_to_file_impl(fname, chunks, flags);
  2044. smartlist_free(chunks);
  2045. return r;
  2046. }
  2047. /** As write_str_to_file, but does not assume a NUL-terminated
  2048. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  2049. int
  2050. write_bytes_to_file(const char *fname, const char *str, size_t len,
  2051. int bin)
  2052. {
  2053. return write_bytes_to_file_impl(fname, str, len,
  2054. OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT));
  2055. }
  2056. /** As write_bytes_to_file, but if the file already exists, append the bytes
  2057. * to the end of the file instead of overwriting it. */
  2058. int
  2059. append_bytes_to_file(const char *fname, const char *str, size_t len,
  2060. int bin)
  2061. {
  2062. return write_bytes_to_file_impl(fname, str, len,
  2063. OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT));
  2064. }
  2065. /** Like write_str_to_file(), but also return -1 if there was a file
  2066. already residing in <b>fname</b>. */
  2067. int
  2068. write_bytes_to_new_file(const char *fname, const char *str, size_t len,
  2069. int bin)
  2070. {
  2071. return write_bytes_to_file_impl(fname, str, len,
  2072. OPEN_FLAGS_DONT_REPLACE|
  2073. (bin?O_BINARY:O_TEXT));
  2074. }
  2075. /**
  2076. * Read the contents of the open file <b>fd</b> presuming it is a FIFO
  2077. * (or similar) file descriptor for which the size of the file isn't
  2078. * known ahead of time. Return NULL on failure, and a NUL-terminated
  2079. * string on success. On success, set <b>sz_out</b> to the number of
  2080. * bytes read.
  2081. */
  2082. char *
  2083. read_file_to_str_until_eof(int fd, size_t max_bytes_to_read, size_t *sz_out)
  2084. {
  2085. ssize_t r;
  2086. size_t pos = 0;
  2087. char *string = NULL;
  2088. size_t string_max = 0;
  2089. if (max_bytes_to_read+1 >= SIZE_T_CEILING)
  2090. return NULL;
  2091. do {
  2092. /* XXXX This "add 1K" approach is a little goofy; if we care about
  2093. * performance here, we should be doubling. But in practice we shouldn't
  2094. * be using this function on big files anyway. */
  2095. string_max = pos + 1024;
  2096. if (string_max > max_bytes_to_read)
  2097. string_max = max_bytes_to_read + 1;
  2098. string = tor_realloc(string, string_max);
  2099. r = read(fd, string + pos, string_max - pos - 1);
  2100. if (r < 0) {
  2101. tor_free(string);
  2102. return NULL;
  2103. }
  2104. pos += r;
  2105. } while (r > 0 && pos < max_bytes_to_read);
  2106. *sz_out = pos;
  2107. string[pos] = '\0';
  2108. return string;
  2109. }
  2110. /** Read the contents of <b>filename</b> into a newly allocated
  2111. * string; return the string on success or NULL on failure.
  2112. *
  2113. * If <b>stat_out</b> is provided, store the result of stat()ing the
  2114. * file into <b>stat_out</b>.
  2115. *
  2116. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  2117. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  2118. * doesn't exist.
  2119. */
  2120. /*
  2121. * This function <em>may</em> return an erroneous result if the file
  2122. * is modified while it is running, but must not crash or overflow.
  2123. * Right now, the error case occurs when the file length grows between
  2124. * the call to stat and the call to read_all: the resulting string will
  2125. * be truncated.
  2126. */
  2127. char *
  2128. read_file_to_str(const char *filename, int flags, struct stat *stat_out)
  2129. {
  2130. int fd; /* router file */
  2131. struct stat statbuf;
  2132. char *string;
  2133. ssize_t r;
  2134. int bin = flags & RFTS_BIN;
  2135. tor_assert(filename);
  2136. fd = tor_open_cloexec(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  2137. if (fd<0) {
  2138. int severity = LOG_WARN;
  2139. int save_errno = errno;
  2140. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  2141. severity = LOG_INFO;
  2142. log_fn(severity, LD_FS,"Could not open \"%s\": %s",filename,
  2143. strerror(errno));
  2144. errno = save_errno;
  2145. return NULL;
  2146. }
  2147. if (fstat(fd, &statbuf)<0) {
  2148. int save_errno = errno;
  2149. close(fd);
  2150. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  2151. errno = save_errno;
  2152. return NULL;
  2153. }
  2154. #ifndef _WIN32
  2155. /** When we detect that we're reading from a FIFO, don't read more than
  2156. * this many bytes. It's insane overkill for most uses. */
  2157. #define FIFO_READ_MAX (1024*1024)
  2158. if (S_ISFIFO(statbuf.st_mode)) {
  2159. size_t sz = 0;
  2160. string = read_file_to_str_until_eof(fd, FIFO_READ_MAX, &sz);
  2161. if (string && stat_out) {
  2162. statbuf.st_size = sz;
  2163. memcpy(stat_out, &statbuf, sizeof(struct stat));
  2164. }
  2165. close(fd);
  2166. return string;
  2167. }
  2168. #endif
  2169. if ((uint64_t)(statbuf.st_size)+1 >= SIZE_T_CEILING)
  2170. return NULL;
  2171. string = tor_malloc((size_t)(statbuf.st_size+1));
  2172. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  2173. if (r<0) {
  2174. int save_errno = errno;
  2175. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  2176. strerror(errno));
  2177. tor_free(string);
  2178. close(fd);
  2179. errno = save_errno;
  2180. return NULL;
  2181. }
  2182. string[r] = '\0'; /* NUL-terminate the result. */
  2183. #if defined(_WIN32) || defined(__CYGWIN__)
  2184. if (!bin && strchr(string, '\r')) {
  2185. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  2186. "when reading %s. Coping.",
  2187. filename);
  2188. tor_strstrip(string, "\r");
  2189. r = strlen(string);
  2190. }
  2191. if (!bin) {
  2192. statbuf.st_size = (size_t) r;
  2193. } else
  2194. #endif
  2195. if (r != statbuf.st_size) {
  2196. /* Unless we're using text mode on win32, we'd better have an exact
  2197. * match for size. */
  2198. int save_errno = errno;
  2199. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  2200. (int)r, (long)statbuf.st_size,filename);
  2201. tor_free(string);
  2202. close(fd);
  2203. errno = save_errno;
  2204. return NULL;
  2205. }
  2206. close(fd);
  2207. if (stat_out) {
  2208. memcpy(stat_out, &statbuf, sizeof(struct stat));
  2209. }
  2210. return string;
  2211. }
  2212. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  2213. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  2214. * decode its contents into a newly allocated string. On success, assign this
  2215. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  2216. * provided), and return a pointer to the position in <b>s</b> immediately
  2217. * after the string. On failure, return NULL.
  2218. */
  2219. static const char *
  2220. unescape_string(const char *s, char **result, size_t *size_out)
  2221. {
  2222. const char *cp;
  2223. char *out;
  2224. if (s[0] != '\"')
  2225. return NULL;
  2226. cp = s+1;
  2227. while (1) {
  2228. switch (*cp) {
  2229. case '\0':
  2230. case '\n':
  2231. return NULL;
  2232. case '\"':
  2233. goto end_of_loop;
  2234. case '\\':
  2235. if (cp[1] == 'x' || cp[1] == 'X') {
  2236. if (!(TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])))
  2237. return NULL;
  2238. cp += 4;
  2239. } else if (TOR_ISODIGIT(cp[1])) {
  2240. cp += 2;
  2241. if (TOR_ISODIGIT(*cp)) ++cp;
  2242. if (TOR_ISODIGIT(*cp)) ++cp;
  2243. } else if (cp[1] == 'n' || cp[1] == 'r' || cp[1] == 't' || cp[1] == '"'
  2244. || cp[1] == '\\' || cp[1] == '\'') {
  2245. cp += 2;
  2246. } else {
  2247. return NULL;
  2248. }
  2249. break;
  2250. default:
  2251. ++cp;
  2252. break;
  2253. }
  2254. }
  2255. end_of_loop:
  2256. out = *result = tor_malloc(cp-s + 1);
  2257. cp = s+1;
  2258. while (1) {
  2259. switch (*cp)
  2260. {
  2261. case '\"':
  2262. *out = '\0';
  2263. if (size_out) *size_out = out - *result;
  2264. return cp+1;
  2265. case '\0':
  2266. tor_fragile_assert();
  2267. tor_free(*result);
  2268. return NULL;
  2269. case '\\':
  2270. switch (cp[1])
  2271. {
  2272. case 'n': *out++ = '\n'; cp += 2; break;
  2273. case 'r': *out++ = '\r'; cp += 2; break;
  2274. case 't': *out++ = '\t'; cp += 2; break;
  2275. case 'x': case 'X':
  2276. {
  2277. int x1, x2;
  2278. x1 = hex_decode_digit(cp[2]);
  2279. x2 = hex_decode_digit(cp[3]);
  2280. if (x1 == -1 || x2 == -1) {
  2281. tor_free(*result);
  2282. return NULL;
  2283. }
  2284. *out++ = ((x1<<4) + x2);
  2285. cp += 4;
  2286. }
  2287. break;
  2288. case '0': case '1': case '2': case '3': case '4': case '5':
  2289. case '6': case '7':
  2290. {
  2291. int n = cp[1]-'0';
  2292. cp += 2;
  2293. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2294. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2295. if (n > 255) { tor_free(*result); return NULL; }
  2296. *out++ = (char)n;
  2297. }
  2298. break;
  2299. case '\'':
  2300. case '\"':
  2301. case '\\':
  2302. case '\?':
  2303. *out++ = cp[1];
  2304. cp += 2;
  2305. break;
  2306. default:
  2307. tor_free(*result); return NULL;
  2308. }
  2309. break;
  2310. default:
  2311. *out++ = *cp++;
  2312. }
  2313. }
  2314. }
  2315. /** Given a string containing part of a configuration file or similar format,
  2316. * advance past comments and whitespace and try to parse a single line. If we
  2317. * parse a line successfully, set *<b>key_out</b> to a new string holding the
  2318. * key portion and *<b>value_out</b> to a new string holding the value portion
  2319. * of the line, and return a pointer to the start of the next line. If we run
  2320. * out of data, return a pointer to the end of the string. If we encounter an
  2321. * error, return NULL.
  2322. */
  2323. const char *
  2324. parse_config_line_from_str(const char *line, char **key_out, char **value_out)
  2325. {
  2326. /* I believe the file format here is supposed to be:
  2327. FILE = (EMPTYLINE | LINE)* (EMPTYLASTLINE | LASTLINE)?
  2328. EMPTYLASTLINE = SPACE* | COMMENT
  2329. EMPTYLINE = EMPTYLASTLINE NL
  2330. SPACE = ' ' | '\r' | '\t'
  2331. COMMENT = '#' NOT-NL*
  2332. NOT-NL = Any character except '\n'
  2333. NL = '\n'
  2334. LASTLINE = SPACE* KEY SPACE* VALUES
  2335. LINE = LASTLINE NL
  2336. KEY = KEYCHAR+
  2337. KEYCHAR = Any character except ' ', '\r', '\n', '\t', '#', "\"
  2338. VALUES = QUOTEDVALUE | NORMALVALUE
  2339. QUOTEDVALUE = QUOTE QVCHAR* QUOTE EOLSPACE?
  2340. QUOTE = '"'
  2341. QVCHAR = KEYCHAR | ESC ('n' | 't' | 'r' | '"' | ESC |'\'' | OCTAL | HEX)
  2342. ESC = "\\"
  2343. OCTAL = ODIGIT (ODIGIT ODIGIT?)?
  2344. HEX = ('x' | 'X') HEXDIGIT HEXDIGIT
  2345. ODIGIT = '0' .. '7'
  2346. HEXDIGIT = '0'..'9' | 'a' .. 'f' | 'A' .. 'F'
  2347. EOLSPACE = SPACE* COMMENT?
  2348. NORMALVALUE = (VALCHAR | ESC ESC_IGNORE | CONTINUATION)* EOLSPACE?
  2349. VALCHAR = Any character except ESC, '#', and '\n'
  2350. ESC_IGNORE = Any character except '#' or '\n'
  2351. CONTINUATION = ESC NL ( COMMENT NL )*
  2352. */
  2353. const char *key, *val, *cp;
  2354. int continuation = 0;
  2355. tor_assert(key_out);
  2356. tor_assert(value_out);
  2357. *key_out = *value_out = NULL;
  2358. key = val = NULL;
  2359. /* Skip until the first keyword. */
  2360. while (1) {
  2361. while (TOR_ISSPACE(*line))
  2362. ++line;
  2363. if (*line == '#') {
  2364. while (*line && *line != '\n')
  2365. ++line;
  2366. } else {
  2367. break;
  2368. }
  2369. }
  2370. if (!*line) { /* End of string? */
  2371. *key_out = *value_out = NULL;
  2372. return line;
  2373. }
  2374. /* Skip until the next space or \ followed by newline. */
  2375. key = line;
  2376. while (*line && !TOR_ISSPACE(*line) && *line != '#' &&
  2377. ! (line[0] == '\\' && line[1] == '\n'))
  2378. ++line;
  2379. *key_out = tor_strndup(key, line-key);
  2380. /* Skip until the value. */
  2381. while (*line == ' ' || *line == '\t')
  2382. ++line;
  2383. val = line;
  2384. /* Find the end of the line. */
  2385. if (*line == '\"') { // XXX No continuation handling is done here
  2386. if (!(line = unescape_string(line, value_out, NULL)))
  2387. return NULL;
  2388. while (*line == ' ' || *line == '\t')
  2389. ++line;
  2390. if (*line && *line != '#' && *line != '\n')
  2391. return NULL;
  2392. } else {
  2393. /* Look for the end of the line. */
  2394. while (*line && *line != '\n' && (*line != '#' || continuation)) {
  2395. if (*line == '\\' && line[1] == '\n') {
  2396. continuation = 1;
  2397. line += 2;
  2398. } else if (*line == '#') {
  2399. do {
  2400. ++line;
  2401. } while (*line && *line != '\n');
  2402. if (*line == '\n')
  2403. ++line;
  2404. } else {
  2405. ++line;
  2406. }
  2407. }
  2408. if (*line == '\n') {
  2409. cp = line++;
  2410. } else {
  2411. cp = line;
  2412. }
  2413. /* Now back cp up to be the last nonspace character */
  2414. while (cp>val && TOR_ISSPACE(*(cp-1)))
  2415. --cp;
  2416. tor_assert(cp >= val);
  2417. /* Now copy out and decode the value. */
  2418. *value_out = tor_strndup(val, cp-val);
  2419. if (continuation) {
  2420. char *v_out, *v_in;
  2421. v_out = v_in = *value_out;
  2422. while (*v_in) {
  2423. if (*v_in == '#') {
  2424. do {
  2425. ++v_in;
  2426. } while (*v_in && *v_in != '\n');
  2427. if (*v_in == '\n')
  2428. ++v_in;
  2429. } else if (v_in[0] == '\\' && v_in[1] == '\n') {
  2430. v_in += 2;
  2431. } else {
  2432. *v_out++ = *v_in++;
  2433. }
  2434. }
  2435. *v_out = '\0';
  2436. }
  2437. }
  2438. if (*line == '#') {
  2439. do {
  2440. ++line;
  2441. } while (*line && *line != '\n');
  2442. }
  2443. while (TOR_ISSPACE(*line)) ++line;
  2444. return line;
  2445. }
  2446. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  2447. * string. */
  2448. char *
  2449. expand_filename(const char *filename)
  2450. {
  2451. tor_assert(filename);
  2452. #ifdef _WIN32
  2453. return tor_strdup(filename);
  2454. #else
  2455. if (*filename == '~') {
  2456. char *home, *result=NULL;
  2457. const char *rest;
  2458. if (filename[1] == '/' || filename[1] == '\0') {
  2459. home = getenv("HOME");
  2460. if (!home) {
  2461. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  2462. "expanding \"%s\"; defaulting to \"\".", filename);
  2463. home = tor_strdup("");
  2464. } else {
  2465. home = tor_strdup(home);
  2466. }
  2467. rest = strlen(filename)>=2?(filename+2):"";
  2468. } else {
  2469. #ifdef HAVE_PWD_H
  2470. char *username, *slash;
  2471. slash = strchr(filename, '/');
  2472. if (slash)
  2473. username = tor_strndup(filename+1,slash-filename-1);
  2474. else
  2475. username = tor_strdup(filename+1);
  2476. if (!(home = get_user_homedir(username))) {
  2477. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2478. tor_free(username);
  2479. return NULL;
  2480. }
  2481. tor_free(username);
  2482. rest = slash ? (slash+1) : "";
  2483. #else
  2484. log_warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
  2485. return tor_strdup(filename);
  2486. #endif
  2487. }
  2488. tor_assert(home);
  2489. /* Remove trailing slash. */
  2490. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2491. home[strlen(home)-1] = '\0';
  2492. }
  2493. tor_asprintf(&result,"%s"PATH_SEPARATOR"%s",home,rest);
  2494. tor_free(home);
  2495. return result;
  2496. } else {
  2497. return tor_strdup(filename);
  2498. }
  2499. #endif
  2500. }
  2501. #define MAX_SCANF_WIDTH 9999
  2502. /** Helper: given an ASCII-encoded decimal digit, return its numeric value.
  2503. * NOTE: requires that its input be in-bounds. */
  2504. static int
  2505. digit_to_num(char d)
  2506. {
  2507. int num = ((int)d) - (int)'0';
  2508. tor_assert(num <= 9 && num >= 0);
  2509. return num;
  2510. }
  2511. /** Helper: Read an unsigned int from *<b>bufp</b> of up to <b>width</b>
  2512. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2513. * success, store the result in <b>out</b>, advance bufp to the next
  2514. * character, and return 0. On failure, return -1. */
  2515. static int
  2516. scan_unsigned(const char **bufp, unsigned long *out, int width, int base)
  2517. {
  2518. unsigned long result = 0;
  2519. int scanned_so_far = 0;
  2520. const int hex = base==16;
  2521. tor_assert(base == 10 || base == 16);
  2522. if (!bufp || !*bufp || !out)
  2523. return -1;
  2524. if (width<0)
  2525. width=MAX_SCANF_WIDTH;
  2526. while (**bufp && (hex?TOR_ISXDIGIT(**bufp):TOR_ISDIGIT(**bufp))
  2527. && scanned_so_far < width) {
  2528. int digit = hex?hex_decode_digit(*(*bufp)++):digit_to_num(*(*bufp)++);
  2529. unsigned long new_result = result * base + digit;
  2530. if (new_result < result)
  2531. return -1; /* over/underflow. */
  2532. result = new_result;
  2533. ++scanned_so_far;
  2534. }
  2535. if (!scanned_so_far) /* No actual digits scanned */
  2536. return -1;
  2537. *out = result;
  2538. return 0;
  2539. }
  2540. /** Helper: Read an signed int from *<b>bufp</b> of up to <b>width</b>
  2541. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2542. * success, store the result in <b>out</b>, advance bufp to the next
  2543. * character, and return 0. On failure, return -1. */
  2544. static int
  2545. scan_signed(const char **bufp, long *out, int width)
  2546. {
  2547. int neg = 0;
  2548. unsigned long result = 0;
  2549. if (!bufp || !*bufp || !out)
  2550. return -1;
  2551. if (width<0)
  2552. width=MAX_SCANF_WIDTH;
  2553. if (**bufp == '-') {
  2554. neg = 1;
  2555. ++*bufp;
  2556. --width;
  2557. }
  2558. if (scan_unsigned(bufp, &result, width, 10) < 0)
  2559. return -1;
  2560. if (neg) {
  2561. if (result > ((unsigned long)LONG_MAX) + 1)
  2562. return -1; /* Underflow */
  2563. *out = -(long)result;
  2564. } else {
  2565. if (result > LONG_MAX)
  2566. return -1; /* Overflow */
  2567. *out = (long)result;
  2568. }
  2569. return 0;
  2570. }
  2571. /** Helper: Read a decimal-formatted double from *<b>bufp</b> of up to
  2572. * <b>width</b> characters. (Handle arbitrary width if <b>width</b> is less
  2573. * than 0.) On success, store the result in <b>out</b>, advance bufp to the
  2574. * next character, and return 0. On failure, return -1. */
  2575. static int
  2576. scan_double(const char **bufp, double *out, int width)
  2577. {
  2578. int neg = 0;
  2579. double result = 0;
  2580. int scanned_so_far = 0;
  2581. if (!bufp || !*bufp || !out)
  2582. return -1;
  2583. if (width<0)
  2584. width=MAX_SCANF_WIDTH;
  2585. if (**bufp == '-') {
  2586. neg = 1;
  2587. ++*bufp;
  2588. }
  2589. while (**bufp && TOR_ISDIGIT(**bufp) && scanned_so_far < width) {
  2590. const int digit = digit_to_num(*(*bufp)++);
  2591. result = result * 10 + digit;
  2592. ++scanned_so_far;
  2593. }
  2594. if (**bufp == '.') {
  2595. double fracval = 0, denominator = 1;
  2596. ++*bufp;
  2597. ++scanned_so_far;
  2598. while (**bufp && TOR_ISDIGIT(**bufp) && scanned_so_far < width) {
  2599. const int digit = digit_to_num(*(*bufp)++);
  2600. fracval = fracval * 10 + digit;
  2601. denominator *= 10;
  2602. ++scanned_so_far;
  2603. }
  2604. result += fracval / denominator;
  2605. }
  2606. if (!scanned_so_far) /* No actual digits scanned */
  2607. return -1;
  2608. *out = neg ? -result : result;
  2609. return 0;
  2610. }
  2611. /** Helper: copy up to <b>width</b> non-space characters from <b>bufp</b> to
  2612. * <b>out</b>. Make sure <b>out</b> is nul-terminated. Advance <b>bufp</b>
  2613. * to the next non-space character or the EOS. */
  2614. static int
  2615. scan_string(const char **bufp, char *out, int width)
  2616. {
  2617. int scanned_so_far = 0;
  2618. if (!bufp || !out || width < 0)
  2619. return -1;
  2620. while (**bufp && ! TOR_ISSPACE(**bufp) && scanned_so_far < width) {
  2621. *out++ = *(*bufp)++;
  2622. ++scanned_so_far;
  2623. }
  2624. *out = '\0';
  2625. return 0;
  2626. }
  2627. /** Locale-independent, minimal, no-surprises scanf variant, accepting only a
  2628. * restricted pattern format. For more info on what it supports, see
  2629. * tor_sscanf() documentation. */
  2630. int
  2631. tor_vsscanf(const char *buf, const char *pattern, va_list ap)
  2632. {
  2633. int n_matched = 0;
  2634. while (*pattern) {
  2635. if (*pattern != '%') {
  2636. if (*buf == *pattern) {
  2637. ++buf;
  2638. ++pattern;
  2639. continue;
  2640. } else {
  2641. return n_matched;
  2642. }
  2643. } else {
  2644. int width = -1;
  2645. int longmod = 0;
  2646. ++pattern;
  2647. if (TOR_ISDIGIT(*pattern)) {
  2648. width = digit_to_num(*pattern++);
  2649. while (TOR_ISDIGIT(*pattern)) {
  2650. width *= 10;
  2651. width += digit_to_num(*pattern++);
  2652. if (width > MAX_SCANF_WIDTH)
  2653. return -1;
  2654. }
  2655. if (!width) /* No zero-width things. */
  2656. return -1;
  2657. }
  2658. if (*pattern == 'l') {
  2659. longmod = 1;
  2660. ++pattern;
  2661. }
  2662. if (*pattern == 'u' || *pattern == 'x') {
  2663. unsigned long u;
  2664. const int base = (*pattern == 'u') ? 10 : 16;
  2665. if (!*buf)
  2666. return n_matched;
  2667. if (scan_unsigned(&buf, &u, width, base)<0)
  2668. return n_matched;
  2669. if (longmod) {
  2670. unsigned long *out = va_arg(ap, unsigned long *);
  2671. *out = u;
  2672. } else {
  2673. unsigned *out = va_arg(ap, unsigned *);
  2674. if (u > UINT_MAX)
  2675. return n_matched;
  2676. *out = (unsigned) u;
  2677. }
  2678. ++pattern;
  2679. ++n_matched;
  2680. } else if (*pattern == 'f') {
  2681. double *d = va_arg(ap, double *);
  2682. if (!longmod)
  2683. return -1; /* float not supported */
  2684. if (!*buf)
  2685. return n_matched;
  2686. if (scan_double(&buf, d, width)<0)
  2687. return n_matched;
  2688. ++pattern;
  2689. ++n_matched;
  2690. } else if (*pattern == 'd') {
  2691. long lng=0;
  2692. if (scan_signed(&buf, &lng, width)<0)
  2693. return n_matched;
  2694. if (longmod) {
  2695. long *out = va_arg(ap, long *);
  2696. *out = lng;
  2697. } else {
  2698. int *out = va_arg(ap, int *);
  2699. if (lng < INT_MIN || lng > INT_MAX)
  2700. return n_matched;
  2701. *out = (int)lng;
  2702. }
  2703. ++pattern;
  2704. ++n_matched;
  2705. } else if (*pattern == 's') {
  2706. char *s = va_arg(ap, char *);
  2707. if (longmod)
  2708. return -1;
  2709. if (width < 0)
  2710. return -1;
  2711. if (scan_string(&buf, s, width)<0)
  2712. return n_matched;
  2713. ++pattern;
  2714. ++n_matched;
  2715. } else if (*pattern == 'c') {
  2716. char *ch = va_arg(ap, char *);
  2717. if (longmod)
  2718. return -1;
  2719. if (width != -1)
  2720. return -1;
  2721. if (!*buf)
  2722. return n_matched;
  2723. *ch = *buf++;
  2724. ++pattern;
  2725. ++n_matched;
  2726. } else if (*pattern == '%') {
  2727. if (*buf != '%')
  2728. return n_matched;
  2729. if (longmod)
  2730. return -1;
  2731. ++buf;
  2732. ++pattern;
  2733. } else {
  2734. return -1; /* Unrecognized pattern component. */
  2735. }
  2736. }
  2737. }
  2738. return n_matched;
  2739. }
  2740. /** Minimal sscanf replacement: parse <b>buf</b> according to <b>pattern</b>
  2741. * and store the results in the corresponding argument fields. Differs from
  2742. * sscanf in that:
  2743. * <ul><li>It only handles %u, %lu, %x, %lx, %<NUM>s, %d, %ld, %lf, and %c.
  2744. * <li>It only handles decimal inputs for %lf. (12.3, not 1.23e1)
  2745. * <li>It does not handle arbitrarily long widths.
  2746. * <li>Numbers do not consume any space characters.
  2747. * <li>It is locale-independent.
  2748. * <li>%u and %x do not consume any space.
  2749. * <li>It returns -1 on malformed patterns.</ul>
  2750. *
  2751. * (As with other locale-independent functions, we need this to parse data that
  2752. * is in ASCII without worrying that the C library's locale-handling will make
  2753. * miscellaneous characters look like numbers, spaces, and so on.)
  2754. */
  2755. int
  2756. tor_sscanf(const char *buf, const char *pattern, ...)
  2757. {
  2758. int r;
  2759. va_list ap;
  2760. va_start(ap, pattern);
  2761. r = tor_vsscanf(buf, pattern, ap);
  2762. va_end(ap);
  2763. return r;
  2764. }
  2765. /** Append the string produced by tor_asprintf(<b>pattern</b>, <b>...</b>)
  2766. * to <b>sl</b>. */
  2767. void
  2768. smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern, ...)
  2769. {
  2770. va_list ap;
  2771. va_start(ap, pattern);
  2772. smartlist_add_vasprintf(sl, pattern, ap);
  2773. va_end(ap);
  2774. }
  2775. /** va_list-based backend of smartlist_add_asprintf. */
  2776. void
  2777. smartlist_add_vasprintf(struct smartlist_t *sl, const char *pattern,
  2778. va_list args)
  2779. {
  2780. char *str = NULL;
  2781. tor_vasprintf(&str, pattern, args);
  2782. tor_assert(str != NULL);
  2783. smartlist_add(sl, str);
  2784. }
  2785. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  2786. * Return NULL on error or if <b>dirname</b> is not a directory.
  2787. */
  2788. smartlist_t *
  2789. tor_listdir(const char *dirname)
  2790. {
  2791. smartlist_t *result;
  2792. #ifdef _WIN32
  2793. char *pattern=NULL;
  2794. TCHAR tpattern[MAX_PATH] = {0};
  2795. char name[MAX_PATH*2+1] = {0};
  2796. HANDLE handle;
  2797. WIN32_FIND_DATA findData;
  2798. tor_asprintf(&pattern, "%s\\*", dirname);
  2799. #ifdef UNICODE
  2800. mbstowcs(tpattern,pattern,MAX_PATH);
  2801. #else
  2802. strlcpy(tpattern, pattern, MAX_PATH);
  2803. #endif
  2804. if (INVALID_HANDLE_VALUE == (handle = FindFirstFile(tpattern, &findData))) {
  2805. tor_free(pattern);
  2806. return NULL;
  2807. }
  2808. result = smartlist_new();
  2809. while (1) {
  2810. #ifdef UNICODE
  2811. wcstombs(name,findData.cFileName,MAX_PATH);
  2812. name[sizeof(name)-1] = '\0';
  2813. #else
  2814. strlcpy(name,findData.cFileName,sizeof(name));
  2815. #endif
  2816. if (strcmp(name, ".") &&
  2817. strcmp(name, "..")) {
  2818. smartlist_add(result, tor_strdup(name));
  2819. }
  2820. if (!FindNextFile(handle, &findData)) {
  2821. DWORD err;
  2822. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  2823. char *errstr = format_win32_error(err);
  2824. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  2825. tor_free(errstr);
  2826. }
  2827. break;
  2828. }
  2829. }
  2830. FindClose(handle);
  2831. tor_free(pattern);
  2832. #else
  2833. DIR *d;
  2834. struct dirent *de;
  2835. if (!(d = opendir(dirname)))
  2836. return NULL;
  2837. result = smartlist_new();
  2838. while ((de = readdir(d))) {
  2839. if (!strcmp(de->d_name, ".") ||
  2840. !strcmp(de->d_name, ".."))
  2841. continue;
  2842. smartlist_add(result, tor_strdup(de->d_name));
  2843. }
  2844. closedir(d);
  2845. #endif
  2846. return result;
  2847. }
  2848. /** Return true iff <b>filename</b> is a relative path. */
  2849. int
  2850. path_is_relative(const char *filename)
  2851. {
  2852. if (filename && filename[0] == '/')
  2853. return 0;
  2854. #ifdef _WIN32
  2855. else if (filename && filename[0] == '\\')
  2856. return 0;
  2857. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  2858. filename[1] == ':' && filename[2] == '\\')
  2859. return 0;
  2860. #endif
  2861. else
  2862. return 1;
  2863. }
  2864. /* =====
  2865. * Process helpers
  2866. * ===== */
  2867. #ifndef _WIN32
  2868. /* Based on code contributed by christian grothoff */
  2869. /** True iff we've called start_daemon(). */
  2870. static int start_daemon_called = 0;
  2871. /** True iff we've called finish_daemon(). */
  2872. static int finish_daemon_called = 0;
  2873. /** Socketpair used to communicate between parent and child process while
  2874. * daemonizing. */
  2875. static int daemon_filedes[2];
  2876. /** Start putting the process into daemon mode: fork and drop all resources
  2877. * except standard fds. The parent process never returns, but stays around
  2878. * until finish_daemon is called. (Note: it's safe to call this more
  2879. * than once: calls after the first are ignored.)
  2880. */
  2881. void
  2882. start_daemon(void)
  2883. {
  2884. pid_t pid;
  2885. if (start_daemon_called)
  2886. return;
  2887. start_daemon_called = 1;
  2888. if (pipe(daemon_filedes)) {
  2889. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  2890. exit(1);
  2891. }
  2892. pid = fork();
  2893. if (pid < 0) {
  2894. log_err(LD_GENERAL,"fork failed. Exiting.");
  2895. exit(1);
  2896. }
  2897. if (pid) { /* Parent */
  2898. int ok;
  2899. char c;
  2900. close(daemon_filedes[1]); /* we only read */
  2901. ok = -1;
  2902. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  2903. if (c == '.')
  2904. ok = 1;
  2905. }
  2906. fflush(stdout);
  2907. if (ok == 1)
  2908. exit(0);
  2909. else
  2910. exit(1); /* child reported error */
  2911. } else { /* Child */
  2912. close(daemon_filedes[0]); /* we only write */
  2913. pid = setsid(); /* Detach from controlling terminal */
  2914. /*
  2915. * Fork one more time, so the parent (the session group leader) can exit.
  2916. * This means that we, as a non-session group leader, can never regain a
  2917. * controlling terminal. This part is recommended by Stevens's
  2918. * _Advanced Programming in the Unix Environment_.
  2919. */
  2920. if (fork() != 0) {
  2921. exit(0);
  2922. }
  2923. set_main_thread(); /* We are now the main thread. */
  2924. return;
  2925. }
  2926. }
  2927. /** Finish putting the process into daemon mode: drop standard fds, and tell
  2928. * the parent process to exit. (Note: it's safe to call this more than once:
  2929. * calls after the first are ignored. Calls start_daemon first if it hasn't
  2930. * been called already.)
  2931. */
  2932. void
  2933. finish_daemon(const char *desired_cwd)
  2934. {
  2935. int nullfd;
  2936. char c = '.';
  2937. if (finish_daemon_called)
  2938. return;
  2939. if (!start_daemon_called)
  2940. start_daemon();
  2941. finish_daemon_called = 1;
  2942. if (!desired_cwd)
  2943. desired_cwd = "/";
  2944. /* Don't hold the wrong FS mounted */
  2945. if (chdir(desired_cwd) < 0) {
  2946. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  2947. exit(1);
  2948. }
  2949. nullfd = tor_open_cloexec("/dev/null", O_RDWR, 0);
  2950. if (nullfd < 0) {
  2951. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  2952. exit(1);
  2953. }
  2954. /* close fds linking to invoking terminal, but
  2955. * close usual incoming fds, but redirect them somewhere
  2956. * useful so the fds don't get reallocated elsewhere.
  2957. */
  2958. if (dup2(nullfd,0) < 0 ||
  2959. dup2(nullfd,1) < 0 ||
  2960. dup2(nullfd,2) < 0) {
  2961. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  2962. exit(1);
  2963. }
  2964. if (nullfd > 2)
  2965. close(nullfd);
  2966. /* signal success */
  2967. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  2968. log_err(LD_GENERAL,"write failed. Exiting.");
  2969. }
  2970. close(daemon_filedes[1]);
  2971. }
  2972. #else
  2973. /* defined(_WIN32) */
  2974. void
  2975. start_daemon(void)
  2976. {
  2977. }
  2978. void
  2979. finish_daemon(const char *cp)
  2980. {
  2981. (void)cp;
  2982. }
  2983. #endif
  2984. /** Write the current process ID, followed by NL, into <b>filename</b>.
  2985. */
  2986. void
  2987. write_pidfile(char *filename)
  2988. {
  2989. FILE *pidfile;
  2990. if ((pidfile = fopen(filename, "w")) == NULL) {
  2991. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  2992. strerror(errno));
  2993. } else {
  2994. #ifdef _WIN32
  2995. fprintf(pidfile, "%d\n", (int)_getpid());
  2996. #else
  2997. fprintf(pidfile, "%d\n", (int)getpid());
  2998. #endif
  2999. fclose(pidfile);
  3000. }
  3001. }
  3002. #ifdef _WIN32
  3003. HANDLE
  3004. load_windows_system_library(const TCHAR *library_name)
  3005. {
  3006. TCHAR path[MAX_PATH];
  3007. unsigned n;
  3008. n = GetSystemDirectory(path, MAX_PATH);
  3009. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  3010. return 0;
  3011. _tcscat(path, TEXT("\\"));
  3012. _tcscat(path, library_name);
  3013. return LoadLibrary(path);
  3014. }
  3015. #endif
  3016. /** Format a single argument for being put on a Windows command line.
  3017. * Returns a newly allocated string */
  3018. static char *
  3019. format_win_cmdline_argument(const char *arg)
  3020. {
  3021. char *formatted_arg;
  3022. char need_quotes;
  3023. const char *c;
  3024. int i;
  3025. int bs_counter = 0;
  3026. /* Backslash we can point to when one is inserted into the string */
  3027. const char backslash = '\\';
  3028. /* Smartlist of *char */
  3029. smartlist_t *arg_chars;
  3030. arg_chars = smartlist_new();
  3031. /* Quote string if it contains whitespace or is empty */
  3032. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  3033. /* Build up smartlist of *chars */
  3034. for (c=arg; *c != '\0'; c++) {
  3035. if ('"' == *c) {
  3036. /* Double up backslashes preceding a quote */
  3037. for (i=0; i<(bs_counter*2); i++)
  3038. smartlist_add(arg_chars, (void*)&backslash);
  3039. bs_counter = 0;
  3040. /* Escape the quote */
  3041. smartlist_add(arg_chars, (void*)&backslash);
  3042. smartlist_add(arg_chars, (void*)c);
  3043. } else if ('\\' == *c) {
  3044. /* Count backslashes until we know whether to double up */
  3045. bs_counter++;
  3046. } else {
  3047. /* Don't double up slashes preceding a non-quote */
  3048. for (i=0; i<bs_counter; i++)
  3049. smartlist_add(arg_chars, (void*)&backslash);
  3050. bs_counter = 0;
  3051. smartlist_add(arg_chars, (void*)c);
  3052. }
  3053. }
  3054. /* Don't double up trailing backslashes */
  3055. for (i=0; i<bs_counter; i++)
  3056. smartlist_add(arg_chars, (void*)&backslash);
  3057. /* Allocate space for argument, quotes (if needed), and terminator */
  3058. formatted_arg = tor_malloc(sizeof(char) *
  3059. (smartlist_len(arg_chars) + (need_quotes?2:0) + 1));
  3060. /* Add leading quote */
  3061. i=0;
  3062. if (need_quotes)
  3063. formatted_arg[i++] = '"';
  3064. /* Add characters */
  3065. SMARTLIST_FOREACH(arg_chars, char*, c,
  3066. {
  3067. formatted_arg[i++] = *c;
  3068. });
  3069. /* Add trailing quote */
  3070. if (need_quotes)
  3071. formatted_arg[i++] = '"';
  3072. formatted_arg[i] = '\0';
  3073. smartlist_free(arg_chars);
  3074. return formatted_arg;
  3075. }
  3076. /** Format a command line for use on Windows, which takes the command as a
  3077. * string rather than string array. Follows the rules from "Parsing C++
  3078. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  3079. * Python subprocess module. Returns a newly allocated string */
  3080. char *
  3081. tor_join_win_cmdline(const char *argv[])
  3082. {
  3083. smartlist_t *argv_list;
  3084. char *joined_argv;
  3085. int i;
  3086. /* Format each argument and put the result in a smartlist */
  3087. argv_list = smartlist_new();
  3088. for (i=0; argv[i] != NULL; i++) {
  3089. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  3090. }
  3091. /* Join the arguments with whitespace */
  3092. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  3093. /* Free the newly allocated arguments, and the smartlist */
  3094. SMARTLIST_FOREACH(argv_list, char *, arg,
  3095. {
  3096. tor_free(arg);
  3097. });
  3098. smartlist_free(argv_list);
  3099. return joined_argv;
  3100. }
  3101. /**
  3102. * Helper function to output hex numbers, called by
  3103. * format_helper_exit_status(). This writes the hexadecimal digits of x into
  3104. * buf, up to max_len digits, and returns the actual number of digits written.
  3105. * If there is insufficient space, it will write nothing and return 0.
  3106. *
  3107. * This function DOES NOT add a terminating NUL character to its output: be
  3108. * careful!
  3109. *
  3110. * This accepts an unsigned int because format_helper_exit_status() needs to
  3111. * call it with a signed int and an unsigned char, and since the C standard
  3112. * does not guarantee that an int is wider than a char (an int must be at
  3113. * least 16 bits but it is permitted for a char to be that wide as well), we
  3114. * can't assume a signed int is sufficient to accomodate an unsigned char.
  3115. * Thus, format_helper_exit_status() will still need to emit any require '-'
  3116. * on its own.
  3117. *
  3118. * For most purposes, you'd want to use tor_snprintf("%x") instead of this
  3119. * function; it's designed to be used in code paths where you can't call
  3120. * arbitrary C functions.
  3121. */
  3122. int
  3123. format_hex_number_for_helper_exit_status(unsigned int x, char *buf,
  3124. int max_len)
  3125. {
  3126. int len;
  3127. unsigned int tmp;
  3128. char *cur;
  3129. /* Sanity check */
  3130. if (!buf || max_len <= 0)
  3131. return 0;
  3132. /* How many chars do we need for x? */
  3133. if (x > 0) {
  3134. len = 0;
  3135. tmp = x;
  3136. while (tmp > 0) {
  3137. tmp >>= 4;
  3138. ++len;
  3139. }
  3140. } else {
  3141. len = 1;
  3142. }
  3143. /* Bail if we would go past the end of the buffer */
  3144. if (len > max_len)
  3145. return 0;
  3146. /* Point to last one */
  3147. cur = buf + len - 1;
  3148. /* Convert x to hex */
  3149. do {
  3150. *cur-- = "0123456789ABCDEF"[x & 0xf];
  3151. x >>= 4;
  3152. } while (x != 0 && cur >= buf);
  3153. /* Return len */
  3154. return len;
  3155. }
  3156. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  3157. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  3158. * safe.
  3159. *
  3160. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE bytes available.
  3161. *
  3162. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  3163. * with spaces. Note that there is no trailing \0. CHILD_STATE indicates where
  3164. * in the processs of starting the child process did the failure occur (see
  3165. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  3166. * errno when the failure occurred.
  3167. *
  3168. * On success return the number of characters added to hex_errno, not counting
  3169. * the terminating NUL; return -1 on error.
  3170. */
  3171. int
  3172. format_helper_exit_status(unsigned char child_state, int saved_errno,
  3173. char *hex_errno)
  3174. {
  3175. unsigned int unsigned_errno;
  3176. int written, left;
  3177. char *cur;
  3178. size_t i;
  3179. int res = -1;
  3180. /* Fill hex_errno with spaces, and a trailing newline (memset may
  3181. not be signal handler safe, so we can't use it) */
  3182. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  3183. hex_errno[i] = ' ';
  3184. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  3185. /* Convert errno to be unsigned for hex conversion */
  3186. if (saved_errno < 0) {
  3187. unsigned_errno = (unsigned int) -saved_errno;
  3188. } else {
  3189. unsigned_errno = (unsigned int) saved_errno;
  3190. }
  3191. /*
  3192. * Count how many chars of space we have left, and keep a pointer into the
  3193. * current point in the buffer.
  3194. */
  3195. left = HEX_ERRNO_SIZE;
  3196. cur = hex_errno;
  3197. /* Emit child_state */
  3198. written = format_hex_number_for_helper_exit_status(child_state,
  3199. cur, left);
  3200. if (written <= 0)
  3201. goto err;
  3202. /* Adjust left and cur */
  3203. left -= written;
  3204. cur += written;
  3205. if (left <= 0)
  3206. goto err;
  3207. /* Now the '/' */
  3208. *cur = '/';
  3209. /* Adjust left and cur */
  3210. ++cur;
  3211. --left;
  3212. if (left <= 0)
  3213. goto err;
  3214. /* Need minus? */
  3215. if (saved_errno < 0) {
  3216. *cur = '-';
  3217. ++cur;
  3218. --left;
  3219. if (left <= 0)
  3220. goto err;
  3221. }
  3222. /* Emit unsigned_errno */
  3223. written = format_hex_number_for_helper_exit_status(unsigned_errno,
  3224. cur, left);
  3225. if (written <= 0)
  3226. goto err;
  3227. /* Adjust left and cur */
  3228. left -= written;
  3229. cur += written;
  3230. /* Check that we have enough space left for a newline */
  3231. if (left <= 0)
  3232. goto err;
  3233. /* Emit the newline and NUL */
  3234. *cur++ = '\n';
  3235. *cur++ = '\0';
  3236. res = (int)(cur - hex_errno - 1);
  3237. goto done;
  3238. err:
  3239. /*
  3240. * In error exit, just write a '\0' in the first char so whatever called
  3241. * this at least won't fall off the end.
  3242. */
  3243. *hex_errno = '\0';
  3244. done:
  3245. return res;
  3246. }
  3247. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  3248. #define DEFAULT_MAX_FD 256
  3249. /** Terminate the process of <b>process_handle</b>.
  3250. * Code borrowed from Python's os.kill. */
  3251. int
  3252. tor_terminate_process(process_handle_t *process_handle)
  3253. {
  3254. #ifdef _WIN32
  3255. if (tor_get_exit_code(process_handle, 0, NULL) == PROCESS_EXIT_RUNNING) {
  3256. HANDLE handle;
  3257. /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
  3258. attempt to open and terminate the process. */
  3259. handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE,
  3260. process_handle->pid.dwProcessId);
  3261. if (!handle)
  3262. return -1;
  3263. if (!TerminateProcess(handle, 0))
  3264. return -1;
  3265. else
  3266. return 0;
  3267. }
  3268. #else /* Unix */
  3269. return kill(process_handle->pid, SIGTERM);
  3270. #endif
  3271. return -1;
  3272. }
  3273. /** Return the Process ID of <b>process_handle</b>. */
  3274. int
  3275. tor_process_get_pid(process_handle_t *process_handle)
  3276. {
  3277. #ifdef _WIN32
  3278. return (int) process_handle->pid.dwProcessId;
  3279. #else
  3280. return (int) process_handle->pid;
  3281. #endif
  3282. }
  3283. #ifdef _WIN32
  3284. HANDLE
  3285. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  3286. {
  3287. return process_handle->stdout_pipe;
  3288. }
  3289. #else
  3290. /* DOCDOC tor_process_get_stdout_pipe */
  3291. FILE *
  3292. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  3293. {
  3294. return process_handle->stdout_handle;
  3295. }
  3296. #endif
  3297. /* DOCDOC process_handle_new */
  3298. static process_handle_t *
  3299. process_handle_new(void)
  3300. {
  3301. process_handle_t *out = tor_malloc_zero(sizeof(process_handle_t));
  3302. #ifdef _WIN32
  3303. out->stdout_pipe = INVALID_HANDLE_VALUE;
  3304. out->stderr_pipe = INVALID_HANDLE_VALUE;
  3305. #else
  3306. out->stdout_pipe = -1;
  3307. out->stderr_pipe = -1;
  3308. #endif
  3309. return out;
  3310. }
  3311. /**
  3312. * @name child-process states
  3313. *
  3314. * Each of these values represents a possible state that a child process can
  3315. * be in. They're used to determine what to say when telling the parent how
  3316. * far along we were before failure.
  3317. *
  3318. * @{
  3319. */
  3320. #define CHILD_STATE_INIT 0
  3321. #define CHILD_STATE_PIPE 1
  3322. #define CHILD_STATE_MAXFD 2
  3323. #define CHILD_STATE_FORK 3
  3324. #define CHILD_STATE_DUPOUT 4
  3325. #define CHILD_STATE_DUPERR 5
  3326. #define CHILD_STATE_REDIRECT 6
  3327. #define CHILD_STATE_CLOSEFD 7
  3328. #define CHILD_STATE_EXEC 8
  3329. #define CHILD_STATE_FAILEXEC 9
  3330. /** @} */
  3331. /** Start a program in the background. If <b>filename</b> contains a '/', then
  3332. * it will be treated as an absolute or relative path. Otherwise, on
  3333. * non-Windows systems, the system path will be searched for <b>filename</b>.
  3334. * On Windows, only the current directory will be searched. Here, to search the
  3335. * system path (as well as the application directory, current working
  3336. * directory, and system directories), set filename to NULL.
  3337. *
  3338. * The strings in <b>argv</b> will be passed as the command line arguments of
  3339. * the child program (following convention, argv[0] should normally be the
  3340. * filename of the executable, and this must be the case if <b>filename</b> is
  3341. * NULL). The last element of argv must be NULL. A handle to the child process
  3342. * will be returned in process_handle (which must be non-NULL). Read
  3343. * process_handle.status to find out if the process was successfully launched.
  3344. * For convenience, process_handle.status is returned by this function.
  3345. *
  3346. * Some parts of this code are based on the POSIX subprocess module from
  3347. * Python, and example code from
  3348. * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
  3349. */
  3350. int
  3351. tor_spawn_background(const char *const filename, const char **argv,
  3352. process_environment_t *env,
  3353. process_handle_t **process_handle_out)
  3354. {
  3355. #ifdef _WIN32
  3356. HANDLE stdout_pipe_read = NULL;
  3357. HANDLE stdout_pipe_write = NULL;
  3358. HANDLE stderr_pipe_read = NULL;
  3359. HANDLE stderr_pipe_write = NULL;
  3360. process_handle_t *process_handle;
  3361. int status;
  3362. STARTUPINFOA siStartInfo;
  3363. BOOL retval = FALSE;
  3364. SECURITY_ATTRIBUTES saAttr;
  3365. char *joined_argv;
  3366. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  3367. saAttr.bInheritHandle = TRUE;
  3368. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3369. saAttr.lpSecurityDescriptor = NULL;
  3370. /* Assume failure to start process */
  3371. status = PROCESS_STATUS_ERROR;
  3372. /* Set up pipe for stdout */
  3373. if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, &saAttr, 0)) {
  3374. log_warn(LD_GENERAL,
  3375. "Failed to create pipe for stdout communication with child process: %s",
  3376. format_win32_error(GetLastError()));
  3377. return status;
  3378. }
  3379. if (!SetHandleInformation(stdout_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3380. log_warn(LD_GENERAL,
  3381. "Failed to configure pipe for stdout communication with child "
  3382. "process: %s", format_win32_error(GetLastError()));
  3383. return status;
  3384. }
  3385. /* Set up pipe for stderr */
  3386. if (!CreatePipe(&stderr_pipe_read, &stderr_pipe_write, &saAttr, 0)) {
  3387. log_warn(LD_GENERAL,
  3388. "Failed to create pipe for stderr communication with child process: %s",
  3389. format_win32_error(GetLastError()));
  3390. return status;
  3391. }
  3392. if (!SetHandleInformation(stderr_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3393. log_warn(LD_GENERAL,
  3394. "Failed to configure pipe for stderr communication with child "
  3395. "process: %s", format_win32_error(GetLastError()));
  3396. return status;
  3397. }
  3398. /* Create the child process */
  3399. /* Windows expects argv to be a whitespace delimited string, so join argv up
  3400. */
  3401. joined_argv = tor_join_win_cmdline(argv);
  3402. process_handle = process_handle_new();
  3403. process_handle->status = status;
  3404. ZeroMemory(&(process_handle->pid), sizeof(PROCESS_INFORMATION));
  3405. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  3406. siStartInfo.cb = sizeof(STARTUPINFO);
  3407. siStartInfo.hStdError = stderr_pipe_write;
  3408. siStartInfo.hStdOutput = stdout_pipe_write;
  3409. siStartInfo.hStdInput = NULL;
  3410. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  3411. /* Create the child process */
  3412. retval = CreateProcessA(filename, // module name
  3413. joined_argv, // command line
  3414. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3415. NULL, // process security attributes
  3416. NULL, // primary thread security attributes
  3417. TRUE, // handles are inherited
  3418. /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
  3419. * work?) */
  3420. 0, // creation flags
  3421. (env==NULL) ? NULL : env->windows_environment_block,
  3422. NULL, // use parent's current directory
  3423. &siStartInfo, // STARTUPINFO pointer
  3424. &(process_handle->pid)); // receives PROCESS_INFORMATION
  3425. tor_free(joined_argv);
  3426. if (!retval) {
  3427. log_warn(LD_GENERAL,
  3428. "Failed to create child process %s: %s", filename?filename:argv[0],
  3429. format_win32_error(GetLastError()));
  3430. tor_free(process_handle);
  3431. } else {
  3432. /* TODO: Close hProcess and hThread in process_handle->pid? */
  3433. process_handle->stdout_pipe = stdout_pipe_read;
  3434. process_handle->stderr_pipe = stderr_pipe_read;
  3435. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3436. }
  3437. /* TODO: Close pipes on exit */
  3438. *process_handle_out = process_handle;
  3439. return status;
  3440. #else // _WIN32
  3441. pid_t pid;
  3442. int stdout_pipe[2];
  3443. int stderr_pipe[2];
  3444. int fd, retval;
  3445. ssize_t nbytes;
  3446. process_handle_t *process_handle;
  3447. int status;
  3448. const char *error_message = SPAWN_ERROR_MESSAGE;
  3449. size_t error_message_length;
  3450. /* Represents where in the process of spawning the program is;
  3451. this is used for printing out the error message */
  3452. unsigned char child_state = CHILD_STATE_INIT;
  3453. char hex_errno[HEX_ERRNO_SIZE];
  3454. static int max_fd = -1;
  3455. status = PROCESS_STATUS_ERROR;
  3456. /* We do the strlen here because strlen() is not signal handler safe,
  3457. and we are not allowed to use unsafe functions between fork and exec */
  3458. error_message_length = strlen(error_message);
  3459. child_state = CHILD_STATE_PIPE;
  3460. /* Set up pipe for redirecting stdout and stderr of child */
  3461. retval = pipe(stdout_pipe);
  3462. if (-1 == retval) {
  3463. log_warn(LD_GENERAL,
  3464. "Failed to set up pipe for stdout communication with child process: %s",
  3465. strerror(errno));
  3466. return status;
  3467. }
  3468. retval = pipe(stderr_pipe);
  3469. if (-1 == retval) {
  3470. log_warn(LD_GENERAL,
  3471. "Failed to set up pipe for stderr communication with child process: %s",
  3472. strerror(errno));
  3473. close(stdout_pipe[0]);
  3474. close(stdout_pipe[1]);
  3475. return status;
  3476. }
  3477. child_state = CHILD_STATE_MAXFD;
  3478. #ifdef _SC_OPEN_MAX
  3479. if (-1 != max_fd) {
  3480. max_fd = (int) sysconf(_SC_OPEN_MAX);
  3481. if (max_fd == -1)
  3482. max_fd = DEFAULT_MAX_FD;
  3483. log_warn(LD_GENERAL,
  3484. "Cannot find maximum file descriptor, assuming %d", max_fd);
  3485. }
  3486. #else
  3487. max_fd = DEFAULT_MAX_FD;
  3488. #endif
  3489. child_state = CHILD_STATE_FORK;
  3490. pid = fork();
  3491. if (0 == pid) {
  3492. /* In child */
  3493. child_state = CHILD_STATE_DUPOUT;
  3494. /* Link child stdout to the write end of the pipe */
  3495. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  3496. if (-1 == retval)
  3497. goto error;
  3498. child_state = CHILD_STATE_DUPERR;
  3499. /* Link child stderr to the write end of the pipe */
  3500. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  3501. if (-1 == retval)
  3502. goto error;
  3503. child_state = CHILD_STATE_REDIRECT;
  3504. /* Link stdin to /dev/null */
  3505. fd = open("/dev/null", O_RDONLY); /* NOT cloexec, obviously. */
  3506. if (fd != -1)
  3507. dup2(fd, STDIN_FILENO);
  3508. else
  3509. goto error;
  3510. child_state = CHILD_STATE_CLOSEFD;
  3511. close(stderr_pipe[0]);
  3512. close(stderr_pipe[1]);
  3513. close(stdout_pipe[0]);
  3514. close(stdout_pipe[1]);
  3515. close(fd);
  3516. /* Close all other fds, including the read end of the pipe */
  3517. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  3518. * this needless. */
  3519. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  3520. close(fd);
  3521. }
  3522. child_state = CHILD_STATE_EXEC;
  3523. /* Call the requested program. We need the cast because
  3524. execvp doesn't define argv as const, even though it
  3525. does not modify the arguments */
  3526. if (env)
  3527. execve(filename, (char *const *) argv, env->unixoid_environment_block);
  3528. else
  3529. execvp(filename, (char *const *) argv);
  3530. /* If we got here, the exec or open(/dev/null) failed */
  3531. child_state = CHILD_STATE_FAILEXEC;
  3532. error:
  3533. {
  3534. /* XXX: are we leaking fds from the pipe? */
  3535. int n;
  3536. n = format_helper_exit_status(child_state, errno, hex_errno);
  3537. if (n >= 0) {
  3538. /* Write the error message. GCC requires that we check the return
  3539. value, but there is nothing we can do if it fails */
  3540. /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
  3541. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  3542. nbytes = write(STDOUT_FILENO, hex_errno, n);
  3543. }
  3544. }
  3545. (void) nbytes;
  3546. _exit(255);
  3547. /* Never reached, but avoids compiler warning */
  3548. return status;
  3549. }
  3550. /* In parent */
  3551. if (-1 == pid) {
  3552. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  3553. close(stdout_pipe[0]);
  3554. close(stdout_pipe[1]);
  3555. close(stderr_pipe[0]);
  3556. close(stderr_pipe[1]);
  3557. return status;
  3558. }
  3559. process_handle = process_handle_new();
  3560. process_handle->status = status;
  3561. process_handle->pid = pid;
  3562. /* TODO: If the child process forked but failed to exec, waitpid it */
  3563. /* Return read end of the pipes to caller, and close write end */
  3564. process_handle->stdout_pipe = stdout_pipe[0];
  3565. retval = close(stdout_pipe[1]);
  3566. if (-1 == retval) {
  3567. log_warn(LD_GENERAL,
  3568. "Failed to close write end of stdout pipe in parent process: %s",
  3569. strerror(errno));
  3570. }
  3571. process_handle->stderr_pipe = stderr_pipe[0];
  3572. retval = close(stderr_pipe[1]);
  3573. if (-1 == retval) {
  3574. log_warn(LD_GENERAL,
  3575. "Failed to close write end of stderr pipe in parent process: %s",
  3576. strerror(errno));
  3577. }
  3578. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3579. /* Set stdout/stderr pipes to be non-blocking */
  3580. fcntl(process_handle->stdout_pipe, F_SETFL, O_NONBLOCK);
  3581. fcntl(process_handle->stderr_pipe, F_SETFL, O_NONBLOCK);
  3582. /* Open the buffered IO streams */
  3583. process_handle->stdout_handle = fdopen(process_handle->stdout_pipe, "r");
  3584. process_handle->stderr_handle = fdopen(process_handle->stderr_pipe, "r");
  3585. *process_handle_out = process_handle;
  3586. return process_handle->status;
  3587. #endif // _WIN32
  3588. }
  3589. /** Destroy all resources allocated by the process handle in
  3590. * <b>process_handle</b>.
  3591. * If <b>also_terminate_process</b> is true, also terminate the
  3592. * process of the process handle. */
  3593. void
  3594. tor_process_handle_destroy(process_handle_t *process_handle,
  3595. int also_terminate_process)
  3596. {
  3597. if (!process_handle)
  3598. return;
  3599. if (also_terminate_process) {
  3600. if (tor_terminate_process(process_handle) < 0) {
  3601. const char *errstr =
  3602. #ifdef _WIN32
  3603. format_win32_error(GetLastError());
  3604. #else
  3605. strerror(errno);
  3606. #endif
  3607. log_notice(LD_GENERAL, "Failed to terminate process with "
  3608. "PID '%d' ('%s').", tor_process_get_pid(process_handle),
  3609. errstr);
  3610. } else {
  3611. log_info(LD_GENERAL, "Terminated process with PID '%d'.",
  3612. tor_process_get_pid(process_handle));
  3613. }
  3614. }
  3615. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  3616. #ifdef _WIN32
  3617. if (process_handle->stdout_pipe)
  3618. CloseHandle(process_handle->stdout_pipe);
  3619. if (process_handle->stderr_pipe)
  3620. CloseHandle(process_handle->stderr_pipe);
  3621. #else
  3622. if (process_handle->stdout_handle)
  3623. fclose(process_handle->stdout_handle);
  3624. if (process_handle->stderr_handle)
  3625. fclose(process_handle->stderr_handle);
  3626. #endif
  3627. memset(process_handle, 0x0f, sizeof(process_handle_t));
  3628. tor_free(process_handle);
  3629. }
  3630. /** Get the exit code of a process specified by <b>process_handle</b> and store
  3631. * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
  3632. * to true, the call will block until the process has exited. Otherwise if
  3633. * the process is still running, the function will return
  3634. * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
  3635. * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
  3636. * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
  3637. * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
  3638. * probably not work in Tor, because waitpid() is called in main.c to reap any
  3639. * terminated child processes.*/
  3640. int
  3641. tor_get_exit_code(const process_handle_t *process_handle,
  3642. int block, int *exit_code)
  3643. {
  3644. #ifdef _WIN32
  3645. DWORD retval;
  3646. BOOL success;
  3647. if (block) {
  3648. /* Wait for the process to exit */
  3649. retval = WaitForSingleObject(process_handle->pid.hProcess, INFINITE);
  3650. if (retval != WAIT_OBJECT_0) {
  3651. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3652. (int)retval, format_win32_error(GetLastError()));
  3653. return PROCESS_EXIT_ERROR;
  3654. }
  3655. } else {
  3656. retval = WaitForSingleObject(process_handle->pid.hProcess, 0);
  3657. if (WAIT_TIMEOUT == retval) {
  3658. /* Process has not exited */
  3659. return PROCESS_EXIT_RUNNING;
  3660. } else if (retval != WAIT_OBJECT_0) {
  3661. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3662. (int)retval, format_win32_error(GetLastError()));
  3663. return PROCESS_EXIT_ERROR;
  3664. }
  3665. }
  3666. if (exit_code != NULL) {
  3667. success = GetExitCodeProcess(process_handle->pid.hProcess,
  3668. (PDWORD)exit_code);
  3669. if (!success) {
  3670. log_warn(LD_GENERAL, "GetExitCodeProcess() failed: %s",
  3671. format_win32_error(GetLastError()));
  3672. return PROCESS_EXIT_ERROR;
  3673. }
  3674. }
  3675. #else
  3676. int stat_loc;
  3677. int retval;
  3678. retval = waitpid(process_handle->pid, &stat_loc, block?0:WNOHANG);
  3679. if (!block && 0 == retval) {
  3680. /* Process has not exited */
  3681. return PROCESS_EXIT_RUNNING;
  3682. } else if (retval != process_handle->pid) {
  3683. log_warn(LD_GENERAL, "waitpid() failed for PID %d: %s",
  3684. process_handle->pid, strerror(errno));
  3685. return PROCESS_EXIT_ERROR;
  3686. }
  3687. if (!WIFEXITED(stat_loc)) {
  3688. log_warn(LD_GENERAL, "Process %d did not exit normally",
  3689. process_handle->pid);
  3690. return PROCESS_EXIT_ERROR;
  3691. }
  3692. if (exit_code != NULL)
  3693. *exit_code = WEXITSTATUS(stat_loc);
  3694. #endif // _WIN32
  3695. return PROCESS_EXIT_EXITED;
  3696. }
  3697. /** Helper: return the number of characters in <b>s</b> preceding the first
  3698. * occurrence of <b>ch</b>. If <b>ch</b> does not occur in <b>s</b>, return
  3699. * the length of <b>s</b>. Should be equivalent to strspn(s, "ch"). */
  3700. static INLINE size_t
  3701. str_num_before(const char *s, char ch)
  3702. {
  3703. const char *cp = strchr(s, ch);
  3704. if (cp)
  3705. return cp - s;
  3706. else
  3707. return strlen(s);
  3708. }
  3709. /** Return non-zero iff getenv would consider <b>s1</b> and <b>s2</b>
  3710. * to have the same name as strings in a process's environment. */
  3711. int
  3712. environment_variable_names_equal(const char *s1, const char *s2)
  3713. {
  3714. size_t s1_name_len = str_num_before(s1, '=');
  3715. size_t s2_name_len = str_num_before(s2, '=');
  3716. return (s1_name_len == s2_name_len &&
  3717. tor_memeq(s1, s2, s1_name_len));
  3718. }
  3719. /** Free <b>env</b> (assuming it was produced by
  3720. * process_environment_make). */
  3721. void
  3722. process_environment_free(process_environment_t *env)
  3723. {
  3724. if (env == NULL) return;
  3725. /* As both an optimization hack to reduce consing on Unixoid systems
  3726. * and a nice way to ensure that some otherwise-Windows-specific
  3727. * code will always get tested before changes to it get merged, the
  3728. * strings which env->unixoid_environment_block points to are packed
  3729. * into env->windows_environment_block. */
  3730. tor_free(env->unixoid_environment_block);
  3731. tor_free(env->windows_environment_block);
  3732. tor_free(env);
  3733. }
  3734. /** Make a process_environment_t containing the environment variables
  3735. * specified in <b>env_vars</b> (as C strings of the form
  3736. * "NAME=VALUE"). */
  3737. process_environment_t *
  3738. process_environment_make(struct smartlist_t *env_vars)
  3739. {
  3740. process_environment_t *env = tor_malloc_zero(sizeof(process_environment_t));
  3741. size_t n_env_vars = smartlist_len(env_vars);
  3742. size_t i;
  3743. size_t total_env_length;
  3744. smartlist_t *env_vars_sorted;
  3745. tor_assert(n_env_vars + 1 != 0);
  3746. env->unixoid_environment_block = tor_calloc(n_env_vars + 1, sizeof(char *));
  3747. /* env->unixoid_environment_block is already NULL-terminated,
  3748. * because we assume that NULL == 0 (and check that during compilation). */
  3749. total_env_length = 1; /* terminating NUL of terminating empty string */
  3750. for (i = 0; i < n_env_vars; ++i) {
  3751. const char *s = smartlist_get(env_vars, i);
  3752. size_t slen = strlen(s);
  3753. tor_assert(slen + 1 != 0);
  3754. tor_assert(slen + 1 < SIZE_MAX - total_env_length);
  3755. total_env_length += slen + 1;
  3756. }
  3757. env->windows_environment_block = tor_malloc_zero(total_env_length);
  3758. /* env->windows_environment_block is already
  3759. * (NUL-terminated-empty-string)-terminated. */
  3760. /* Some versions of Windows supposedly require that environment
  3761. * blocks be sorted. Or maybe some Windows programs (or their
  3762. * runtime libraries) fail to look up strings in non-sorted
  3763. * environment blocks.
  3764. *
  3765. * Also, sorting strings makes it easy to find duplicate environment
  3766. * variables and environment-variable strings without an '=' on all
  3767. * OSes, and they can cause badness. Let's complain about those. */
  3768. env_vars_sorted = smartlist_new();
  3769. smartlist_add_all(env_vars_sorted, env_vars);
  3770. smartlist_sort_strings(env_vars_sorted);
  3771. /* Now copy the strings into the environment blocks. */
  3772. {
  3773. char *cp = env->windows_environment_block;
  3774. const char *prev_env_var = NULL;
  3775. for (i = 0; i < n_env_vars; ++i) {
  3776. const char *s = smartlist_get(env_vars_sorted, i);
  3777. size_t slen = strlen(s);
  3778. size_t s_name_len = str_num_before(s, '=');
  3779. if (s_name_len == slen) {
  3780. log_warn(LD_GENERAL,
  3781. "Preparing an environment containing a variable "
  3782. "without a value: %s",
  3783. s);
  3784. }
  3785. if (prev_env_var != NULL &&
  3786. environment_variable_names_equal(s, prev_env_var)) {
  3787. log_warn(LD_GENERAL,
  3788. "Preparing an environment containing two variables "
  3789. "with the same name: %s and %s",
  3790. prev_env_var, s);
  3791. }
  3792. prev_env_var = s;
  3793. /* Actually copy the string into the environment. */
  3794. memcpy(cp, s, slen+1);
  3795. env->unixoid_environment_block[i] = cp;
  3796. cp += slen+1;
  3797. }
  3798. tor_assert(cp == env->windows_environment_block + total_env_length - 1);
  3799. }
  3800. smartlist_free(env_vars_sorted);
  3801. return env;
  3802. }
  3803. /** Return a newly allocated smartlist containing every variable in
  3804. * this process's environment, as a NUL-terminated string of the form
  3805. * "NAME=VALUE". Note that on some/many/most/all OSes, the parent
  3806. * process can put strings not of that form in our environment;
  3807. * callers should try to not get crashed by that.
  3808. *
  3809. * The returned strings are heap-allocated, and must be freed by the
  3810. * caller. */
  3811. struct smartlist_t *
  3812. get_current_process_environment_variables(void)
  3813. {
  3814. smartlist_t *sl = smartlist_new();
  3815. char **environ_tmp; /* Not const char ** ? Really? */
  3816. for (environ_tmp = get_environment(); *environ_tmp; ++environ_tmp) {
  3817. smartlist_add(sl, tor_strdup(*environ_tmp));
  3818. }
  3819. return sl;
  3820. }
  3821. /** For each string s in <b>env_vars</b> such that
  3822. * environment_variable_names_equal(s, <b>new_var</b>), remove it; if
  3823. * <b>free_p</b> is non-zero, call <b>free_old</b>(s). If
  3824. * <b>new_var</b> contains '=', insert it into <b>env_vars</b>. */
  3825. void
  3826. set_environment_variable_in_smartlist(struct smartlist_t *env_vars,
  3827. const char *new_var,
  3828. void (*free_old)(void*),
  3829. int free_p)
  3830. {
  3831. SMARTLIST_FOREACH_BEGIN(env_vars, const char *, s) {
  3832. if (environment_variable_names_equal(s, new_var)) {
  3833. SMARTLIST_DEL_CURRENT(env_vars, s);
  3834. if (free_p) {
  3835. free_old((void *)s);
  3836. }
  3837. }
  3838. } SMARTLIST_FOREACH_END(s);
  3839. if (strchr(new_var, '=') != NULL) {
  3840. smartlist_add(env_vars, (void *)new_var);
  3841. }
  3842. }
  3843. #ifdef _WIN32
  3844. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3845. * <b>hProcess</b> is NULL, the function will return immediately if there is
  3846. * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
  3847. * to the process owning the <b>h</b>. In this case, the function will exit
  3848. * only once the process has exited, or <b>count</b> bytes are read. Returns
  3849. * the number of bytes read, or -1 on error. */
  3850. ssize_t
  3851. tor_read_all_handle(HANDLE h, char *buf, size_t count,
  3852. const process_handle_t *process)
  3853. {
  3854. size_t numread = 0;
  3855. BOOL retval;
  3856. DWORD byte_count;
  3857. BOOL process_exited = FALSE;
  3858. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  3859. return -1;
  3860. while (numread != count) {
  3861. /* Check if there is anything to read */
  3862. retval = PeekNamedPipe(h, NULL, 0, NULL, &byte_count, NULL);
  3863. if (!retval) {
  3864. log_warn(LD_GENERAL,
  3865. "Failed to peek from handle: %s",
  3866. format_win32_error(GetLastError()));
  3867. return -1;
  3868. } else if (0 == byte_count) {
  3869. /* Nothing available: process exited or it is busy */
  3870. /* Exit if we don't know whether the process is running */
  3871. if (NULL == process)
  3872. break;
  3873. /* The process exited and there's nothing left to read from it */
  3874. if (process_exited)
  3875. break;
  3876. /* If process is not running, check for output one more time in case
  3877. it wrote something after the peek was performed. Otherwise keep on
  3878. waiting for output */
  3879. tor_assert(process != NULL);
  3880. byte_count = WaitForSingleObject(process->pid.hProcess, 0);
  3881. if (WAIT_TIMEOUT != byte_count)
  3882. process_exited = TRUE;
  3883. continue;
  3884. }
  3885. /* There is data to read; read it */
  3886. retval = ReadFile(h, buf+numread, count-numread, &byte_count, NULL);
  3887. tor_assert(byte_count + numread <= count);
  3888. if (!retval) {
  3889. log_warn(LD_GENERAL, "Failed to read from handle: %s",
  3890. format_win32_error(GetLastError()));
  3891. return -1;
  3892. } else if (0 == byte_count) {
  3893. /* End of file */
  3894. break;
  3895. }
  3896. numread += byte_count;
  3897. }
  3898. return (ssize_t)numread;
  3899. }
  3900. #else
  3901. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3902. * <b>process</b> is NULL, the function will return immediately if there is
  3903. * nothing more to read. Otherwise data will be read until end of file, or
  3904. * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
  3905. * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
  3906. * file has been reached. */
  3907. ssize_t
  3908. tor_read_all_handle(FILE *h, char *buf, size_t count,
  3909. const process_handle_t *process,
  3910. int *eof)
  3911. {
  3912. size_t numread = 0;
  3913. char *retval;
  3914. if (eof)
  3915. *eof = 0;
  3916. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  3917. return -1;
  3918. while (numread != count) {
  3919. /* Use fgets because that is what we use in log_from_pipe() */
  3920. retval = fgets(buf+numread, (int)(count-numread), h);
  3921. if (NULL == retval) {
  3922. if (feof(h)) {
  3923. log_debug(LD_GENERAL, "fgets() reached end of file");
  3924. if (eof)
  3925. *eof = 1;
  3926. break;
  3927. } else {
  3928. if (EAGAIN == errno) {
  3929. if (process)
  3930. continue;
  3931. else
  3932. break;
  3933. } else {
  3934. log_warn(LD_GENERAL, "fgets() from handle failed: %s",
  3935. strerror(errno));
  3936. return -1;
  3937. }
  3938. }
  3939. }
  3940. tor_assert(retval != NULL);
  3941. tor_assert(strlen(retval) + numread <= count);
  3942. numread += strlen(retval);
  3943. }
  3944. log_debug(LD_GENERAL, "fgets() read %d bytes from handle", (int)numread);
  3945. return (ssize_t)numread;
  3946. }
  3947. #endif
  3948. /** Read from stdout of a process until the process exits. */
  3949. ssize_t
  3950. tor_read_all_from_process_stdout(const process_handle_t *process_handle,
  3951. char *buf, size_t count)
  3952. {
  3953. #ifdef _WIN32
  3954. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  3955. process_handle);
  3956. #else
  3957. return tor_read_all_handle(process_handle->stdout_handle, buf, count,
  3958. process_handle, NULL);
  3959. #endif
  3960. }
  3961. /** Read from stdout of a process until the process exits. */
  3962. ssize_t
  3963. tor_read_all_from_process_stderr(const process_handle_t *process_handle,
  3964. char *buf, size_t count)
  3965. {
  3966. #ifdef _WIN32
  3967. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  3968. process_handle);
  3969. #else
  3970. return tor_read_all_handle(process_handle->stderr_handle, buf, count,
  3971. process_handle, NULL);
  3972. #endif
  3973. }
  3974. /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
  3975. * modified. The resulting smartlist will consist of pointers to buf, so there
  3976. * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
  3977. * string. <b>len</b> should be set to the length of the buffer excluding the
  3978. * NUL. Non-printable characters (including NUL) will be replaced with "." */
  3979. int
  3980. tor_split_lines(smartlist_t *sl, char *buf, int len)
  3981. {
  3982. /* Index in buf of the start of the current line */
  3983. int start = 0;
  3984. /* Index in buf of the current character being processed */
  3985. int cur = 0;
  3986. /* Are we currently in a line */
  3987. char in_line = 0;
  3988. /* Loop over string */
  3989. while (cur < len) {
  3990. /* Loop until end of line or end of string */
  3991. for (; cur < len; cur++) {
  3992. if (in_line) {
  3993. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  3994. /* End of line */
  3995. buf[cur] = '\0';
  3996. /* Point cur to the next line */
  3997. cur++;
  3998. /* Line starts at start and ends with a nul */
  3999. break;
  4000. } else {
  4001. if (!TOR_ISPRINT(buf[cur]))
  4002. buf[cur] = '.';
  4003. }
  4004. } else {
  4005. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  4006. /* Skip leading vertical space */
  4007. ;
  4008. } else {
  4009. in_line = 1;
  4010. start = cur;
  4011. if (!TOR_ISPRINT(buf[cur]))
  4012. buf[cur] = '.';
  4013. }
  4014. }
  4015. }
  4016. /* We are at the end of the line or end of string. If in_line is true there
  4017. * is a line which starts at buf+start and ends at a NUL. cur points to
  4018. * the character after the NUL. */
  4019. if (in_line)
  4020. smartlist_add(sl, (void *)(buf+start));
  4021. in_line = 0;
  4022. }
  4023. return smartlist_len(sl);
  4024. }
  4025. /** Return a string corresponding to <b>stream_status</b>. */
  4026. const char *
  4027. stream_status_to_string(enum stream_status stream_status)
  4028. {
  4029. switch (stream_status) {
  4030. case IO_STREAM_OKAY:
  4031. return "okay";
  4032. case IO_STREAM_EAGAIN:
  4033. return "temporarily unavailable";
  4034. case IO_STREAM_TERM:
  4035. return "terminated";
  4036. case IO_STREAM_CLOSED:
  4037. return "closed";
  4038. default:
  4039. tor_fragile_assert();
  4040. return "unknown";
  4041. }
  4042. }
  4043. #ifdef _WIN32
  4044. /** Return a smartlist containing lines outputted from
  4045. * <b>handle</b>. Return NULL on error, and set
  4046. * <b>stream_status_out</b> appropriately. */
  4047. smartlist_t *
  4048. tor_get_lines_from_handle(HANDLE *handle,
  4049. enum stream_status *stream_status_out)
  4050. {
  4051. int pos;
  4052. char stdout_buf[600] = {0};
  4053. smartlist_t *lines = NULL;
  4054. tor_assert(stream_status_out);
  4055. *stream_status_out = IO_STREAM_TERM;
  4056. pos = tor_read_all_handle(handle, stdout_buf, sizeof(stdout_buf) - 1, NULL);
  4057. if (pos < 0) {
  4058. *stream_status_out = IO_STREAM_TERM;
  4059. return NULL;
  4060. }
  4061. if (pos == 0) {
  4062. *stream_status_out = IO_STREAM_EAGAIN;
  4063. return NULL;
  4064. }
  4065. /* End with a null even if there isn't a \r\n at the end */
  4066. /* TODO: What if this is a partial line? */
  4067. stdout_buf[pos] = '\0';
  4068. /* Split up the buffer */
  4069. lines = smartlist_new();
  4070. tor_split_lines(lines, stdout_buf, pos);
  4071. /* Currently 'lines' is populated with strings residing on the
  4072. stack. Replace them with their exact copies on the heap: */
  4073. SMARTLIST_FOREACH(lines, char *, line,
  4074. SMARTLIST_REPLACE_CURRENT(lines, line, tor_strdup(line)));
  4075. *stream_status_out = IO_STREAM_OKAY;
  4076. return lines;
  4077. }
  4078. /** Read from stream, and send lines to log at the specified log level.
  4079. * Returns -1 if there is a error reading, and 0 otherwise.
  4080. * If the generated stream is flushed more often than on new lines, or
  4081. * a read exceeds 256 bytes, lines will be truncated. This should be fixed,
  4082. * along with the corresponding problem on *nix (see bug #2045).
  4083. */
  4084. static int
  4085. log_from_handle(HANDLE *pipe, int severity)
  4086. {
  4087. char buf[256];
  4088. int pos;
  4089. smartlist_t *lines;
  4090. pos = tor_read_all_handle(pipe, buf, sizeof(buf) - 1, NULL);
  4091. if (pos < 0) {
  4092. /* Error */
  4093. log_warn(LD_GENERAL, "Failed to read data from subprocess");
  4094. return -1;
  4095. }
  4096. if (0 == pos) {
  4097. /* There's nothing to read (process is busy or has exited) */
  4098. log_debug(LD_GENERAL, "Subprocess had nothing to say");
  4099. return 0;
  4100. }
  4101. /* End with a null even if there isn't a \r\n at the end */
  4102. /* TODO: What if this is a partial line? */
  4103. buf[pos] = '\0';
  4104. log_debug(LD_GENERAL, "Subprocess had %d bytes to say", pos);
  4105. /* Split up the buffer */
  4106. lines = smartlist_new();
  4107. tor_split_lines(lines, buf, pos);
  4108. /* Log each line */
  4109. SMARTLIST_FOREACH(lines, char *, line,
  4110. {
  4111. log_fn(severity, LD_GENERAL, "Port forwarding helper says: %s", line);
  4112. });
  4113. smartlist_free(lines);
  4114. return 0;
  4115. }
  4116. #else
  4117. /** Return a smartlist containing lines outputted from
  4118. * <b>handle</b>. Return NULL on error, and set
  4119. * <b>stream_status_out</b> appropriately. */
  4120. smartlist_t *
  4121. tor_get_lines_from_handle(FILE *handle, enum stream_status *stream_status_out)
  4122. {
  4123. enum stream_status stream_status;
  4124. char stdout_buf[400];
  4125. smartlist_t *lines = NULL;
  4126. while (1) {
  4127. memset(stdout_buf, 0, sizeof(stdout_buf));
  4128. stream_status = get_string_from_pipe(handle,
  4129. stdout_buf, sizeof(stdout_buf) - 1);
  4130. if (stream_status != IO_STREAM_OKAY)
  4131. goto done;
  4132. if (!lines) lines = smartlist_new();
  4133. smartlist_add(lines, tor_strdup(stdout_buf));
  4134. }
  4135. done:
  4136. *stream_status_out = stream_status;
  4137. return lines;
  4138. }
  4139. /** Read from stream, and send lines to log at the specified log level.
  4140. * Returns 1 if stream is closed normally, -1 if there is a error reading, and
  4141. * 0 otherwise. Handles lines from tor-fw-helper and
  4142. * tor_spawn_background() specially.
  4143. */
  4144. static int
  4145. log_from_pipe(FILE *stream, int severity, const char *executable,
  4146. int *child_status)
  4147. {
  4148. char buf[256];
  4149. enum stream_status r;
  4150. for (;;) {
  4151. r = get_string_from_pipe(stream, buf, sizeof(buf) - 1);
  4152. if (r == IO_STREAM_CLOSED) {
  4153. return 1;
  4154. } else if (r == IO_STREAM_EAGAIN) {
  4155. return 0;
  4156. } else if (r == IO_STREAM_TERM) {
  4157. return -1;
  4158. }
  4159. tor_assert(r == IO_STREAM_OKAY);
  4160. /* Check if buf starts with SPAWN_ERROR_MESSAGE */
  4161. if (strcmpstart(buf, SPAWN_ERROR_MESSAGE) == 0) {
  4162. /* Parse error message */
  4163. int retval, child_state, saved_errno;
  4164. retval = tor_sscanf(buf, SPAWN_ERROR_MESSAGE "%x/%x",
  4165. &child_state, &saved_errno);
  4166. if (retval == 2) {
  4167. log_warn(LD_GENERAL,
  4168. "Failed to start child process \"%s\" in state %d: %s",
  4169. executable, child_state, strerror(saved_errno));
  4170. if (child_status)
  4171. *child_status = 1;
  4172. } else {
  4173. /* Failed to parse message from child process, log it as a
  4174. warning */
  4175. log_warn(LD_GENERAL,
  4176. "Unexpected message from port forwarding helper \"%s\": %s",
  4177. executable, buf);
  4178. }
  4179. } else {
  4180. log_fn(severity, LD_GENERAL, "Port forwarding helper says: %s", buf);
  4181. }
  4182. }
  4183. /* We should never get here */
  4184. return -1;
  4185. }
  4186. #endif
  4187. /** Reads from <b>stream</b> and stores input in <b>buf_out</b> making
  4188. * sure it's below <b>count</b> bytes.
  4189. * If the string has a trailing newline, we strip it off.
  4190. *
  4191. * This function is specifically created to handle input from managed
  4192. * proxies, according to the pluggable transports spec. Make sure it
  4193. * fits your needs before using it.
  4194. *
  4195. * Returns:
  4196. * IO_STREAM_CLOSED: If the stream is closed.
  4197. * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
  4198. * later.
  4199. * IO_STREAM_TERM: If something is wrong with the stream.
  4200. * IO_STREAM_OKAY: If everything went okay and we got a string
  4201. * in <b>buf_out</b>. */
  4202. enum stream_status
  4203. get_string_from_pipe(FILE *stream, char *buf_out, size_t count)
  4204. {
  4205. char *retval;
  4206. size_t len;
  4207. tor_assert(count <= INT_MAX);
  4208. retval = fgets(buf_out, (int)count, stream);
  4209. if (!retval) {
  4210. if (feof(stream)) {
  4211. /* Program has closed stream (probably it exited) */
  4212. /* TODO: check error */
  4213. return IO_STREAM_CLOSED;
  4214. } else {
  4215. if (EAGAIN == errno) {
  4216. /* Nothing more to read, try again next time */
  4217. return IO_STREAM_EAGAIN;
  4218. } else {
  4219. /* There was a problem, abandon this child process */
  4220. return IO_STREAM_TERM;
  4221. }
  4222. }
  4223. } else {
  4224. len = strlen(buf_out);
  4225. if (len == 0) {
  4226. /* this probably means we got a NUL at the start of the string. */
  4227. return IO_STREAM_EAGAIN;
  4228. }
  4229. if (buf_out[len - 1] == '\n') {
  4230. /* Remove the trailing newline */
  4231. buf_out[len - 1] = '\0';
  4232. } else {
  4233. /* No newline; check whether we overflowed the buffer */
  4234. if (!feof(stream))
  4235. log_info(LD_GENERAL,
  4236. "Line from stream was truncated: %s", buf_out);
  4237. /* TODO: What to do with this error? */
  4238. }
  4239. return IO_STREAM_OKAY;
  4240. }
  4241. /* We should never get here */
  4242. return IO_STREAM_TERM;
  4243. }
  4244. /** Parse a <b>line</b> from tor-fw-helper and issue an appropriate
  4245. * log message to our user. */
  4246. static void
  4247. handle_fw_helper_line(const char *line)
  4248. {
  4249. smartlist_t *tokens = smartlist_new();
  4250. char *message = NULL;
  4251. char *message_for_log = NULL;
  4252. const char *external_port = NULL;
  4253. const char *internal_port = NULL;
  4254. const char *result = NULL;
  4255. int port = 0;
  4256. int success = 0;
  4257. smartlist_split_string(tokens, line, NULL,
  4258. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4259. if (smartlist_len(tokens) < 5)
  4260. goto err;
  4261. if (strcmp(smartlist_get(tokens, 0), "tor-fw-helper") ||
  4262. strcmp(smartlist_get(tokens, 1), "tcp-forward"))
  4263. goto err;
  4264. external_port = smartlist_get(tokens, 2);
  4265. internal_port = smartlist_get(tokens, 3);
  4266. result = smartlist_get(tokens, 4);
  4267. if (smartlist_len(tokens) > 5) {
  4268. /* If there are more than 5 tokens, they are part of [<message>].
  4269. Let's use a second smartlist to form the whole message;
  4270. strncat loops suck. */
  4271. int i;
  4272. int message_words_n = smartlist_len(tokens) - 5;
  4273. smartlist_t *message_sl = smartlist_new();
  4274. for (i = 0; i < message_words_n; i++)
  4275. smartlist_add(message_sl, smartlist_get(tokens, 5+i));
  4276. tor_assert(smartlist_len(message_sl) > 0);
  4277. message = smartlist_join_strings(message_sl, " ", 0, NULL);
  4278. /* wrap the message in log-friendly wrapping */
  4279. tor_asprintf(&message_for_log, " ('%s')", message);
  4280. smartlist_free(message_sl);
  4281. }
  4282. port = atoi(external_port);
  4283. if (port < 1 || port > 65535)
  4284. goto err;
  4285. port = atoi(internal_port);
  4286. if (port < 1 || port > 65535)
  4287. goto err;
  4288. if (!strcmp(result, "SUCCESS"))
  4289. success = 1;
  4290. else if (!strcmp(result, "FAIL"))
  4291. success = 0;
  4292. else
  4293. goto err;
  4294. if (!success) {
  4295. log_warn(LD_GENERAL, "Tor was unable to forward TCP port '%s' to '%s'%s. "
  4296. "Please make sure that your router supports port "
  4297. "forwarding protocols (like NAT-PMP). Note that if '%s' is "
  4298. "your ORPort, your relay will be unable to receive inbound "
  4299. "traffic.", external_port, internal_port,
  4300. message_for_log ? message_for_log : "",
  4301. internal_port);
  4302. } else {
  4303. log_info(LD_GENERAL,
  4304. "Tor successfully forwarded TCP port '%s' to '%s'%s.",
  4305. external_port, internal_port,
  4306. message_for_log ? message_for_log : "");
  4307. }
  4308. goto done;
  4309. err:
  4310. log_warn(LD_GENERAL, "tor-fw-helper sent us a string we could not "
  4311. "parse (%s).", line);
  4312. done:
  4313. SMARTLIST_FOREACH(tokens, char *, cp, tor_free(cp));
  4314. smartlist_free(tokens);
  4315. tor_free(message);
  4316. tor_free(message_for_log);
  4317. }
  4318. /** Read what tor-fw-helper has to say in its stdout and handle it
  4319. * appropriately */
  4320. static int
  4321. handle_fw_helper_output(process_handle_t *process_handle)
  4322. {
  4323. smartlist_t *fw_helper_output = NULL;
  4324. enum stream_status stream_status = 0;
  4325. fw_helper_output =
  4326. tor_get_lines_from_handle(tor_process_get_stdout_pipe(process_handle),
  4327. &stream_status);
  4328. if (!fw_helper_output) { /* didn't get any output from tor-fw-helper */
  4329. /* if EAGAIN we should retry in the future */
  4330. return (stream_status == IO_STREAM_EAGAIN) ? 0 : -1;
  4331. }
  4332. /* Handle the lines we got: */
  4333. SMARTLIST_FOREACH_BEGIN(fw_helper_output, char *, line) {
  4334. handle_fw_helper_line(line);
  4335. tor_free(line);
  4336. } SMARTLIST_FOREACH_END(line);
  4337. smartlist_free(fw_helper_output);
  4338. return 0;
  4339. }
  4340. /** Spawn tor-fw-helper and ask it to forward the ports in
  4341. * <b>ports_to_forward</b>. <b>ports_to_forward</b> contains strings
  4342. * of the form "<external port>:<internal port>", which is the format
  4343. * that tor-fw-helper expects. */
  4344. void
  4345. tor_check_port_forwarding(const char *filename,
  4346. smartlist_t *ports_to_forward,
  4347. time_t now)
  4348. {
  4349. /* When fw-helper succeeds, how long do we wait until running it again */
  4350. #define TIME_TO_EXEC_FWHELPER_SUCCESS 300
  4351. /* When fw-helper failed to start, how long do we wait until running it again
  4352. */
  4353. #define TIME_TO_EXEC_FWHELPER_FAIL 60
  4354. /* Static variables are initialized to zero, so child_handle.status=0
  4355. * which corresponds to it not running on startup */
  4356. static process_handle_t *child_handle=NULL;
  4357. static time_t time_to_run_helper = 0;
  4358. int stderr_status, retval;
  4359. int stdout_status = 0;
  4360. tor_assert(filename);
  4361. /* Start the child, if it is not already running */
  4362. if ((!child_handle || child_handle->status != PROCESS_STATUS_RUNNING) &&
  4363. time_to_run_helper < now) {
  4364. /*tor-fw-helper cli looks like this: tor_fw_helper -p :5555 -p 4555:1111 */
  4365. const char **argv; /* cli arguments */
  4366. int args_n, status;
  4367. int argv_index = 0; /* index inside 'argv' */
  4368. tor_assert(smartlist_len(ports_to_forward) > 0);
  4369. /* check for overflow during 'argv' allocation:
  4370. (len(ports_to_forward)*2 + 2)*sizeof(char*) > SIZE_MAX ==
  4371. len(ports_to_forward) > (((SIZE_MAX/sizeof(char*)) - 2)/2) */
  4372. if ((size_t) smartlist_len(ports_to_forward) >
  4373. (((SIZE_MAX/sizeof(char*)) - 2)/2)) {
  4374. log_warn(LD_GENERAL,
  4375. "Overflow during argv allocation. This shouldn't happen.");
  4376. return;
  4377. }
  4378. /* check for overflow during 'argv_index' increase:
  4379. ((len(ports_to_forward)*2 + 2) > INT_MAX) ==
  4380. len(ports_to_forward) > (INT_MAX - 2)/2 */
  4381. if (smartlist_len(ports_to_forward) > (INT_MAX - 2)/2) {
  4382. log_warn(LD_GENERAL,
  4383. "Overflow during argv_index increase. This shouldn't happen.");
  4384. return;
  4385. }
  4386. /* Calculate number of cli arguments: one for the filename, two
  4387. for each smartlist element (one for "-p" and one for the
  4388. ports), and one for the final NULL. */
  4389. args_n = 1 + 2*smartlist_len(ports_to_forward) + 1;
  4390. argv = tor_malloc_zero(sizeof(char*)*args_n);
  4391. argv[argv_index++] = filename;
  4392. SMARTLIST_FOREACH_BEGIN(ports_to_forward, const char *, port) {
  4393. argv[argv_index++] = "-p";
  4394. argv[argv_index++] = port;
  4395. } SMARTLIST_FOREACH_END(port);
  4396. argv[argv_index] = NULL;
  4397. /* Assume tor-fw-helper will succeed, start it later*/
  4398. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_SUCCESS;
  4399. if (child_handle) {
  4400. tor_process_handle_destroy(child_handle, 1);
  4401. child_handle = NULL;
  4402. }
  4403. #ifdef _WIN32
  4404. /* Passing NULL as lpApplicationName makes Windows search for the .exe */
  4405. status = tor_spawn_background(NULL, argv, NULL, &child_handle);
  4406. #else
  4407. status = tor_spawn_background(filename, argv, NULL, &child_handle);
  4408. #endif
  4409. tor_free(argv);
  4410. if (PROCESS_STATUS_ERROR == status) {
  4411. log_warn(LD_GENERAL, "Failed to start port forwarding helper %s",
  4412. filename);
  4413. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_FAIL;
  4414. return;
  4415. }
  4416. log_info(LD_GENERAL,
  4417. "Started port forwarding helper (%s) with pid '%d'",
  4418. filename, tor_process_get_pid(child_handle));
  4419. }
  4420. /* If child is running, read from its stdout and stderr) */
  4421. if (child_handle && PROCESS_STATUS_RUNNING == child_handle->status) {
  4422. /* Read from stdout/stderr and log result */
  4423. retval = 0;
  4424. #ifdef _WIN32
  4425. stderr_status = log_from_handle(child_handle->stderr_pipe, LOG_INFO);
  4426. #else
  4427. stderr_status = log_from_pipe(child_handle->stderr_handle,
  4428. LOG_INFO, filename, &retval);
  4429. #endif
  4430. if (handle_fw_helper_output(child_handle) < 0) {
  4431. log_warn(LD_GENERAL, "Failed to handle fw helper output.");
  4432. stdout_status = -1;
  4433. retval = -1;
  4434. }
  4435. if (retval) {
  4436. /* There was a problem in the child process */
  4437. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_FAIL;
  4438. }
  4439. /* Combine the two statuses in order of severity */
  4440. if (-1 == stdout_status || -1 == stderr_status)
  4441. /* There was a failure */
  4442. retval = -1;
  4443. #ifdef _WIN32
  4444. else if (!child_handle || tor_get_exit_code(child_handle, 0, NULL) !=
  4445. PROCESS_EXIT_RUNNING) {
  4446. /* process has exited or there was an error */
  4447. /* TODO: Do something with the process return value */
  4448. /* TODO: What if the process output something since
  4449. * between log_from_handle and tor_get_exit_code? */
  4450. retval = 1;
  4451. }
  4452. #else
  4453. else if (1 == stdout_status || 1 == stderr_status)
  4454. /* stdout or stderr was closed, the process probably
  4455. * exited. It will be reaped by waitpid() in main.c */
  4456. /* TODO: Do something with the process return value */
  4457. retval = 1;
  4458. #endif
  4459. else
  4460. /* Both are fine */
  4461. retval = 0;
  4462. /* If either pipe indicates a failure, act on it */
  4463. if (0 != retval) {
  4464. if (1 == retval) {
  4465. log_info(LD_GENERAL, "Port forwarding helper terminated");
  4466. child_handle->status = PROCESS_STATUS_NOTRUNNING;
  4467. } else {
  4468. log_warn(LD_GENERAL, "Failed to read from port forwarding helper");
  4469. child_handle->status = PROCESS_STATUS_ERROR;
  4470. }
  4471. /* TODO: The child might not actually be finished (maybe it failed or
  4472. closed stdout/stderr), so maybe we shouldn't start another? */
  4473. }
  4474. }
  4475. }