util.c 114 KB

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