util.c 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138
  1. /* Copyright (c) 2003, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, 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. #include "orconfig.h"
  11. #ifdef HAVE_FCNTL_H
  12. #include <fcntl.h>
  13. #endif
  14. #define UTIL_PRIVATE
  15. #include "common/util.h"
  16. #include "common/torlog.h"
  17. #include "lib/crypt_ops/crypto_digest.h"
  18. #include "lib/cc/torint.h"
  19. #include "lib/container/smartlist.h"
  20. #include "common/address.h"
  21. #include "common/sandbox.h"
  22. #include "lib/err/backtrace.h"
  23. #include "common/util_process.h"
  24. #include "common/util_format.h"
  25. #ifdef _WIN32
  26. #include <io.h>
  27. #include <direct.h>
  28. #include <process.h>
  29. #include <tchar.h>
  30. #include <winbase.h>
  31. #else /* !(defined(_WIN32)) */
  32. #include <dirent.h>
  33. #include <pwd.h>
  34. #include <grp.h>
  35. #endif /* defined(_WIN32) */
  36. /* math.h needs this on Linux */
  37. #ifndef _USE_ISOC99_
  38. #define _USE_ISOC99_ 1
  39. #endif
  40. #include <math.h>
  41. #include <stdlib.h>
  42. #include <stdio.h>
  43. #include <string.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 /* !defined(OpenBSD) && !defined(__FreeBSD__) */
  82. #endif /* defined(HAVE_MALLOC_H) */
  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. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  90. #include <sys/prctl.h>
  91. #endif
  92. /* =====
  93. * Memory management
  94. * ===== */
  95. DISABLE_GCC_WARNING(aggregate-return)
  96. /** Call the platform malloc info function, and dump the results to the log at
  97. * level <b>severity</b>. If no such function exists, do nothing. */
  98. void
  99. tor_log_mallinfo(int severity)
  100. {
  101. #ifdef HAVE_MALLINFO
  102. struct mallinfo mi;
  103. memset(&mi, 0, sizeof(mi));
  104. mi = mallinfo();
  105. tor_log(severity, LD_MM,
  106. "mallinfo() said: arena=%d, ordblks=%d, smblks=%d, hblks=%d, "
  107. "hblkhd=%d, usmblks=%d, fsmblks=%d, uordblks=%d, fordblks=%d, "
  108. "keepcost=%d",
  109. mi.arena, mi.ordblks, mi.smblks, mi.hblks,
  110. mi.hblkhd, mi.usmblks, mi.fsmblks, mi.uordblks, mi.fordblks,
  111. mi.keepcost);
  112. #else /* !(defined(HAVE_MALLINFO)) */
  113. (void)severity;
  114. #endif /* defined(HAVE_MALLINFO) */
  115. }
  116. ENABLE_GCC_WARNING(aggregate-return)
  117. /* =====
  118. * Math
  119. * ===== */
  120. /**
  121. * Returns the natural logarithm of d base e. We defined this wrapper here so
  122. * to avoid conflicts with old versions of tor_log(), which were named log().
  123. */
  124. double
  125. tor_mathlog(double d)
  126. {
  127. return log(d);
  128. }
  129. /** Return the long integer closest to <b>d</b>. We define this wrapper
  130. * here so that not all users of math.h need to use the right incantations
  131. * to get the c99 functions. */
  132. long
  133. tor_lround(double d)
  134. {
  135. #if defined(HAVE_LROUND)
  136. return lround(d);
  137. #elif defined(HAVE_RINT)
  138. return (long)rint(d);
  139. #else
  140. return (long)(d > 0 ? d + 0.5 : ceil(d - 0.5));
  141. #endif /* defined(HAVE_LROUND) || ... */
  142. }
  143. /** Return the 64-bit integer closest to d. We define this wrapper here so
  144. * that not all users of math.h need to use the right incantations to get the
  145. * c99 functions. */
  146. int64_t
  147. tor_llround(double d)
  148. {
  149. #if defined(HAVE_LLROUND)
  150. return (int64_t)llround(d);
  151. #elif defined(HAVE_RINT)
  152. return (int64_t)rint(d);
  153. #else
  154. return (int64_t)(d > 0 ? d + 0.5 : ceil(d - 0.5));
  155. #endif /* defined(HAVE_LLROUND) || ... */
  156. }
  157. /** Transform a random value <b>p</b> from the uniform distribution in
  158. * [0.0, 1.0[ into a Laplace distributed value with location parameter
  159. * <b>mu</b> and scale parameter <b>b</b>. Truncate the final result
  160. * to be an integer in [INT64_MIN, INT64_MAX]. */
  161. int64_t
  162. sample_laplace_distribution(double mu, double b, double p)
  163. {
  164. double result;
  165. tor_assert(p >= 0.0 && p < 1.0);
  166. /* This is the "inverse cumulative distribution function" from:
  167. * http://en.wikipedia.org/wiki/Laplace_distribution */
  168. if (p <= 0.0) {
  169. /* Avoid taking log(0.0) == -INFINITY, as some processors or compiler
  170. * options can cause the program to trap. */
  171. return INT64_MIN;
  172. }
  173. result = mu - b * (p > 0.5 ? 1.0 : -1.0)
  174. * tor_mathlog(1.0 - 2.0 * fabs(p - 0.5));
  175. return clamp_double_to_int64(result);
  176. }
  177. /** Add random noise between INT64_MIN and INT64_MAX coming from a Laplace
  178. * distribution with mu = 0 and b = <b>delta_f</b>/<b>epsilon</b> to
  179. * <b>signal</b> based on the provided <b>random</b> value in [0.0, 1.0[.
  180. * The epsilon value must be between ]0.0, 1.0]. delta_f must be greater
  181. * than 0. */
  182. int64_t
  183. add_laplace_noise(int64_t signal_, double random_, double delta_f,
  184. double epsilon)
  185. {
  186. int64_t noise;
  187. /* epsilon MUST be between ]0.0, 1.0] */
  188. tor_assert(epsilon > 0.0 && epsilon <= 1.0);
  189. /* delta_f MUST be greater than 0. */
  190. tor_assert(delta_f > 0.0);
  191. /* Just add noise, no further signal */
  192. noise = sample_laplace_distribution(0.0,
  193. delta_f / epsilon,
  194. random_);
  195. /* Clip (signal + noise) to [INT64_MIN, INT64_MAX] */
  196. if (noise > 0 && INT64_MAX - noise < signal_)
  197. return INT64_MAX;
  198. else if (noise < 0 && INT64_MIN - noise > signal_)
  199. return INT64_MIN;
  200. else
  201. return signal_ + noise;
  202. }
  203. /* =====
  204. * String manipulation
  205. * ===== */
  206. /** Return a pointer to a NUL-terminated hexadecimal string encoding
  207. * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
  208. * result does not need to be deallocated, but repeated calls to
  209. * hex_str will trash old results.
  210. */
  211. const char *
  212. hex_str(const char *from, size_t fromlen)
  213. {
  214. static char buf[65];
  215. if (fromlen>(sizeof(buf)-1)/2)
  216. fromlen = (sizeof(buf)-1)/2;
  217. base16_encode(buf,sizeof(buf),from,fromlen);
  218. return buf;
  219. }
  220. /** Compare the value of the string <b>prefix</b> with the start of the
  221. * <b>memlen</b>-byte memory chunk at <b>mem</b>. Return as for strcmp.
  222. *
  223. * [As fast_memcmp(mem, prefix, strlen(prefix)) but returns -1 if memlen is
  224. * less than strlen(prefix).]
  225. */
  226. int
  227. fast_memcmpstart(const void *mem, size_t memlen,
  228. const char *prefix)
  229. {
  230. size_t plen = strlen(prefix);
  231. if (memlen < plen)
  232. return -1;
  233. return fast_memcmp(mem, prefix, plen);
  234. }
  235. /** Return true iff the 'len' bytes at 'mem' are all zero. */
  236. int
  237. tor_mem_is_zero(const char *mem, size_t len)
  238. {
  239. static const char ZERO[] = {
  240. 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,
  241. };
  242. while (len >= sizeof(ZERO)) {
  243. /* It's safe to use fast_memcmp here, since the very worst thing an
  244. * attacker could learn is how many initial bytes of a secret were zero */
  245. if (fast_memcmp(mem, ZERO, sizeof(ZERO)))
  246. return 0;
  247. len -= sizeof(ZERO);
  248. mem += sizeof(ZERO);
  249. }
  250. /* Deal with leftover bytes. */
  251. if (len)
  252. return fast_memeq(mem, ZERO, len);
  253. return 1;
  254. }
  255. /** Return true iff the DIGEST_LEN bytes in digest are all zero. */
  256. int
  257. tor_digest_is_zero(const char *digest)
  258. {
  259. static const uint8_t ZERO_DIGEST[] = {
  260. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
  261. };
  262. return tor_memeq(digest, ZERO_DIGEST, DIGEST_LEN);
  263. }
  264. /** Return true if <b>string</b> is a valid 'key=[value]' string.
  265. * "value" is optional, to indicate the empty string. Log at logging
  266. * <b>severity</b> if something ugly happens. */
  267. int
  268. string_is_key_value(int severity, const char *string)
  269. {
  270. /* position of equal sign in string */
  271. const char *equal_sign_pos = NULL;
  272. tor_assert(string);
  273. if (strlen(string) < 2) { /* "x=" is shortest args string */
  274. tor_log(severity, LD_GENERAL, "'%s' is too short to be a k=v value.",
  275. escaped(string));
  276. return 0;
  277. }
  278. equal_sign_pos = strchr(string, '=');
  279. if (!equal_sign_pos) {
  280. tor_log(severity, LD_GENERAL, "'%s' is not a k=v value.", escaped(string));
  281. return 0;
  282. }
  283. /* validate that the '=' is not in the beginning of the string. */
  284. if (equal_sign_pos == string) {
  285. tor_log(severity, LD_GENERAL, "'%s' is not a valid k=v value.",
  286. escaped(string));
  287. return 0;
  288. }
  289. return 1;
  290. }
  291. /** Return true if <b>string</b> represents a valid IPv4 adddress in
  292. * 'a.b.c.d' form.
  293. */
  294. int
  295. string_is_valid_ipv4_address(const char *string)
  296. {
  297. struct in_addr addr;
  298. return (tor_inet_pton(AF_INET,string,&addr) == 1);
  299. }
  300. /** Return true if <b>string</b> represents a valid IPv6 address in
  301. * a form that inet_pton() can parse.
  302. */
  303. int
  304. string_is_valid_ipv6_address(const char *string)
  305. {
  306. struct in6_addr addr;
  307. return (tor_inet_pton(AF_INET6,string,&addr) == 1);
  308. }
  309. /** Return true iff <b>string</b> is a valid destination address,
  310. * i.e. either a DNS hostname or IPv4/IPv6 address string.
  311. */
  312. int
  313. string_is_valid_dest(const char *string)
  314. {
  315. char *tmp = NULL;
  316. int retval;
  317. size_t len;
  318. if (string == NULL)
  319. return 0;
  320. len = strlen(string);
  321. if (len == 0)
  322. return 0;
  323. if (string[0] == '[' && string[len - 1] == ']')
  324. string = tmp = tor_strndup(string + 1, len - 2);
  325. retval = string_is_valid_ipv4_address(string) ||
  326. string_is_valid_ipv6_address(string) ||
  327. string_is_valid_nonrfc_hostname(string);
  328. tor_free(tmp);
  329. return retval;
  330. }
  331. /** Return true iff <b>string</b> matches a pattern of DNS names
  332. * that we allow Tor clients to connect to.
  333. *
  334. * Note: This allows certain technically invalid characters ('_') to cope
  335. * with misconfigured zones that have been encountered in the wild.
  336. */
  337. int
  338. string_is_valid_nonrfc_hostname(const char *string)
  339. {
  340. int result = 1;
  341. int has_trailing_dot;
  342. char *last_label;
  343. smartlist_t *components;
  344. if (!string || strlen(string) == 0)
  345. return 0;
  346. if (string_is_valid_ipv4_address(string))
  347. return 0;
  348. components = smartlist_new();
  349. smartlist_split_string(components,string,".",0,0);
  350. if (BUG(smartlist_len(components) == 0))
  351. return 0; // LCOV_EXCL_LINE should be impossible given the earlier checks.
  352. /* Allow a single terminating '.' used rarely to indicate domains
  353. * are FQDNs rather than relative. */
  354. last_label = (char *)smartlist_get(components,
  355. smartlist_len(components) - 1);
  356. has_trailing_dot = (last_label[0] == '\0');
  357. if (has_trailing_dot) {
  358. smartlist_pop_last(components);
  359. tor_free(last_label);
  360. last_label = NULL;
  361. }
  362. SMARTLIST_FOREACH_BEGIN(components, char *, c) {
  363. if ((c[0] == '-') || (*c == '_')) {
  364. result = 0;
  365. break;
  366. }
  367. do {
  368. result = (TOR_ISALNUM(*c) || (*c == '-') || (*c == '_'));
  369. c++;
  370. } while (result && *c);
  371. if (result == 0) {
  372. break;
  373. }
  374. } SMARTLIST_FOREACH_END(c);
  375. SMARTLIST_FOREACH_BEGIN(components, char *, c) {
  376. tor_free(c);
  377. } SMARTLIST_FOREACH_END(c);
  378. smartlist_free(components);
  379. return result;
  380. }
  381. /** Return true iff the DIGEST256_LEN bytes in digest are all zero. */
  382. int
  383. tor_digest256_is_zero(const char *digest)
  384. {
  385. return tor_mem_is_zero(digest, DIGEST256_LEN);
  386. }
  387. /* Helper: common code to check whether the result of a strtol or strtoul or
  388. * strtoll is correct. */
  389. #define CHECK_STRTOX_RESULT() \
  390. /* Did an overflow occur? */ \
  391. if (errno == ERANGE) \
  392. goto err; \
  393. /* Was at least one character converted? */ \
  394. if (endptr == s) \
  395. goto err; \
  396. /* Were there unexpected unconverted characters? */ \
  397. if (!next && *endptr) \
  398. goto err; \
  399. /* Illogical (max, min) inputs? */ \
  400. if (BUG(max < min)) \
  401. goto err; \
  402. /* Is r within limits? */ \
  403. if (r < min || r > max) \
  404. goto err; \
  405. if (ok) *ok = 1; \
  406. if (next) *next = endptr; \
  407. return r; \
  408. err: \
  409. if (ok) *ok = 0; \
  410. if (next) *next = endptr; \
  411. return 0
  412. /** Extract a long from the start of <b>s</b>, in the given numeric
  413. * <b>base</b>. If <b>base</b> is 0, <b>s</b> is parsed as a decimal,
  414. * octal, or hex number in the syntax of a C integer literal. If
  415. * there is unconverted data and <b>next</b> is provided, set
  416. * *<b>next</b> to the first unconverted character. An error has
  417. * occurred if no characters are converted; or if there are
  418. * unconverted characters and <b>next</b> is NULL; or if the parsed
  419. * value is not between <b>min</b> and <b>max</b>. When no error
  420. * occurs, return the parsed value and set *<b>ok</b> (if provided) to
  421. * 1. When an error occurs, return 0 and set *<b>ok</b> (if provided)
  422. * to 0.
  423. */
  424. long
  425. tor_parse_long(const char *s, int base, long min, long max,
  426. int *ok, char **next)
  427. {
  428. char *endptr;
  429. long r;
  430. if (BUG(base < 0)) {
  431. if (ok)
  432. *ok = 0;
  433. return 0;
  434. }
  435. errno = 0;
  436. r = strtol(s, &endptr, base);
  437. CHECK_STRTOX_RESULT();
  438. }
  439. /** As tor_parse_long(), but return an unsigned long. */
  440. unsigned long
  441. tor_parse_ulong(const char *s, int base, unsigned long min,
  442. unsigned long max, int *ok, char **next)
  443. {
  444. char *endptr;
  445. unsigned long r;
  446. if (BUG(base < 0)) {
  447. if (ok)
  448. *ok = 0;
  449. return 0;
  450. }
  451. errno = 0;
  452. r = strtoul(s, &endptr, base);
  453. CHECK_STRTOX_RESULT();
  454. }
  455. /** As tor_parse_long(), but return a double. */
  456. double
  457. tor_parse_double(const char *s, double min, double max, int *ok, char **next)
  458. {
  459. char *endptr;
  460. double r;
  461. errno = 0;
  462. r = strtod(s, &endptr);
  463. CHECK_STRTOX_RESULT();
  464. }
  465. /** As tor_parse_long, but return a uint64_t. Only base 10 is guaranteed to
  466. * work for now. */
  467. uint64_t
  468. tor_parse_uint64(const char *s, int base, uint64_t min,
  469. uint64_t max, int *ok, char **next)
  470. {
  471. char *endptr;
  472. uint64_t r;
  473. if (BUG(base < 0)) {
  474. if (ok)
  475. *ok = 0;
  476. return 0;
  477. }
  478. errno = 0;
  479. #ifdef HAVE_STRTOULL
  480. r = (uint64_t)strtoull(s, &endptr, base);
  481. #elif defined(_WIN32)
  482. r = (uint64_t)_strtoui64(s, &endptr, base);
  483. #elif SIZEOF_LONG == 8
  484. r = (uint64_t)strtoul(s, &endptr, base);
  485. #else
  486. #error "I don't know how to parse 64-bit numbers."
  487. #endif /* defined(HAVE_STRTOULL) || ... */
  488. CHECK_STRTOX_RESULT();
  489. }
  490. /** Allocate and return a new string representing the contents of <b>s</b>,
  491. * surrounded by quotes and using standard C escapes.
  492. *
  493. * Generally, we use this for logging values that come in over the network to
  494. * keep them from tricking users, and for sending certain values to the
  495. * controller.
  496. *
  497. * We trust values from the resolver, OS, configuration file, and command line
  498. * to not be maliciously ill-formed. We validate incoming routerdescs and
  499. * SOCKS requests and addresses from BEGIN cells as they're parsed;
  500. * afterwards, we trust them as non-malicious.
  501. */
  502. char *
  503. esc_for_log(const char *s)
  504. {
  505. const char *cp;
  506. char *result, *outp;
  507. size_t len = 3;
  508. if (!s) {
  509. return tor_strdup("(null)");
  510. }
  511. for (cp = s; *cp; ++cp) {
  512. switch (*cp) {
  513. case '\\':
  514. case '\"':
  515. case '\'':
  516. case '\r':
  517. case '\n':
  518. case '\t':
  519. len += 2;
  520. break;
  521. default:
  522. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127)
  523. ++len;
  524. else
  525. len += 4;
  526. break;
  527. }
  528. }
  529. tor_assert(len <= SSIZE_MAX);
  530. result = outp = tor_malloc(len);
  531. *outp++ = '\"';
  532. for (cp = s; *cp; ++cp) {
  533. /* This assertion should always succeed, since we will write at least
  534. * one char here, and two chars for closing quote and nul later */
  535. tor_assert((outp-result) < (ssize_t)len-2);
  536. switch (*cp) {
  537. case '\\':
  538. case '\"':
  539. case '\'':
  540. *outp++ = '\\';
  541. *outp++ = *cp;
  542. break;
  543. case '\n':
  544. *outp++ = '\\';
  545. *outp++ = 'n';
  546. break;
  547. case '\t':
  548. *outp++ = '\\';
  549. *outp++ = 't';
  550. break;
  551. case '\r':
  552. *outp++ = '\\';
  553. *outp++ = 'r';
  554. break;
  555. default:
  556. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127) {
  557. *outp++ = *cp;
  558. } else {
  559. tor_assert((outp-result) < (ssize_t)len-4);
  560. tor_snprintf(outp, 5, "\\%03o", (int)(uint8_t) *cp);
  561. outp += 4;
  562. }
  563. break;
  564. }
  565. }
  566. tor_assert((outp-result) <= (ssize_t)len-2);
  567. *outp++ = '\"';
  568. *outp++ = 0;
  569. return result;
  570. }
  571. /** Similar to esc_for_log. Allocate and return a new string representing
  572. * the first n characters in <b>chars</b>, surround by quotes and using
  573. * standard C escapes. If a NUL character is encountered in <b>chars</b>,
  574. * the resulting string will be terminated there.
  575. */
  576. char *
  577. esc_for_log_len(const char *chars, size_t n)
  578. {
  579. char *string = tor_strndup(chars, n);
  580. char *string_escaped = esc_for_log(string);
  581. tor_free(string);
  582. return string_escaped;
  583. }
  584. /** Allocate and return a new string representing the contents of <b>s</b>,
  585. * surrounded by quotes and using standard C escapes.
  586. *
  587. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  588. * thread. Also, each call invalidates the last-returned value, so don't
  589. * try log_warn(LD_GENERAL, "%s %s", escaped(a), escaped(b));
  590. */
  591. const char *
  592. escaped(const char *s)
  593. {
  594. static char *escaped_val_ = NULL;
  595. tor_free(escaped_val_);
  596. if (s)
  597. escaped_val_ = esc_for_log(s);
  598. else
  599. escaped_val_ = NULL;
  600. return escaped_val_;
  601. }
  602. /** Return a newly allocated string equal to <b>string</b>, except that every
  603. * character in <b>chars_to_escape</b> is preceded by a backslash. */
  604. char *
  605. tor_escape_str_for_pt_args(const char *string, const char *chars_to_escape)
  606. {
  607. char *new_string = NULL;
  608. char *new_cp = NULL;
  609. size_t length, new_length;
  610. tor_assert(string);
  611. length = strlen(string);
  612. if (!length) /* If we were given the empty string, return the same. */
  613. return tor_strdup("");
  614. /* (new_length > SIZE_MAX) => ((length * 2) + 1 > SIZE_MAX) =>
  615. (length*2 > SIZE_MAX - 1) => (length > (SIZE_MAX - 1)/2) */
  616. if (length > (SIZE_MAX - 1)/2) /* check for overflow */
  617. return NULL;
  618. /* this should be enough even if all characters must be escaped */
  619. new_length = (length * 2) + 1;
  620. new_string = new_cp = tor_malloc(new_length);
  621. while (*string) {
  622. if (strchr(chars_to_escape, *string))
  623. *new_cp++ = '\\';
  624. *new_cp++ = *string++;
  625. }
  626. *new_cp = '\0'; /* NUL-terminate the new string */
  627. return new_string;
  628. }
  629. /* =====
  630. * Time
  631. * ===== */
  632. #define TOR_USEC_PER_SEC 1000000
  633. /** Return the difference between start->tv_sec and end->tv_sec.
  634. * Returns INT64_MAX on overflow and underflow.
  635. */
  636. static int64_t
  637. tv_secdiff_impl(const struct timeval *start, const struct timeval *end)
  638. {
  639. const int64_t s = (int64_t)start->tv_sec;
  640. const int64_t e = (int64_t)end->tv_sec;
  641. /* This may not be the most efficient way of implemeting this check,
  642. * but it's easy to see that it's correct and doesn't overflow */
  643. if (s > 0 && e < INT64_MIN + s) {
  644. /* s is positive: equivalent to e - s < INT64_MIN, but without any
  645. * overflow */
  646. return INT64_MAX;
  647. } else if (s < 0 && e > INT64_MAX + s) {
  648. /* s is negative: equivalent to e - s > INT64_MAX, but without any
  649. * overflow */
  650. return INT64_MAX;
  651. }
  652. return e - s;
  653. }
  654. /** Return the number of microseconds elapsed between *start and *end.
  655. * Returns LONG_MAX on overflow and underflow.
  656. */
  657. long
  658. tv_udiff(const struct timeval *start, const struct timeval *end)
  659. {
  660. /* Sanity check tv_usec */
  661. if (start->tv_usec > TOR_USEC_PER_SEC || start->tv_usec < 0) {
  662. log_warn(LD_GENERAL, "comparing times on microsecond detail with bad "
  663. "start tv_usec: " I64_FORMAT " microseconds",
  664. I64_PRINTF_ARG(start->tv_usec));
  665. return LONG_MAX;
  666. }
  667. if (end->tv_usec > TOR_USEC_PER_SEC || end->tv_usec < 0) {
  668. log_warn(LD_GENERAL, "comparing times on microsecond detail with bad "
  669. "end tv_usec: " I64_FORMAT " microseconds",
  670. I64_PRINTF_ARG(end->tv_usec));
  671. return LONG_MAX;
  672. }
  673. /* Some BSDs have struct timeval.tv_sec 64-bit, but time_t (and long) 32-bit
  674. */
  675. int64_t udiff;
  676. const int64_t secdiff = tv_secdiff_impl(start, end);
  677. /* end->tv_usec - start->tv_usec can be up to 1 second either way */
  678. if (secdiff > (int64_t)(LONG_MAX/1000000 - 1) ||
  679. secdiff < (int64_t)(LONG_MIN/1000000 + 1)) {
  680. log_warn(LD_GENERAL, "comparing times on microsecond detail too far "
  681. "apart: " I64_FORMAT " seconds", I64_PRINTF_ARG(secdiff));
  682. return LONG_MAX;
  683. }
  684. /* we'll never get an overflow here, because we check that both usecs are
  685. * between 0 and TV_USEC_PER_SEC. */
  686. udiff = secdiff*1000000 + ((int64_t)end->tv_usec - (int64_t)start->tv_usec);
  687. /* Some compilers are smart enough to work out this is a no-op on L64 */
  688. #if SIZEOF_LONG < 8
  689. if (udiff > (int64_t)LONG_MAX || udiff < (int64_t)LONG_MIN) {
  690. return LONG_MAX;
  691. }
  692. #endif
  693. return (long)udiff;
  694. }
  695. /** Return the number of milliseconds elapsed between *start and *end.
  696. * If the tv_usec difference is 500, rounds away from zero.
  697. * Returns LONG_MAX on overflow and underflow.
  698. */
  699. long
  700. tv_mdiff(const struct timeval *start, const struct timeval *end)
  701. {
  702. /* Sanity check tv_usec */
  703. if (start->tv_usec > TOR_USEC_PER_SEC || start->tv_usec < 0) {
  704. log_warn(LD_GENERAL, "comparing times on millisecond detail with bad "
  705. "start tv_usec: " I64_FORMAT " microseconds",
  706. I64_PRINTF_ARG(start->tv_usec));
  707. return LONG_MAX;
  708. }
  709. if (end->tv_usec > TOR_USEC_PER_SEC || end->tv_usec < 0) {
  710. log_warn(LD_GENERAL, "comparing times on millisecond detail with bad "
  711. "end tv_usec: " I64_FORMAT " microseconds",
  712. I64_PRINTF_ARG(end->tv_usec));
  713. return LONG_MAX;
  714. }
  715. /* Some BSDs have struct timeval.tv_sec 64-bit, but time_t (and long) 32-bit
  716. */
  717. int64_t mdiff;
  718. const int64_t secdiff = tv_secdiff_impl(start, end);
  719. /* end->tv_usec - start->tv_usec can be up to 1 second either way, but the
  720. * mdiff calculation may add another temporary second for rounding.
  721. * Whether this actually causes overflow depends on the compiler's constant
  722. * folding and order of operations. */
  723. if (secdiff > (int64_t)(LONG_MAX/1000 - 2) ||
  724. secdiff < (int64_t)(LONG_MIN/1000 + 1)) {
  725. log_warn(LD_GENERAL, "comparing times on millisecond detail too far "
  726. "apart: " I64_FORMAT " seconds", I64_PRINTF_ARG(secdiff));
  727. return LONG_MAX;
  728. }
  729. /* Subtract and round */
  730. mdiff = secdiff*1000 +
  731. /* We add a million usec here to ensure that the result is positive,
  732. * so that the round-towards-zero behavior of the division will give
  733. * the right result for rounding to the nearest msec. Later we subtract
  734. * 1000 in order to get the correct result.
  735. * We'll never get an overflow here, because we check that both usecs are
  736. * between 0 and TV_USEC_PER_SEC. */
  737. ((int64_t)end->tv_usec - (int64_t)start->tv_usec + 500 + 1000000) / 1000
  738. - 1000;
  739. /* Some compilers are smart enough to work out this is a no-op on L64 */
  740. #if SIZEOF_LONG < 8
  741. if (mdiff > (int64_t)LONG_MAX || mdiff < (int64_t)LONG_MIN) {
  742. return LONG_MAX;
  743. }
  744. #endif
  745. return (long)mdiff;
  746. }
  747. /**
  748. * Converts timeval to milliseconds.
  749. */
  750. int64_t
  751. tv_to_msec(const struct timeval *tv)
  752. {
  753. int64_t conv = ((int64_t)tv->tv_sec)*1000L;
  754. /* Round ghetto-style */
  755. conv += ((int64_t)tv->tv_usec+500)/1000L;
  756. return conv;
  757. }
  758. /** Yield true iff <b>y</b> is a leap-year. */
  759. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  760. /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
  761. static int
  762. n_leapdays(int year1, int year2)
  763. {
  764. --year1;
  765. --year2;
  766. return (year2/4 - year1/4) - (year2/100 - year1/100)
  767. + (year2/400 - year1/400);
  768. }
  769. /** Number of days per month in non-leap year; used by tor_timegm and
  770. * parse_rfc1123_time. */
  771. static const int days_per_month[] =
  772. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  773. /** Compute a time_t given a struct tm. The result is given in UTC, and
  774. * does not account for leap seconds. Return 0 on success, -1 on failure.
  775. */
  776. int
  777. tor_timegm(const struct tm *tm, time_t *time_out)
  778. {
  779. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  780. * It's way more brute-force than fiddling with tzset().
  781. *
  782. * We use int64_t rather than time_t to avoid overflow on multiplication on
  783. * platforms with 32-bit time_t. Since year is clipped to INT32_MAX, and
  784. * since 365 * 24 * 60 * 60 is approximately 31 million, it's not possible
  785. * for INT32_MAX years to overflow int64_t when converted to seconds. */
  786. int64_t year, days, hours, minutes, seconds;
  787. int i, invalid_year, dpm;
  788. /* Initialize time_out to 0 for now, to avoid bad usage in case this function
  789. fails and the caller ignores the return value. */
  790. tor_assert(time_out);
  791. *time_out = 0;
  792. /* avoid int overflow on addition */
  793. if (tm->tm_year < INT32_MAX-1900) {
  794. year = tm->tm_year + 1900;
  795. } else {
  796. /* clamp year */
  797. year = INT32_MAX;
  798. }
  799. invalid_year = (year < 1970 || tm->tm_year >= INT32_MAX-1900);
  800. if (tm->tm_mon >= 0 && tm->tm_mon <= 11) {
  801. dpm = days_per_month[tm->tm_mon];
  802. if (tm->tm_mon == 1 && !invalid_year && IS_LEAPYEAR(tm->tm_year)) {
  803. dpm = 29;
  804. }
  805. } else {
  806. /* invalid month - default to 0 days per month */
  807. dpm = 0;
  808. }
  809. if (invalid_year ||
  810. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  811. tm->tm_mday < 1 || tm->tm_mday > dpm ||
  812. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  813. tm->tm_min < 0 || tm->tm_min > 59 ||
  814. tm->tm_sec < 0 || tm->tm_sec > 60) {
  815. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  816. return -1;
  817. }
  818. days = 365 * (year-1970) + n_leapdays(1970,(int)year);
  819. for (i = 0; i < tm->tm_mon; ++i)
  820. days += days_per_month[i];
  821. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  822. ++days;
  823. days += tm->tm_mday - 1;
  824. hours = days*24 + tm->tm_hour;
  825. minutes = hours*60 + tm->tm_min;
  826. seconds = minutes*60 + tm->tm_sec;
  827. /* Check that "seconds" will fit in a time_t. On platforms where time_t is
  828. * 32-bit, this check will fail for dates in and after 2038.
  829. *
  830. * We already know that "seconds" can't be negative because "year" >= 1970 */
  831. #if SIZEOF_TIME_T < 8
  832. if (seconds < TIME_MIN || seconds > TIME_MAX) {
  833. log_warn(LD_BUG, "Result does not fit in tor_timegm");
  834. return -1;
  835. }
  836. #endif /* SIZEOF_TIME_T < 8 */
  837. *time_out = (time_t)seconds;
  838. return 0;
  839. }
  840. /* strftime is locale-specific, so we need to replace those parts */
  841. /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
  842. static const char *WEEKDAY_NAMES[] =
  843. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  844. /** A c-locale array of 3-letter names of months, starting with Jan. */
  845. static const char *MONTH_NAMES[] =
  846. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  847. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  848. /** Set <b>buf</b> to the RFC1123 encoding of the UTC value of <b>t</b>.
  849. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  850. *
  851. * (RFC1123 format is "Fri, 29 Sep 2006 15:54:20 GMT". Note the "GMT"
  852. * rather than "UTC".)
  853. */
  854. void
  855. format_rfc1123_time(char *buf, time_t t)
  856. {
  857. struct tm tm;
  858. tor_gmtime_r(&t, &tm);
  859. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  860. tor_assert(tm.tm_wday >= 0);
  861. tor_assert(tm.tm_wday <= 6);
  862. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  863. tor_assert(tm.tm_mon >= 0);
  864. tor_assert(tm.tm_mon <= 11);
  865. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  866. }
  867. /** Parse the (a subset of) the RFC1123 encoding of some time (in UTC) from
  868. * <b>buf</b>, and store the result in *<b>t</b>.
  869. *
  870. * Note that we only accept the subset generated by format_rfc1123_time above,
  871. * not the full range of formats suggested by RFC 1123.
  872. *
  873. * Return 0 on success, -1 on failure.
  874. */
  875. int
  876. parse_rfc1123_time(const char *buf, time_t *t)
  877. {
  878. struct tm tm;
  879. char month[4];
  880. char weekday[4];
  881. int i, m, invalid_year;
  882. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  883. unsigned dpm;
  884. if (strlen(buf) != RFC1123_TIME_LEN)
  885. return -1;
  886. memset(&tm, 0, sizeof(tm));
  887. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  888. &tm_mday, month, &tm_year, &tm_hour,
  889. &tm_min, &tm_sec) < 7) {
  890. char *esc = esc_for_log(buf);
  891. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  892. tor_free(esc);
  893. return -1;
  894. }
  895. m = -1;
  896. for (i = 0; i < 12; ++i) {
  897. if (!strcmp(month, MONTH_NAMES[i])) {
  898. m = i;
  899. break;
  900. }
  901. }
  902. if (m<0) {
  903. char *esc = esc_for_log(buf);
  904. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  905. tor_free(esc);
  906. return -1;
  907. }
  908. tm.tm_mon = m;
  909. invalid_year = (tm_year >= INT32_MAX || tm_year < 1970);
  910. tor_assert(m >= 0 && m <= 11);
  911. dpm = days_per_month[m];
  912. if (m == 1 && !invalid_year && IS_LEAPYEAR(tm_year)) {
  913. dpm = 29;
  914. }
  915. if (invalid_year || tm_mday < 1 || tm_mday > dpm ||
  916. tm_hour > 23 || tm_min > 59 || tm_sec > 60) {
  917. char *esc = esc_for_log(buf);
  918. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  919. tor_free(esc);
  920. return -1;
  921. }
  922. tm.tm_mday = (int)tm_mday;
  923. tm.tm_year = (int)tm_year;
  924. tm.tm_hour = (int)tm_hour;
  925. tm.tm_min = (int)tm_min;
  926. tm.tm_sec = (int)tm_sec;
  927. if (tm.tm_year < 1970) {
  928. /* LCOV_EXCL_START
  929. * XXXX I think this is dead code; we already checked for
  930. * invalid_year above. */
  931. tor_assert_nonfatal_unreached();
  932. char *esc = esc_for_log(buf);
  933. log_warn(LD_GENERAL,
  934. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  935. tor_free(esc);
  936. return -1;
  937. /* LCOV_EXCL_STOP */
  938. }
  939. tm.tm_year -= 1900;
  940. return tor_timegm(&tm, t);
  941. }
  942. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  943. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  944. *
  945. * (ISO8601 format is 2006-10-29 10:57:20)
  946. */
  947. void
  948. format_local_iso_time(char *buf, time_t t)
  949. {
  950. struct tm tm;
  951. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  952. }
  953. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  954. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  955. */
  956. void
  957. format_iso_time(char *buf, time_t t)
  958. {
  959. struct tm tm;
  960. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  961. }
  962. /** As format_local_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  963. * embedding an internal space. */
  964. void
  965. format_local_iso_time_nospace(char *buf, time_t t)
  966. {
  967. format_local_iso_time(buf, t);
  968. buf[10] = 'T';
  969. }
  970. /** As format_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  971. * embedding an internal space. */
  972. void
  973. format_iso_time_nospace(char *buf, time_t t)
  974. {
  975. format_iso_time(buf, t);
  976. buf[10] = 'T';
  977. }
  978. /** As format_iso_time_nospace, but include microseconds in decimal
  979. * fixed-point format. Requires that buf be at least ISO_TIME_USEC_LEN+1
  980. * bytes long. */
  981. void
  982. format_iso_time_nospace_usec(char *buf, const struct timeval *tv)
  983. {
  984. tor_assert(tv);
  985. format_iso_time_nospace(buf, (time_t)tv->tv_sec);
  986. tor_snprintf(buf+ISO_TIME_LEN, 8, ".%06d", (int)tv->tv_usec);
  987. }
  988. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  989. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  990. * failure. Ignore extraneous stuff in <b>cp</b> after the end of the time
  991. * string, unless <b>strict</b> is set. If <b>nospace</b> is set,
  992. * expect the YYYY-MM-DDTHH:MM:SS format. */
  993. int
  994. parse_iso_time_(const char *cp, time_t *t, int strict, int nospace)
  995. {
  996. struct tm st_tm;
  997. unsigned int year=0, month=0, day=0, hour=0, minute=0, second=0;
  998. int n_fields;
  999. char extra_char, separator_char;
  1000. n_fields = tor_sscanf(cp, "%u-%2u-%2u%c%2u:%2u:%2u%c",
  1001. &year, &month, &day,
  1002. &separator_char,
  1003. &hour, &minute, &second, &extra_char);
  1004. if (strict ? (n_fields != 7) : (n_fields < 7)) {
  1005. char *esc = esc_for_log(cp);
  1006. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  1007. tor_free(esc);
  1008. return -1;
  1009. }
  1010. if (separator_char != (nospace ? 'T' : ' ')) {
  1011. char *esc = esc_for_log(cp);
  1012. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  1013. tor_free(esc);
  1014. return -1;
  1015. }
  1016. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  1017. hour > 23 || minute > 59 || second > 60 || year >= INT32_MAX) {
  1018. char *esc = esc_for_log(cp);
  1019. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  1020. tor_free(esc);
  1021. return -1;
  1022. }
  1023. st_tm.tm_year = (int)year-1900;
  1024. st_tm.tm_mon = month-1;
  1025. st_tm.tm_mday = day;
  1026. st_tm.tm_hour = hour;
  1027. st_tm.tm_min = minute;
  1028. st_tm.tm_sec = second;
  1029. st_tm.tm_wday = 0; /* Should be ignored. */
  1030. if (st_tm.tm_year < 70) {
  1031. /* LCOV_EXCL_START
  1032. * XXXX I think this is dead code; we already checked for
  1033. * year < 1970 above. */
  1034. tor_assert_nonfatal_unreached();
  1035. char *esc = esc_for_log(cp);
  1036. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  1037. tor_free(esc);
  1038. return -1;
  1039. /* LCOV_EXCL_STOP */
  1040. }
  1041. return tor_timegm(&st_tm, t);
  1042. }
  1043. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  1044. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  1045. * failure. Reject the string if any characters are present after the time.
  1046. */
  1047. int
  1048. parse_iso_time(const char *cp, time_t *t)
  1049. {
  1050. return parse_iso_time_(cp, t, 1, 0);
  1051. }
  1052. /**
  1053. * As parse_iso_time, but parses a time encoded by format_iso_time_nospace().
  1054. */
  1055. int
  1056. parse_iso_time_nospace(const char *cp, time_t *t)
  1057. {
  1058. return parse_iso_time_(cp, t, 1, 1);
  1059. }
  1060. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  1061. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  1062. int
  1063. parse_http_time(const char *date, struct tm *tm)
  1064. {
  1065. const char *cp;
  1066. char month[4];
  1067. char wkday[4];
  1068. int i;
  1069. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1070. tor_assert(tm);
  1071. memset(tm, 0, sizeof(*tm));
  1072. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  1073. if ((cp = strchr(date, ','))) {
  1074. ++cp;
  1075. if (*cp != ' ')
  1076. return -1;
  1077. ++cp;
  1078. if (tor_sscanf(cp, "%2u %3s %4u %2u:%2u:%2u GMT",
  1079. &tm_mday, month, &tm_year,
  1080. &tm_hour, &tm_min, &tm_sec) == 6) {
  1081. /* rfc1123-date */
  1082. tm_year -= 1900;
  1083. } else if (tor_sscanf(cp, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  1084. &tm_mday, month, &tm_year,
  1085. &tm_hour, &tm_min, &tm_sec) == 6) {
  1086. /* rfc850-date */
  1087. } else {
  1088. return -1;
  1089. }
  1090. } else {
  1091. /* No comma; possibly asctime() format. */
  1092. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  1093. wkday, month, &tm_mday,
  1094. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  1095. tm_year -= 1900;
  1096. } else {
  1097. return -1;
  1098. }
  1099. }
  1100. tm->tm_mday = (int)tm_mday;
  1101. tm->tm_year = (int)tm_year;
  1102. tm->tm_hour = (int)tm_hour;
  1103. tm->tm_min = (int)tm_min;
  1104. tm->tm_sec = (int)tm_sec;
  1105. tm->tm_wday = 0; /* Leave this unset. */
  1106. month[3] = '\0';
  1107. /* Okay, now decode the month. */
  1108. /* set tm->tm_mon to dummy value so the check below fails. */
  1109. tm->tm_mon = -1;
  1110. for (i = 0; i < 12; ++i) {
  1111. if (!strcasecmp(MONTH_NAMES[i], month)) {
  1112. tm->tm_mon = i;
  1113. }
  1114. }
  1115. if (tm->tm_year < 0 ||
  1116. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  1117. tm->tm_mday < 1 || tm->tm_mday > 31 ||
  1118. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1119. tm->tm_min < 0 || tm->tm_min > 59 ||
  1120. tm->tm_sec < 0 || tm->tm_sec > 60)
  1121. return -1; /* Out of range, or bad month. */
  1122. return 0;
  1123. }
  1124. /** Given an <b>interval</b> in seconds, try to write it to the
  1125. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  1126. * Returns a non-negative integer on success, -1 on failure.
  1127. */
  1128. int
  1129. format_time_interval(char *out, size_t out_len, long interval)
  1130. {
  1131. /* We only report seconds if there's no hours. */
  1132. long sec = 0, min = 0, hour = 0, day = 0;
  1133. /* -LONG_MIN is LONG_MAX + 1, which causes signed overflow */
  1134. if (interval < -LONG_MAX)
  1135. interval = LONG_MAX;
  1136. else if (interval < 0)
  1137. interval = -interval;
  1138. if (interval >= 86400) {
  1139. day = interval / 86400;
  1140. interval %= 86400;
  1141. }
  1142. if (interval >= 3600) {
  1143. hour = interval / 3600;
  1144. interval %= 3600;
  1145. }
  1146. if (interval >= 60) {
  1147. min = interval / 60;
  1148. interval %= 60;
  1149. }
  1150. sec = interval;
  1151. if (day) {
  1152. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  1153. day, hour, min);
  1154. } else if (hour) {
  1155. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  1156. } else if (min) {
  1157. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  1158. } else {
  1159. return tor_snprintf(out, out_len, "%ld seconds", sec);
  1160. }
  1161. }
  1162. /* =====
  1163. * File helpers
  1164. * ===== */
  1165. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1166. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1167. * was returned by open(). Return the number of bytes written, or -1
  1168. * on error. Only use if fd is a blocking fd. */
  1169. ssize_t
  1170. write_all(tor_socket_t fd, const char *buf, size_t count, int isSocket)
  1171. {
  1172. size_t written = 0;
  1173. ssize_t result;
  1174. raw_assert(count < SSIZE_MAX);
  1175. while (written != count) {
  1176. if (isSocket)
  1177. result = tor_socket_send(fd, buf+written, count-written, 0);
  1178. else
  1179. result = write((int)fd, buf+written, count-written);
  1180. if (result<0)
  1181. return -1;
  1182. written += result;
  1183. }
  1184. return (ssize_t)count;
  1185. }
  1186. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1187. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1188. * was returned by socket() or accept(), and 0 if fd was returned by
  1189. * open(). Return the number of bytes read, or -1 on error. Only use
  1190. * if fd is a blocking fd. */
  1191. ssize_t
  1192. read_all(tor_socket_t fd, char *buf, size_t count, int isSocket)
  1193. {
  1194. size_t numread = 0;
  1195. ssize_t result;
  1196. if (count > SIZE_T_CEILING || count > SSIZE_MAX) {
  1197. errno = EINVAL;
  1198. return -1;
  1199. }
  1200. while (numread < count) {
  1201. if (isSocket)
  1202. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1203. else
  1204. result = read((int)fd, buf+numread, count-numread);
  1205. if (result<0)
  1206. return -1;
  1207. else if (result == 0)
  1208. break;
  1209. numread += result;
  1210. }
  1211. return (ssize_t)numread;
  1212. }
  1213. /*
  1214. * Filesystem operations.
  1215. */
  1216. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1217. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1218. * the root of a disk. */
  1219. static void
  1220. clean_name_for_stat(char *name)
  1221. {
  1222. #ifdef _WIN32
  1223. size_t len = strlen(name);
  1224. if (!len)
  1225. return;
  1226. if (name[len-1]=='\\' || name[len-1]=='/') {
  1227. if (len == 1 || (len==3 && name[1]==':'))
  1228. return;
  1229. name[len-1]='\0';
  1230. }
  1231. #else /* !(defined(_WIN32)) */
  1232. (void)name;
  1233. #endif /* defined(_WIN32) */
  1234. }
  1235. /** Wrapper for unlink() to make it mockable for the test suite; returns 0
  1236. * if unlinking the file succeeded, -1 and sets errno if unlinking fails.
  1237. */
  1238. MOCK_IMPL(int,
  1239. tor_unlink,(const char *pathname))
  1240. {
  1241. return unlink(pathname);
  1242. }
  1243. /** Return:
  1244. * FN_ERROR if filename can't be read, is NULL, or is zero-length,
  1245. * FN_NOENT if it doesn't exist,
  1246. * FN_FILE if it is a non-empty regular file, or a FIFO on unix-like systems,
  1247. * FN_EMPTY for zero-byte regular files,
  1248. * FN_DIR if it's a directory, and
  1249. * FN_ERROR for any other file type.
  1250. * On FN_ERROR and FN_NOENT, sets errno. (errno is not set when FN_ERROR
  1251. * is returned due to an unhandled file type.) */
  1252. file_status_t
  1253. file_status(const char *fname)
  1254. {
  1255. struct stat st;
  1256. char *f;
  1257. int r;
  1258. if (!fname || strlen(fname) == 0) {
  1259. return FN_ERROR;
  1260. }
  1261. f = tor_strdup(fname);
  1262. clean_name_for_stat(f);
  1263. log_debug(LD_FS, "stat()ing %s", f);
  1264. r = stat(sandbox_intern_string(f), &st);
  1265. tor_free(f);
  1266. if (r) {
  1267. if (errno == ENOENT) {
  1268. return FN_NOENT;
  1269. }
  1270. return FN_ERROR;
  1271. }
  1272. if (st.st_mode & S_IFDIR) {
  1273. return FN_DIR;
  1274. } else if (st.st_mode & S_IFREG) {
  1275. if (st.st_size > 0) {
  1276. return FN_FILE;
  1277. } else if (st.st_size == 0) {
  1278. return FN_EMPTY;
  1279. } else {
  1280. return FN_ERROR;
  1281. }
  1282. #ifndef _WIN32
  1283. } else if (st.st_mode & S_IFIFO) {
  1284. return FN_FILE;
  1285. #endif
  1286. } else {
  1287. return FN_ERROR;
  1288. }
  1289. }
  1290. /** Check whether <b>dirname</b> exists and is private. If yes return 0.
  1291. * If <b>dirname</b> does not exist:
  1292. * - if <b>check</b>&CPD_CREATE, try to create it and return 0 on success.
  1293. * - if <b>check</b>&CPD_CHECK, and we think we can create it, return 0.
  1294. * - if <b>check</b>&CPD_CHECK is false, and the directory exists, return 0.
  1295. * - otherwise, return -1.
  1296. * If CPD_GROUP_OK is set, then it's okay if the directory
  1297. * is group-readable, but in all cases we create the directory mode 0700.
  1298. * If CPD_GROUP_READ is set, existing directory behaves as CPD_GROUP_OK and
  1299. * if the directory is created it will use mode 0750 with group read
  1300. * permission. Group read privileges also assume execute permission
  1301. * as norm for directories. If CPD_CHECK_MODE_ONLY is set, then we don't
  1302. * alter the directory permissions if they are too permissive:
  1303. * we just return -1.
  1304. * When effective_user is not NULL, check permissions against the given user
  1305. * and its primary group.
  1306. */
  1307. MOCK_IMPL(int,
  1308. check_private_dir,(const char *dirname, cpd_check_t check,
  1309. const char *effective_user))
  1310. {
  1311. int r;
  1312. struct stat st;
  1313. tor_assert(dirname);
  1314. #ifndef _WIN32
  1315. int fd;
  1316. const struct passwd *pw = NULL;
  1317. uid_t running_uid;
  1318. gid_t running_gid;
  1319. /*
  1320. * Goal is to harden the implementation by removing any
  1321. * potential for race between stat() and chmod().
  1322. * chmod() accepts filename as argument. If an attacker can move
  1323. * the file between stat() and chmod(), a potential race exists.
  1324. *
  1325. * Several suggestions taken from:
  1326. * https://developer.apple.com/library/mac/documentation/
  1327. * Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html
  1328. */
  1329. /* Open directory.
  1330. * O_NOFOLLOW to ensure that it does not follow symbolic links */
  1331. fd = open(sandbox_intern_string(dirname), O_NOFOLLOW);
  1332. /* Was there an error? Maybe the directory does not exist? */
  1333. if (fd == -1) {
  1334. if (errno != ENOENT) {
  1335. /* Other directory error */
  1336. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1337. strerror(errno));
  1338. return -1;
  1339. }
  1340. /* Received ENOENT: Directory does not exist */
  1341. /* Should we create the directory? */
  1342. if (check & CPD_CREATE) {
  1343. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1344. if (check & CPD_GROUP_READ) {
  1345. r = mkdir(dirname, 0750);
  1346. } else {
  1347. r = mkdir(dirname, 0700);
  1348. }
  1349. /* check for mkdir() error */
  1350. if (r) {
  1351. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1352. strerror(errno));
  1353. return -1;
  1354. }
  1355. /* we just created the directory. try to open it again.
  1356. * permissions on the directory will be checked again below.*/
  1357. fd = open(sandbox_intern_string(dirname), O_NOFOLLOW);
  1358. if (fd == -1) {
  1359. log_warn(LD_FS, "Could not reopen recently created directory %s: %s",
  1360. dirname,
  1361. strerror(errno));
  1362. return -1;
  1363. } else {
  1364. close(fd);
  1365. }
  1366. } else if (!(check & CPD_CHECK)) {
  1367. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1368. return -1;
  1369. }
  1370. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1371. * parent directory a little harder. */
  1372. return 0;
  1373. }
  1374. tor_assert(fd >= 0);
  1375. //f = tor_strdup(dirname);
  1376. //clean_name_for_stat(f);
  1377. log_debug(LD_FS, "stat()ing %s", dirname);
  1378. //r = stat(sandbox_intern_string(f), &st);
  1379. r = fstat(fd, &st);
  1380. if (r == -1) {
  1381. log_warn(LD_FS, "fstat() on directory %s failed.", dirname);
  1382. close(fd);
  1383. return -1;
  1384. }
  1385. //tor_free(f);
  1386. /* check that dirname is a directory */
  1387. if (!(st.st_mode & S_IFDIR)) {
  1388. log_warn(LD_FS, "%s is not a directory", dirname);
  1389. close(fd);
  1390. return -1;
  1391. }
  1392. if (effective_user) {
  1393. /* Look up the user and group information.
  1394. * If we have a problem, bail out. */
  1395. pw = tor_getpwnam(effective_user);
  1396. if (pw == NULL) {
  1397. log_warn(LD_CONFIG, "Error setting configured user: %s not found",
  1398. effective_user);
  1399. close(fd);
  1400. return -1;
  1401. }
  1402. running_uid = pw->pw_uid;
  1403. running_gid = pw->pw_gid;
  1404. } else {
  1405. running_uid = getuid();
  1406. running_gid = getgid();
  1407. }
  1408. if (st.st_uid != running_uid) {
  1409. char *process_ownername = NULL, *file_ownername = NULL;
  1410. {
  1411. const struct passwd *pw_running = tor_getpwuid(running_uid);
  1412. process_ownername = pw_running ? tor_strdup(pw_running->pw_name) :
  1413. tor_strdup("<unknown>");
  1414. }
  1415. {
  1416. const struct passwd *pw_stat = tor_getpwuid(st.st_uid);
  1417. file_ownername = pw_stat ? tor_strdup(pw_stat->pw_name) :
  1418. tor_strdup("<unknown>");
  1419. }
  1420. log_warn(LD_FS, "%s is not owned by this user (%s, %d) but by "
  1421. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1422. dirname, process_ownername, (int)running_uid,
  1423. file_ownername, (int)st.st_uid);
  1424. tor_free(process_ownername);
  1425. tor_free(file_ownername);
  1426. close(fd);
  1427. return -1;
  1428. }
  1429. if ( (check & (CPD_GROUP_OK|CPD_GROUP_READ))
  1430. && (st.st_gid != running_gid) && (st.st_gid != 0)) {
  1431. struct group *gr;
  1432. char *process_groupname = NULL;
  1433. gr = getgrgid(running_gid);
  1434. process_groupname = gr ? tor_strdup(gr->gr_name) : tor_strdup("<unknown>");
  1435. gr = getgrgid(st.st_gid);
  1436. log_warn(LD_FS, "%s is not owned by this group (%s, %d) but by group "
  1437. "%s (%d). Are you running Tor as the wrong user?",
  1438. dirname, process_groupname, (int)running_gid,
  1439. gr ? gr->gr_name : "<unknown>", (int)st.st_gid);
  1440. tor_free(process_groupname);
  1441. close(fd);
  1442. return -1;
  1443. }
  1444. unsigned unwanted_bits = 0;
  1445. if (check & (CPD_GROUP_OK|CPD_GROUP_READ)) {
  1446. unwanted_bits = 0027;
  1447. } else {
  1448. unwanted_bits = 0077;
  1449. }
  1450. unsigned check_bits_filter = ~0;
  1451. if (check & CPD_RELAX_DIRMODE_CHECK) {
  1452. check_bits_filter = 0022;
  1453. }
  1454. if ((st.st_mode & unwanted_bits & check_bits_filter) != 0) {
  1455. unsigned new_mode;
  1456. if (check & CPD_CHECK_MODE_ONLY) {
  1457. log_warn(LD_FS, "Permissions on directory %s are too permissive.",
  1458. dirname);
  1459. close(fd);
  1460. return -1;
  1461. }
  1462. log_warn(LD_FS, "Fixing permissions on directory %s", dirname);
  1463. new_mode = st.st_mode;
  1464. new_mode |= 0700; /* Owner should have rwx */
  1465. if (check & CPD_GROUP_READ) {
  1466. new_mode |= 0050; /* Group should have rx */
  1467. }
  1468. new_mode &= ~unwanted_bits; /* Clear the bits that we didn't want set...*/
  1469. if (fchmod(fd, new_mode)) {
  1470. log_warn(LD_FS, "Could not chmod directory %s: %s", dirname,
  1471. strerror(errno));
  1472. close(fd);
  1473. return -1;
  1474. } else {
  1475. close(fd);
  1476. return 0;
  1477. }
  1478. }
  1479. close(fd);
  1480. #else /* !(!defined(_WIN32)) */
  1481. /* Win32 case: we can't open() a directory. */
  1482. (void)effective_user;
  1483. char *f = tor_strdup(dirname);
  1484. clean_name_for_stat(f);
  1485. log_debug(LD_FS, "stat()ing %s", f);
  1486. r = stat(sandbox_intern_string(f), &st);
  1487. tor_free(f);
  1488. if (r) {
  1489. if (errno != ENOENT) {
  1490. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1491. strerror(errno));
  1492. return -1;
  1493. }
  1494. if (check & CPD_CREATE) {
  1495. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1496. r = mkdir(dirname);
  1497. if (r) {
  1498. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1499. strerror(errno));
  1500. return -1;
  1501. }
  1502. } else if (!(check & CPD_CHECK)) {
  1503. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1504. return -1;
  1505. }
  1506. return 0;
  1507. }
  1508. if (!(st.st_mode & S_IFDIR)) {
  1509. log_warn(LD_FS, "%s is not a directory", dirname);
  1510. return -1;
  1511. }
  1512. #endif /* !defined(_WIN32) */
  1513. return 0;
  1514. }
  1515. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1516. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1517. *
  1518. * This function replaces the old file atomically, if possible. This
  1519. * function, and all other functions in util.c that create files, create them
  1520. * with mode 0600.
  1521. */
  1522. MOCK_IMPL(int,
  1523. write_str_to_file,(const char *fname, const char *str, int bin))
  1524. {
  1525. #ifdef _WIN32
  1526. if (!bin && strchr(str, '\r')) {
  1527. log_warn(LD_BUG,
  1528. "We're writing a text string that already contains a CR to %s",
  1529. escaped(fname));
  1530. }
  1531. #endif /* defined(_WIN32) */
  1532. return write_bytes_to_file(fname, str, strlen(str), bin);
  1533. }
  1534. /** Represents a file that we're writing to, with support for atomic commit:
  1535. * we can write into a temporary file, and either remove the file on
  1536. * failure, or replace the original file on success. */
  1537. struct open_file_t {
  1538. char *tempname; /**< Name of the temporary file. */
  1539. char *filename; /**< Name of the original file. */
  1540. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  1541. unsigned binary:1; /**< Did we open in binary mode? */
  1542. int fd; /**< fd for the open file. */
  1543. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  1544. };
  1545. /** Try to start writing to the file in <b>fname</b>, passing the flags
  1546. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  1547. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  1548. * original file. Otherwise, we open a new temporary file in the same
  1549. * directory, and either replace the original or remove the temporary file
  1550. * when we're done.
  1551. *
  1552. * Return the fd for the newly opened file, and store working data in
  1553. * *<b>data_out</b>. The caller should not close the fd manually:
  1554. * instead, call finish_writing_to_file() or abort_writing_to_file().
  1555. * Returns -1 on failure.
  1556. *
  1557. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  1558. * as true and the flag O_EXCL is treated as false.
  1559. *
  1560. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  1561. * write()". We don't do that.
  1562. */
  1563. int
  1564. start_writing_to_file(const char *fname, int open_flags, int mode,
  1565. open_file_t **data_out)
  1566. {
  1567. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  1568. const char *open_name;
  1569. int append = 0;
  1570. tor_assert(fname);
  1571. tor_assert(data_out);
  1572. #if (O_BINARY != 0 && O_TEXT != 0)
  1573. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  1574. #endif
  1575. new_file->fd = -1;
  1576. new_file->filename = tor_strdup(fname);
  1577. if (open_flags & O_APPEND) {
  1578. open_name = fname;
  1579. new_file->rename_on_close = 0;
  1580. append = 1;
  1581. open_flags &= ~O_APPEND;
  1582. } else {
  1583. tor_asprintf(&new_file->tempname, "%s.tmp", fname);
  1584. open_name = new_file->tempname;
  1585. /* We always replace an existing temporary file if there is one. */
  1586. open_flags |= O_CREAT|O_TRUNC;
  1587. open_flags &= ~O_EXCL;
  1588. new_file->rename_on_close = 1;
  1589. }
  1590. #if O_BINARY != 0
  1591. if (open_flags & O_BINARY)
  1592. new_file->binary = 1;
  1593. #endif
  1594. new_file->fd = tor_open_cloexec(open_name, open_flags, mode);
  1595. if (new_file->fd < 0) {
  1596. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  1597. open_name, fname, strerror(errno));
  1598. goto err;
  1599. }
  1600. if (append) {
  1601. if (tor_fd_seekend(new_file->fd) < 0) {
  1602. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  1603. strerror(errno));
  1604. goto err;
  1605. }
  1606. }
  1607. *data_out = new_file;
  1608. return new_file->fd;
  1609. err:
  1610. if (new_file->fd >= 0)
  1611. close(new_file->fd);
  1612. *data_out = NULL;
  1613. tor_free(new_file->filename);
  1614. tor_free(new_file->tempname);
  1615. tor_free(new_file);
  1616. return -1;
  1617. }
  1618. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  1619. * that can be used to write to the same file. The caller should not mix
  1620. * stdio calls with non-stdio calls. */
  1621. FILE *
  1622. fdopen_file(open_file_t *file_data)
  1623. {
  1624. tor_assert(file_data);
  1625. if (file_data->stdio_file)
  1626. return file_data->stdio_file;
  1627. tor_assert(file_data->fd >= 0);
  1628. if (!(file_data->stdio_file = fdopen(file_data->fd,
  1629. file_data->binary?"ab":"a"))) {
  1630. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  1631. file_data->fd, strerror(errno));
  1632. }
  1633. return file_data->stdio_file;
  1634. }
  1635. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  1636. * for start_writing_to_file, but */
  1637. FILE *
  1638. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  1639. open_file_t **data_out)
  1640. {
  1641. FILE *res;
  1642. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  1643. return NULL;
  1644. if (!(res = fdopen_file(*data_out))) {
  1645. abort_writing_to_file(*data_out);
  1646. *data_out = NULL;
  1647. }
  1648. return res;
  1649. }
  1650. /** Helper function: close and free the underlying file and memory in
  1651. * <b>file_data</b>. If we were writing into a temporary file, then delete
  1652. * that file (if abort_write is true) or replaces the target file with
  1653. * the temporary file (if abort_write is false). */
  1654. static int
  1655. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  1656. {
  1657. int r = 0;
  1658. tor_assert(file_data && file_data->filename);
  1659. if (file_data->stdio_file) {
  1660. if (fclose(file_data->stdio_file)) {
  1661. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  1662. strerror(errno));
  1663. abort_write = r = -1;
  1664. }
  1665. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  1666. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  1667. strerror(errno));
  1668. abort_write = r = -1;
  1669. }
  1670. if (file_data->rename_on_close) {
  1671. tor_assert(file_data->tempname && file_data->filename);
  1672. if (!abort_write) {
  1673. tor_assert(strcmp(file_data->filename, file_data->tempname));
  1674. if (replace_file(file_data->tempname, file_data->filename)) {
  1675. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  1676. strerror(errno));
  1677. abort_write = r = -1;
  1678. }
  1679. }
  1680. if (abort_write) {
  1681. int res = unlink(file_data->tempname);
  1682. if (res != 0) {
  1683. /* We couldn't unlink and we'll leave a mess behind */
  1684. log_warn(LD_FS, "Failed to unlink %s: %s",
  1685. file_data->tempname, strerror(errno));
  1686. r = -1;
  1687. }
  1688. }
  1689. }
  1690. tor_free(file_data->filename);
  1691. tor_free(file_data->tempname);
  1692. tor_free(file_data);
  1693. return r;
  1694. }
  1695. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1696. * needed, and if using a temporary file, replace the original file with
  1697. * the temporary file. */
  1698. int
  1699. finish_writing_to_file(open_file_t *file_data)
  1700. {
  1701. return finish_writing_to_file_impl(file_data, 0);
  1702. }
  1703. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1704. * needed, and if using a temporary file, delete it. */
  1705. int
  1706. abort_writing_to_file(open_file_t *file_data)
  1707. {
  1708. return finish_writing_to_file_impl(file_data, 1);
  1709. }
  1710. /** Helper: given a set of flags as passed to open(2), open the file
  1711. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  1712. * the file. Do so as atomically as possible e.g. by opening temp files and
  1713. * renaming. */
  1714. static int
  1715. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  1716. int open_flags)
  1717. {
  1718. open_file_t *file = NULL;
  1719. int fd;
  1720. ssize_t result;
  1721. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  1722. if (fd<0)
  1723. return -1;
  1724. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  1725. {
  1726. result = write_all(fd, chunk->bytes, chunk->len, 0);
  1727. if (result < 0) {
  1728. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  1729. strerror(errno));
  1730. goto err;
  1731. }
  1732. tor_assert((size_t)result == chunk->len);
  1733. });
  1734. return finish_writing_to_file(file);
  1735. err:
  1736. abort_writing_to_file(file);
  1737. return -1;
  1738. }
  1739. /** Given a smartlist of sized_chunk_t, write them to a file
  1740. * <b>fname</b>, overwriting or creating the file as necessary.
  1741. * If <b>no_tempfile</b> is 0 then the file will be written
  1742. * atomically. */
  1743. int
  1744. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin,
  1745. int no_tempfile)
  1746. {
  1747. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1748. if (no_tempfile) {
  1749. /* O_APPEND stops write_chunks_to_file from using tempfiles */
  1750. flags |= O_APPEND;
  1751. }
  1752. return write_chunks_to_file_impl(fname, chunks, flags);
  1753. }
  1754. /** Write <b>len</b> bytes, starting at <b>str</b>, to <b>fname</b>
  1755. using the open() flags passed in <b>flags</b>. */
  1756. static int
  1757. write_bytes_to_file_impl(const char *fname, const char *str, size_t len,
  1758. int flags)
  1759. {
  1760. int r;
  1761. sized_chunk_t c = { str, len };
  1762. smartlist_t *chunks = smartlist_new();
  1763. smartlist_add(chunks, &c);
  1764. r = write_chunks_to_file_impl(fname, chunks, flags);
  1765. smartlist_free(chunks);
  1766. return r;
  1767. }
  1768. /** As write_str_to_file, but does not assume a NUL-terminated
  1769. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  1770. MOCK_IMPL(int,
  1771. write_bytes_to_file,(const char *fname, const char *str, size_t len,
  1772. int bin))
  1773. {
  1774. return write_bytes_to_file_impl(fname, str, len,
  1775. OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT));
  1776. }
  1777. /** As write_bytes_to_file, but if the file already exists, append the bytes
  1778. * to the end of the file instead of overwriting it. */
  1779. int
  1780. append_bytes_to_file(const char *fname, const char *str, size_t len,
  1781. int bin)
  1782. {
  1783. return write_bytes_to_file_impl(fname, str, len,
  1784. OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT));
  1785. }
  1786. /** Like write_str_to_file(), but also return -1 if there was a file
  1787. already residing in <b>fname</b>. */
  1788. int
  1789. write_bytes_to_new_file(const char *fname, const char *str, size_t len,
  1790. int bin)
  1791. {
  1792. return write_bytes_to_file_impl(fname, str, len,
  1793. OPEN_FLAGS_DONT_REPLACE|
  1794. (bin?O_BINARY:O_TEXT));
  1795. }
  1796. /**
  1797. * Read the contents of the open file <b>fd</b> presuming it is a FIFO
  1798. * (or similar) file descriptor for which the size of the file isn't
  1799. * known ahead of time. Return NULL on failure, and a NUL-terminated
  1800. * string on success. On success, set <b>sz_out</b> to the number of
  1801. * bytes read.
  1802. */
  1803. char *
  1804. read_file_to_str_until_eof(int fd, size_t max_bytes_to_read, size_t *sz_out)
  1805. {
  1806. ssize_t r;
  1807. size_t pos = 0;
  1808. char *string = NULL;
  1809. size_t string_max = 0;
  1810. if (max_bytes_to_read+1 >= SIZE_T_CEILING) {
  1811. errno = EINVAL;
  1812. return NULL;
  1813. }
  1814. do {
  1815. /* XXXX This "add 1K" approach is a little goofy; if we care about
  1816. * performance here, we should be doubling. But in practice we shouldn't
  1817. * be using this function on big files anyway. */
  1818. string_max = pos + 1024;
  1819. if (string_max > max_bytes_to_read)
  1820. string_max = max_bytes_to_read + 1;
  1821. string = tor_realloc(string, string_max);
  1822. r = read(fd, string + pos, string_max - pos - 1);
  1823. if (r < 0) {
  1824. int save_errno = errno;
  1825. tor_free(string);
  1826. errno = save_errno;
  1827. return NULL;
  1828. }
  1829. pos += r;
  1830. } while (r > 0 && pos < max_bytes_to_read);
  1831. tor_assert(pos < string_max);
  1832. *sz_out = pos;
  1833. string[pos] = '\0';
  1834. return string;
  1835. }
  1836. /** Read the contents of <b>filename</b> into a newly allocated
  1837. * string; return the string on success or NULL on failure.
  1838. *
  1839. * If <b>stat_out</b> is provided, store the result of stat()ing the
  1840. * file into <b>stat_out</b>.
  1841. *
  1842. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  1843. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  1844. * doesn't exist.
  1845. */
  1846. /*
  1847. * This function <em>may</em> return an erroneous result if the file
  1848. * is modified while it is running, but must not crash or overflow.
  1849. * Right now, the error case occurs when the file length grows between
  1850. * the call to stat and the call to read_all: the resulting string will
  1851. * be truncated.
  1852. */
  1853. MOCK_IMPL(char *,
  1854. read_file_to_str, (const char *filename, int flags, struct stat *stat_out))
  1855. {
  1856. int fd; /* router file */
  1857. struct stat statbuf;
  1858. char *string;
  1859. ssize_t r;
  1860. int bin = flags & RFTS_BIN;
  1861. tor_assert(filename);
  1862. fd = tor_open_cloexec(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  1863. if (fd<0) {
  1864. int severity = LOG_WARN;
  1865. int save_errno = errno;
  1866. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  1867. severity = LOG_INFO;
  1868. log_fn(severity, LD_FS,"Could not open \"%s\": %s",filename,
  1869. strerror(errno));
  1870. errno = save_errno;
  1871. return NULL;
  1872. }
  1873. if (fstat(fd, &statbuf)<0) {
  1874. int save_errno = errno;
  1875. close(fd);
  1876. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  1877. errno = save_errno;
  1878. return NULL;
  1879. }
  1880. #ifndef _WIN32
  1881. /** When we detect that we're reading from a FIFO, don't read more than
  1882. * this many bytes. It's insane overkill for most uses. */
  1883. #define FIFO_READ_MAX (1024*1024)
  1884. if (S_ISFIFO(statbuf.st_mode)) {
  1885. size_t sz = 0;
  1886. string = read_file_to_str_until_eof(fd, FIFO_READ_MAX, &sz);
  1887. int save_errno = errno;
  1888. if (string && stat_out) {
  1889. statbuf.st_size = sz;
  1890. memcpy(stat_out, &statbuf, sizeof(struct stat));
  1891. }
  1892. close(fd);
  1893. if (!string)
  1894. errno = save_errno;
  1895. return string;
  1896. }
  1897. #endif /* !defined(_WIN32) */
  1898. if ((uint64_t)(statbuf.st_size)+1 >= SIZE_T_CEILING) {
  1899. close(fd);
  1900. errno = EINVAL;
  1901. return NULL;
  1902. }
  1903. string = tor_malloc((size_t)(statbuf.st_size+1));
  1904. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  1905. if (r<0) {
  1906. int save_errno = errno;
  1907. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  1908. strerror(errno));
  1909. tor_free(string);
  1910. close(fd);
  1911. errno = save_errno;
  1912. return NULL;
  1913. }
  1914. string[r] = '\0'; /* NUL-terminate the result. */
  1915. #if defined(_WIN32) || defined(__CYGWIN__)
  1916. if (!bin && strchr(string, '\r')) {
  1917. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  1918. "when reading %s. Coping.",
  1919. filename);
  1920. tor_strstrip(string, "\r");
  1921. r = strlen(string);
  1922. }
  1923. if (!bin) {
  1924. statbuf.st_size = (size_t) r;
  1925. } else
  1926. #endif /* defined(_WIN32) || defined(__CYGWIN__) */
  1927. if (r != statbuf.st_size) {
  1928. /* Unless we're using text mode on win32, we'd better have an exact
  1929. * match for size. */
  1930. int save_errno = errno;
  1931. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  1932. (int)r, (long)statbuf.st_size,filename);
  1933. tor_free(string);
  1934. close(fd);
  1935. errno = save_errno;
  1936. return NULL;
  1937. }
  1938. close(fd);
  1939. if (stat_out) {
  1940. memcpy(stat_out, &statbuf, sizeof(struct stat));
  1941. }
  1942. return string;
  1943. }
  1944. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  1945. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  1946. * decode its contents into a newly allocated string. On success, assign this
  1947. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  1948. * provided), and return a pointer to the position in <b>s</b> immediately
  1949. * after the string. On failure, return NULL.
  1950. */
  1951. const char *
  1952. unescape_string(const char *s, char **result, size_t *size_out)
  1953. {
  1954. const char *cp;
  1955. char *out;
  1956. if (s[0] != '\"')
  1957. return NULL;
  1958. cp = s+1;
  1959. while (1) {
  1960. switch (*cp) {
  1961. case '\0':
  1962. case '\n':
  1963. return NULL;
  1964. case '\"':
  1965. goto end_of_loop;
  1966. case '\\':
  1967. if (cp[1] == 'x' || cp[1] == 'X') {
  1968. if (!(TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])))
  1969. return NULL;
  1970. cp += 4;
  1971. } else if (TOR_ISODIGIT(cp[1])) {
  1972. cp += 2;
  1973. if (TOR_ISODIGIT(*cp)) ++cp;
  1974. if (TOR_ISODIGIT(*cp)) ++cp;
  1975. } else if (cp[1] == 'n' || cp[1] == 'r' || cp[1] == 't' || cp[1] == '"'
  1976. || cp[1] == '\\' || cp[1] == '\'') {
  1977. cp += 2;
  1978. } else {
  1979. return NULL;
  1980. }
  1981. break;
  1982. default:
  1983. ++cp;
  1984. break;
  1985. }
  1986. }
  1987. end_of_loop:
  1988. out = *result = tor_malloc(cp-s + 1);
  1989. cp = s+1;
  1990. while (1) {
  1991. switch (*cp)
  1992. {
  1993. case '\"':
  1994. *out = '\0';
  1995. if (size_out) *size_out = out - *result;
  1996. return cp+1;
  1997. /* LCOV_EXCL_START -- we caught this in parse_config_from_line. */
  1998. case '\0':
  1999. tor_fragile_assert();
  2000. tor_free(*result);
  2001. return NULL;
  2002. /* LCOV_EXCL_STOP */
  2003. case '\\':
  2004. switch (cp[1])
  2005. {
  2006. case 'n': *out++ = '\n'; cp += 2; break;
  2007. case 'r': *out++ = '\r'; cp += 2; break;
  2008. case 't': *out++ = '\t'; cp += 2; break;
  2009. case 'x': case 'X':
  2010. {
  2011. int x1, x2;
  2012. x1 = hex_decode_digit(cp[2]);
  2013. x2 = hex_decode_digit(cp[3]);
  2014. if (x1 == -1 || x2 == -1) {
  2015. /* LCOV_EXCL_START */
  2016. /* we caught this above in the initial loop. */
  2017. tor_assert_nonfatal_unreached();
  2018. tor_free(*result);
  2019. return NULL;
  2020. /* LCOV_EXCL_STOP */
  2021. }
  2022. *out++ = ((x1<<4) + x2);
  2023. cp += 4;
  2024. }
  2025. break;
  2026. case '0': case '1': case '2': case '3': case '4': case '5':
  2027. case '6': case '7':
  2028. {
  2029. int n = cp[1]-'0';
  2030. cp += 2;
  2031. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2032. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2033. if (n > 255) { tor_free(*result); return NULL; }
  2034. *out++ = (char)n;
  2035. }
  2036. break;
  2037. case '\'':
  2038. case '\"':
  2039. case '\\':
  2040. case '\?':
  2041. *out++ = cp[1];
  2042. cp += 2;
  2043. break;
  2044. /* LCOV_EXCL_START */
  2045. default:
  2046. /* we caught this above in the initial loop. */
  2047. tor_assert_nonfatal_unreached();
  2048. tor_free(*result); return NULL;
  2049. /* LCOV_EXCL_STOP */
  2050. }
  2051. break;
  2052. default:
  2053. *out++ = *cp++;
  2054. }
  2055. }
  2056. }
  2057. /** Removes enclosing quotes from <b>path</b> and unescapes quotes between the
  2058. * enclosing quotes. Backslashes are not unescaped. Return the unquoted
  2059. * <b>path</b> on success or 0 if <b>path</b> is not quoted correctly. */
  2060. char *
  2061. get_unquoted_path(const char *path)
  2062. {
  2063. size_t len = strlen(path);
  2064. if (len == 0) {
  2065. return tor_strdup("");
  2066. }
  2067. int has_start_quote = (path[0] == '\"');
  2068. int has_end_quote = (len > 0 && path[len-1] == '\"');
  2069. if (has_start_quote != has_end_quote || (len == 1 && has_start_quote)) {
  2070. return NULL;
  2071. }
  2072. char *unquoted_path = tor_malloc(len - has_start_quote - has_end_quote + 1);
  2073. char *s = unquoted_path;
  2074. size_t i;
  2075. for (i = has_start_quote; i < len - has_end_quote; i++) {
  2076. if (path[i] == '\"' && (i > 0 && path[i-1] == '\\')) {
  2077. *(s-1) = path[i];
  2078. } else if (path[i] != '\"') {
  2079. *s++ = path[i];
  2080. } else { /* unescaped quote */
  2081. tor_free(unquoted_path);
  2082. return NULL;
  2083. }
  2084. }
  2085. *s = '\0';
  2086. return unquoted_path;
  2087. }
  2088. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  2089. * string. */
  2090. char *
  2091. expand_filename(const char *filename)
  2092. {
  2093. tor_assert(filename);
  2094. #ifdef _WIN32
  2095. /* Might consider using GetFullPathName() as described here:
  2096. * http://etutorials.org/Programming/secure+programming/
  2097. * Chapter+3.+Input+Validation/3.7+Validating+Filenames+and+Paths/
  2098. */
  2099. return tor_strdup(filename);
  2100. #else /* !(defined(_WIN32)) */
  2101. if (*filename == '~') {
  2102. char *home, *result=NULL;
  2103. const char *rest;
  2104. if (filename[1] == '/' || filename[1] == '\0') {
  2105. home = getenv("HOME");
  2106. if (!home) {
  2107. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  2108. "expanding \"%s\"; defaulting to \"\".", filename);
  2109. home = tor_strdup("");
  2110. } else {
  2111. home = tor_strdup(home);
  2112. }
  2113. rest = strlen(filename)>=2?(filename+2):"";
  2114. } else {
  2115. #ifdef HAVE_PWD_H
  2116. char *username, *slash;
  2117. slash = strchr(filename, '/');
  2118. if (slash)
  2119. username = tor_strndup(filename+1,slash-filename-1);
  2120. else
  2121. username = tor_strdup(filename+1);
  2122. if (!(home = get_user_homedir(username))) {
  2123. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2124. tor_free(username);
  2125. return NULL;
  2126. }
  2127. tor_free(username);
  2128. rest = slash ? (slash+1) : "";
  2129. #else /* !(defined(HAVE_PWD_H)) */
  2130. log_warn(LD_CONFIG, "Couldn't expand homedir on system without pwd.h");
  2131. return tor_strdup(filename);
  2132. #endif /* defined(HAVE_PWD_H) */
  2133. }
  2134. tor_assert(home);
  2135. /* Remove trailing slash. */
  2136. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2137. home[strlen(home)-1] = '\0';
  2138. }
  2139. tor_asprintf(&result,"%s"PATH_SEPARATOR"%s",home,rest);
  2140. tor_free(home);
  2141. return result;
  2142. } else {
  2143. return tor_strdup(filename);
  2144. }
  2145. #endif /* defined(_WIN32) */
  2146. }
  2147. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  2148. * Return NULL on error or if <b>dirname</b> is not a directory.
  2149. */
  2150. MOCK_IMPL(smartlist_t *,
  2151. tor_listdir, (const char *dirname))
  2152. {
  2153. smartlist_t *result;
  2154. #ifdef _WIN32
  2155. char *pattern=NULL;
  2156. TCHAR tpattern[MAX_PATH] = {0};
  2157. char name[MAX_PATH*2+1] = {0};
  2158. HANDLE handle;
  2159. WIN32_FIND_DATA findData;
  2160. tor_asprintf(&pattern, "%s\\*", dirname);
  2161. #ifdef UNICODE
  2162. mbstowcs(tpattern,pattern,MAX_PATH);
  2163. #else
  2164. strlcpy(tpattern, pattern, MAX_PATH);
  2165. #endif
  2166. if (INVALID_HANDLE_VALUE == (handle = FindFirstFile(tpattern, &findData))) {
  2167. tor_free(pattern);
  2168. return NULL;
  2169. }
  2170. result = smartlist_new();
  2171. while (1) {
  2172. #ifdef UNICODE
  2173. wcstombs(name,findData.cFileName,MAX_PATH);
  2174. name[sizeof(name)-1] = '\0';
  2175. #else
  2176. strlcpy(name,findData.cFileName,sizeof(name));
  2177. #endif /* defined(UNICODE) */
  2178. if (strcmp(name, ".") &&
  2179. strcmp(name, "..")) {
  2180. smartlist_add_strdup(result, name);
  2181. }
  2182. if (!FindNextFile(handle, &findData)) {
  2183. DWORD err;
  2184. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  2185. char *errstr = format_win32_error(err);
  2186. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  2187. tor_free(errstr);
  2188. }
  2189. break;
  2190. }
  2191. }
  2192. FindClose(handle);
  2193. tor_free(pattern);
  2194. #else /* !(defined(_WIN32)) */
  2195. const char *prot_dname = sandbox_intern_string(dirname);
  2196. DIR *d;
  2197. struct dirent *de;
  2198. if (!(d = opendir(prot_dname)))
  2199. return NULL;
  2200. result = smartlist_new();
  2201. while ((de = readdir(d))) {
  2202. if (!strcmp(de->d_name, ".") ||
  2203. !strcmp(de->d_name, ".."))
  2204. continue;
  2205. smartlist_add_strdup(result, de->d_name);
  2206. }
  2207. closedir(d);
  2208. #endif /* defined(_WIN32) */
  2209. return result;
  2210. }
  2211. /** Return true iff <b>filename</b> is a relative path. */
  2212. int
  2213. path_is_relative(const char *filename)
  2214. {
  2215. if (filename && filename[0] == '/')
  2216. return 0;
  2217. #ifdef _WIN32
  2218. else if (filename && filename[0] == '\\')
  2219. return 0;
  2220. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  2221. filename[1] == ':' && filename[2] == '\\')
  2222. return 0;
  2223. #endif /* defined(_WIN32) */
  2224. else
  2225. return 1;
  2226. }
  2227. /* =====
  2228. * Process helpers
  2229. * ===== */
  2230. #ifndef _WIN32
  2231. /* Based on code contributed by christian grothoff */
  2232. /** True iff we've called start_daemon(). */
  2233. static int start_daemon_called = 0;
  2234. /** True iff we've called finish_daemon(). */
  2235. static int finish_daemon_called = 0;
  2236. /** Socketpair used to communicate between parent and child process while
  2237. * daemonizing. */
  2238. static int daemon_filedes[2];
  2239. /** Start putting the process into daemon mode: fork and drop all resources
  2240. * except standard fds. The parent process never returns, but stays around
  2241. * until finish_daemon is called. (Note: it's safe to call this more
  2242. * than once: calls after the first are ignored.)
  2243. */
  2244. void
  2245. start_daemon(void)
  2246. {
  2247. pid_t pid;
  2248. if (start_daemon_called)
  2249. return;
  2250. start_daemon_called = 1;
  2251. if (pipe(daemon_filedes)) {
  2252. /* LCOV_EXCL_START */
  2253. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  2254. exit(1); // exit ok: during daemonize, pipe failed.
  2255. /* LCOV_EXCL_STOP */
  2256. }
  2257. pid = fork();
  2258. if (pid < 0) {
  2259. /* LCOV_EXCL_START */
  2260. log_err(LD_GENERAL,"fork failed. Exiting.");
  2261. exit(1); // exit ok: during daemonize, fork failed
  2262. /* LCOV_EXCL_STOP */
  2263. }
  2264. if (pid) { /* Parent */
  2265. int ok;
  2266. char c;
  2267. close(daemon_filedes[1]); /* we only read */
  2268. ok = -1;
  2269. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  2270. if (c == '.')
  2271. ok = 1;
  2272. }
  2273. fflush(stdout);
  2274. if (ok == 1)
  2275. exit(0); // exit ok: during daemonize, daemonizing.
  2276. else
  2277. exit(1); /* child reported error. exit ok: daemonize failed. */
  2278. } else { /* Child */
  2279. close(daemon_filedes[0]); /* we only write */
  2280. (void) setsid(); /* Detach from controlling terminal */
  2281. /*
  2282. * Fork one more time, so the parent (the session group leader) can exit.
  2283. * This means that we, as a non-session group leader, can never regain a
  2284. * controlling terminal. This part is recommended by Stevens's
  2285. * _Advanced Programming in the Unix Environment_.
  2286. */
  2287. if (fork() != 0) {
  2288. exit(0); // exit ok: during daemonize, fork failed (2)
  2289. }
  2290. set_main_thread(); /* We are now the main thread. */
  2291. return;
  2292. }
  2293. }
  2294. /** Finish putting the process into daemon mode: drop standard fds, and tell
  2295. * the parent process to exit. (Note: it's safe to call this more than once:
  2296. * calls after the first are ignored. Calls start_daemon first if it hasn't
  2297. * been called already.)
  2298. */
  2299. void
  2300. finish_daemon(const char *desired_cwd)
  2301. {
  2302. int nullfd;
  2303. char c = '.';
  2304. if (finish_daemon_called)
  2305. return;
  2306. if (!start_daemon_called)
  2307. start_daemon();
  2308. finish_daemon_called = 1;
  2309. if (!desired_cwd)
  2310. desired_cwd = "/";
  2311. /* Don't hold the wrong FS mounted */
  2312. if (chdir(desired_cwd) < 0) {
  2313. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  2314. exit(1); // exit ok: during daemonize, chdir failed.
  2315. }
  2316. nullfd = tor_open_cloexec("/dev/null", O_RDWR, 0);
  2317. if (nullfd < 0) {
  2318. /* LCOV_EXCL_START */
  2319. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  2320. exit(1); // exit ok: during daemonize, couldn't open /dev/null
  2321. /* LCOV_EXCL_STOP */
  2322. }
  2323. /* close fds linking to invoking terminal, but
  2324. * close usual incoming fds, but redirect them somewhere
  2325. * useful so the fds don't get reallocated elsewhere.
  2326. */
  2327. if (dup2(nullfd,0) < 0 ||
  2328. dup2(nullfd,1) < 0 ||
  2329. dup2(nullfd,2) < 0) {
  2330. /* LCOV_EXCL_START */
  2331. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  2332. exit(1); // exit ok: during daemonize, dup2 failed.
  2333. /* LCOV_EXCL_STOP */
  2334. }
  2335. if (nullfd > 2)
  2336. close(nullfd);
  2337. /* signal success */
  2338. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  2339. log_err(LD_GENERAL,"write failed. Exiting.");
  2340. }
  2341. close(daemon_filedes[1]);
  2342. }
  2343. #else /* !(!defined(_WIN32)) */
  2344. /* defined(_WIN32) */
  2345. void
  2346. start_daemon(void)
  2347. {
  2348. }
  2349. void
  2350. finish_daemon(const char *cp)
  2351. {
  2352. (void)cp;
  2353. }
  2354. #endif /* !defined(_WIN32) */
  2355. /** Write the current process ID, followed by NL, into <b>filename</b>.
  2356. * Return 0 on success, -1 on failure.
  2357. */
  2358. int
  2359. write_pidfile(const char *filename)
  2360. {
  2361. FILE *pidfile;
  2362. if ((pidfile = fopen(filename, "w")) == NULL) {
  2363. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  2364. strerror(errno));
  2365. return -1;
  2366. } else {
  2367. #ifdef _WIN32
  2368. int pid = (int)_getpid();
  2369. #else
  2370. int pid = (int)getpid();
  2371. #endif
  2372. int rv = 0;
  2373. if (fprintf(pidfile, "%d\n", pid) < 0)
  2374. rv = -1;
  2375. if (fclose(pidfile) < 0)
  2376. rv = -1;
  2377. return rv;
  2378. }
  2379. }
  2380. #ifdef _WIN32
  2381. HANDLE
  2382. load_windows_system_library(const TCHAR *library_name)
  2383. {
  2384. TCHAR path[MAX_PATH];
  2385. unsigned n;
  2386. n = GetSystemDirectory(path, MAX_PATH);
  2387. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  2388. return 0;
  2389. _tcscat(path, TEXT("\\"));
  2390. _tcscat(path, library_name);
  2391. return LoadLibrary(path);
  2392. }
  2393. #endif /* defined(_WIN32) */
  2394. /** Format a single argument for being put on a Windows command line.
  2395. * Returns a newly allocated string */
  2396. static char *
  2397. format_win_cmdline_argument(const char *arg)
  2398. {
  2399. char *formatted_arg;
  2400. char need_quotes;
  2401. const char *c;
  2402. int i;
  2403. int bs_counter = 0;
  2404. /* Backslash we can point to when one is inserted into the string */
  2405. const char backslash = '\\';
  2406. /* Smartlist of *char */
  2407. smartlist_t *arg_chars;
  2408. arg_chars = smartlist_new();
  2409. /* Quote string if it contains whitespace or is empty */
  2410. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  2411. /* Build up smartlist of *chars */
  2412. for (c=arg; *c != '\0'; c++) {
  2413. if ('"' == *c) {
  2414. /* Double up backslashes preceding a quote */
  2415. for (i=0; i<(bs_counter*2); i++)
  2416. smartlist_add(arg_chars, (void*)&backslash);
  2417. bs_counter = 0;
  2418. /* Escape the quote */
  2419. smartlist_add(arg_chars, (void*)&backslash);
  2420. smartlist_add(arg_chars, (void*)c);
  2421. } else if ('\\' == *c) {
  2422. /* Count backslashes until we know whether to double up */
  2423. bs_counter++;
  2424. } else {
  2425. /* Don't double up slashes preceding a non-quote */
  2426. for (i=0; i<bs_counter; i++)
  2427. smartlist_add(arg_chars, (void*)&backslash);
  2428. bs_counter = 0;
  2429. smartlist_add(arg_chars, (void*)c);
  2430. }
  2431. }
  2432. /* Don't double up trailing backslashes */
  2433. for (i=0; i<bs_counter; i++)
  2434. smartlist_add(arg_chars, (void*)&backslash);
  2435. /* Allocate space for argument, quotes (if needed), and terminator */
  2436. const size_t formatted_arg_len = smartlist_len(arg_chars) +
  2437. (need_quotes ? 2 : 0) + 1;
  2438. formatted_arg = tor_malloc_zero(formatted_arg_len);
  2439. /* Add leading quote */
  2440. i=0;
  2441. if (need_quotes)
  2442. formatted_arg[i++] = '"';
  2443. /* Add characters */
  2444. SMARTLIST_FOREACH(arg_chars, char*, ch,
  2445. {
  2446. formatted_arg[i++] = *ch;
  2447. });
  2448. /* Add trailing quote */
  2449. if (need_quotes)
  2450. formatted_arg[i++] = '"';
  2451. formatted_arg[i] = '\0';
  2452. smartlist_free(arg_chars);
  2453. return formatted_arg;
  2454. }
  2455. /** Format a command line for use on Windows, which takes the command as a
  2456. * string rather than string array. Follows the rules from "Parsing C++
  2457. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  2458. * Python subprocess module. Returns a newly allocated string */
  2459. char *
  2460. tor_join_win_cmdline(const char *argv[])
  2461. {
  2462. smartlist_t *argv_list;
  2463. char *joined_argv;
  2464. int i;
  2465. /* Format each argument and put the result in a smartlist */
  2466. argv_list = smartlist_new();
  2467. for (i=0; argv[i] != NULL; i++) {
  2468. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  2469. }
  2470. /* Join the arguments with whitespace */
  2471. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  2472. /* Free the newly allocated arguments, and the smartlist */
  2473. SMARTLIST_FOREACH(argv_list, char *, arg,
  2474. {
  2475. tor_free(arg);
  2476. });
  2477. smartlist_free(argv_list);
  2478. return joined_argv;
  2479. }
  2480. #ifndef _WIN32
  2481. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  2482. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  2483. * safe.
  2484. *
  2485. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE+1 bytes available.
  2486. *
  2487. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  2488. * with spaces. CHILD_STATE indicates where
  2489. * in the process of starting the child process did the failure occur (see
  2490. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  2491. * errno when the failure occurred.
  2492. *
  2493. * On success return the number of characters added to hex_errno, not counting
  2494. * the terminating NUL; return -1 on error.
  2495. */
  2496. STATIC int
  2497. format_helper_exit_status(unsigned char child_state, int saved_errno,
  2498. char *hex_errno)
  2499. {
  2500. unsigned int unsigned_errno;
  2501. int written, left;
  2502. char *cur;
  2503. size_t i;
  2504. int res = -1;
  2505. /* Fill hex_errno with spaces, and a trailing newline (memset may
  2506. not be signal handler safe, so we can't use it) */
  2507. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  2508. hex_errno[i] = ' ';
  2509. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  2510. /* Convert errno to be unsigned for hex conversion */
  2511. if (saved_errno < 0) {
  2512. // Avoid overflow on the cast to unsigned int when result is INT_MIN
  2513. // by adding 1 to the signed int negative value,
  2514. // then, after it has been negated and cast to unsigned,
  2515. // adding the original 1 back (the double-addition is intentional).
  2516. // Otherwise, the cast to signed could cause a temporary int
  2517. // to equal INT_MAX + 1, which is undefined.
  2518. unsigned_errno = ((unsigned int) -(saved_errno + 1)) + 1;
  2519. } else {
  2520. unsigned_errno = (unsigned int) saved_errno;
  2521. }
  2522. /*
  2523. * Count how many chars of space we have left, and keep a pointer into the
  2524. * current point in the buffer.
  2525. */
  2526. left = HEX_ERRNO_SIZE+1;
  2527. cur = hex_errno;
  2528. /* Emit child_state */
  2529. written = format_hex_number_sigsafe(child_state, cur, left);
  2530. if (written <= 0)
  2531. goto err;
  2532. /* Adjust left and cur */
  2533. left -= written;
  2534. cur += written;
  2535. if (left <= 0)
  2536. goto err;
  2537. /* Now the '/' */
  2538. *cur = '/';
  2539. /* Adjust left and cur */
  2540. ++cur;
  2541. --left;
  2542. if (left <= 0)
  2543. goto err;
  2544. /* Need minus? */
  2545. if (saved_errno < 0) {
  2546. *cur = '-';
  2547. ++cur;
  2548. --left;
  2549. if (left <= 0)
  2550. goto err;
  2551. }
  2552. /* Emit unsigned_errno */
  2553. written = format_hex_number_sigsafe(unsigned_errno, cur, left);
  2554. if (written <= 0)
  2555. goto err;
  2556. /* Adjust left and cur */
  2557. left -= written;
  2558. cur += written;
  2559. /* Check that we have enough space left for a newline and a NUL */
  2560. if (left <= 1)
  2561. goto err;
  2562. /* Emit the newline and NUL */
  2563. *cur++ = '\n';
  2564. *cur++ = '\0';
  2565. res = (int)(cur - hex_errno - 1);
  2566. goto done;
  2567. err:
  2568. /*
  2569. * In error exit, just write a '\0' in the first char so whatever called
  2570. * this at least won't fall off the end.
  2571. */
  2572. *hex_errno = '\0';
  2573. done:
  2574. return res;
  2575. }
  2576. #endif /* !defined(_WIN32) */
  2577. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  2578. #define DEFAULT_MAX_FD 256
  2579. /** Terminate the process of <b>process_handle</b>, if that process has not
  2580. * already exited.
  2581. *
  2582. * Return 0 if we succeeded in terminating the process (or if the process
  2583. * already exited), and -1 if we tried to kill the process but failed.
  2584. *
  2585. * Based on code originally borrowed from Python's os.kill. */
  2586. int
  2587. tor_terminate_process(process_handle_t *process_handle)
  2588. {
  2589. #ifdef _WIN32
  2590. if (tor_get_exit_code(process_handle, 0, NULL) == PROCESS_EXIT_RUNNING) {
  2591. HANDLE handle = process_handle->pid.hProcess;
  2592. if (!TerminateProcess(handle, 0))
  2593. return -1;
  2594. else
  2595. return 0;
  2596. }
  2597. #else /* !(defined(_WIN32)) */
  2598. if (process_handle->waitpid_cb) {
  2599. /* We haven't got a waitpid yet, so we can just kill off the process. */
  2600. return kill(process_handle->pid, SIGTERM);
  2601. }
  2602. #endif /* defined(_WIN32) */
  2603. return 0; /* We didn't need to kill the process, so report success */
  2604. }
  2605. /** Return the Process ID of <b>process_handle</b>. */
  2606. int
  2607. tor_process_get_pid(process_handle_t *process_handle)
  2608. {
  2609. #ifdef _WIN32
  2610. return (int) process_handle->pid.dwProcessId;
  2611. #else
  2612. return (int) process_handle->pid;
  2613. #endif
  2614. }
  2615. #ifdef _WIN32
  2616. HANDLE
  2617. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  2618. {
  2619. return process_handle->stdout_pipe;
  2620. }
  2621. #else /* !(defined(_WIN32)) */
  2622. /* DOCDOC tor_process_get_stdout_pipe */
  2623. int
  2624. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  2625. {
  2626. return process_handle->stdout_pipe;
  2627. }
  2628. #endif /* defined(_WIN32) */
  2629. /* DOCDOC process_handle_new */
  2630. static process_handle_t *
  2631. process_handle_new(void)
  2632. {
  2633. process_handle_t *out = tor_malloc_zero(sizeof(process_handle_t));
  2634. #ifdef _WIN32
  2635. out->stdin_pipe = INVALID_HANDLE_VALUE;
  2636. out->stdout_pipe = INVALID_HANDLE_VALUE;
  2637. out->stderr_pipe = INVALID_HANDLE_VALUE;
  2638. #else
  2639. out->stdin_pipe = -1;
  2640. out->stdout_pipe = -1;
  2641. out->stderr_pipe = -1;
  2642. #endif /* defined(_WIN32) */
  2643. return out;
  2644. }
  2645. #ifndef _WIN32
  2646. /** Invoked when a process that we've launched via tor_spawn_background() has
  2647. * been found to have terminated.
  2648. */
  2649. static void
  2650. process_handle_waitpid_cb(int status, void *arg)
  2651. {
  2652. process_handle_t *process_handle = arg;
  2653. process_handle->waitpid_exit_status = status;
  2654. clear_waitpid_callback(process_handle->waitpid_cb);
  2655. if (process_handle->status == PROCESS_STATUS_RUNNING)
  2656. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  2657. process_handle->waitpid_cb = 0;
  2658. }
  2659. #endif /* !defined(_WIN32) */
  2660. /**
  2661. * @name child-process states
  2662. *
  2663. * Each of these values represents a possible state that a child process can
  2664. * be in. They're used to determine what to say when telling the parent how
  2665. * far along we were before failure.
  2666. *
  2667. * @{
  2668. */
  2669. #define CHILD_STATE_INIT 0
  2670. #define CHILD_STATE_PIPE 1
  2671. #define CHILD_STATE_MAXFD 2
  2672. #define CHILD_STATE_FORK 3
  2673. #define CHILD_STATE_DUPOUT 4
  2674. #define CHILD_STATE_DUPERR 5
  2675. #define CHILD_STATE_DUPIN 6
  2676. #define CHILD_STATE_CLOSEFD 7
  2677. #define CHILD_STATE_EXEC 8
  2678. #define CHILD_STATE_FAILEXEC 9
  2679. /** @} */
  2680. /**
  2681. * Boolean. If true, then Tor may call execve or CreateProcess via
  2682. * tor_spawn_background.
  2683. **/
  2684. static int may_spawn_background_process = 1;
  2685. /**
  2686. * Turn off may_spawn_background_process, so that all future calls to
  2687. * tor_spawn_background are guaranteed to fail.
  2688. **/
  2689. void
  2690. tor_disable_spawning_background_processes(void)
  2691. {
  2692. may_spawn_background_process = 0;
  2693. }
  2694. /** Start a program in the background. If <b>filename</b> contains a '/', then
  2695. * it will be treated as an absolute or relative path. Otherwise, on
  2696. * non-Windows systems, the system path will be searched for <b>filename</b>.
  2697. * On Windows, only the current directory will be searched. Here, to search the
  2698. * system path (as well as the application directory, current working
  2699. * directory, and system directories), set filename to NULL.
  2700. *
  2701. * The strings in <b>argv</b> will be passed as the command line arguments of
  2702. * the child program (following convention, argv[0] should normally be the
  2703. * filename of the executable, and this must be the case if <b>filename</b> is
  2704. * NULL). The last element of argv must be NULL. A handle to the child process
  2705. * will be returned in process_handle (which must be non-NULL). Read
  2706. * process_handle.status to find out if the process was successfully launched.
  2707. * For convenience, process_handle.status is returned by this function.
  2708. *
  2709. * Some parts of this code are based on the POSIX subprocess module from
  2710. * Python, and example code from
  2711. * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
  2712. */
  2713. int
  2714. tor_spawn_background(const char *const filename, const char **argv,
  2715. process_environment_t *env,
  2716. process_handle_t **process_handle_out)
  2717. {
  2718. if (BUG(may_spawn_background_process == 0)) {
  2719. /* We should never reach this point if we're forbidden to spawn
  2720. * processes. Instead we should have caught the attempt earlier. */
  2721. return PROCESS_STATUS_ERROR;
  2722. }
  2723. #ifdef _WIN32
  2724. HANDLE stdout_pipe_read = NULL;
  2725. HANDLE stdout_pipe_write = NULL;
  2726. HANDLE stderr_pipe_read = NULL;
  2727. HANDLE stderr_pipe_write = NULL;
  2728. HANDLE stdin_pipe_read = NULL;
  2729. HANDLE stdin_pipe_write = NULL;
  2730. process_handle_t *process_handle;
  2731. int status;
  2732. STARTUPINFOA siStartInfo;
  2733. BOOL retval = FALSE;
  2734. SECURITY_ATTRIBUTES saAttr;
  2735. char *joined_argv;
  2736. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  2737. saAttr.bInheritHandle = TRUE;
  2738. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  2739. saAttr.lpSecurityDescriptor = NULL;
  2740. /* Assume failure to start process */
  2741. status = PROCESS_STATUS_ERROR;
  2742. /* Set up pipe for stdout */
  2743. if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, &saAttr, 0)) {
  2744. log_warn(LD_GENERAL,
  2745. "Failed to create pipe for stdout communication with child process: %s",
  2746. format_win32_error(GetLastError()));
  2747. return status;
  2748. }
  2749. if (!SetHandleInformation(stdout_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  2750. log_warn(LD_GENERAL,
  2751. "Failed to configure pipe for stdout communication with child "
  2752. "process: %s", format_win32_error(GetLastError()));
  2753. return status;
  2754. }
  2755. /* Set up pipe for stderr */
  2756. if (!CreatePipe(&stderr_pipe_read, &stderr_pipe_write, &saAttr, 0)) {
  2757. log_warn(LD_GENERAL,
  2758. "Failed to create pipe for stderr communication with child process: %s",
  2759. format_win32_error(GetLastError()));
  2760. return status;
  2761. }
  2762. if (!SetHandleInformation(stderr_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  2763. log_warn(LD_GENERAL,
  2764. "Failed to configure pipe for stderr communication with child "
  2765. "process: %s", format_win32_error(GetLastError()));
  2766. return status;
  2767. }
  2768. /* Set up pipe for stdin */
  2769. if (!CreatePipe(&stdin_pipe_read, &stdin_pipe_write, &saAttr, 0)) {
  2770. log_warn(LD_GENERAL,
  2771. "Failed to create pipe for stdin communication with child process: %s",
  2772. format_win32_error(GetLastError()));
  2773. return status;
  2774. }
  2775. if (!SetHandleInformation(stdin_pipe_write, HANDLE_FLAG_INHERIT, 0)) {
  2776. log_warn(LD_GENERAL,
  2777. "Failed to configure pipe for stdin communication with child "
  2778. "process: %s", format_win32_error(GetLastError()));
  2779. return status;
  2780. }
  2781. /* Create the child process */
  2782. /* Windows expects argv to be a whitespace delimited string, so join argv up
  2783. */
  2784. joined_argv = tor_join_win_cmdline(argv);
  2785. process_handle = process_handle_new();
  2786. process_handle->status = status;
  2787. ZeroMemory(&(process_handle->pid), sizeof(PROCESS_INFORMATION));
  2788. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  2789. siStartInfo.cb = sizeof(STARTUPINFO);
  2790. siStartInfo.hStdError = stderr_pipe_write;
  2791. siStartInfo.hStdOutput = stdout_pipe_write;
  2792. siStartInfo.hStdInput = stdin_pipe_read;
  2793. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  2794. /* Create the child process */
  2795. retval = CreateProcessA(filename, // module name
  2796. joined_argv, // command line
  2797. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  2798. NULL, // process security attributes
  2799. NULL, // primary thread security attributes
  2800. TRUE, // handles are inherited
  2801. /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
  2802. * work?) */
  2803. CREATE_NO_WINDOW, // creation flags
  2804. (env==NULL) ? NULL : env->windows_environment_block,
  2805. NULL, // use parent's current directory
  2806. &siStartInfo, // STARTUPINFO pointer
  2807. &(process_handle->pid)); // receives PROCESS_INFORMATION
  2808. tor_free(joined_argv);
  2809. if (!retval) {
  2810. log_warn(LD_GENERAL,
  2811. "Failed to create child process %s: %s", filename?filename:argv[0],
  2812. format_win32_error(GetLastError()));
  2813. tor_free(process_handle);
  2814. } else {
  2815. /* TODO: Close hProcess and hThread in process_handle->pid? */
  2816. process_handle->stdout_pipe = stdout_pipe_read;
  2817. process_handle->stderr_pipe = stderr_pipe_read;
  2818. process_handle->stdin_pipe = stdin_pipe_write;
  2819. status = process_handle->status = PROCESS_STATUS_RUNNING;
  2820. }
  2821. /* TODO: Close pipes on exit */
  2822. *process_handle_out = process_handle;
  2823. return status;
  2824. #else /* !(defined(_WIN32)) */
  2825. pid_t pid;
  2826. int stdout_pipe[2];
  2827. int stderr_pipe[2];
  2828. int stdin_pipe[2];
  2829. int fd, retval;
  2830. process_handle_t *process_handle;
  2831. int status;
  2832. const char *error_message = SPAWN_ERROR_MESSAGE;
  2833. size_t error_message_length;
  2834. /* Represents where in the process of spawning the program is;
  2835. this is used for printing out the error message */
  2836. unsigned char child_state = CHILD_STATE_INIT;
  2837. char hex_errno[HEX_ERRNO_SIZE + 2]; /* + 1 should be sufficient actually */
  2838. static int max_fd = -1;
  2839. status = PROCESS_STATUS_ERROR;
  2840. /* We do the strlen here because strlen() is not signal handler safe,
  2841. and we are not allowed to use unsafe functions between fork and exec */
  2842. error_message_length = strlen(error_message);
  2843. // child_state = CHILD_STATE_PIPE;
  2844. /* Set up pipe for redirecting stdout, stderr, and stdin of child */
  2845. retval = pipe(stdout_pipe);
  2846. if (-1 == retval) {
  2847. log_warn(LD_GENERAL,
  2848. "Failed to set up pipe for stdout communication with child process: %s",
  2849. strerror(errno));
  2850. return status;
  2851. }
  2852. retval = pipe(stderr_pipe);
  2853. if (-1 == retval) {
  2854. log_warn(LD_GENERAL,
  2855. "Failed to set up pipe for stderr communication with child process: %s",
  2856. strerror(errno));
  2857. close(stdout_pipe[0]);
  2858. close(stdout_pipe[1]);
  2859. return status;
  2860. }
  2861. retval = pipe(stdin_pipe);
  2862. if (-1 == retval) {
  2863. log_warn(LD_GENERAL,
  2864. "Failed to set up pipe for stdin communication with child process: %s",
  2865. strerror(errno));
  2866. close(stdout_pipe[0]);
  2867. close(stdout_pipe[1]);
  2868. close(stderr_pipe[0]);
  2869. close(stderr_pipe[1]);
  2870. return status;
  2871. }
  2872. // child_state = CHILD_STATE_MAXFD;
  2873. #ifdef _SC_OPEN_MAX
  2874. if (-1 == max_fd) {
  2875. max_fd = (int) sysconf(_SC_OPEN_MAX);
  2876. if (max_fd == -1) {
  2877. max_fd = DEFAULT_MAX_FD;
  2878. log_warn(LD_GENERAL,
  2879. "Cannot find maximum file descriptor, assuming %d", max_fd);
  2880. }
  2881. }
  2882. #else /* !(defined(_SC_OPEN_MAX)) */
  2883. max_fd = DEFAULT_MAX_FD;
  2884. #endif /* defined(_SC_OPEN_MAX) */
  2885. // child_state = CHILD_STATE_FORK;
  2886. pid = fork();
  2887. if (0 == pid) {
  2888. /* In child */
  2889. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  2890. /* Attempt to have the kernel issue a SIGTERM if the parent
  2891. * goes away. Certain attributes of the binary being execve()ed
  2892. * will clear this during the execve() call, but it's better
  2893. * than nothing.
  2894. */
  2895. prctl(PR_SET_PDEATHSIG, SIGTERM);
  2896. #endif /* defined(HAVE_SYS_PRCTL_H) && defined(__linux__) */
  2897. child_state = CHILD_STATE_DUPOUT;
  2898. /* Link child stdout to the write end of the pipe */
  2899. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  2900. if (-1 == retval)
  2901. goto error;
  2902. child_state = CHILD_STATE_DUPERR;
  2903. /* Link child stderr to the write end of the pipe */
  2904. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  2905. if (-1 == retval)
  2906. goto error;
  2907. child_state = CHILD_STATE_DUPIN;
  2908. /* Link child stdin to the read end of the pipe */
  2909. retval = dup2(stdin_pipe[0], STDIN_FILENO);
  2910. if (-1 == retval)
  2911. goto error;
  2912. // child_state = CHILD_STATE_CLOSEFD;
  2913. close(stderr_pipe[0]);
  2914. close(stderr_pipe[1]);
  2915. close(stdout_pipe[0]);
  2916. close(stdout_pipe[1]);
  2917. close(stdin_pipe[0]);
  2918. close(stdin_pipe[1]);
  2919. /* Close all other fds, including the read end of the pipe */
  2920. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  2921. * this needless. */
  2922. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  2923. close(fd);
  2924. }
  2925. // child_state = CHILD_STATE_EXEC;
  2926. /* Call the requested program. We need the cast because
  2927. execvp doesn't define argv as const, even though it
  2928. does not modify the arguments */
  2929. if (env)
  2930. execve(filename, (char *const *) argv, env->unixoid_environment_block);
  2931. else {
  2932. static char *new_env[] = { NULL };
  2933. execve(filename, (char *const *) argv, new_env);
  2934. }
  2935. /* If we got here, the exec or open(/dev/null) failed */
  2936. child_state = CHILD_STATE_FAILEXEC;
  2937. error:
  2938. {
  2939. /* XXX: are we leaking fds from the pipe? */
  2940. int n, err=0;
  2941. ssize_t nbytes;
  2942. n = format_helper_exit_status(child_state, errno, hex_errno);
  2943. if (n >= 0) {
  2944. /* Write the error message. GCC requires that we check the return
  2945. value, but there is nothing we can do if it fails */
  2946. /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
  2947. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  2948. err = (nbytes < 0);
  2949. nbytes = write(STDOUT_FILENO, hex_errno, n);
  2950. err += (nbytes < 0);
  2951. }
  2952. _exit(err?254:255); // exit ok: in child.
  2953. }
  2954. /* Never reached, but avoids compiler warning */
  2955. return status; // LCOV_EXCL_LINE
  2956. }
  2957. /* In parent */
  2958. if (-1 == pid) {
  2959. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  2960. close(stdin_pipe[0]);
  2961. close(stdin_pipe[1]);
  2962. close(stdout_pipe[0]);
  2963. close(stdout_pipe[1]);
  2964. close(stderr_pipe[0]);
  2965. close(stderr_pipe[1]);
  2966. return status;
  2967. }
  2968. process_handle = process_handle_new();
  2969. process_handle->status = status;
  2970. process_handle->pid = pid;
  2971. /* TODO: If the child process forked but failed to exec, waitpid it */
  2972. /* Return read end of the pipes to caller, and close write end */
  2973. process_handle->stdout_pipe = stdout_pipe[0];
  2974. retval = close(stdout_pipe[1]);
  2975. if (-1 == retval) {
  2976. log_warn(LD_GENERAL,
  2977. "Failed to close write end of stdout pipe in parent process: %s",
  2978. strerror(errno));
  2979. }
  2980. process_handle->waitpid_cb = set_waitpid_callback(pid,
  2981. process_handle_waitpid_cb,
  2982. process_handle);
  2983. process_handle->stderr_pipe = stderr_pipe[0];
  2984. retval = close(stderr_pipe[1]);
  2985. if (-1 == retval) {
  2986. log_warn(LD_GENERAL,
  2987. "Failed to close write end of stderr pipe in parent process: %s",
  2988. strerror(errno));
  2989. }
  2990. /* Return write end of the stdin pipe to caller, and close the read end */
  2991. process_handle->stdin_pipe = stdin_pipe[1];
  2992. retval = close(stdin_pipe[0]);
  2993. if (-1 == retval) {
  2994. log_warn(LD_GENERAL,
  2995. "Failed to close read end of stdin pipe in parent process: %s",
  2996. strerror(errno));
  2997. }
  2998. status = process_handle->status = PROCESS_STATUS_RUNNING;
  2999. /* Set stdin/stdout/stderr pipes to be non-blocking */
  3000. if (fcntl(process_handle->stdout_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  3001. fcntl(process_handle->stderr_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  3002. fcntl(process_handle->stdin_pipe, F_SETFL, O_NONBLOCK) < 0) {
  3003. log_warn(LD_GENERAL, "Failed to set stderror/stdout/stdin pipes "
  3004. "nonblocking in parent process: %s", strerror(errno));
  3005. }
  3006. *process_handle_out = process_handle;
  3007. return status;
  3008. #endif /* defined(_WIN32) */
  3009. }
  3010. /** Destroy all resources allocated by the process handle in
  3011. * <b>process_handle</b>.
  3012. * If <b>also_terminate_process</b> is true, also terminate the
  3013. * process of the process handle. */
  3014. MOCK_IMPL(void,
  3015. tor_process_handle_destroy,(process_handle_t *process_handle,
  3016. int also_terminate_process))
  3017. {
  3018. if (!process_handle)
  3019. return;
  3020. if (also_terminate_process) {
  3021. if (tor_terminate_process(process_handle) < 0) {
  3022. const char *errstr =
  3023. #ifdef _WIN32
  3024. format_win32_error(GetLastError());
  3025. #else
  3026. strerror(errno);
  3027. #endif
  3028. log_notice(LD_GENERAL, "Failed to terminate process with "
  3029. "PID '%d' ('%s').", tor_process_get_pid(process_handle),
  3030. errstr);
  3031. } else {
  3032. log_info(LD_GENERAL, "Terminated process with PID '%d'.",
  3033. tor_process_get_pid(process_handle));
  3034. }
  3035. }
  3036. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  3037. #ifdef _WIN32
  3038. if (process_handle->stdout_pipe)
  3039. CloseHandle(process_handle->stdout_pipe);
  3040. if (process_handle->stderr_pipe)
  3041. CloseHandle(process_handle->stderr_pipe);
  3042. if (process_handle->stdin_pipe)
  3043. CloseHandle(process_handle->stdin_pipe);
  3044. #else /* !(defined(_WIN32)) */
  3045. close(process_handle->stdout_pipe);
  3046. close(process_handle->stderr_pipe);
  3047. close(process_handle->stdin_pipe);
  3048. clear_waitpid_callback(process_handle->waitpid_cb);
  3049. #endif /* defined(_WIN32) */
  3050. memset(process_handle, 0x0f, sizeof(process_handle_t));
  3051. tor_free(process_handle);
  3052. }
  3053. /** Get the exit code of a process specified by <b>process_handle</b> and store
  3054. * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
  3055. * to true, the call will block until the process has exited. Otherwise if
  3056. * the process is still running, the function will return
  3057. * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
  3058. * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
  3059. * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
  3060. * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
  3061. * probably not work in Tor, because waitpid() is called in main.c to reap any
  3062. * terminated child processes.*/
  3063. int
  3064. tor_get_exit_code(process_handle_t *process_handle,
  3065. int block, int *exit_code)
  3066. {
  3067. #ifdef _WIN32
  3068. DWORD retval;
  3069. BOOL success;
  3070. if (block) {
  3071. /* Wait for the process to exit */
  3072. retval = WaitForSingleObject(process_handle->pid.hProcess, INFINITE);
  3073. if (retval != WAIT_OBJECT_0) {
  3074. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3075. (int)retval, format_win32_error(GetLastError()));
  3076. return PROCESS_EXIT_ERROR;
  3077. }
  3078. } else {
  3079. retval = WaitForSingleObject(process_handle->pid.hProcess, 0);
  3080. if (WAIT_TIMEOUT == retval) {
  3081. /* Process has not exited */
  3082. return PROCESS_EXIT_RUNNING;
  3083. } else if (retval != WAIT_OBJECT_0) {
  3084. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3085. (int)retval, format_win32_error(GetLastError()));
  3086. return PROCESS_EXIT_ERROR;
  3087. }
  3088. }
  3089. if (exit_code != NULL) {
  3090. success = GetExitCodeProcess(process_handle->pid.hProcess,
  3091. (PDWORD)exit_code);
  3092. if (!success) {
  3093. log_warn(LD_GENERAL, "GetExitCodeProcess() failed: %s",
  3094. format_win32_error(GetLastError()));
  3095. return PROCESS_EXIT_ERROR;
  3096. }
  3097. }
  3098. #else /* !(defined(_WIN32)) */
  3099. int stat_loc;
  3100. int retval;
  3101. if (process_handle->waitpid_cb) {
  3102. /* We haven't processed a SIGCHLD yet. */
  3103. retval = waitpid(process_handle->pid, &stat_loc, block?0:WNOHANG);
  3104. if (retval == process_handle->pid) {
  3105. clear_waitpid_callback(process_handle->waitpid_cb);
  3106. process_handle->waitpid_cb = NULL;
  3107. process_handle->waitpid_exit_status = stat_loc;
  3108. }
  3109. } else {
  3110. /* We already got a SIGCHLD for this process, and handled it. */
  3111. retval = process_handle->pid;
  3112. stat_loc = process_handle->waitpid_exit_status;
  3113. }
  3114. if (!block && 0 == retval) {
  3115. /* Process has not exited */
  3116. return PROCESS_EXIT_RUNNING;
  3117. } else if (retval != process_handle->pid) {
  3118. log_warn(LD_GENERAL, "waitpid() failed for PID %d: %s",
  3119. (int)process_handle->pid, strerror(errno));
  3120. return PROCESS_EXIT_ERROR;
  3121. }
  3122. if (!WIFEXITED(stat_loc)) {
  3123. log_warn(LD_GENERAL, "Process %d did not exit normally",
  3124. (int)process_handle->pid);
  3125. return PROCESS_EXIT_ERROR;
  3126. }
  3127. if (exit_code != NULL)
  3128. *exit_code = WEXITSTATUS(stat_loc);
  3129. #endif /* defined(_WIN32) */
  3130. return PROCESS_EXIT_EXITED;
  3131. }
  3132. /** Helper: return the number of characters in <b>s</b> preceding the first
  3133. * occurrence of <b>ch</b>. If <b>ch</b> does not occur in <b>s</b>, return
  3134. * the length of <b>s</b>. Should be equivalent to strspn(s, "ch"). */
  3135. static inline size_t
  3136. str_num_before(const char *s, char ch)
  3137. {
  3138. const char *cp = strchr(s, ch);
  3139. if (cp)
  3140. return cp - s;
  3141. else
  3142. return strlen(s);
  3143. }
  3144. /** Return non-zero iff getenv would consider <b>s1</b> and <b>s2</b>
  3145. * to have the same name as strings in a process's environment. */
  3146. int
  3147. environment_variable_names_equal(const char *s1, const char *s2)
  3148. {
  3149. size_t s1_name_len = str_num_before(s1, '=');
  3150. size_t s2_name_len = str_num_before(s2, '=');
  3151. return (s1_name_len == s2_name_len &&
  3152. tor_memeq(s1, s2, s1_name_len));
  3153. }
  3154. /** Free <b>env</b> (assuming it was produced by
  3155. * process_environment_make). */
  3156. void
  3157. process_environment_free_(process_environment_t *env)
  3158. {
  3159. if (env == NULL) return;
  3160. /* As both an optimization hack to reduce consing on Unixoid systems
  3161. * and a nice way to ensure that some otherwise-Windows-specific
  3162. * code will always get tested before changes to it get merged, the
  3163. * strings which env->unixoid_environment_block points to are packed
  3164. * into env->windows_environment_block. */
  3165. tor_free(env->unixoid_environment_block);
  3166. tor_free(env->windows_environment_block);
  3167. tor_free(env);
  3168. }
  3169. /** Make a process_environment_t containing the environment variables
  3170. * specified in <b>env_vars</b> (as C strings of the form
  3171. * "NAME=VALUE"). */
  3172. process_environment_t *
  3173. process_environment_make(struct smartlist_t *env_vars)
  3174. {
  3175. process_environment_t *env = tor_malloc_zero(sizeof(process_environment_t));
  3176. int n_env_vars = smartlist_len(env_vars);
  3177. int i;
  3178. size_t total_env_length;
  3179. smartlist_t *env_vars_sorted;
  3180. tor_assert(n_env_vars + 1 != 0);
  3181. env->unixoid_environment_block = tor_calloc(n_env_vars + 1, sizeof(char *));
  3182. /* env->unixoid_environment_block is already NULL-terminated,
  3183. * because we assume that NULL == 0 (and check that during compilation). */
  3184. total_env_length = 1; /* terminating NUL of terminating empty string */
  3185. for (i = 0; i < n_env_vars; ++i) {
  3186. const char *s = smartlist_get(env_vars, (int)i);
  3187. size_t slen = strlen(s);
  3188. tor_assert(slen + 1 != 0);
  3189. tor_assert(slen + 1 < SIZE_MAX - total_env_length);
  3190. total_env_length += slen + 1;
  3191. }
  3192. env->windows_environment_block = tor_malloc_zero(total_env_length);
  3193. /* env->windows_environment_block is already
  3194. * (NUL-terminated-empty-string)-terminated. */
  3195. /* Some versions of Windows supposedly require that environment
  3196. * blocks be sorted. Or maybe some Windows programs (or their
  3197. * runtime libraries) fail to look up strings in non-sorted
  3198. * environment blocks.
  3199. *
  3200. * Also, sorting strings makes it easy to find duplicate environment
  3201. * variables and environment-variable strings without an '=' on all
  3202. * OSes, and they can cause badness. Let's complain about those. */
  3203. env_vars_sorted = smartlist_new();
  3204. smartlist_add_all(env_vars_sorted, env_vars);
  3205. smartlist_sort_strings(env_vars_sorted);
  3206. /* Now copy the strings into the environment blocks. */
  3207. {
  3208. char *cp = env->windows_environment_block;
  3209. const char *prev_env_var = NULL;
  3210. for (i = 0; i < n_env_vars; ++i) {
  3211. const char *s = smartlist_get(env_vars_sorted, (int)i);
  3212. size_t slen = strlen(s);
  3213. size_t s_name_len = str_num_before(s, '=');
  3214. if (s_name_len == slen) {
  3215. log_warn(LD_GENERAL,
  3216. "Preparing an environment containing a variable "
  3217. "without a value: %s",
  3218. s);
  3219. }
  3220. if (prev_env_var != NULL &&
  3221. environment_variable_names_equal(s, prev_env_var)) {
  3222. log_warn(LD_GENERAL,
  3223. "Preparing an environment containing two variables "
  3224. "with the same name: %s and %s",
  3225. prev_env_var, s);
  3226. }
  3227. prev_env_var = s;
  3228. /* Actually copy the string into the environment. */
  3229. memcpy(cp, s, slen+1);
  3230. env->unixoid_environment_block[i] = cp;
  3231. cp += slen+1;
  3232. }
  3233. tor_assert(cp == env->windows_environment_block + total_env_length - 1);
  3234. }
  3235. smartlist_free(env_vars_sorted);
  3236. return env;
  3237. }
  3238. /** Return a newly allocated smartlist containing every variable in
  3239. * this process's environment, as a NUL-terminated string of the form
  3240. * "NAME=VALUE". Note that on some/many/most/all OSes, the parent
  3241. * process can put strings not of that form in our environment;
  3242. * callers should try to not get crashed by that.
  3243. *
  3244. * The returned strings are heap-allocated, and must be freed by the
  3245. * caller. */
  3246. struct smartlist_t *
  3247. get_current_process_environment_variables(void)
  3248. {
  3249. smartlist_t *sl = smartlist_new();
  3250. char **environ_tmp; /* Not const char ** ? Really? */
  3251. for (environ_tmp = get_environment(); *environ_tmp; ++environ_tmp) {
  3252. smartlist_add_strdup(sl, *environ_tmp);
  3253. }
  3254. return sl;
  3255. }
  3256. /** For each string s in <b>env_vars</b> such that
  3257. * environment_variable_names_equal(s, <b>new_var</b>), remove it; if
  3258. * <b>free_p</b> is non-zero, call <b>free_old</b>(s). If
  3259. * <b>new_var</b> contains '=', insert it into <b>env_vars</b>. */
  3260. void
  3261. set_environment_variable_in_smartlist(struct smartlist_t *env_vars,
  3262. const char *new_var,
  3263. void (*free_old)(void*),
  3264. int free_p)
  3265. {
  3266. SMARTLIST_FOREACH_BEGIN(env_vars, const char *, s) {
  3267. if (environment_variable_names_equal(s, new_var)) {
  3268. SMARTLIST_DEL_CURRENT(env_vars, s);
  3269. if (free_p) {
  3270. free_old((void *)s);
  3271. }
  3272. }
  3273. } SMARTLIST_FOREACH_END(s);
  3274. if (strchr(new_var, '=') != NULL) {
  3275. smartlist_add(env_vars, (void *)new_var);
  3276. }
  3277. }
  3278. #ifdef _WIN32
  3279. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3280. * <b>hProcess</b> is NULL, the function will return immediately if there is
  3281. * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
  3282. * to the process owning the <b>h</b>. In this case, the function will exit
  3283. * only once the process has exited, or <b>count</b> bytes are read. Returns
  3284. * the number of bytes read, or -1 on error. */
  3285. ssize_t
  3286. tor_read_all_handle(HANDLE h, char *buf, size_t count,
  3287. const process_handle_t *process)
  3288. {
  3289. size_t numread = 0;
  3290. BOOL retval;
  3291. DWORD byte_count;
  3292. BOOL process_exited = FALSE;
  3293. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  3294. return -1;
  3295. while (numread < count) {
  3296. /* Check if there is anything to read */
  3297. retval = PeekNamedPipe(h, NULL, 0, NULL, &byte_count, NULL);
  3298. if (!retval) {
  3299. log_warn(LD_GENERAL,
  3300. "Failed to peek from handle: %s",
  3301. format_win32_error(GetLastError()));
  3302. return -1;
  3303. } else if (0 == byte_count) {
  3304. /* Nothing available: process exited or it is busy */
  3305. /* Exit if we don't know whether the process is running */
  3306. if (NULL == process)
  3307. break;
  3308. /* The process exited and there's nothing left to read from it */
  3309. if (process_exited)
  3310. break;
  3311. /* If process is not running, check for output one more time in case
  3312. it wrote something after the peek was performed. Otherwise keep on
  3313. waiting for output */
  3314. tor_assert(process != NULL);
  3315. byte_count = WaitForSingleObject(process->pid.hProcess, 0);
  3316. if (WAIT_TIMEOUT != byte_count)
  3317. process_exited = TRUE;
  3318. continue;
  3319. }
  3320. /* There is data to read; read it */
  3321. retval = ReadFile(h, buf+numread, count-numread, &byte_count, NULL);
  3322. tor_assert(byte_count + numread <= count);
  3323. if (!retval) {
  3324. log_warn(LD_GENERAL, "Failed to read from handle: %s",
  3325. format_win32_error(GetLastError()));
  3326. return -1;
  3327. } else if (0 == byte_count) {
  3328. /* End of file */
  3329. break;
  3330. }
  3331. numread += byte_count;
  3332. }
  3333. return (ssize_t)numread;
  3334. }
  3335. #else /* !(defined(_WIN32)) */
  3336. /** Read from a handle <b>fd</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3337. * <b>process</b> is NULL, the function will return immediately if there is
  3338. * nothing more to read. Otherwise data will be read until end of file, or
  3339. * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
  3340. * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
  3341. * file has been reached. */
  3342. ssize_t
  3343. tor_read_all_handle(int fd, char *buf, size_t count,
  3344. const process_handle_t *process,
  3345. int *eof)
  3346. {
  3347. size_t numread = 0;
  3348. ssize_t result;
  3349. if (eof)
  3350. *eof = 0;
  3351. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  3352. return -1;
  3353. while (numread < count) {
  3354. result = read(fd, buf+numread, count-numread);
  3355. if (result == 0) {
  3356. log_debug(LD_GENERAL, "read() reached end of file");
  3357. if (eof)
  3358. *eof = 1;
  3359. break;
  3360. } else if (result < 0 && errno == EAGAIN) {
  3361. if (process)
  3362. continue;
  3363. else
  3364. break;
  3365. } else if (result < 0) {
  3366. log_warn(LD_GENERAL, "read() failed: %s", strerror(errno));
  3367. return -1;
  3368. }
  3369. numread += result;
  3370. }
  3371. log_debug(LD_GENERAL, "read() read %d bytes from handle", (int)numread);
  3372. return (ssize_t)numread;
  3373. }
  3374. #endif /* defined(_WIN32) */
  3375. /** Read from stdout of a process until the process exits. */
  3376. ssize_t
  3377. tor_read_all_from_process_stdout(const process_handle_t *process_handle,
  3378. char *buf, size_t count)
  3379. {
  3380. #ifdef _WIN32
  3381. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  3382. process_handle);
  3383. #else
  3384. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  3385. process_handle, NULL);
  3386. #endif /* defined(_WIN32) */
  3387. }
  3388. /** Read from stdout of a process until the process exits. */
  3389. ssize_t
  3390. tor_read_all_from_process_stderr(const process_handle_t *process_handle,
  3391. char *buf, size_t count)
  3392. {
  3393. #ifdef _WIN32
  3394. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  3395. process_handle);
  3396. #else
  3397. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  3398. process_handle, NULL);
  3399. #endif /* defined(_WIN32) */
  3400. }
  3401. /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
  3402. * modified. The resulting smartlist will consist of pointers to buf, so there
  3403. * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
  3404. * string. <b>len</b> should be set to the length of the buffer excluding the
  3405. * NUL. Non-printable characters (including NUL) will be replaced with "." */
  3406. int
  3407. tor_split_lines(smartlist_t *sl, char *buf, int len)
  3408. {
  3409. /* Index in buf of the start of the current line */
  3410. int start = 0;
  3411. /* Index in buf of the current character being processed */
  3412. int cur = 0;
  3413. /* Are we currently in a line */
  3414. char in_line = 0;
  3415. /* Loop over string */
  3416. while (cur < len) {
  3417. /* Loop until end of line or end of string */
  3418. for (; cur < len; cur++) {
  3419. if (in_line) {
  3420. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  3421. /* End of line */
  3422. buf[cur] = '\0';
  3423. /* Point cur to the next line */
  3424. cur++;
  3425. /* Line starts at start and ends with a nul */
  3426. break;
  3427. } else {
  3428. if (!TOR_ISPRINT(buf[cur]))
  3429. buf[cur] = '.';
  3430. }
  3431. } else {
  3432. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  3433. /* Skip leading vertical space */
  3434. ;
  3435. } else {
  3436. in_line = 1;
  3437. start = cur;
  3438. if (!TOR_ISPRINT(buf[cur]))
  3439. buf[cur] = '.';
  3440. }
  3441. }
  3442. }
  3443. /* We are at the end of the line or end of string. If in_line is true there
  3444. * is a line which starts at buf+start and ends at a NUL. cur points to
  3445. * the character after the NUL. */
  3446. if (in_line)
  3447. smartlist_add(sl, (void *)(buf+start));
  3448. in_line = 0;
  3449. }
  3450. return smartlist_len(sl);
  3451. }
  3452. /** Return a string corresponding to <b>stream_status</b>. */
  3453. const char *
  3454. stream_status_to_string(enum stream_status stream_status)
  3455. {
  3456. switch (stream_status) {
  3457. case IO_STREAM_OKAY:
  3458. return "okay";
  3459. case IO_STREAM_EAGAIN:
  3460. return "temporarily unavailable";
  3461. case IO_STREAM_TERM:
  3462. return "terminated";
  3463. case IO_STREAM_CLOSED:
  3464. return "closed";
  3465. default:
  3466. tor_fragile_assert();
  3467. return "unknown";
  3468. }
  3469. }
  3470. #ifdef _WIN32
  3471. /** Return a smartlist containing lines outputted from
  3472. * <b>handle</b>. Return NULL on error, and set
  3473. * <b>stream_status_out</b> appropriately. */
  3474. MOCK_IMPL(smartlist_t *,
  3475. tor_get_lines_from_handle, (HANDLE *handle,
  3476. enum stream_status *stream_status_out))
  3477. {
  3478. int pos;
  3479. char stdout_buf[600] = {0};
  3480. smartlist_t *lines = NULL;
  3481. tor_assert(stream_status_out);
  3482. *stream_status_out = IO_STREAM_TERM;
  3483. pos = tor_read_all_handle(handle, stdout_buf, sizeof(stdout_buf) - 1, NULL);
  3484. if (pos < 0) {
  3485. *stream_status_out = IO_STREAM_TERM;
  3486. return NULL;
  3487. }
  3488. if (pos == 0) {
  3489. *stream_status_out = IO_STREAM_EAGAIN;
  3490. return NULL;
  3491. }
  3492. /* End with a null even if there isn't a \r\n at the end */
  3493. /* TODO: What if this is a partial line? */
  3494. stdout_buf[pos] = '\0';
  3495. /* Split up the buffer */
  3496. lines = smartlist_new();
  3497. tor_split_lines(lines, stdout_buf, pos);
  3498. /* Currently 'lines' is populated with strings residing on the
  3499. stack. Replace them with their exact copies on the heap: */
  3500. SMARTLIST_FOREACH(lines, char *, line,
  3501. SMARTLIST_REPLACE_CURRENT(lines, line, tor_strdup(line)));
  3502. *stream_status_out = IO_STREAM_OKAY;
  3503. return lines;
  3504. }
  3505. #else /* !(defined(_WIN32)) */
  3506. /** Return a smartlist containing lines outputted from
  3507. * <b>fd</b>. Return NULL on error, and set
  3508. * <b>stream_status_out</b> appropriately. */
  3509. MOCK_IMPL(smartlist_t *,
  3510. tor_get_lines_from_handle, (int fd, enum stream_status *stream_status_out))
  3511. {
  3512. enum stream_status stream_status;
  3513. char stdout_buf[400];
  3514. smartlist_t *lines = NULL;
  3515. while (1) {
  3516. memset(stdout_buf, 0, sizeof(stdout_buf));
  3517. stream_status = get_string_from_pipe(fd,
  3518. stdout_buf, sizeof(stdout_buf) - 1);
  3519. if (stream_status != IO_STREAM_OKAY)
  3520. goto done;
  3521. if (!lines) lines = smartlist_new();
  3522. smartlist_split_string(lines, stdout_buf, "\n", 0, 0);
  3523. }
  3524. done:
  3525. *stream_status_out = stream_status;
  3526. return lines;
  3527. }
  3528. #endif /* defined(_WIN32) */
  3529. /** Reads from <b>fd</b> and stores input in <b>buf_out</b> making
  3530. * sure it's below <b>count</b> bytes.
  3531. * If the string has a trailing newline, we strip it off.
  3532. *
  3533. * This function is specifically created to handle input from managed
  3534. * proxies, according to the pluggable transports spec. Make sure it
  3535. * fits your needs before using it.
  3536. *
  3537. * Returns:
  3538. * IO_STREAM_CLOSED: If the stream is closed.
  3539. * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
  3540. * later.
  3541. * IO_STREAM_TERM: If something is wrong with the stream.
  3542. * IO_STREAM_OKAY: If everything went okay and we got a string
  3543. * in <b>buf_out</b>. */
  3544. enum stream_status
  3545. get_string_from_pipe(int fd, char *buf_out, size_t count)
  3546. {
  3547. ssize_t ret;
  3548. tor_assert(count <= INT_MAX);
  3549. ret = read(fd, buf_out, count);
  3550. if (ret == 0)
  3551. return IO_STREAM_CLOSED;
  3552. else if (ret < 0 && errno == EAGAIN)
  3553. return IO_STREAM_EAGAIN;
  3554. else if (ret < 0)
  3555. return IO_STREAM_TERM;
  3556. if (buf_out[ret - 1] == '\n') {
  3557. /* Remove the trailing newline */
  3558. buf_out[ret - 1] = '\0';
  3559. } else
  3560. buf_out[ret] = '\0';
  3561. return IO_STREAM_OKAY;
  3562. }
  3563. /** Initialize the insecure RNG <b>rng</b> from a seed value <b>seed</b>. */
  3564. void
  3565. tor_init_weak_random(tor_weak_rng_t *rng, unsigned seed)
  3566. {
  3567. rng->state = (uint32_t)(seed & 0x7fffffff);
  3568. }
  3569. /** Return a randomly chosen value in the range 0..TOR_WEAK_RANDOM_MAX based
  3570. * on the RNG state of <b>rng</b>. This entropy will not be cryptographically
  3571. * strong; do not rely on it for anything an adversary should not be able to
  3572. * predict. */
  3573. int32_t
  3574. tor_weak_random(tor_weak_rng_t *rng)
  3575. {
  3576. /* Here's a linear congruential generator. OpenBSD and glibc use these
  3577. * parameters; they aren't too bad, and should have maximal period over the
  3578. * range 0..INT32_MAX. We don't want to use the platform rand() or random(),
  3579. * since some platforms have bad weak RNGs that only return values in the
  3580. * range 0..INT16_MAX, which just isn't enough. */
  3581. rng->state = (rng->state * 1103515245 + 12345) & 0x7fffffff;
  3582. return (int32_t) rng->state;
  3583. }
  3584. /** Return a random number in the range [0 , <b>top</b>). {That is, the range
  3585. * of integers i such that 0 <= i < top.} Chooses uniformly. Requires that
  3586. * top is greater than 0. This randomness is not cryptographically strong; do
  3587. * not rely on it for anything an adversary should not be able to predict. */
  3588. int32_t
  3589. tor_weak_random_range(tor_weak_rng_t *rng, int32_t top)
  3590. {
  3591. /* We don't want to just do tor_weak_random() % top, since random() is often
  3592. * implemented with an LCG whose modulus is a power of 2, and those are
  3593. * cyclic in their low-order bits. */
  3594. int divisor, result;
  3595. tor_assert(top > 0);
  3596. divisor = TOR_WEAK_RANDOM_MAX / top;
  3597. do {
  3598. result = (int32_t)(tor_weak_random(rng) / divisor);
  3599. } while (result >= top);
  3600. return result;
  3601. }
  3602. /** Cast a given double value to a int64_t. Return 0 if number is NaN.
  3603. * Returns either INT64_MIN or INT64_MAX if number is outside of the int64_t
  3604. * range. */
  3605. int64_t
  3606. clamp_double_to_int64(double number)
  3607. {
  3608. int exponent;
  3609. #if defined(MINGW_ANY) && GCC_VERSION >= 409
  3610. /*
  3611. Mingw's math.h uses gcc's __builtin_choose_expr() facility to declare
  3612. isnan, isfinite, and signbit. But as implemented in at least some
  3613. versions of gcc, __builtin_choose_expr() can generate type warnings
  3614. even from branches that are not taken. So, suppress those warnings.
  3615. */
  3616. #define PROBLEMATIC_FLOAT_CONVERSION_WARNING
  3617. DISABLE_GCC_WARNING(float-conversion)
  3618. #endif /* defined(MINGW_ANY) && GCC_VERSION >= 409 */
  3619. /*
  3620. With clang 4.0 we apparently run into "double promotion" warnings here,
  3621. since clang thinks we're promoting a double to a long double.
  3622. */
  3623. #if defined(__clang__)
  3624. #if __has_warning("-Wdouble-promotion")
  3625. #define PROBLEMATIC_DOUBLE_PROMOTION_WARNING
  3626. DISABLE_GCC_WARNING(double-promotion)
  3627. #endif
  3628. #endif /* defined(__clang__) */
  3629. /* NaN is a special case that can't be used with the logic below. */
  3630. if (isnan(number)) {
  3631. return 0;
  3632. }
  3633. /* Time to validate if result can overflows a int64_t value. Fun with
  3634. * float! Find that exponent exp such that
  3635. * number == x * 2^exp
  3636. * for some x with abs(x) in [0.5, 1.0). Note that this implies that the
  3637. * magnitude of number is strictly less than 2^exp.
  3638. *
  3639. * If number is infinite, the call to frexp is legal but the contents of
  3640. * are exponent unspecified. */
  3641. frexp(number, &exponent);
  3642. /* If the magnitude of number is strictly less than 2^63, the truncated
  3643. * version of number is guaranteed to be representable. The only
  3644. * representable integer for which this is not the case is INT64_MIN, but
  3645. * it is covered by the logic below. */
  3646. if (isfinite(number) && exponent <= 63) {
  3647. return (int64_t)number;
  3648. }
  3649. /* Handle infinities and finite numbers with magnitude >= 2^63. */
  3650. return signbit(number) ? INT64_MIN : INT64_MAX;
  3651. #ifdef PROBLEMATIC_DOUBLE_PROMOTION_WARNING
  3652. ENABLE_GCC_WARNING(double-promotion)
  3653. #endif
  3654. #ifdef PROBLEMATIC_FLOAT_CONVERSION_WARNING
  3655. ENABLE_GCC_WARNING(float-conversion)
  3656. #endif
  3657. }
  3658. /** Return a uint64_t value from <b>a</b> in network byte order. */
  3659. uint64_t
  3660. tor_htonll(uint64_t a)
  3661. {
  3662. #ifdef WORDS_BIGENDIAN
  3663. /* Big endian. */
  3664. return a;
  3665. #else /* WORDS_BIGENDIAN */
  3666. /* Little endian. The worst... */
  3667. return htonl((uint32_t)(a>>32)) |
  3668. (((uint64_t)htonl((uint32_t)a))<<32);
  3669. #endif /* defined(WORDS_BIGENDIAN) */
  3670. }
  3671. /** Return a uint64_t value from <b>a</b> in host byte order. */
  3672. uint64_t
  3673. tor_ntohll(uint64_t a)
  3674. {
  3675. return tor_htonll(a);
  3676. }