util.c 155 KB

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