util.c 145 KB

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