util.c 148 KB

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