util.c 136 KB

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