util.c 145 KB

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