util.c 155 KB

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