util.c 122 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189
  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. * Rate limiting
  1164. * ===== */
  1165. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return the number
  1166. * of calls to rate_limit_is_ready (including this one!) since the last time
  1167. * rate_limit_is_ready returned nonzero. Otherwise return 0.
  1168. * If the call number hits <b>RATELIM_TOOMANY</b> limit, drop a warning
  1169. * about this event and stop counting. */
  1170. static int
  1171. rate_limit_is_ready(ratelim_t *lim, time_t now)
  1172. {
  1173. if (lim->rate + lim->last_allowed <= now) {
  1174. int res = lim->n_calls_since_last_time + 1;
  1175. lim->last_allowed = now;
  1176. lim->n_calls_since_last_time = 0;
  1177. return res;
  1178. } else {
  1179. if (lim->n_calls_since_last_time <= RATELIM_TOOMANY) {
  1180. ++lim->n_calls_since_last_time;
  1181. }
  1182. return 0;
  1183. }
  1184. }
  1185. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return a newly
  1186. * allocated string indicating how many messages were suppressed, suitable to
  1187. * append to a log message. Otherwise return NULL. */
  1188. char *
  1189. rate_limit_log(ratelim_t *lim, time_t now)
  1190. {
  1191. int n;
  1192. if ((n = rate_limit_is_ready(lim, now))) {
  1193. if (n == 1) {
  1194. return tor_strdup("");
  1195. } else {
  1196. char *cp=NULL;
  1197. const char *opt_over = (n >= RATELIM_TOOMANY) ? "over " : "";
  1198. /* XXXX this is not exactly correct: the messages could have occurred
  1199. * any time between the old value of lim->allowed and now. */
  1200. tor_asprintf(&cp,
  1201. " [%s%d similar message(s) suppressed in last %d seconds]",
  1202. opt_over, n-1, lim->rate);
  1203. return cp;
  1204. }
  1205. } else {
  1206. return NULL;
  1207. }
  1208. }
  1209. /* =====
  1210. * File helpers
  1211. * ===== */
  1212. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1213. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1214. * was returned by open(). Return the number of bytes written, or -1
  1215. * on error. Only use if fd is a blocking fd. */
  1216. ssize_t
  1217. write_all(tor_socket_t fd, const char *buf, size_t count, int isSocket)
  1218. {
  1219. size_t written = 0;
  1220. ssize_t result;
  1221. raw_assert(count < SSIZE_MAX);
  1222. while (written != count) {
  1223. if (isSocket)
  1224. result = tor_socket_send(fd, buf+written, count-written, 0);
  1225. else
  1226. result = write((int)fd, buf+written, count-written);
  1227. if (result<0)
  1228. return -1;
  1229. written += result;
  1230. }
  1231. return (ssize_t)count;
  1232. }
  1233. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1234. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1235. * was returned by socket() or accept(), and 0 if fd was returned by
  1236. * open(). Return the number of bytes read, or -1 on error. Only use
  1237. * if fd is a blocking fd. */
  1238. ssize_t
  1239. read_all(tor_socket_t fd, char *buf, size_t count, int isSocket)
  1240. {
  1241. size_t numread = 0;
  1242. ssize_t result;
  1243. if (count > SIZE_T_CEILING || count > SSIZE_MAX) {
  1244. errno = EINVAL;
  1245. return -1;
  1246. }
  1247. while (numread < count) {
  1248. if (isSocket)
  1249. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1250. else
  1251. result = read((int)fd, buf+numread, count-numread);
  1252. if (result<0)
  1253. return -1;
  1254. else if (result == 0)
  1255. break;
  1256. numread += result;
  1257. }
  1258. return (ssize_t)numread;
  1259. }
  1260. /*
  1261. * Filesystem operations.
  1262. */
  1263. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1264. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1265. * the root of a disk. */
  1266. static void
  1267. clean_name_for_stat(char *name)
  1268. {
  1269. #ifdef _WIN32
  1270. size_t len = strlen(name);
  1271. if (!len)
  1272. return;
  1273. if (name[len-1]=='\\' || name[len-1]=='/') {
  1274. if (len == 1 || (len==3 && name[1]==':'))
  1275. return;
  1276. name[len-1]='\0';
  1277. }
  1278. #else /* !(defined(_WIN32)) */
  1279. (void)name;
  1280. #endif /* defined(_WIN32) */
  1281. }
  1282. /** Wrapper for unlink() to make it mockable for the test suite; returns 0
  1283. * if unlinking the file succeeded, -1 and sets errno if unlinking fails.
  1284. */
  1285. MOCK_IMPL(int,
  1286. tor_unlink,(const char *pathname))
  1287. {
  1288. return unlink(pathname);
  1289. }
  1290. /** Return:
  1291. * FN_ERROR if filename can't be read, is NULL, or is zero-length,
  1292. * FN_NOENT if it doesn't exist,
  1293. * FN_FILE if it is a non-empty regular file, or a FIFO on unix-like systems,
  1294. * FN_EMPTY for zero-byte regular files,
  1295. * FN_DIR if it's a directory, and
  1296. * FN_ERROR for any other file type.
  1297. * On FN_ERROR and FN_NOENT, sets errno. (errno is not set when FN_ERROR
  1298. * is returned due to an unhandled file type.) */
  1299. file_status_t
  1300. file_status(const char *fname)
  1301. {
  1302. struct stat st;
  1303. char *f;
  1304. int r;
  1305. if (!fname || strlen(fname) == 0) {
  1306. return FN_ERROR;
  1307. }
  1308. f = tor_strdup(fname);
  1309. clean_name_for_stat(f);
  1310. log_debug(LD_FS, "stat()ing %s", f);
  1311. r = stat(sandbox_intern_string(f), &st);
  1312. tor_free(f);
  1313. if (r) {
  1314. if (errno == ENOENT) {
  1315. return FN_NOENT;
  1316. }
  1317. return FN_ERROR;
  1318. }
  1319. if (st.st_mode & S_IFDIR) {
  1320. return FN_DIR;
  1321. } else if (st.st_mode & S_IFREG) {
  1322. if (st.st_size > 0) {
  1323. return FN_FILE;
  1324. } else if (st.st_size == 0) {
  1325. return FN_EMPTY;
  1326. } else {
  1327. return FN_ERROR;
  1328. }
  1329. #ifndef _WIN32
  1330. } else if (st.st_mode & S_IFIFO) {
  1331. return FN_FILE;
  1332. #endif
  1333. } else {
  1334. return FN_ERROR;
  1335. }
  1336. }
  1337. /** Check whether <b>dirname</b> exists and is private. If yes return 0.
  1338. * If <b>dirname</b> does not exist:
  1339. * - if <b>check</b>&CPD_CREATE, try to create it and return 0 on success.
  1340. * - if <b>check</b>&CPD_CHECK, and we think we can create it, return 0.
  1341. * - if <b>check</b>&CPD_CHECK is false, and the directory exists, return 0.
  1342. * - otherwise, return -1.
  1343. * If CPD_GROUP_OK is set, then it's okay if the directory
  1344. * is group-readable, but in all cases we create the directory mode 0700.
  1345. * If CPD_GROUP_READ is set, existing directory behaves as CPD_GROUP_OK and
  1346. * if the directory is created it will use mode 0750 with group read
  1347. * permission. Group read privileges also assume execute permission
  1348. * as norm for directories. If CPD_CHECK_MODE_ONLY is set, then we don't
  1349. * alter the directory permissions if they are too permissive:
  1350. * we just return -1.
  1351. * When effective_user is not NULL, check permissions against the given user
  1352. * and its primary group.
  1353. */
  1354. MOCK_IMPL(int,
  1355. check_private_dir,(const char *dirname, cpd_check_t check,
  1356. const char *effective_user))
  1357. {
  1358. int r;
  1359. struct stat st;
  1360. tor_assert(dirname);
  1361. #ifndef _WIN32
  1362. int fd;
  1363. const struct passwd *pw = NULL;
  1364. uid_t running_uid;
  1365. gid_t running_gid;
  1366. /*
  1367. * Goal is to harden the implementation by removing any
  1368. * potential for race between stat() and chmod().
  1369. * chmod() accepts filename as argument. If an attacker can move
  1370. * the file between stat() and chmod(), a potential race exists.
  1371. *
  1372. * Several suggestions taken from:
  1373. * https://developer.apple.com/library/mac/documentation/
  1374. * Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html
  1375. */
  1376. /* Open directory.
  1377. * O_NOFOLLOW to ensure that it does not follow symbolic links */
  1378. fd = open(sandbox_intern_string(dirname), O_NOFOLLOW);
  1379. /* Was there an error? Maybe the directory does not exist? */
  1380. if (fd == -1) {
  1381. if (errno != ENOENT) {
  1382. /* Other directory error */
  1383. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1384. strerror(errno));
  1385. return -1;
  1386. }
  1387. /* Received ENOENT: Directory does not exist */
  1388. /* Should we create the directory? */
  1389. if (check & CPD_CREATE) {
  1390. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1391. if (check & CPD_GROUP_READ) {
  1392. r = mkdir(dirname, 0750);
  1393. } else {
  1394. r = mkdir(dirname, 0700);
  1395. }
  1396. /* check for mkdir() error */
  1397. if (r) {
  1398. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1399. strerror(errno));
  1400. return -1;
  1401. }
  1402. /* we just created the directory. try to open it again.
  1403. * permissions on the directory will be checked again below.*/
  1404. fd = open(sandbox_intern_string(dirname), O_NOFOLLOW);
  1405. if (fd == -1) {
  1406. log_warn(LD_FS, "Could not reopen recently created directory %s: %s",
  1407. dirname,
  1408. strerror(errno));
  1409. return -1;
  1410. } else {
  1411. close(fd);
  1412. }
  1413. } else if (!(check & CPD_CHECK)) {
  1414. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1415. return -1;
  1416. }
  1417. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1418. * parent directory a little harder. */
  1419. return 0;
  1420. }
  1421. tor_assert(fd >= 0);
  1422. //f = tor_strdup(dirname);
  1423. //clean_name_for_stat(f);
  1424. log_debug(LD_FS, "stat()ing %s", dirname);
  1425. //r = stat(sandbox_intern_string(f), &st);
  1426. r = fstat(fd, &st);
  1427. if (r == -1) {
  1428. log_warn(LD_FS, "fstat() on directory %s failed.", dirname);
  1429. close(fd);
  1430. return -1;
  1431. }
  1432. //tor_free(f);
  1433. /* check that dirname is a directory */
  1434. if (!(st.st_mode & S_IFDIR)) {
  1435. log_warn(LD_FS, "%s is not a directory", dirname);
  1436. close(fd);
  1437. return -1;
  1438. }
  1439. if (effective_user) {
  1440. /* Look up the user and group information.
  1441. * If we have a problem, bail out. */
  1442. pw = tor_getpwnam(effective_user);
  1443. if (pw == NULL) {
  1444. log_warn(LD_CONFIG, "Error setting configured user: %s not found",
  1445. effective_user);
  1446. close(fd);
  1447. return -1;
  1448. }
  1449. running_uid = pw->pw_uid;
  1450. running_gid = pw->pw_gid;
  1451. } else {
  1452. running_uid = getuid();
  1453. running_gid = getgid();
  1454. }
  1455. if (st.st_uid != running_uid) {
  1456. char *process_ownername = NULL, *file_ownername = NULL;
  1457. {
  1458. const struct passwd *pw_running = tor_getpwuid(running_uid);
  1459. process_ownername = pw_running ? tor_strdup(pw_running->pw_name) :
  1460. tor_strdup("<unknown>");
  1461. }
  1462. {
  1463. const struct passwd *pw_stat = tor_getpwuid(st.st_uid);
  1464. file_ownername = pw_stat ? tor_strdup(pw_stat->pw_name) :
  1465. tor_strdup("<unknown>");
  1466. }
  1467. log_warn(LD_FS, "%s is not owned by this user (%s, %d) but by "
  1468. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1469. dirname, process_ownername, (int)running_uid,
  1470. file_ownername, (int)st.st_uid);
  1471. tor_free(process_ownername);
  1472. tor_free(file_ownername);
  1473. close(fd);
  1474. return -1;
  1475. }
  1476. if ( (check & (CPD_GROUP_OK|CPD_GROUP_READ))
  1477. && (st.st_gid != running_gid) && (st.st_gid != 0)) {
  1478. struct group *gr;
  1479. char *process_groupname = NULL;
  1480. gr = getgrgid(running_gid);
  1481. process_groupname = gr ? tor_strdup(gr->gr_name) : tor_strdup("<unknown>");
  1482. gr = getgrgid(st.st_gid);
  1483. log_warn(LD_FS, "%s is not owned by this group (%s, %d) but by group "
  1484. "%s (%d). Are you running Tor as the wrong user?",
  1485. dirname, process_groupname, (int)running_gid,
  1486. gr ? gr->gr_name : "<unknown>", (int)st.st_gid);
  1487. tor_free(process_groupname);
  1488. close(fd);
  1489. return -1;
  1490. }
  1491. unsigned unwanted_bits = 0;
  1492. if (check & (CPD_GROUP_OK|CPD_GROUP_READ)) {
  1493. unwanted_bits = 0027;
  1494. } else {
  1495. unwanted_bits = 0077;
  1496. }
  1497. unsigned check_bits_filter = ~0;
  1498. if (check & CPD_RELAX_DIRMODE_CHECK) {
  1499. check_bits_filter = 0022;
  1500. }
  1501. if ((st.st_mode & unwanted_bits & check_bits_filter) != 0) {
  1502. unsigned new_mode;
  1503. if (check & CPD_CHECK_MODE_ONLY) {
  1504. log_warn(LD_FS, "Permissions on directory %s are too permissive.",
  1505. dirname);
  1506. close(fd);
  1507. return -1;
  1508. }
  1509. log_warn(LD_FS, "Fixing permissions on directory %s", dirname);
  1510. new_mode = st.st_mode;
  1511. new_mode |= 0700; /* Owner should have rwx */
  1512. if (check & CPD_GROUP_READ) {
  1513. new_mode |= 0050; /* Group should have rx */
  1514. }
  1515. new_mode &= ~unwanted_bits; /* Clear the bits that we didn't want set...*/
  1516. if (fchmod(fd, new_mode)) {
  1517. log_warn(LD_FS, "Could not chmod directory %s: %s", dirname,
  1518. strerror(errno));
  1519. close(fd);
  1520. return -1;
  1521. } else {
  1522. close(fd);
  1523. return 0;
  1524. }
  1525. }
  1526. close(fd);
  1527. #else /* !(!defined(_WIN32)) */
  1528. /* Win32 case: we can't open() a directory. */
  1529. (void)effective_user;
  1530. char *f = tor_strdup(dirname);
  1531. clean_name_for_stat(f);
  1532. log_debug(LD_FS, "stat()ing %s", f);
  1533. r = stat(sandbox_intern_string(f), &st);
  1534. tor_free(f);
  1535. if (r) {
  1536. if (errno != ENOENT) {
  1537. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1538. strerror(errno));
  1539. return -1;
  1540. }
  1541. if (check & CPD_CREATE) {
  1542. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1543. r = mkdir(dirname);
  1544. if (r) {
  1545. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1546. strerror(errno));
  1547. return -1;
  1548. }
  1549. } else if (!(check & CPD_CHECK)) {
  1550. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1551. return -1;
  1552. }
  1553. return 0;
  1554. }
  1555. if (!(st.st_mode & S_IFDIR)) {
  1556. log_warn(LD_FS, "%s is not a directory", dirname);
  1557. return -1;
  1558. }
  1559. #endif /* !defined(_WIN32) */
  1560. return 0;
  1561. }
  1562. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1563. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1564. *
  1565. * This function replaces the old file atomically, if possible. This
  1566. * function, and all other functions in util.c that create files, create them
  1567. * with mode 0600.
  1568. */
  1569. MOCK_IMPL(int,
  1570. write_str_to_file,(const char *fname, const char *str, int bin))
  1571. {
  1572. #ifdef _WIN32
  1573. if (!bin && strchr(str, '\r')) {
  1574. log_warn(LD_BUG,
  1575. "We're writing a text string that already contains a CR to %s",
  1576. escaped(fname));
  1577. }
  1578. #endif /* defined(_WIN32) */
  1579. return write_bytes_to_file(fname, str, strlen(str), bin);
  1580. }
  1581. /** Represents a file that we're writing to, with support for atomic commit:
  1582. * we can write into a temporary file, and either remove the file on
  1583. * failure, or replace the original file on success. */
  1584. struct open_file_t {
  1585. char *tempname; /**< Name of the temporary file. */
  1586. char *filename; /**< Name of the original file. */
  1587. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  1588. unsigned binary:1; /**< Did we open in binary mode? */
  1589. int fd; /**< fd for the open file. */
  1590. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  1591. };
  1592. /** Try to start writing to the file in <b>fname</b>, passing the flags
  1593. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  1594. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  1595. * original file. Otherwise, we open a new temporary file in the same
  1596. * directory, and either replace the original or remove the temporary file
  1597. * when we're done.
  1598. *
  1599. * Return the fd for the newly opened file, and store working data in
  1600. * *<b>data_out</b>. The caller should not close the fd manually:
  1601. * instead, call finish_writing_to_file() or abort_writing_to_file().
  1602. * Returns -1 on failure.
  1603. *
  1604. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  1605. * as true and the flag O_EXCL is treated as false.
  1606. *
  1607. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  1608. * write()". We don't do that.
  1609. */
  1610. int
  1611. start_writing_to_file(const char *fname, int open_flags, int mode,
  1612. open_file_t **data_out)
  1613. {
  1614. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  1615. const char *open_name;
  1616. int append = 0;
  1617. tor_assert(fname);
  1618. tor_assert(data_out);
  1619. #if (O_BINARY != 0 && O_TEXT != 0)
  1620. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  1621. #endif
  1622. new_file->fd = -1;
  1623. new_file->filename = tor_strdup(fname);
  1624. if (open_flags & O_APPEND) {
  1625. open_name = fname;
  1626. new_file->rename_on_close = 0;
  1627. append = 1;
  1628. open_flags &= ~O_APPEND;
  1629. } else {
  1630. tor_asprintf(&new_file->tempname, "%s.tmp", fname);
  1631. open_name = new_file->tempname;
  1632. /* We always replace an existing temporary file if there is one. */
  1633. open_flags |= O_CREAT|O_TRUNC;
  1634. open_flags &= ~O_EXCL;
  1635. new_file->rename_on_close = 1;
  1636. }
  1637. #if O_BINARY != 0
  1638. if (open_flags & O_BINARY)
  1639. new_file->binary = 1;
  1640. #endif
  1641. new_file->fd = tor_open_cloexec(open_name, open_flags, mode);
  1642. if (new_file->fd < 0) {
  1643. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  1644. open_name, fname, strerror(errno));
  1645. goto err;
  1646. }
  1647. if (append) {
  1648. if (tor_fd_seekend(new_file->fd) < 0) {
  1649. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  1650. strerror(errno));
  1651. goto err;
  1652. }
  1653. }
  1654. *data_out = new_file;
  1655. return new_file->fd;
  1656. err:
  1657. if (new_file->fd >= 0)
  1658. close(new_file->fd);
  1659. *data_out = NULL;
  1660. tor_free(new_file->filename);
  1661. tor_free(new_file->tempname);
  1662. tor_free(new_file);
  1663. return -1;
  1664. }
  1665. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  1666. * that can be used to write to the same file. The caller should not mix
  1667. * stdio calls with non-stdio calls. */
  1668. FILE *
  1669. fdopen_file(open_file_t *file_data)
  1670. {
  1671. tor_assert(file_data);
  1672. if (file_data->stdio_file)
  1673. return file_data->stdio_file;
  1674. tor_assert(file_data->fd >= 0);
  1675. if (!(file_data->stdio_file = fdopen(file_data->fd,
  1676. file_data->binary?"ab":"a"))) {
  1677. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  1678. file_data->fd, strerror(errno));
  1679. }
  1680. return file_data->stdio_file;
  1681. }
  1682. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  1683. * for start_writing_to_file, but */
  1684. FILE *
  1685. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  1686. open_file_t **data_out)
  1687. {
  1688. FILE *res;
  1689. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  1690. return NULL;
  1691. if (!(res = fdopen_file(*data_out))) {
  1692. abort_writing_to_file(*data_out);
  1693. *data_out = NULL;
  1694. }
  1695. return res;
  1696. }
  1697. /** Helper function: close and free the underlying file and memory in
  1698. * <b>file_data</b>. If we were writing into a temporary file, then delete
  1699. * that file (if abort_write is true) or replaces the target file with
  1700. * the temporary file (if abort_write is false). */
  1701. static int
  1702. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  1703. {
  1704. int r = 0;
  1705. tor_assert(file_data && file_data->filename);
  1706. if (file_data->stdio_file) {
  1707. if (fclose(file_data->stdio_file)) {
  1708. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  1709. strerror(errno));
  1710. abort_write = r = -1;
  1711. }
  1712. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  1713. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  1714. strerror(errno));
  1715. abort_write = r = -1;
  1716. }
  1717. if (file_data->rename_on_close) {
  1718. tor_assert(file_data->tempname && file_data->filename);
  1719. if (!abort_write) {
  1720. tor_assert(strcmp(file_data->filename, file_data->tempname));
  1721. if (replace_file(file_data->tempname, file_data->filename)) {
  1722. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  1723. strerror(errno));
  1724. abort_write = r = -1;
  1725. }
  1726. }
  1727. if (abort_write) {
  1728. int res = unlink(file_data->tempname);
  1729. if (res != 0) {
  1730. /* We couldn't unlink and we'll leave a mess behind */
  1731. log_warn(LD_FS, "Failed to unlink %s: %s",
  1732. file_data->tempname, strerror(errno));
  1733. r = -1;
  1734. }
  1735. }
  1736. }
  1737. tor_free(file_data->filename);
  1738. tor_free(file_data->tempname);
  1739. tor_free(file_data);
  1740. return r;
  1741. }
  1742. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1743. * needed, and if using a temporary file, replace the original file with
  1744. * the temporary file. */
  1745. int
  1746. finish_writing_to_file(open_file_t *file_data)
  1747. {
  1748. return finish_writing_to_file_impl(file_data, 0);
  1749. }
  1750. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1751. * needed, and if using a temporary file, delete it. */
  1752. int
  1753. abort_writing_to_file(open_file_t *file_data)
  1754. {
  1755. return finish_writing_to_file_impl(file_data, 1);
  1756. }
  1757. /** Helper: given a set of flags as passed to open(2), open the file
  1758. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  1759. * the file. Do so as atomically as possible e.g. by opening temp files and
  1760. * renaming. */
  1761. static int
  1762. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  1763. int open_flags)
  1764. {
  1765. open_file_t *file = NULL;
  1766. int fd;
  1767. ssize_t result;
  1768. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  1769. if (fd<0)
  1770. return -1;
  1771. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  1772. {
  1773. result = write_all(fd, chunk->bytes, chunk->len, 0);
  1774. if (result < 0) {
  1775. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  1776. strerror(errno));
  1777. goto err;
  1778. }
  1779. tor_assert((size_t)result == chunk->len);
  1780. });
  1781. return finish_writing_to_file(file);
  1782. err:
  1783. abort_writing_to_file(file);
  1784. return -1;
  1785. }
  1786. /** Given a smartlist of sized_chunk_t, write them to a file
  1787. * <b>fname</b>, overwriting or creating the file as necessary.
  1788. * If <b>no_tempfile</b> is 0 then the file will be written
  1789. * atomically. */
  1790. int
  1791. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin,
  1792. int no_tempfile)
  1793. {
  1794. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1795. if (no_tempfile) {
  1796. /* O_APPEND stops write_chunks_to_file from using tempfiles */
  1797. flags |= O_APPEND;
  1798. }
  1799. return write_chunks_to_file_impl(fname, chunks, flags);
  1800. }
  1801. /** Write <b>len</b> bytes, starting at <b>str</b>, to <b>fname</b>
  1802. using the open() flags passed in <b>flags</b>. */
  1803. static int
  1804. write_bytes_to_file_impl(const char *fname, const char *str, size_t len,
  1805. int flags)
  1806. {
  1807. int r;
  1808. sized_chunk_t c = { str, len };
  1809. smartlist_t *chunks = smartlist_new();
  1810. smartlist_add(chunks, &c);
  1811. r = write_chunks_to_file_impl(fname, chunks, flags);
  1812. smartlist_free(chunks);
  1813. return r;
  1814. }
  1815. /** As write_str_to_file, but does not assume a NUL-terminated
  1816. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  1817. MOCK_IMPL(int,
  1818. write_bytes_to_file,(const char *fname, const char *str, size_t len,
  1819. int bin))
  1820. {
  1821. return write_bytes_to_file_impl(fname, str, len,
  1822. OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT));
  1823. }
  1824. /** As write_bytes_to_file, but if the file already exists, append the bytes
  1825. * to the end of the file instead of overwriting it. */
  1826. int
  1827. append_bytes_to_file(const char *fname, const char *str, size_t len,
  1828. int bin)
  1829. {
  1830. return write_bytes_to_file_impl(fname, str, len,
  1831. OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT));
  1832. }
  1833. /** Like write_str_to_file(), but also return -1 if there was a file
  1834. already residing in <b>fname</b>. */
  1835. int
  1836. write_bytes_to_new_file(const char *fname, const char *str, size_t len,
  1837. int bin)
  1838. {
  1839. return write_bytes_to_file_impl(fname, str, len,
  1840. OPEN_FLAGS_DONT_REPLACE|
  1841. (bin?O_BINARY:O_TEXT));
  1842. }
  1843. /**
  1844. * Read the contents of the open file <b>fd</b> presuming it is a FIFO
  1845. * (or similar) file descriptor for which the size of the file isn't
  1846. * known ahead of time. Return NULL on failure, and a NUL-terminated
  1847. * string on success. On success, set <b>sz_out</b> to the number of
  1848. * bytes read.
  1849. */
  1850. char *
  1851. read_file_to_str_until_eof(int fd, size_t max_bytes_to_read, size_t *sz_out)
  1852. {
  1853. ssize_t r;
  1854. size_t pos = 0;
  1855. char *string = NULL;
  1856. size_t string_max = 0;
  1857. if (max_bytes_to_read+1 >= SIZE_T_CEILING) {
  1858. errno = EINVAL;
  1859. return NULL;
  1860. }
  1861. do {
  1862. /* XXXX This "add 1K" approach is a little goofy; if we care about
  1863. * performance here, we should be doubling. But in practice we shouldn't
  1864. * be using this function on big files anyway. */
  1865. string_max = pos + 1024;
  1866. if (string_max > max_bytes_to_read)
  1867. string_max = max_bytes_to_read + 1;
  1868. string = tor_realloc(string, string_max);
  1869. r = read(fd, string + pos, string_max - pos - 1);
  1870. if (r < 0) {
  1871. int save_errno = errno;
  1872. tor_free(string);
  1873. errno = save_errno;
  1874. return NULL;
  1875. }
  1876. pos += r;
  1877. } while (r > 0 && pos < max_bytes_to_read);
  1878. tor_assert(pos < string_max);
  1879. *sz_out = pos;
  1880. string[pos] = '\0';
  1881. return string;
  1882. }
  1883. /** Read the contents of <b>filename</b> into a newly allocated
  1884. * string; return the string on success or NULL on failure.
  1885. *
  1886. * If <b>stat_out</b> is provided, store the result of stat()ing the
  1887. * file into <b>stat_out</b>.
  1888. *
  1889. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  1890. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  1891. * doesn't exist.
  1892. */
  1893. /*
  1894. * This function <em>may</em> return an erroneous result if the file
  1895. * is modified while it is running, but must not crash or overflow.
  1896. * Right now, the error case occurs when the file length grows between
  1897. * the call to stat and the call to read_all: the resulting string will
  1898. * be truncated.
  1899. */
  1900. MOCK_IMPL(char *,
  1901. read_file_to_str, (const char *filename, int flags, struct stat *stat_out))
  1902. {
  1903. int fd; /* router file */
  1904. struct stat statbuf;
  1905. char *string;
  1906. ssize_t r;
  1907. int bin = flags & RFTS_BIN;
  1908. tor_assert(filename);
  1909. fd = tor_open_cloexec(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  1910. if (fd<0) {
  1911. int severity = LOG_WARN;
  1912. int save_errno = errno;
  1913. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  1914. severity = LOG_INFO;
  1915. log_fn(severity, LD_FS,"Could not open \"%s\": %s",filename,
  1916. strerror(errno));
  1917. errno = save_errno;
  1918. return NULL;
  1919. }
  1920. if (fstat(fd, &statbuf)<0) {
  1921. int save_errno = errno;
  1922. close(fd);
  1923. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  1924. errno = save_errno;
  1925. return NULL;
  1926. }
  1927. #ifndef _WIN32
  1928. /** When we detect that we're reading from a FIFO, don't read more than
  1929. * this many bytes. It's insane overkill for most uses. */
  1930. #define FIFO_READ_MAX (1024*1024)
  1931. if (S_ISFIFO(statbuf.st_mode)) {
  1932. size_t sz = 0;
  1933. string = read_file_to_str_until_eof(fd, FIFO_READ_MAX, &sz);
  1934. int save_errno = errno;
  1935. if (string && stat_out) {
  1936. statbuf.st_size = sz;
  1937. memcpy(stat_out, &statbuf, sizeof(struct stat));
  1938. }
  1939. close(fd);
  1940. if (!string)
  1941. errno = save_errno;
  1942. return string;
  1943. }
  1944. #endif /* !defined(_WIN32) */
  1945. if ((uint64_t)(statbuf.st_size)+1 >= SIZE_T_CEILING) {
  1946. close(fd);
  1947. errno = EINVAL;
  1948. return NULL;
  1949. }
  1950. string = tor_malloc((size_t)(statbuf.st_size+1));
  1951. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  1952. if (r<0) {
  1953. int save_errno = errno;
  1954. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  1955. strerror(errno));
  1956. tor_free(string);
  1957. close(fd);
  1958. errno = save_errno;
  1959. return NULL;
  1960. }
  1961. string[r] = '\0'; /* NUL-terminate the result. */
  1962. #if defined(_WIN32) || defined(__CYGWIN__)
  1963. if (!bin && strchr(string, '\r')) {
  1964. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  1965. "when reading %s. Coping.",
  1966. filename);
  1967. tor_strstrip(string, "\r");
  1968. r = strlen(string);
  1969. }
  1970. if (!bin) {
  1971. statbuf.st_size = (size_t) r;
  1972. } else
  1973. #endif /* defined(_WIN32) || defined(__CYGWIN__) */
  1974. if (r != statbuf.st_size) {
  1975. /* Unless we're using text mode on win32, we'd better have an exact
  1976. * match for size. */
  1977. int save_errno = errno;
  1978. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  1979. (int)r, (long)statbuf.st_size,filename);
  1980. tor_free(string);
  1981. close(fd);
  1982. errno = save_errno;
  1983. return NULL;
  1984. }
  1985. close(fd);
  1986. if (stat_out) {
  1987. memcpy(stat_out, &statbuf, sizeof(struct stat));
  1988. }
  1989. return string;
  1990. }
  1991. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  1992. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  1993. * decode its contents into a newly allocated string. On success, assign this
  1994. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  1995. * provided), and return a pointer to the position in <b>s</b> immediately
  1996. * after the string. On failure, return NULL.
  1997. */
  1998. const char *
  1999. unescape_string(const char *s, char **result, size_t *size_out)
  2000. {
  2001. const char *cp;
  2002. char *out;
  2003. if (s[0] != '\"')
  2004. return NULL;
  2005. cp = s+1;
  2006. while (1) {
  2007. switch (*cp) {
  2008. case '\0':
  2009. case '\n':
  2010. return NULL;
  2011. case '\"':
  2012. goto end_of_loop;
  2013. case '\\':
  2014. if (cp[1] == 'x' || cp[1] == 'X') {
  2015. if (!(TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])))
  2016. return NULL;
  2017. cp += 4;
  2018. } else if (TOR_ISODIGIT(cp[1])) {
  2019. cp += 2;
  2020. if (TOR_ISODIGIT(*cp)) ++cp;
  2021. if (TOR_ISODIGIT(*cp)) ++cp;
  2022. } else if (cp[1] == 'n' || cp[1] == 'r' || cp[1] == 't' || cp[1] == '"'
  2023. || cp[1] == '\\' || cp[1] == '\'') {
  2024. cp += 2;
  2025. } else {
  2026. return NULL;
  2027. }
  2028. break;
  2029. default:
  2030. ++cp;
  2031. break;
  2032. }
  2033. }
  2034. end_of_loop:
  2035. out = *result = tor_malloc(cp-s + 1);
  2036. cp = s+1;
  2037. while (1) {
  2038. switch (*cp)
  2039. {
  2040. case '\"':
  2041. *out = '\0';
  2042. if (size_out) *size_out = out - *result;
  2043. return cp+1;
  2044. /* LCOV_EXCL_START -- we caught this in parse_config_from_line. */
  2045. case '\0':
  2046. tor_fragile_assert();
  2047. tor_free(*result);
  2048. return NULL;
  2049. /* LCOV_EXCL_STOP */
  2050. case '\\':
  2051. switch (cp[1])
  2052. {
  2053. case 'n': *out++ = '\n'; cp += 2; break;
  2054. case 'r': *out++ = '\r'; cp += 2; break;
  2055. case 't': *out++ = '\t'; cp += 2; break;
  2056. case 'x': case 'X':
  2057. {
  2058. int x1, x2;
  2059. x1 = hex_decode_digit(cp[2]);
  2060. x2 = hex_decode_digit(cp[3]);
  2061. if (x1 == -1 || x2 == -1) {
  2062. /* LCOV_EXCL_START */
  2063. /* we caught this above in the initial loop. */
  2064. tor_assert_nonfatal_unreached();
  2065. tor_free(*result);
  2066. return NULL;
  2067. /* LCOV_EXCL_STOP */
  2068. }
  2069. *out++ = ((x1<<4) + x2);
  2070. cp += 4;
  2071. }
  2072. break;
  2073. case '0': case '1': case '2': case '3': case '4': case '5':
  2074. case '6': case '7':
  2075. {
  2076. int n = cp[1]-'0';
  2077. cp += 2;
  2078. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2079. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2080. if (n > 255) { tor_free(*result); return NULL; }
  2081. *out++ = (char)n;
  2082. }
  2083. break;
  2084. case '\'':
  2085. case '\"':
  2086. case '\\':
  2087. case '\?':
  2088. *out++ = cp[1];
  2089. cp += 2;
  2090. break;
  2091. /* LCOV_EXCL_START */
  2092. default:
  2093. /* we caught this above in the initial loop. */
  2094. tor_assert_nonfatal_unreached();
  2095. tor_free(*result); return NULL;
  2096. /* LCOV_EXCL_STOP */
  2097. }
  2098. break;
  2099. default:
  2100. *out++ = *cp++;
  2101. }
  2102. }
  2103. }
  2104. /** Removes enclosing quotes from <b>path</b> and unescapes quotes between the
  2105. * enclosing quotes. Backslashes are not unescaped. Return the unquoted
  2106. * <b>path</b> on success or 0 if <b>path</b> is not quoted correctly. */
  2107. char *
  2108. get_unquoted_path(const char *path)
  2109. {
  2110. size_t len = strlen(path);
  2111. if (len == 0) {
  2112. return tor_strdup("");
  2113. }
  2114. int has_start_quote = (path[0] == '\"');
  2115. int has_end_quote = (len > 0 && path[len-1] == '\"');
  2116. if (has_start_quote != has_end_quote || (len == 1 && has_start_quote)) {
  2117. return NULL;
  2118. }
  2119. char *unquoted_path = tor_malloc(len - has_start_quote - has_end_quote + 1);
  2120. char *s = unquoted_path;
  2121. size_t i;
  2122. for (i = has_start_quote; i < len - has_end_quote; i++) {
  2123. if (path[i] == '\"' && (i > 0 && path[i-1] == '\\')) {
  2124. *(s-1) = path[i];
  2125. } else if (path[i] != '\"') {
  2126. *s++ = path[i];
  2127. } else { /* unescaped quote */
  2128. tor_free(unquoted_path);
  2129. return NULL;
  2130. }
  2131. }
  2132. *s = '\0';
  2133. return unquoted_path;
  2134. }
  2135. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  2136. * string. */
  2137. char *
  2138. expand_filename(const char *filename)
  2139. {
  2140. tor_assert(filename);
  2141. #ifdef _WIN32
  2142. /* Might consider using GetFullPathName() as described here:
  2143. * http://etutorials.org/Programming/secure+programming/
  2144. * Chapter+3.+Input+Validation/3.7+Validating+Filenames+and+Paths/
  2145. */
  2146. return tor_strdup(filename);
  2147. #else /* !(defined(_WIN32)) */
  2148. if (*filename == '~') {
  2149. char *home, *result=NULL;
  2150. const char *rest;
  2151. if (filename[1] == '/' || filename[1] == '\0') {
  2152. home = getenv("HOME");
  2153. if (!home) {
  2154. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  2155. "expanding \"%s\"; defaulting to \"\".", filename);
  2156. home = tor_strdup("");
  2157. } else {
  2158. home = tor_strdup(home);
  2159. }
  2160. rest = strlen(filename)>=2?(filename+2):"";
  2161. } else {
  2162. #ifdef HAVE_PWD_H
  2163. char *username, *slash;
  2164. slash = strchr(filename, '/');
  2165. if (slash)
  2166. username = tor_strndup(filename+1,slash-filename-1);
  2167. else
  2168. username = tor_strdup(filename+1);
  2169. if (!(home = get_user_homedir(username))) {
  2170. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2171. tor_free(username);
  2172. return NULL;
  2173. }
  2174. tor_free(username);
  2175. rest = slash ? (slash+1) : "";
  2176. #else /* !(defined(HAVE_PWD_H)) */
  2177. log_warn(LD_CONFIG, "Couldn't expand homedir on system without pwd.h");
  2178. return tor_strdup(filename);
  2179. #endif /* defined(HAVE_PWD_H) */
  2180. }
  2181. tor_assert(home);
  2182. /* Remove trailing slash. */
  2183. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2184. home[strlen(home)-1] = '\0';
  2185. }
  2186. tor_asprintf(&result,"%s"PATH_SEPARATOR"%s",home,rest);
  2187. tor_free(home);
  2188. return result;
  2189. } else {
  2190. return tor_strdup(filename);
  2191. }
  2192. #endif /* defined(_WIN32) */
  2193. }
  2194. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  2195. * Return NULL on error or if <b>dirname</b> is not a directory.
  2196. */
  2197. MOCK_IMPL(smartlist_t *,
  2198. tor_listdir, (const char *dirname))
  2199. {
  2200. smartlist_t *result;
  2201. #ifdef _WIN32
  2202. char *pattern=NULL;
  2203. TCHAR tpattern[MAX_PATH] = {0};
  2204. char name[MAX_PATH*2+1] = {0};
  2205. HANDLE handle;
  2206. WIN32_FIND_DATA findData;
  2207. tor_asprintf(&pattern, "%s\\*", dirname);
  2208. #ifdef UNICODE
  2209. mbstowcs(tpattern,pattern,MAX_PATH);
  2210. #else
  2211. strlcpy(tpattern, pattern, MAX_PATH);
  2212. #endif
  2213. if (INVALID_HANDLE_VALUE == (handle = FindFirstFile(tpattern, &findData))) {
  2214. tor_free(pattern);
  2215. return NULL;
  2216. }
  2217. result = smartlist_new();
  2218. while (1) {
  2219. #ifdef UNICODE
  2220. wcstombs(name,findData.cFileName,MAX_PATH);
  2221. name[sizeof(name)-1] = '\0';
  2222. #else
  2223. strlcpy(name,findData.cFileName,sizeof(name));
  2224. #endif /* defined(UNICODE) */
  2225. if (strcmp(name, ".") &&
  2226. strcmp(name, "..")) {
  2227. smartlist_add_strdup(result, name);
  2228. }
  2229. if (!FindNextFile(handle, &findData)) {
  2230. DWORD err;
  2231. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  2232. char *errstr = format_win32_error(err);
  2233. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  2234. tor_free(errstr);
  2235. }
  2236. break;
  2237. }
  2238. }
  2239. FindClose(handle);
  2240. tor_free(pattern);
  2241. #else /* !(defined(_WIN32)) */
  2242. const char *prot_dname = sandbox_intern_string(dirname);
  2243. DIR *d;
  2244. struct dirent *de;
  2245. if (!(d = opendir(prot_dname)))
  2246. return NULL;
  2247. result = smartlist_new();
  2248. while ((de = readdir(d))) {
  2249. if (!strcmp(de->d_name, ".") ||
  2250. !strcmp(de->d_name, ".."))
  2251. continue;
  2252. smartlist_add_strdup(result, de->d_name);
  2253. }
  2254. closedir(d);
  2255. #endif /* defined(_WIN32) */
  2256. return result;
  2257. }
  2258. /** Return true iff <b>filename</b> is a relative path. */
  2259. int
  2260. path_is_relative(const char *filename)
  2261. {
  2262. if (filename && filename[0] == '/')
  2263. return 0;
  2264. #ifdef _WIN32
  2265. else if (filename && filename[0] == '\\')
  2266. return 0;
  2267. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  2268. filename[1] == ':' && filename[2] == '\\')
  2269. return 0;
  2270. #endif /* defined(_WIN32) */
  2271. else
  2272. return 1;
  2273. }
  2274. /* =====
  2275. * Process helpers
  2276. * ===== */
  2277. #ifndef _WIN32
  2278. /* Based on code contributed by christian grothoff */
  2279. /** True iff we've called start_daemon(). */
  2280. static int start_daemon_called = 0;
  2281. /** True iff we've called finish_daemon(). */
  2282. static int finish_daemon_called = 0;
  2283. /** Socketpair used to communicate between parent and child process while
  2284. * daemonizing. */
  2285. static int daemon_filedes[2];
  2286. /** Start putting the process into daemon mode: fork and drop all resources
  2287. * except standard fds. The parent process never returns, but stays around
  2288. * until finish_daemon is called. (Note: it's safe to call this more
  2289. * than once: calls after the first are ignored.)
  2290. */
  2291. void
  2292. start_daemon(void)
  2293. {
  2294. pid_t pid;
  2295. if (start_daemon_called)
  2296. return;
  2297. start_daemon_called = 1;
  2298. if (pipe(daemon_filedes)) {
  2299. /* LCOV_EXCL_START */
  2300. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  2301. exit(1); // exit ok: during daemonize, pipe failed.
  2302. /* LCOV_EXCL_STOP */
  2303. }
  2304. pid = fork();
  2305. if (pid < 0) {
  2306. /* LCOV_EXCL_START */
  2307. log_err(LD_GENERAL,"fork failed. Exiting.");
  2308. exit(1); // exit ok: during daemonize, fork failed
  2309. /* LCOV_EXCL_STOP */
  2310. }
  2311. if (pid) { /* Parent */
  2312. int ok;
  2313. char c;
  2314. close(daemon_filedes[1]); /* we only read */
  2315. ok = -1;
  2316. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  2317. if (c == '.')
  2318. ok = 1;
  2319. }
  2320. fflush(stdout);
  2321. if (ok == 1)
  2322. exit(0); // exit ok: during daemonize, daemonizing.
  2323. else
  2324. exit(1); /* child reported error. exit ok: daemonize failed. */
  2325. } else { /* Child */
  2326. close(daemon_filedes[0]); /* we only write */
  2327. (void) setsid(); /* Detach from controlling terminal */
  2328. /*
  2329. * Fork one more time, so the parent (the session group leader) can exit.
  2330. * This means that we, as a non-session group leader, can never regain a
  2331. * controlling terminal. This part is recommended by Stevens's
  2332. * _Advanced Programming in the Unix Environment_.
  2333. */
  2334. if (fork() != 0) {
  2335. exit(0); // exit ok: during daemonize, fork failed (2)
  2336. }
  2337. set_main_thread(); /* We are now the main thread. */
  2338. return;
  2339. }
  2340. }
  2341. /** Finish putting the process into daemon mode: drop standard fds, and tell
  2342. * the parent process to exit. (Note: it's safe to call this more than once:
  2343. * calls after the first are ignored. Calls start_daemon first if it hasn't
  2344. * been called already.)
  2345. */
  2346. void
  2347. finish_daemon(const char *desired_cwd)
  2348. {
  2349. int nullfd;
  2350. char c = '.';
  2351. if (finish_daemon_called)
  2352. return;
  2353. if (!start_daemon_called)
  2354. start_daemon();
  2355. finish_daemon_called = 1;
  2356. if (!desired_cwd)
  2357. desired_cwd = "/";
  2358. /* Don't hold the wrong FS mounted */
  2359. if (chdir(desired_cwd) < 0) {
  2360. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  2361. exit(1); // exit ok: during daemonize, chdir failed.
  2362. }
  2363. nullfd = tor_open_cloexec("/dev/null", O_RDWR, 0);
  2364. if (nullfd < 0) {
  2365. /* LCOV_EXCL_START */
  2366. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  2367. exit(1); // exit ok: during daemonize, couldn't open /dev/null
  2368. /* LCOV_EXCL_STOP */
  2369. }
  2370. /* close fds linking to invoking terminal, but
  2371. * close usual incoming fds, but redirect them somewhere
  2372. * useful so the fds don't get reallocated elsewhere.
  2373. */
  2374. if (dup2(nullfd,0) < 0 ||
  2375. dup2(nullfd,1) < 0 ||
  2376. dup2(nullfd,2) < 0) {
  2377. /* LCOV_EXCL_START */
  2378. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  2379. exit(1); // exit ok: during daemonize, dup2 failed.
  2380. /* LCOV_EXCL_STOP */
  2381. }
  2382. if (nullfd > 2)
  2383. close(nullfd);
  2384. /* signal success */
  2385. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  2386. log_err(LD_GENERAL,"write failed. Exiting.");
  2387. }
  2388. close(daemon_filedes[1]);
  2389. }
  2390. #else /* !(!defined(_WIN32)) */
  2391. /* defined(_WIN32) */
  2392. void
  2393. start_daemon(void)
  2394. {
  2395. }
  2396. void
  2397. finish_daemon(const char *cp)
  2398. {
  2399. (void)cp;
  2400. }
  2401. #endif /* !defined(_WIN32) */
  2402. /** Write the current process ID, followed by NL, into <b>filename</b>.
  2403. * Return 0 on success, -1 on failure.
  2404. */
  2405. int
  2406. write_pidfile(const char *filename)
  2407. {
  2408. FILE *pidfile;
  2409. if ((pidfile = fopen(filename, "w")) == NULL) {
  2410. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  2411. strerror(errno));
  2412. return -1;
  2413. } else {
  2414. #ifdef _WIN32
  2415. int pid = (int)_getpid();
  2416. #else
  2417. int pid = (int)getpid();
  2418. #endif
  2419. int rv = 0;
  2420. if (fprintf(pidfile, "%d\n", pid) < 0)
  2421. rv = -1;
  2422. if (fclose(pidfile) < 0)
  2423. rv = -1;
  2424. return rv;
  2425. }
  2426. }
  2427. #ifdef _WIN32
  2428. HANDLE
  2429. load_windows_system_library(const TCHAR *library_name)
  2430. {
  2431. TCHAR path[MAX_PATH];
  2432. unsigned n;
  2433. n = GetSystemDirectory(path, MAX_PATH);
  2434. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  2435. return 0;
  2436. _tcscat(path, TEXT("\\"));
  2437. _tcscat(path, library_name);
  2438. return LoadLibrary(path);
  2439. }
  2440. #endif /* defined(_WIN32) */
  2441. /** Format a single argument for being put on a Windows command line.
  2442. * Returns a newly allocated string */
  2443. static char *
  2444. format_win_cmdline_argument(const char *arg)
  2445. {
  2446. char *formatted_arg;
  2447. char need_quotes;
  2448. const char *c;
  2449. int i;
  2450. int bs_counter = 0;
  2451. /* Backslash we can point to when one is inserted into the string */
  2452. const char backslash = '\\';
  2453. /* Smartlist of *char */
  2454. smartlist_t *arg_chars;
  2455. arg_chars = smartlist_new();
  2456. /* Quote string if it contains whitespace or is empty */
  2457. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  2458. /* Build up smartlist of *chars */
  2459. for (c=arg; *c != '\0'; c++) {
  2460. if ('"' == *c) {
  2461. /* Double up backslashes preceding a quote */
  2462. for (i=0; i<(bs_counter*2); i++)
  2463. smartlist_add(arg_chars, (void*)&backslash);
  2464. bs_counter = 0;
  2465. /* Escape the quote */
  2466. smartlist_add(arg_chars, (void*)&backslash);
  2467. smartlist_add(arg_chars, (void*)c);
  2468. } else if ('\\' == *c) {
  2469. /* Count backslashes until we know whether to double up */
  2470. bs_counter++;
  2471. } else {
  2472. /* Don't double up slashes preceding a non-quote */
  2473. for (i=0; i<bs_counter; i++)
  2474. smartlist_add(arg_chars, (void*)&backslash);
  2475. bs_counter = 0;
  2476. smartlist_add(arg_chars, (void*)c);
  2477. }
  2478. }
  2479. /* Don't double up trailing backslashes */
  2480. for (i=0; i<bs_counter; i++)
  2481. smartlist_add(arg_chars, (void*)&backslash);
  2482. /* Allocate space for argument, quotes (if needed), and terminator */
  2483. const size_t formatted_arg_len = smartlist_len(arg_chars) +
  2484. (need_quotes ? 2 : 0) + 1;
  2485. formatted_arg = tor_malloc_zero(formatted_arg_len);
  2486. /* Add leading quote */
  2487. i=0;
  2488. if (need_quotes)
  2489. formatted_arg[i++] = '"';
  2490. /* Add characters */
  2491. SMARTLIST_FOREACH(arg_chars, char*, ch,
  2492. {
  2493. formatted_arg[i++] = *ch;
  2494. });
  2495. /* Add trailing quote */
  2496. if (need_quotes)
  2497. formatted_arg[i++] = '"';
  2498. formatted_arg[i] = '\0';
  2499. smartlist_free(arg_chars);
  2500. return formatted_arg;
  2501. }
  2502. /** Format a command line for use on Windows, which takes the command as a
  2503. * string rather than string array. Follows the rules from "Parsing C++
  2504. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  2505. * Python subprocess module. Returns a newly allocated string */
  2506. char *
  2507. tor_join_win_cmdline(const char *argv[])
  2508. {
  2509. smartlist_t *argv_list;
  2510. char *joined_argv;
  2511. int i;
  2512. /* Format each argument and put the result in a smartlist */
  2513. argv_list = smartlist_new();
  2514. for (i=0; argv[i] != NULL; i++) {
  2515. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  2516. }
  2517. /* Join the arguments with whitespace */
  2518. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  2519. /* Free the newly allocated arguments, and the smartlist */
  2520. SMARTLIST_FOREACH(argv_list, char *, arg,
  2521. {
  2522. tor_free(arg);
  2523. });
  2524. smartlist_free(argv_list);
  2525. return joined_argv;
  2526. }
  2527. #ifndef _WIN32
  2528. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  2529. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  2530. * safe.
  2531. *
  2532. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE+1 bytes available.
  2533. *
  2534. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  2535. * with spaces. CHILD_STATE indicates where
  2536. * in the process of starting the child process did the failure occur (see
  2537. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  2538. * errno when the failure occurred.
  2539. *
  2540. * On success return the number of characters added to hex_errno, not counting
  2541. * the terminating NUL; return -1 on error.
  2542. */
  2543. STATIC int
  2544. format_helper_exit_status(unsigned char child_state, int saved_errno,
  2545. char *hex_errno)
  2546. {
  2547. unsigned int unsigned_errno;
  2548. int written, left;
  2549. char *cur;
  2550. size_t i;
  2551. int res = -1;
  2552. /* Fill hex_errno with spaces, and a trailing newline (memset may
  2553. not be signal handler safe, so we can't use it) */
  2554. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  2555. hex_errno[i] = ' ';
  2556. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  2557. /* Convert errno to be unsigned for hex conversion */
  2558. if (saved_errno < 0) {
  2559. // Avoid overflow on the cast to unsigned int when result is INT_MIN
  2560. // by adding 1 to the signed int negative value,
  2561. // then, after it has been negated and cast to unsigned,
  2562. // adding the original 1 back (the double-addition is intentional).
  2563. // Otherwise, the cast to signed could cause a temporary int
  2564. // to equal INT_MAX + 1, which is undefined.
  2565. unsigned_errno = ((unsigned int) -(saved_errno + 1)) + 1;
  2566. } else {
  2567. unsigned_errno = (unsigned int) saved_errno;
  2568. }
  2569. /*
  2570. * Count how many chars of space we have left, and keep a pointer into the
  2571. * current point in the buffer.
  2572. */
  2573. left = HEX_ERRNO_SIZE+1;
  2574. cur = hex_errno;
  2575. /* Emit child_state */
  2576. written = format_hex_number_sigsafe(child_state, cur, left);
  2577. if (written <= 0)
  2578. goto err;
  2579. /* Adjust left and cur */
  2580. left -= written;
  2581. cur += written;
  2582. if (left <= 0)
  2583. goto err;
  2584. /* Now the '/' */
  2585. *cur = '/';
  2586. /* Adjust left and cur */
  2587. ++cur;
  2588. --left;
  2589. if (left <= 0)
  2590. goto err;
  2591. /* Need minus? */
  2592. if (saved_errno < 0) {
  2593. *cur = '-';
  2594. ++cur;
  2595. --left;
  2596. if (left <= 0)
  2597. goto err;
  2598. }
  2599. /* Emit unsigned_errno */
  2600. written = format_hex_number_sigsafe(unsigned_errno, cur, left);
  2601. if (written <= 0)
  2602. goto err;
  2603. /* Adjust left and cur */
  2604. left -= written;
  2605. cur += written;
  2606. /* Check that we have enough space left for a newline and a NUL */
  2607. if (left <= 1)
  2608. goto err;
  2609. /* Emit the newline and NUL */
  2610. *cur++ = '\n';
  2611. *cur++ = '\0';
  2612. res = (int)(cur - hex_errno - 1);
  2613. goto done;
  2614. err:
  2615. /*
  2616. * In error exit, just write a '\0' in the first char so whatever called
  2617. * this at least won't fall off the end.
  2618. */
  2619. *hex_errno = '\0';
  2620. done:
  2621. return res;
  2622. }
  2623. #endif /* !defined(_WIN32) */
  2624. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  2625. #define DEFAULT_MAX_FD 256
  2626. /** Terminate the process of <b>process_handle</b>, if that process has not
  2627. * already exited.
  2628. *
  2629. * Return 0 if we succeeded in terminating the process (or if the process
  2630. * already exited), and -1 if we tried to kill the process but failed.
  2631. *
  2632. * Based on code originally borrowed from Python's os.kill. */
  2633. int
  2634. tor_terminate_process(process_handle_t *process_handle)
  2635. {
  2636. #ifdef _WIN32
  2637. if (tor_get_exit_code(process_handle, 0, NULL) == PROCESS_EXIT_RUNNING) {
  2638. HANDLE handle = process_handle->pid.hProcess;
  2639. if (!TerminateProcess(handle, 0))
  2640. return -1;
  2641. else
  2642. return 0;
  2643. }
  2644. #else /* !(defined(_WIN32)) */
  2645. if (process_handle->waitpid_cb) {
  2646. /* We haven't got a waitpid yet, so we can just kill off the process. */
  2647. return kill(process_handle->pid, SIGTERM);
  2648. }
  2649. #endif /* defined(_WIN32) */
  2650. return 0; /* We didn't need to kill the process, so report success */
  2651. }
  2652. /** Return the Process ID of <b>process_handle</b>. */
  2653. int
  2654. tor_process_get_pid(process_handle_t *process_handle)
  2655. {
  2656. #ifdef _WIN32
  2657. return (int) process_handle->pid.dwProcessId;
  2658. #else
  2659. return (int) process_handle->pid;
  2660. #endif
  2661. }
  2662. #ifdef _WIN32
  2663. HANDLE
  2664. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  2665. {
  2666. return process_handle->stdout_pipe;
  2667. }
  2668. #else /* !(defined(_WIN32)) */
  2669. /* DOCDOC tor_process_get_stdout_pipe */
  2670. int
  2671. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  2672. {
  2673. return process_handle->stdout_pipe;
  2674. }
  2675. #endif /* defined(_WIN32) */
  2676. /* DOCDOC process_handle_new */
  2677. static process_handle_t *
  2678. process_handle_new(void)
  2679. {
  2680. process_handle_t *out = tor_malloc_zero(sizeof(process_handle_t));
  2681. #ifdef _WIN32
  2682. out->stdin_pipe = INVALID_HANDLE_VALUE;
  2683. out->stdout_pipe = INVALID_HANDLE_VALUE;
  2684. out->stderr_pipe = INVALID_HANDLE_VALUE;
  2685. #else
  2686. out->stdin_pipe = -1;
  2687. out->stdout_pipe = -1;
  2688. out->stderr_pipe = -1;
  2689. #endif /* defined(_WIN32) */
  2690. return out;
  2691. }
  2692. #ifndef _WIN32
  2693. /** Invoked when a process that we've launched via tor_spawn_background() has
  2694. * been found to have terminated.
  2695. */
  2696. static void
  2697. process_handle_waitpid_cb(int status, void *arg)
  2698. {
  2699. process_handle_t *process_handle = arg;
  2700. process_handle->waitpid_exit_status = status;
  2701. clear_waitpid_callback(process_handle->waitpid_cb);
  2702. if (process_handle->status == PROCESS_STATUS_RUNNING)
  2703. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  2704. process_handle->waitpid_cb = 0;
  2705. }
  2706. #endif /* !defined(_WIN32) */
  2707. /**
  2708. * @name child-process states
  2709. *
  2710. * Each of these values represents a possible state that a child process can
  2711. * be in. They're used to determine what to say when telling the parent how
  2712. * far along we were before failure.
  2713. *
  2714. * @{
  2715. */
  2716. #define CHILD_STATE_INIT 0
  2717. #define CHILD_STATE_PIPE 1
  2718. #define CHILD_STATE_MAXFD 2
  2719. #define CHILD_STATE_FORK 3
  2720. #define CHILD_STATE_DUPOUT 4
  2721. #define CHILD_STATE_DUPERR 5
  2722. #define CHILD_STATE_DUPIN 6
  2723. #define CHILD_STATE_CLOSEFD 7
  2724. #define CHILD_STATE_EXEC 8
  2725. #define CHILD_STATE_FAILEXEC 9
  2726. /** @} */
  2727. /**
  2728. * Boolean. If true, then Tor may call execve or CreateProcess via
  2729. * tor_spawn_background.
  2730. **/
  2731. static int may_spawn_background_process = 1;
  2732. /**
  2733. * Turn off may_spawn_background_process, so that all future calls to
  2734. * tor_spawn_background are guaranteed to fail.
  2735. **/
  2736. void
  2737. tor_disable_spawning_background_processes(void)
  2738. {
  2739. may_spawn_background_process = 0;
  2740. }
  2741. /** Start a program in the background. If <b>filename</b> contains a '/', then
  2742. * it will be treated as an absolute or relative path. Otherwise, on
  2743. * non-Windows systems, the system path will be searched for <b>filename</b>.
  2744. * On Windows, only the current directory will be searched. Here, to search the
  2745. * system path (as well as the application directory, current working
  2746. * directory, and system directories), set filename to NULL.
  2747. *
  2748. * The strings in <b>argv</b> will be passed as the command line arguments of
  2749. * the child program (following convention, argv[0] should normally be the
  2750. * filename of the executable, and this must be the case if <b>filename</b> is
  2751. * NULL). The last element of argv must be NULL. A handle to the child process
  2752. * will be returned in process_handle (which must be non-NULL). Read
  2753. * process_handle.status to find out if the process was successfully launched.
  2754. * For convenience, process_handle.status is returned by this function.
  2755. *
  2756. * Some parts of this code are based on the POSIX subprocess module from
  2757. * Python, and example code from
  2758. * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
  2759. */
  2760. int
  2761. tor_spawn_background(const char *const filename, const char **argv,
  2762. process_environment_t *env,
  2763. process_handle_t **process_handle_out)
  2764. {
  2765. if (BUG(may_spawn_background_process == 0)) {
  2766. /* We should never reach this point if we're forbidden to spawn
  2767. * processes. Instead we should have caught the attempt earlier. */
  2768. return PROCESS_STATUS_ERROR;
  2769. }
  2770. #ifdef _WIN32
  2771. HANDLE stdout_pipe_read = NULL;
  2772. HANDLE stdout_pipe_write = NULL;
  2773. HANDLE stderr_pipe_read = NULL;
  2774. HANDLE stderr_pipe_write = NULL;
  2775. HANDLE stdin_pipe_read = NULL;
  2776. HANDLE stdin_pipe_write = NULL;
  2777. process_handle_t *process_handle;
  2778. int status;
  2779. STARTUPINFOA siStartInfo;
  2780. BOOL retval = FALSE;
  2781. SECURITY_ATTRIBUTES saAttr;
  2782. char *joined_argv;
  2783. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  2784. saAttr.bInheritHandle = TRUE;
  2785. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  2786. saAttr.lpSecurityDescriptor = NULL;
  2787. /* Assume failure to start process */
  2788. status = PROCESS_STATUS_ERROR;
  2789. /* Set up pipe for stdout */
  2790. if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, &saAttr, 0)) {
  2791. log_warn(LD_GENERAL,
  2792. "Failed to create pipe for stdout communication with child process: %s",
  2793. format_win32_error(GetLastError()));
  2794. return status;
  2795. }
  2796. if (!SetHandleInformation(stdout_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  2797. log_warn(LD_GENERAL,
  2798. "Failed to configure pipe for stdout communication with child "
  2799. "process: %s", format_win32_error(GetLastError()));
  2800. return status;
  2801. }
  2802. /* Set up pipe for stderr */
  2803. if (!CreatePipe(&stderr_pipe_read, &stderr_pipe_write, &saAttr, 0)) {
  2804. log_warn(LD_GENERAL,
  2805. "Failed to create pipe for stderr communication with child process: %s",
  2806. format_win32_error(GetLastError()));
  2807. return status;
  2808. }
  2809. if (!SetHandleInformation(stderr_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  2810. log_warn(LD_GENERAL,
  2811. "Failed to configure pipe for stderr communication with child "
  2812. "process: %s", format_win32_error(GetLastError()));
  2813. return status;
  2814. }
  2815. /* Set up pipe for stdin */
  2816. if (!CreatePipe(&stdin_pipe_read, &stdin_pipe_write, &saAttr, 0)) {
  2817. log_warn(LD_GENERAL,
  2818. "Failed to create pipe for stdin communication with child process: %s",
  2819. format_win32_error(GetLastError()));
  2820. return status;
  2821. }
  2822. if (!SetHandleInformation(stdin_pipe_write, HANDLE_FLAG_INHERIT, 0)) {
  2823. log_warn(LD_GENERAL,
  2824. "Failed to configure pipe for stdin communication with child "
  2825. "process: %s", format_win32_error(GetLastError()));
  2826. return status;
  2827. }
  2828. /* Create the child process */
  2829. /* Windows expects argv to be a whitespace delimited string, so join argv up
  2830. */
  2831. joined_argv = tor_join_win_cmdline(argv);
  2832. process_handle = process_handle_new();
  2833. process_handle->status = status;
  2834. ZeroMemory(&(process_handle->pid), sizeof(PROCESS_INFORMATION));
  2835. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  2836. siStartInfo.cb = sizeof(STARTUPINFO);
  2837. siStartInfo.hStdError = stderr_pipe_write;
  2838. siStartInfo.hStdOutput = stdout_pipe_write;
  2839. siStartInfo.hStdInput = stdin_pipe_read;
  2840. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  2841. /* Create the child process */
  2842. retval = CreateProcessA(filename, // module name
  2843. joined_argv, // command line
  2844. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  2845. NULL, // process security attributes
  2846. NULL, // primary thread security attributes
  2847. TRUE, // handles are inherited
  2848. /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
  2849. * work?) */
  2850. CREATE_NO_WINDOW, // creation flags
  2851. (env==NULL) ? NULL : env->windows_environment_block,
  2852. NULL, // use parent's current directory
  2853. &siStartInfo, // STARTUPINFO pointer
  2854. &(process_handle->pid)); // receives PROCESS_INFORMATION
  2855. tor_free(joined_argv);
  2856. if (!retval) {
  2857. log_warn(LD_GENERAL,
  2858. "Failed to create child process %s: %s", filename?filename:argv[0],
  2859. format_win32_error(GetLastError()));
  2860. tor_free(process_handle);
  2861. } else {
  2862. /* TODO: Close hProcess and hThread in process_handle->pid? */
  2863. process_handle->stdout_pipe = stdout_pipe_read;
  2864. process_handle->stderr_pipe = stderr_pipe_read;
  2865. process_handle->stdin_pipe = stdin_pipe_write;
  2866. status = process_handle->status = PROCESS_STATUS_RUNNING;
  2867. }
  2868. /* TODO: Close pipes on exit */
  2869. *process_handle_out = process_handle;
  2870. return status;
  2871. #else /* !(defined(_WIN32)) */
  2872. pid_t pid;
  2873. int stdout_pipe[2];
  2874. int stderr_pipe[2];
  2875. int stdin_pipe[2];
  2876. int fd, retval;
  2877. process_handle_t *process_handle;
  2878. int status;
  2879. const char *error_message = SPAWN_ERROR_MESSAGE;
  2880. size_t error_message_length;
  2881. /* Represents where in the process of spawning the program is;
  2882. this is used for printing out the error message */
  2883. unsigned char child_state = CHILD_STATE_INIT;
  2884. char hex_errno[HEX_ERRNO_SIZE + 2]; /* + 1 should be sufficient actually */
  2885. static int max_fd = -1;
  2886. status = PROCESS_STATUS_ERROR;
  2887. /* We do the strlen here because strlen() is not signal handler safe,
  2888. and we are not allowed to use unsafe functions between fork and exec */
  2889. error_message_length = strlen(error_message);
  2890. // child_state = CHILD_STATE_PIPE;
  2891. /* Set up pipe for redirecting stdout, stderr, and stdin of child */
  2892. retval = pipe(stdout_pipe);
  2893. if (-1 == retval) {
  2894. log_warn(LD_GENERAL,
  2895. "Failed to set up pipe for stdout communication with child process: %s",
  2896. strerror(errno));
  2897. return status;
  2898. }
  2899. retval = pipe(stderr_pipe);
  2900. if (-1 == retval) {
  2901. log_warn(LD_GENERAL,
  2902. "Failed to set up pipe for stderr communication with child process: %s",
  2903. strerror(errno));
  2904. close(stdout_pipe[0]);
  2905. close(stdout_pipe[1]);
  2906. return status;
  2907. }
  2908. retval = pipe(stdin_pipe);
  2909. if (-1 == retval) {
  2910. log_warn(LD_GENERAL,
  2911. "Failed to set up pipe for stdin communication with child process: %s",
  2912. strerror(errno));
  2913. close(stdout_pipe[0]);
  2914. close(stdout_pipe[1]);
  2915. close(stderr_pipe[0]);
  2916. close(stderr_pipe[1]);
  2917. return status;
  2918. }
  2919. // child_state = CHILD_STATE_MAXFD;
  2920. #ifdef _SC_OPEN_MAX
  2921. if (-1 == max_fd) {
  2922. max_fd = (int) sysconf(_SC_OPEN_MAX);
  2923. if (max_fd == -1) {
  2924. max_fd = DEFAULT_MAX_FD;
  2925. log_warn(LD_GENERAL,
  2926. "Cannot find maximum file descriptor, assuming %d", max_fd);
  2927. }
  2928. }
  2929. #else /* !(defined(_SC_OPEN_MAX)) */
  2930. max_fd = DEFAULT_MAX_FD;
  2931. #endif /* defined(_SC_OPEN_MAX) */
  2932. // child_state = CHILD_STATE_FORK;
  2933. pid = fork();
  2934. if (0 == pid) {
  2935. /* In child */
  2936. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  2937. /* Attempt to have the kernel issue a SIGTERM if the parent
  2938. * goes away. Certain attributes of the binary being execve()ed
  2939. * will clear this during the execve() call, but it's better
  2940. * than nothing.
  2941. */
  2942. prctl(PR_SET_PDEATHSIG, SIGTERM);
  2943. #endif /* defined(HAVE_SYS_PRCTL_H) && defined(__linux__) */
  2944. child_state = CHILD_STATE_DUPOUT;
  2945. /* Link child stdout to the write end of the pipe */
  2946. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  2947. if (-1 == retval)
  2948. goto error;
  2949. child_state = CHILD_STATE_DUPERR;
  2950. /* Link child stderr to the write end of the pipe */
  2951. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  2952. if (-1 == retval)
  2953. goto error;
  2954. child_state = CHILD_STATE_DUPIN;
  2955. /* Link child stdin to the read end of the pipe */
  2956. retval = dup2(stdin_pipe[0], STDIN_FILENO);
  2957. if (-1 == retval)
  2958. goto error;
  2959. // child_state = CHILD_STATE_CLOSEFD;
  2960. close(stderr_pipe[0]);
  2961. close(stderr_pipe[1]);
  2962. close(stdout_pipe[0]);
  2963. close(stdout_pipe[1]);
  2964. close(stdin_pipe[0]);
  2965. close(stdin_pipe[1]);
  2966. /* Close all other fds, including the read end of the pipe */
  2967. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  2968. * this needless. */
  2969. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  2970. close(fd);
  2971. }
  2972. // child_state = CHILD_STATE_EXEC;
  2973. /* Call the requested program. We need the cast because
  2974. execvp doesn't define argv as const, even though it
  2975. does not modify the arguments */
  2976. if (env)
  2977. execve(filename, (char *const *) argv, env->unixoid_environment_block);
  2978. else {
  2979. static char *new_env[] = { NULL };
  2980. execve(filename, (char *const *) argv, new_env);
  2981. }
  2982. /* If we got here, the exec or open(/dev/null) failed */
  2983. child_state = CHILD_STATE_FAILEXEC;
  2984. error:
  2985. {
  2986. /* XXX: are we leaking fds from the pipe? */
  2987. int n, err=0;
  2988. ssize_t nbytes;
  2989. n = format_helper_exit_status(child_state, errno, hex_errno);
  2990. if (n >= 0) {
  2991. /* Write the error message. GCC requires that we check the return
  2992. value, but there is nothing we can do if it fails */
  2993. /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
  2994. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  2995. err = (nbytes < 0);
  2996. nbytes = write(STDOUT_FILENO, hex_errno, n);
  2997. err += (nbytes < 0);
  2998. }
  2999. _exit(err?254:255); // exit ok: in child.
  3000. }
  3001. /* Never reached, but avoids compiler warning */
  3002. return status; // LCOV_EXCL_LINE
  3003. }
  3004. /* In parent */
  3005. if (-1 == pid) {
  3006. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  3007. close(stdin_pipe[0]);
  3008. close(stdin_pipe[1]);
  3009. close(stdout_pipe[0]);
  3010. close(stdout_pipe[1]);
  3011. close(stderr_pipe[0]);
  3012. close(stderr_pipe[1]);
  3013. return status;
  3014. }
  3015. process_handle = process_handle_new();
  3016. process_handle->status = status;
  3017. process_handle->pid = pid;
  3018. /* TODO: If the child process forked but failed to exec, waitpid it */
  3019. /* Return read end of the pipes to caller, and close write end */
  3020. process_handle->stdout_pipe = stdout_pipe[0];
  3021. retval = close(stdout_pipe[1]);
  3022. if (-1 == retval) {
  3023. log_warn(LD_GENERAL,
  3024. "Failed to close write end of stdout pipe in parent process: %s",
  3025. strerror(errno));
  3026. }
  3027. process_handle->waitpid_cb = set_waitpid_callback(pid,
  3028. process_handle_waitpid_cb,
  3029. process_handle);
  3030. process_handle->stderr_pipe = stderr_pipe[0];
  3031. retval = close(stderr_pipe[1]);
  3032. if (-1 == retval) {
  3033. log_warn(LD_GENERAL,
  3034. "Failed to close write end of stderr pipe in parent process: %s",
  3035. strerror(errno));
  3036. }
  3037. /* Return write end of the stdin pipe to caller, and close the read end */
  3038. process_handle->stdin_pipe = stdin_pipe[1];
  3039. retval = close(stdin_pipe[0]);
  3040. if (-1 == retval) {
  3041. log_warn(LD_GENERAL,
  3042. "Failed to close read end of stdin pipe in parent process: %s",
  3043. strerror(errno));
  3044. }
  3045. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3046. /* Set stdin/stdout/stderr pipes to be non-blocking */
  3047. if (fcntl(process_handle->stdout_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  3048. fcntl(process_handle->stderr_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  3049. fcntl(process_handle->stdin_pipe, F_SETFL, O_NONBLOCK) < 0) {
  3050. log_warn(LD_GENERAL, "Failed to set stderror/stdout/stdin pipes "
  3051. "nonblocking in parent process: %s", strerror(errno));
  3052. }
  3053. *process_handle_out = process_handle;
  3054. return status;
  3055. #endif /* defined(_WIN32) */
  3056. }
  3057. /** Destroy all resources allocated by the process handle in
  3058. * <b>process_handle</b>.
  3059. * If <b>also_terminate_process</b> is true, also terminate the
  3060. * process of the process handle. */
  3061. MOCK_IMPL(void,
  3062. tor_process_handle_destroy,(process_handle_t *process_handle,
  3063. int also_terminate_process))
  3064. {
  3065. if (!process_handle)
  3066. return;
  3067. if (also_terminate_process) {
  3068. if (tor_terminate_process(process_handle) < 0) {
  3069. const char *errstr =
  3070. #ifdef _WIN32
  3071. format_win32_error(GetLastError());
  3072. #else
  3073. strerror(errno);
  3074. #endif
  3075. log_notice(LD_GENERAL, "Failed to terminate process with "
  3076. "PID '%d' ('%s').", tor_process_get_pid(process_handle),
  3077. errstr);
  3078. } else {
  3079. log_info(LD_GENERAL, "Terminated process with PID '%d'.",
  3080. tor_process_get_pid(process_handle));
  3081. }
  3082. }
  3083. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  3084. #ifdef _WIN32
  3085. if (process_handle->stdout_pipe)
  3086. CloseHandle(process_handle->stdout_pipe);
  3087. if (process_handle->stderr_pipe)
  3088. CloseHandle(process_handle->stderr_pipe);
  3089. if (process_handle->stdin_pipe)
  3090. CloseHandle(process_handle->stdin_pipe);
  3091. #else /* !(defined(_WIN32)) */
  3092. close(process_handle->stdout_pipe);
  3093. close(process_handle->stderr_pipe);
  3094. close(process_handle->stdin_pipe);
  3095. clear_waitpid_callback(process_handle->waitpid_cb);
  3096. #endif /* defined(_WIN32) */
  3097. memset(process_handle, 0x0f, sizeof(process_handle_t));
  3098. tor_free(process_handle);
  3099. }
  3100. /** Get the exit code of a process specified by <b>process_handle</b> and store
  3101. * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
  3102. * to true, the call will block until the process has exited. Otherwise if
  3103. * the process is still running, the function will return
  3104. * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
  3105. * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
  3106. * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
  3107. * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
  3108. * probably not work in Tor, because waitpid() is called in main.c to reap any
  3109. * terminated child processes.*/
  3110. int
  3111. tor_get_exit_code(process_handle_t *process_handle,
  3112. int block, int *exit_code)
  3113. {
  3114. #ifdef _WIN32
  3115. DWORD retval;
  3116. BOOL success;
  3117. if (block) {
  3118. /* Wait for the process to exit */
  3119. retval = WaitForSingleObject(process_handle->pid.hProcess, INFINITE);
  3120. if (retval != WAIT_OBJECT_0) {
  3121. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3122. (int)retval, format_win32_error(GetLastError()));
  3123. return PROCESS_EXIT_ERROR;
  3124. }
  3125. } else {
  3126. retval = WaitForSingleObject(process_handle->pid.hProcess, 0);
  3127. if (WAIT_TIMEOUT == retval) {
  3128. /* Process has not exited */
  3129. return PROCESS_EXIT_RUNNING;
  3130. } else if (retval != WAIT_OBJECT_0) {
  3131. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3132. (int)retval, format_win32_error(GetLastError()));
  3133. return PROCESS_EXIT_ERROR;
  3134. }
  3135. }
  3136. if (exit_code != NULL) {
  3137. success = GetExitCodeProcess(process_handle->pid.hProcess,
  3138. (PDWORD)exit_code);
  3139. if (!success) {
  3140. log_warn(LD_GENERAL, "GetExitCodeProcess() failed: %s",
  3141. format_win32_error(GetLastError()));
  3142. return PROCESS_EXIT_ERROR;
  3143. }
  3144. }
  3145. #else /* !(defined(_WIN32)) */
  3146. int stat_loc;
  3147. int retval;
  3148. if (process_handle->waitpid_cb) {
  3149. /* We haven't processed a SIGCHLD yet. */
  3150. retval = waitpid(process_handle->pid, &stat_loc, block?0:WNOHANG);
  3151. if (retval == process_handle->pid) {
  3152. clear_waitpid_callback(process_handle->waitpid_cb);
  3153. process_handle->waitpid_cb = NULL;
  3154. process_handle->waitpid_exit_status = stat_loc;
  3155. }
  3156. } else {
  3157. /* We already got a SIGCHLD for this process, and handled it. */
  3158. retval = process_handle->pid;
  3159. stat_loc = process_handle->waitpid_exit_status;
  3160. }
  3161. if (!block && 0 == retval) {
  3162. /* Process has not exited */
  3163. return PROCESS_EXIT_RUNNING;
  3164. } else if (retval != process_handle->pid) {
  3165. log_warn(LD_GENERAL, "waitpid() failed for PID %d: %s",
  3166. (int)process_handle->pid, strerror(errno));
  3167. return PROCESS_EXIT_ERROR;
  3168. }
  3169. if (!WIFEXITED(stat_loc)) {
  3170. log_warn(LD_GENERAL, "Process %d did not exit normally",
  3171. (int)process_handle->pid);
  3172. return PROCESS_EXIT_ERROR;
  3173. }
  3174. if (exit_code != NULL)
  3175. *exit_code = WEXITSTATUS(stat_loc);
  3176. #endif /* defined(_WIN32) */
  3177. return PROCESS_EXIT_EXITED;
  3178. }
  3179. /** Helper: return the number of characters in <b>s</b> preceding the first
  3180. * occurrence of <b>ch</b>. If <b>ch</b> does not occur in <b>s</b>, return
  3181. * the length of <b>s</b>. Should be equivalent to strspn(s, "ch"). */
  3182. static inline size_t
  3183. str_num_before(const char *s, char ch)
  3184. {
  3185. const char *cp = strchr(s, ch);
  3186. if (cp)
  3187. return cp - s;
  3188. else
  3189. return strlen(s);
  3190. }
  3191. /** Return non-zero iff getenv would consider <b>s1</b> and <b>s2</b>
  3192. * to have the same name as strings in a process's environment. */
  3193. int
  3194. environment_variable_names_equal(const char *s1, const char *s2)
  3195. {
  3196. size_t s1_name_len = str_num_before(s1, '=');
  3197. size_t s2_name_len = str_num_before(s2, '=');
  3198. return (s1_name_len == s2_name_len &&
  3199. tor_memeq(s1, s2, s1_name_len));
  3200. }
  3201. /** Free <b>env</b> (assuming it was produced by
  3202. * process_environment_make). */
  3203. void
  3204. process_environment_free_(process_environment_t *env)
  3205. {
  3206. if (env == NULL) return;
  3207. /* As both an optimization hack to reduce consing on Unixoid systems
  3208. * and a nice way to ensure that some otherwise-Windows-specific
  3209. * code will always get tested before changes to it get merged, the
  3210. * strings which env->unixoid_environment_block points to are packed
  3211. * into env->windows_environment_block. */
  3212. tor_free(env->unixoid_environment_block);
  3213. tor_free(env->windows_environment_block);
  3214. tor_free(env);
  3215. }
  3216. /** Make a process_environment_t containing the environment variables
  3217. * specified in <b>env_vars</b> (as C strings of the form
  3218. * "NAME=VALUE"). */
  3219. process_environment_t *
  3220. process_environment_make(struct smartlist_t *env_vars)
  3221. {
  3222. process_environment_t *env = tor_malloc_zero(sizeof(process_environment_t));
  3223. int n_env_vars = smartlist_len(env_vars);
  3224. int i;
  3225. size_t total_env_length;
  3226. smartlist_t *env_vars_sorted;
  3227. tor_assert(n_env_vars + 1 != 0);
  3228. env->unixoid_environment_block = tor_calloc(n_env_vars + 1, sizeof(char *));
  3229. /* env->unixoid_environment_block is already NULL-terminated,
  3230. * because we assume that NULL == 0 (and check that during compilation). */
  3231. total_env_length = 1; /* terminating NUL of terminating empty string */
  3232. for (i = 0; i < n_env_vars; ++i) {
  3233. const char *s = smartlist_get(env_vars, (int)i);
  3234. size_t slen = strlen(s);
  3235. tor_assert(slen + 1 != 0);
  3236. tor_assert(slen + 1 < SIZE_MAX - total_env_length);
  3237. total_env_length += slen + 1;
  3238. }
  3239. env->windows_environment_block = tor_malloc_zero(total_env_length);
  3240. /* env->windows_environment_block is already
  3241. * (NUL-terminated-empty-string)-terminated. */
  3242. /* Some versions of Windows supposedly require that environment
  3243. * blocks be sorted. Or maybe some Windows programs (or their
  3244. * runtime libraries) fail to look up strings in non-sorted
  3245. * environment blocks.
  3246. *
  3247. * Also, sorting strings makes it easy to find duplicate environment
  3248. * variables and environment-variable strings without an '=' on all
  3249. * OSes, and they can cause badness. Let's complain about those. */
  3250. env_vars_sorted = smartlist_new();
  3251. smartlist_add_all(env_vars_sorted, env_vars);
  3252. smartlist_sort_strings(env_vars_sorted);
  3253. /* Now copy the strings into the environment blocks. */
  3254. {
  3255. char *cp = env->windows_environment_block;
  3256. const char *prev_env_var = NULL;
  3257. for (i = 0; i < n_env_vars; ++i) {
  3258. const char *s = smartlist_get(env_vars_sorted, (int)i);
  3259. size_t slen = strlen(s);
  3260. size_t s_name_len = str_num_before(s, '=');
  3261. if (s_name_len == slen) {
  3262. log_warn(LD_GENERAL,
  3263. "Preparing an environment containing a variable "
  3264. "without a value: %s",
  3265. s);
  3266. }
  3267. if (prev_env_var != NULL &&
  3268. environment_variable_names_equal(s, prev_env_var)) {
  3269. log_warn(LD_GENERAL,
  3270. "Preparing an environment containing two variables "
  3271. "with the same name: %s and %s",
  3272. prev_env_var, s);
  3273. }
  3274. prev_env_var = s;
  3275. /* Actually copy the string into the environment. */
  3276. memcpy(cp, s, slen+1);
  3277. env->unixoid_environment_block[i] = cp;
  3278. cp += slen+1;
  3279. }
  3280. tor_assert(cp == env->windows_environment_block + total_env_length - 1);
  3281. }
  3282. smartlist_free(env_vars_sorted);
  3283. return env;
  3284. }
  3285. /** Return a newly allocated smartlist containing every variable in
  3286. * this process's environment, as a NUL-terminated string of the form
  3287. * "NAME=VALUE". Note that on some/many/most/all OSes, the parent
  3288. * process can put strings not of that form in our environment;
  3289. * callers should try to not get crashed by that.
  3290. *
  3291. * The returned strings are heap-allocated, and must be freed by the
  3292. * caller. */
  3293. struct smartlist_t *
  3294. get_current_process_environment_variables(void)
  3295. {
  3296. smartlist_t *sl = smartlist_new();
  3297. char **environ_tmp; /* Not const char ** ? Really? */
  3298. for (environ_tmp = get_environment(); *environ_tmp; ++environ_tmp) {
  3299. smartlist_add_strdup(sl, *environ_tmp);
  3300. }
  3301. return sl;
  3302. }
  3303. /** For each string s in <b>env_vars</b> such that
  3304. * environment_variable_names_equal(s, <b>new_var</b>), remove it; if
  3305. * <b>free_p</b> is non-zero, call <b>free_old</b>(s). If
  3306. * <b>new_var</b> contains '=', insert it into <b>env_vars</b>. */
  3307. void
  3308. set_environment_variable_in_smartlist(struct smartlist_t *env_vars,
  3309. const char *new_var,
  3310. void (*free_old)(void*),
  3311. int free_p)
  3312. {
  3313. SMARTLIST_FOREACH_BEGIN(env_vars, const char *, s) {
  3314. if (environment_variable_names_equal(s, new_var)) {
  3315. SMARTLIST_DEL_CURRENT(env_vars, s);
  3316. if (free_p) {
  3317. free_old((void *)s);
  3318. }
  3319. }
  3320. } SMARTLIST_FOREACH_END(s);
  3321. if (strchr(new_var, '=') != NULL) {
  3322. smartlist_add(env_vars, (void *)new_var);
  3323. }
  3324. }
  3325. #ifdef _WIN32
  3326. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3327. * <b>hProcess</b> is NULL, the function will return immediately if there is
  3328. * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
  3329. * to the process owning the <b>h</b>. In this case, the function will exit
  3330. * only once the process has exited, or <b>count</b> bytes are read. Returns
  3331. * the number of bytes read, or -1 on error. */
  3332. ssize_t
  3333. tor_read_all_handle(HANDLE h, char *buf, size_t count,
  3334. const process_handle_t *process)
  3335. {
  3336. size_t numread = 0;
  3337. BOOL retval;
  3338. DWORD byte_count;
  3339. BOOL process_exited = FALSE;
  3340. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  3341. return -1;
  3342. while (numread < count) {
  3343. /* Check if there is anything to read */
  3344. retval = PeekNamedPipe(h, NULL, 0, NULL, &byte_count, NULL);
  3345. if (!retval) {
  3346. log_warn(LD_GENERAL,
  3347. "Failed to peek from handle: %s",
  3348. format_win32_error(GetLastError()));
  3349. return -1;
  3350. } else if (0 == byte_count) {
  3351. /* Nothing available: process exited or it is busy */
  3352. /* Exit if we don't know whether the process is running */
  3353. if (NULL == process)
  3354. break;
  3355. /* The process exited and there's nothing left to read from it */
  3356. if (process_exited)
  3357. break;
  3358. /* If process is not running, check for output one more time in case
  3359. it wrote something after the peek was performed. Otherwise keep on
  3360. waiting for output */
  3361. tor_assert(process != NULL);
  3362. byte_count = WaitForSingleObject(process->pid.hProcess, 0);
  3363. if (WAIT_TIMEOUT != byte_count)
  3364. process_exited = TRUE;
  3365. continue;
  3366. }
  3367. /* There is data to read; read it */
  3368. retval = ReadFile(h, buf+numread, count-numread, &byte_count, NULL);
  3369. tor_assert(byte_count + numread <= count);
  3370. if (!retval) {
  3371. log_warn(LD_GENERAL, "Failed to read from handle: %s",
  3372. format_win32_error(GetLastError()));
  3373. return -1;
  3374. } else if (0 == byte_count) {
  3375. /* End of file */
  3376. break;
  3377. }
  3378. numread += byte_count;
  3379. }
  3380. return (ssize_t)numread;
  3381. }
  3382. #else /* !(defined(_WIN32)) */
  3383. /** Read from a handle <b>fd</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3384. * <b>process</b> is NULL, the function will return immediately if there is
  3385. * nothing more to read. Otherwise data will be read until end of file, or
  3386. * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
  3387. * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
  3388. * file has been reached. */
  3389. ssize_t
  3390. tor_read_all_handle(int fd, char *buf, size_t count,
  3391. const process_handle_t *process,
  3392. int *eof)
  3393. {
  3394. size_t numread = 0;
  3395. ssize_t result;
  3396. if (eof)
  3397. *eof = 0;
  3398. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  3399. return -1;
  3400. while (numread < count) {
  3401. result = read(fd, buf+numread, count-numread);
  3402. if (result == 0) {
  3403. log_debug(LD_GENERAL, "read() reached end of file");
  3404. if (eof)
  3405. *eof = 1;
  3406. break;
  3407. } else if (result < 0 && errno == EAGAIN) {
  3408. if (process)
  3409. continue;
  3410. else
  3411. break;
  3412. } else if (result < 0) {
  3413. log_warn(LD_GENERAL, "read() failed: %s", strerror(errno));
  3414. return -1;
  3415. }
  3416. numread += result;
  3417. }
  3418. log_debug(LD_GENERAL, "read() read %d bytes from handle", (int)numread);
  3419. return (ssize_t)numread;
  3420. }
  3421. #endif /* defined(_WIN32) */
  3422. /** Read from stdout of a process until the process exits. */
  3423. ssize_t
  3424. tor_read_all_from_process_stdout(const process_handle_t *process_handle,
  3425. char *buf, size_t count)
  3426. {
  3427. #ifdef _WIN32
  3428. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  3429. process_handle);
  3430. #else
  3431. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  3432. process_handle, NULL);
  3433. #endif /* defined(_WIN32) */
  3434. }
  3435. /** Read from stdout of a process until the process exits. */
  3436. ssize_t
  3437. tor_read_all_from_process_stderr(const process_handle_t *process_handle,
  3438. char *buf, size_t count)
  3439. {
  3440. #ifdef _WIN32
  3441. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  3442. process_handle);
  3443. #else
  3444. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  3445. process_handle, NULL);
  3446. #endif /* defined(_WIN32) */
  3447. }
  3448. /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
  3449. * modified. The resulting smartlist will consist of pointers to buf, so there
  3450. * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
  3451. * string. <b>len</b> should be set to the length of the buffer excluding the
  3452. * NUL. Non-printable characters (including NUL) will be replaced with "." */
  3453. int
  3454. tor_split_lines(smartlist_t *sl, char *buf, int len)
  3455. {
  3456. /* Index in buf of the start of the current line */
  3457. int start = 0;
  3458. /* Index in buf of the current character being processed */
  3459. int cur = 0;
  3460. /* Are we currently in a line */
  3461. char in_line = 0;
  3462. /* Loop over string */
  3463. while (cur < len) {
  3464. /* Loop until end of line or end of string */
  3465. for (; cur < len; cur++) {
  3466. if (in_line) {
  3467. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  3468. /* End of line */
  3469. buf[cur] = '\0';
  3470. /* Point cur to the next line */
  3471. cur++;
  3472. /* Line starts at start and ends with a nul */
  3473. break;
  3474. } else {
  3475. if (!TOR_ISPRINT(buf[cur]))
  3476. buf[cur] = '.';
  3477. }
  3478. } else {
  3479. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  3480. /* Skip leading vertical space */
  3481. ;
  3482. } else {
  3483. in_line = 1;
  3484. start = cur;
  3485. if (!TOR_ISPRINT(buf[cur]))
  3486. buf[cur] = '.';
  3487. }
  3488. }
  3489. }
  3490. /* We are at the end of the line or end of string. If in_line is true there
  3491. * is a line which starts at buf+start and ends at a NUL. cur points to
  3492. * the character after the NUL. */
  3493. if (in_line)
  3494. smartlist_add(sl, (void *)(buf+start));
  3495. in_line = 0;
  3496. }
  3497. return smartlist_len(sl);
  3498. }
  3499. /** Return a string corresponding to <b>stream_status</b>. */
  3500. const char *
  3501. stream_status_to_string(enum stream_status stream_status)
  3502. {
  3503. switch (stream_status) {
  3504. case IO_STREAM_OKAY:
  3505. return "okay";
  3506. case IO_STREAM_EAGAIN:
  3507. return "temporarily unavailable";
  3508. case IO_STREAM_TERM:
  3509. return "terminated";
  3510. case IO_STREAM_CLOSED:
  3511. return "closed";
  3512. default:
  3513. tor_fragile_assert();
  3514. return "unknown";
  3515. }
  3516. }
  3517. #ifdef _WIN32
  3518. /** Return a smartlist containing lines outputted from
  3519. * <b>handle</b>. Return NULL on error, and set
  3520. * <b>stream_status_out</b> appropriately. */
  3521. MOCK_IMPL(smartlist_t *,
  3522. tor_get_lines_from_handle, (HANDLE *handle,
  3523. enum stream_status *stream_status_out))
  3524. {
  3525. int pos;
  3526. char stdout_buf[600] = {0};
  3527. smartlist_t *lines = NULL;
  3528. tor_assert(stream_status_out);
  3529. *stream_status_out = IO_STREAM_TERM;
  3530. pos = tor_read_all_handle(handle, stdout_buf, sizeof(stdout_buf) - 1, NULL);
  3531. if (pos < 0) {
  3532. *stream_status_out = IO_STREAM_TERM;
  3533. return NULL;
  3534. }
  3535. if (pos == 0) {
  3536. *stream_status_out = IO_STREAM_EAGAIN;
  3537. return NULL;
  3538. }
  3539. /* End with a null even if there isn't a \r\n at the end */
  3540. /* TODO: What if this is a partial line? */
  3541. stdout_buf[pos] = '\0';
  3542. /* Split up the buffer */
  3543. lines = smartlist_new();
  3544. tor_split_lines(lines, stdout_buf, pos);
  3545. /* Currently 'lines' is populated with strings residing on the
  3546. stack. Replace them with their exact copies on the heap: */
  3547. SMARTLIST_FOREACH(lines, char *, line,
  3548. SMARTLIST_REPLACE_CURRENT(lines, line, tor_strdup(line)));
  3549. *stream_status_out = IO_STREAM_OKAY;
  3550. return lines;
  3551. }
  3552. #else /* !(defined(_WIN32)) */
  3553. /** Return a smartlist containing lines outputted from
  3554. * <b>fd</b>. Return NULL on error, and set
  3555. * <b>stream_status_out</b> appropriately. */
  3556. MOCK_IMPL(smartlist_t *,
  3557. tor_get_lines_from_handle, (int fd, enum stream_status *stream_status_out))
  3558. {
  3559. enum stream_status stream_status;
  3560. char stdout_buf[400];
  3561. smartlist_t *lines = NULL;
  3562. while (1) {
  3563. memset(stdout_buf, 0, sizeof(stdout_buf));
  3564. stream_status = get_string_from_pipe(fd,
  3565. stdout_buf, sizeof(stdout_buf) - 1);
  3566. if (stream_status != IO_STREAM_OKAY)
  3567. goto done;
  3568. if (!lines) lines = smartlist_new();
  3569. smartlist_split_string(lines, stdout_buf, "\n", 0, 0);
  3570. }
  3571. done:
  3572. *stream_status_out = stream_status;
  3573. return lines;
  3574. }
  3575. #endif /* defined(_WIN32) */
  3576. /** Reads from <b>fd</b> and stores input in <b>buf_out</b> making
  3577. * sure it's below <b>count</b> bytes.
  3578. * If the string has a trailing newline, we strip it off.
  3579. *
  3580. * This function is specifically created to handle input from managed
  3581. * proxies, according to the pluggable transports spec. Make sure it
  3582. * fits your needs before using it.
  3583. *
  3584. * Returns:
  3585. * IO_STREAM_CLOSED: If the stream is closed.
  3586. * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
  3587. * later.
  3588. * IO_STREAM_TERM: If something is wrong with the stream.
  3589. * IO_STREAM_OKAY: If everything went okay and we got a string
  3590. * in <b>buf_out</b>. */
  3591. enum stream_status
  3592. get_string_from_pipe(int fd, char *buf_out, size_t count)
  3593. {
  3594. ssize_t ret;
  3595. tor_assert(count <= INT_MAX);
  3596. ret = read(fd, buf_out, count);
  3597. if (ret == 0)
  3598. return IO_STREAM_CLOSED;
  3599. else if (ret < 0 && errno == EAGAIN)
  3600. return IO_STREAM_EAGAIN;
  3601. else if (ret < 0)
  3602. return IO_STREAM_TERM;
  3603. if (buf_out[ret - 1] == '\n') {
  3604. /* Remove the trailing newline */
  3605. buf_out[ret - 1] = '\0';
  3606. } else
  3607. buf_out[ret] = '\0';
  3608. return IO_STREAM_OKAY;
  3609. }
  3610. /** Initialize the insecure RNG <b>rng</b> from a seed value <b>seed</b>. */
  3611. void
  3612. tor_init_weak_random(tor_weak_rng_t *rng, unsigned seed)
  3613. {
  3614. rng->state = (uint32_t)(seed & 0x7fffffff);
  3615. }
  3616. /** Return a randomly chosen value in the range 0..TOR_WEAK_RANDOM_MAX based
  3617. * on the RNG state of <b>rng</b>. This entropy will not be cryptographically
  3618. * strong; do not rely on it for anything an adversary should not be able to
  3619. * predict. */
  3620. int32_t
  3621. tor_weak_random(tor_weak_rng_t *rng)
  3622. {
  3623. /* Here's a linear congruential generator. OpenBSD and glibc use these
  3624. * parameters; they aren't too bad, and should have maximal period over the
  3625. * range 0..INT32_MAX. We don't want to use the platform rand() or random(),
  3626. * since some platforms have bad weak RNGs that only return values in the
  3627. * range 0..INT16_MAX, which just isn't enough. */
  3628. rng->state = (rng->state * 1103515245 + 12345) & 0x7fffffff;
  3629. return (int32_t) rng->state;
  3630. }
  3631. /** Return a random number in the range [0 , <b>top</b>). {That is, the range
  3632. * of integers i such that 0 <= i < top.} Chooses uniformly. Requires that
  3633. * top is greater than 0. This randomness is not cryptographically strong; do
  3634. * not rely on it for anything an adversary should not be able to predict. */
  3635. int32_t
  3636. tor_weak_random_range(tor_weak_rng_t *rng, int32_t top)
  3637. {
  3638. /* We don't want to just do tor_weak_random() % top, since random() is often
  3639. * implemented with an LCG whose modulus is a power of 2, and those are
  3640. * cyclic in their low-order bits. */
  3641. int divisor, result;
  3642. tor_assert(top > 0);
  3643. divisor = TOR_WEAK_RANDOM_MAX / top;
  3644. do {
  3645. result = (int32_t)(tor_weak_random(rng) / divisor);
  3646. } while (result >= top);
  3647. return result;
  3648. }
  3649. /** Cast a given double value to a int64_t. Return 0 if number is NaN.
  3650. * Returns either INT64_MIN or INT64_MAX if number is outside of the int64_t
  3651. * range. */
  3652. int64_t
  3653. clamp_double_to_int64(double number)
  3654. {
  3655. int exponent;
  3656. #if defined(MINGW_ANY) && GCC_VERSION >= 409
  3657. /*
  3658. Mingw's math.h uses gcc's __builtin_choose_expr() facility to declare
  3659. isnan, isfinite, and signbit. But as implemented in at least some
  3660. versions of gcc, __builtin_choose_expr() can generate type warnings
  3661. even from branches that are not taken. So, suppress those warnings.
  3662. */
  3663. #define PROBLEMATIC_FLOAT_CONVERSION_WARNING
  3664. DISABLE_GCC_WARNING(float-conversion)
  3665. #endif /* defined(MINGW_ANY) && GCC_VERSION >= 409 */
  3666. /*
  3667. With clang 4.0 we apparently run into "double promotion" warnings here,
  3668. since clang thinks we're promoting a double to a long double.
  3669. */
  3670. #if defined(__clang__)
  3671. #if __has_warning("-Wdouble-promotion")
  3672. #define PROBLEMATIC_DOUBLE_PROMOTION_WARNING
  3673. DISABLE_GCC_WARNING(double-promotion)
  3674. #endif
  3675. #endif /* defined(__clang__) */
  3676. /* NaN is a special case that can't be used with the logic below. */
  3677. if (isnan(number)) {
  3678. return 0;
  3679. }
  3680. /* Time to validate if result can overflows a int64_t value. Fun with
  3681. * float! Find that exponent exp such that
  3682. * number == x * 2^exp
  3683. * for some x with abs(x) in [0.5, 1.0). Note that this implies that the
  3684. * magnitude of number is strictly less than 2^exp.
  3685. *
  3686. * If number is infinite, the call to frexp is legal but the contents of
  3687. * are exponent unspecified. */
  3688. frexp(number, &exponent);
  3689. /* If the magnitude of number is strictly less than 2^63, the truncated
  3690. * version of number is guaranteed to be representable. The only
  3691. * representable integer for which this is not the case is INT64_MIN, but
  3692. * it is covered by the logic below. */
  3693. if (isfinite(number) && exponent <= 63) {
  3694. return (int64_t)number;
  3695. }
  3696. /* Handle infinities and finite numbers with magnitude >= 2^63. */
  3697. return signbit(number) ? INT64_MIN : INT64_MAX;
  3698. #ifdef PROBLEMATIC_DOUBLE_PROMOTION_WARNING
  3699. ENABLE_GCC_WARNING(double-promotion)
  3700. #endif
  3701. #ifdef PROBLEMATIC_FLOAT_CONVERSION_WARNING
  3702. ENABLE_GCC_WARNING(float-conversion)
  3703. #endif
  3704. }
  3705. /** Return a uint64_t value from <b>a</b> in network byte order. */
  3706. uint64_t
  3707. tor_htonll(uint64_t a)
  3708. {
  3709. #ifdef WORDS_BIGENDIAN
  3710. /* Big endian. */
  3711. return a;
  3712. #else /* WORDS_BIGENDIAN */
  3713. /* Little endian. The worst... */
  3714. return htonl((uint32_t)(a>>32)) |
  3715. (((uint64_t)htonl((uint32_t)a))<<32);
  3716. #endif /* defined(WORDS_BIGENDIAN) */
  3717. }
  3718. /** Return a uint64_t value from <b>a</b> in host byte order. */
  3719. uint64_t
  3720. tor_ntohll(uint64_t a)
  3721. {
  3722. return tor_htonll(a);
  3723. }