util.c 143 KB

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