util.c 142 KB

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