util.c 139 KB

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