util.c 152 KB

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