util.c 152 KB

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