util.c 138 KB

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