util.c 147 KB

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