util.c 150 KB

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