util.c 127 KB

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