util.c 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680
  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 "lib/encoding/binascii.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. /** Return true if <b>string</b> is a valid 'key=[value]' string.
  222. * "value" is optional, to indicate the empty string. Log at logging
  223. * <b>severity</b> if something ugly happens. */
  224. int
  225. string_is_key_value(int severity, const char *string)
  226. {
  227. /* position of equal sign in string */
  228. const char *equal_sign_pos = NULL;
  229. tor_assert(string);
  230. if (strlen(string) < 2) { /* "x=" is shortest args string */
  231. tor_log(severity, LD_GENERAL, "'%s' is too short to be a k=v value.",
  232. escaped(string));
  233. return 0;
  234. }
  235. equal_sign_pos = strchr(string, '=');
  236. if (!equal_sign_pos) {
  237. tor_log(severity, LD_GENERAL, "'%s' is not a k=v value.", escaped(string));
  238. return 0;
  239. }
  240. /* validate that the '=' is not in the beginning of the string. */
  241. if (equal_sign_pos == string) {
  242. tor_log(severity, LD_GENERAL, "'%s' is not a valid k=v value.",
  243. escaped(string));
  244. return 0;
  245. }
  246. return 1;
  247. }
  248. /** Return a newly allocated string equal to <b>string</b>, except that every
  249. * character in <b>chars_to_escape</b> is preceded by a backslash. */
  250. char *
  251. tor_escape_str_for_pt_args(const char *string, const char *chars_to_escape)
  252. {
  253. char *new_string = NULL;
  254. char *new_cp = NULL;
  255. size_t length, new_length;
  256. tor_assert(string);
  257. length = strlen(string);
  258. if (!length) /* If we were given the empty string, return the same. */
  259. return tor_strdup("");
  260. /* (new_length > SIZE_MAX) => ((length * 2) + 1 > SIZE_MAX) =>
  261. (length*2 > SIZE_MAX - 1) => (length > (SIZE_MAX - 1)/2) */
  262. if (length > (SIZE_MAX - 1)/2) /* check for overflow */
  263. return NULL;
  264. /* this should be enough even if all characters must be escaped */
  265. new_length = (length * 2) + 1;
  266. new_string = new_cp = tor_malloc(new_length);
  267. while (*string) {
  268. if (strchr(chars_to_escape, *string))
  269. *new_cp++ = '\\';
  270. *new_cp++ = *string++;
  271. }
  272. *new_cp = '\0'; /* NUL-terminate the new string */
  273. return new_string;
  274. }
  275. /* =====
  276. * Time
  277. * ===== */
  278. #define TOR_USEC_PER_SEC 1000000
  279. /** Return the difference between start->tv_sec and end->tv_sec.
  280. * Returns INT64_MAX on overflow and underflow.
  281. */
  282. static int64_t
  283. tv_secdiff_impl(const struct timeval *start, const struct timeval *end)
  284. {
  285. const int64_t s = (int64_t)start->tv_sec;
  286. const int64_t e = (int64_t)end->tv_sec;
  287. /* This may not be the most efficient way of implemeting this check,
  288. * but it's easy to see that it's correct and doesn't overflow */
  289. if (s > 0 && e < INT64_MIN + s) {
  290. /* s is positive: equivalent to e - s < INT64_MIN, but without any
  291. * overflow */
  292. return INT64_MAX;
  293. } else if (s < 0 && e > INT64_MAX + s) {
  294. /* s is negative: equivalent to e - s > INT64_MAX, but without any
  295. * overflow */
  296. return INT64_MAX;
  297. }
  298. return e - s;
  299. }
  300. /** Return the number of microseconds elapsed between *start and *end.
  301. * Returns LONG_MAX on overflow and underflow.
  302. */
  303. long
  304. tv_udiff(const struct timeval *start, const struct timeval *end)
  305. {
  306. /* Sanity check tv_usec */
  307. if (start->tv_usec > TOR_USEC_PER_SEC || start->tv_usec < 0) {
  308. log_warn(LD_GENERAL, "comparing times on microsecond detail with bad "
  309. "start tv_usec: " I64_FORMAT " microseconds",
  310. I64_PRINTF_ARG(start->tv_usec));
  311. return LONG_MAX;
  312. }
  313. if (end->tv_usec > TOR_USEC_PER_SEC || end->tv_usec < 0) {
  314. log_warn(LD_GENERAL, "comparing times on microsecond detail with bad "
  315. "end tv_usec: " I64_FORMAT " microseconds",
  316. I64_PRINTF_ARG(end->tv_usec));
  317. return LONG_MAX;
  318. }
  319. /* Some BSDs have struct timeval.tv_sec 64-bit, but time_t (and long) 32-bit
  320. */
  321. int64_t udiff;
  322. const int64_t secdiff = tv_secdiff_impl(start, end);
  323. /* end->tv_usec - start->tv_usec can be up to 1 second either way */
  324. if (secdiff > (int64_t)(LONG_MAX/1000000 - 1) ||
  325. secdiff < (int64_t)(LONG_MIN/1000000 + 1)) {
  326. log_warn(LD_GENERAL, "comparing times on microsecond detail too far "
  327. "apart: " I64_FORMAT " seconds", I64_PRINTF_ARG(secdiff));
  328. return LONG_MAX;
  329. }
  330. /* we'll never get an overflow here, because we check that both usecs are
  331. * between 0 and TV_USEC_PER_SEC. */
  332. udiff = secdiff*1000000 + ((int64_t)end->tv_usec - (int64_t)start->tv_usec);
  333. /* Some compilers are smart enough to work out this is a no-op on L64 */
  334. #if SIZEOF_LONG < 8
  335. if (udiff > (int64_t)LONG_MAX || udiff < (int64_t)LONG_MIN) {
  336. return LONG_MAX;
  337. }
  338. #endif
  339. return (long)udiff;
  340. }
  341. /** Return the number of milliseconds elapsed between *start and *end.
  342. * If the tv_usec difference is 500, rounds away from zero.
  343. * Returns LONG_MAX on overflow and underflow.
  344. */
  345. long
  346. tv_mdiff(const struct timeval *start, const struct timeval *end)
  347. {
  348. /* Sanity check tv_usec */
  349. if (start->tv_usec > TOR_USEC_PER_SEC || start->tv_usec < 0) {
  350. log_warn(LD_GENERAL, "comparing times on millisecond detail with bad "
  351. "start tv_usec: " I64_FORMAT " microseconds",
  352. I64_PRINTF_ARG(start->tv_usec));
  353. return LONG_MAX;
  354. }
  355. if (end->tv_usec > TOR_USEC_PER_SEC || end->tv_usec < 0) {
  356. log_warn(LD_GENERAL, "comparing times on millisecond detail with bad "
  357. "end tv_usec: " I64_FORMAT " microseconds",
  358. I64_PRINTF_ARG(end->tv_usec));
  359. return LONG_MAX;
  360. }
  361. /* Some BSDs have struct timeval.tv_sec 64-bit, but time_t (and long) 32-bit
  362. */
  363. int64_t mdiff;
  364. const int64_t secdiff = tv_secdiff_impl(start, end);
  365. /* end->tv_usec - start->tv_usec can be up to 1 second either way, but the
  366. * mdiff calculation may add another temporary second for rounding.
  367. * Whether this actually causes overflow depends on the compiler's constant
  368. * folding and order of operations. */
  369. if (secdiff > (int64_t)(LONG_MAX/1000 - 2) ||
  370. secdiff < (int64_t)(LONG_MIN/1000 + 1)) {
  371. log_warn(LD_GENERAL, "comparing times on millisecond detail too far "
  372. "apart: " I64_FORMAT " seconds", I64_PRINTF_ARG(secdiff));
  373. return LONG_MAX;
  374. }
  375. /* Subtract and round */
  376. mdiff = secdiff*1000 +
  377. /* We add a million usec here to ensure that the result is positive,
  378. * so that the round-towards-zero behavior of the division will give
  379. * the right result for rounding to the nearest msec. Later we subtract
  380. * 1000 in order to get the correct result.
  381. * We'll never get an overflow here, because we check that both usecs are
  382. * between 0 and TV_USEC_PER_SEC. */
  383. ((int64_t)end->tv_usec - (int64_t)start->tv_usec + 500 + 1000000) / 1000
  384. - 1000;
  385. /* Some compilers are smart enough to work out this is a no-op on L64 */
  386. #if SIZEOF_LONG < 8
  387. if (mdiff > (int64_t)LONG_MAX || mdiff < (int64_t)LONG_MIN) {
  388. return LONG_MAX;
  389. }
  390. #endif
  391. return (long)mdiff;
  392. }
  393. /**
  394. * Converts timeval to milliseconds.
  395. */
  396. int64_t
  397. tv_to_msec(const struct timeval *tv)
  398. {
  399. int64_t conv = ((int64_t)tv->tv_sec)*1000L;
  400. /* Round ghetto-style */
  401. conv += ((int64_t)tv->tv_usec+500)/1000L;
  402. return conv;
  403. }
  404. /** Yield true iff <b>y</b> is a leap-year. */
  405. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  406. /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
  407. static int
  408. n_leapdays(int year1, int year2)
  409. {
  410. --year1;
  411. --year2;
  412. return (year2/4 - year1/4) - (year2/100 - year1/100)
  413. + (year2/400 - year1/400);
  414. }
  415. /** Number of days per month in non-leap year; used by tor_timegm and
  416. * parse_rfc1123_time. */
  417. static const int days_per_month[] =
  418. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  419. /** Compute a time_t given a struct tm. The result is given in UTC, and
  420. * does not account for leap seconds. Return 0 on success, -1 on failure.
  421. */
  422. int
  423. tor_timegm(const struct tm *tm, time_t *time_out)
  424. {
  425. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  426. * It's way more brute-force than fiddling with tzset().
  427. *
  428. * We use int64_t rather than time_t to avoid overflow on multiplication on
  429. * platforms with 32-bit time_t. Since year is clipped to INT32_MAX, and
  430. * since 365 * 24 * 60 * 60 is approximately 31 million, it's not possible
  431. * for INT32_MAX years to overflow int64_t when converted to seconds. */
  432. int64_t year, days, hours, minutes, seconds;
  433. int i, invalid_year, dpm;
  434. /* Initialize time_out to 0 for now, to avoid bad usage in case this function
  435. fails and the caller ignores the return value. */
  436. tor_assert(time_out);
  437. *time_out = 0;
  438. /* avoid int overflow on addition */
  439. if (tm->tm_year < INT32_MAX-1900) {
  440. year = tm->tm_year + 1900;
  441. } else {
  442. /* clamp year */
  443. year = INT32_MAX;
  444. }
  445. invalid_year = (year < 1970 || tm->tm_year >= INT32_MAX-1900);
  446. if (tm->tm_mon >= 0 && tm->tm_mon <= 11) {
  447. dpm = days_per_month[tm->tm_mon];
  448. if (tm->tm_mon == 1 && !invalid_year && IS_LEAPYEAR(tm->tm_year)) {
  449. dpm = 29;
  450. }
  451. } else {
  452. /* invalid month - default to 0 days per month */
  453. dpm = 0;
  454. }
  455. if (invalid_year ||
  456. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  457. tm->tm_mday < 1 || tm->tm_mday > dpm ||
  458. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  459. tm->tm_min < 0 || tm->tm_min > 59 ||
  460. tm->tm_sec < 0 || tm->tm_sec > 60) {
  461. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  462. return -1;
  463. }
  464. days = 365 * (year-1970) + n_leapdays(1970,(int)year);
  465. for (i = 0; i < tm->tm_mon; ++i)
  466. days += days_per_month[i];
  467. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  468. ++days;
  469. days += tm->tm_mday - 1;
  470. hours = days*24 + tm->tm_hour;
  471. minutes = hours*60 + tm->tm_min;
  472. seconds = minutes*60 + tm->tm_sec;
  473. /* Check that "seconds" will fit in a time_t. On platforms where time_t is
  474. * 32-bit, this check will fail for dates in and after 2038.
  475. *
  476. * We already know that "seconds" can't be negative because "year" >= 1970 */
  477. #if SIZEOF_TIME_T < 8
  478. if (seconds < TIME_MIN || seconds > TIME_MAX) {
  479. log_warn(LD_BUG, "Result does not fit in tor_timegm");
  480. return -1;
  481. }
  482. #endif /* SIZEOF_TIME_T < 8 */
  483. *time_out = (time_t)seconds;
  484. return 0;
  485. }
  486. /* strftime is locale-specific, so we need to replace those parts */
  487. /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
  488. static const char *WEEKDAY_NAMES[] =
  489. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  490. /** A c-locale array of 3-letter names of months, starting with Jan. */
  491. static const char *MONTH_NAMES[] =
  492. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  493. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  494. /** Set <b>buf</b> to the RFC1123 encoding of the UTC value of <b>t</b>.
  495. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  496. *
  497. * (RFC1123 format is "Fri, 29 Sep 2006 15:54:20 GMT". Note the "GMT"
  498. * rather than "UTC".)
  499. */
  500. void
  501. format_rfc1123_time(char *buf, time_t t)
  502. {
  503. struct tm tm;
  504. tor_gmtime_r(&t, &tm);
  505. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  506. tor_assert(tm.tm_wday >= 0);
  507. tor_assert(tm.tm_wday <= 6);
  508. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  509. tor_assert(tm.tm_mon >= 0);
  510. tor_assert(tm.tm_mon <= 11);
  511. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  512. }
  513. /** Parse the (a subset of) the RFC1123 encoding of some time (in UTC) from
  514. * <b>buf</b>, and store the result in *<b>t</b>.
  515. *
  516. * Note that we only accept the subset generated by format_rfc1123_time above,
  517. * not the full range of formats suggested by RFC 1123.
  518. *
  519. * Return 0 on success, -1 on failure.
  520. */
  521. int
  522. parse_rfc1123_time(const char *buf, time_t *t)
  523. {
  524. struct tm tm;
  525. char month[4];
  526. char weekday[4];
  527. int i, m, invalid_year;
  528. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  529. unsigned dpm;
  530. if (strlen(buf) != RFC1123_TIME_LEN)
  531. return -1;
  532. memset(&tm, 0, sizeof(tm));
  533. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  534. &tm_mday, month, &tm_year, &tm_hour,
  535. &tm_min, &tm_sec) < 7) {
  536. char *esc = esc_for_log(buf);
  537. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  538. tor_free(esc);
  539. return -1;
  540. }
  541. m = -1;
  542. for (i = 0; i < 12; ++i) {
  543. if (!strcmp(month, MONTH_NAMES[i])) {
  544. m = i;
  545. break;
  546. }
  547. }
  548. if (m<0) {
  549. char *esc = esc_for_log(buf);
  550. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  551. tor_free(esc);
  552. return -1;
  553. }
  554. tm.tm_mon = m;
  555. invalid_year = (tm_year >= INT32_MAX || tm_year < 1970);
  556. tor_assert(m >= 0 && m <= 11);
  557. dpm = days_per_month[m];
  558. if (m == 1 && !invalid_year && IS_LEAPYEAR(tm_year)) {
  559. dpm = 29;
  560. }
  561. if (invalid_year || tm_mday < 1 || tm_mday > dpm ||
  562. tm_hour > 23 || tm_min > 59 || tm_sec > 60) {
  563. char *esc = esc_for_log(buf);
  564. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  565. tor_free(esc);
  566. return -1;
  567. }
  568. tm.tm_mday = (int)tm_mday;
  569. tm.tm_year = (int)tm_year;
  570. tm.tm_hour = (int)tm_hour;
  571. tm.tm_min = (int)tm_min;
  572. tm.tm_sec = (int)tm_sec;
  573. if (tm.tm_year < 1970) {
  574. /* LCOV_EXCL_START
  575. * XXXX I think this is dead code; we already checked for
  576. * invalid_year above. */
  577. tor_assert_nonfatal_unreached();
  578. char *esc = esc_for_log(buf);
  579. log_warn(LD_GENERAL,
  580. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  581. tor_free(esc);
  582. return -1;
  583. /* LCOV_EXCL_STOP */
  584. }
  585. tm.tm_year -= 1900;
  586. return tor_timegm(&tm, t);
  587. }
  588. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  589. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  590. *
  591. * (ISO8601 format is 2006-10-29 10:57:20)
  592. */
  593. void
  594. format_local_iso_time(char *buf, time_t t)
  595. {
  596. struct tm tm;
  597. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  598. }
  599. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  600. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  601. */
  602. void
  603. format_iso_time(char *buf, time_t t)
  604. {
  605. struct tm tm;
  606. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  607. }
  608. /** As format_local_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  609. * embedding an internal space. */
  610. void
  611. format_local_iso_time_nospace(char *buf, time_t t)
  612. {
  613. format_local_iso_time(buf, t);
  614. buf[10] = 'T';
  615. }
  616. /** As format_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  617. * embedding an internal space. */
  618. void
  619. format_iso_time_nospace(char *buf, time_t t)
  620. {
  621. format_iso_time(buf, t);
  622. buf[10] = 'T';
  623. }
  624. /** As format_iso_time_nospace, but include microseconds in decimal
  625. * fixed-point format. Requires that buf be at least ISO_TIME_USEC_LEN+1
  626. * bytes long. */
  627. void
  628. format_iso_time_nospace_usec(char *buf, const struct timeval *tv)
  629. {
  630. tor_assert(tv);
  631. format_iso_time_nospace(buf, (time_t)tv->tv_sec);
  632. tor_snprintf(buf+ISO_TIME_LEN, 8, ".%06d", (int)tv->tv_usec);
  633. }
  634. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  635. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  636. * failure. Ignore extraneous stuff in <b>cp</b> after the end of the time
  637. * string, unless <b>strict</b> is set. If <b>nospace</b> is set,
  638. * expect the YYYY-MM-DDTHH:MM:SS format. */
  639. int
  640. parse_iso_time_(const char *cp, time_t *t, int strict, int nospace)
  641. {
  642. struct tm st_tm;
  643. unsigned int year=0, month=0, day=0, hour=0, minute=0, second=0;
  644. int n_fields;
  645. char extra_char, separator_char;
  646. n_fields = tor_sscanf(cp, "%u-%2u-%2u%c%2u:%2u:%2u%c",
  647. &year, &month, &day,
  648. &separator_char,
  649. &hour, &minute, &second, &extra_char);
  650. if (strict ? (n_fields != 7) : (n_fields < 7)) {
  651. char *esc = esc_for_log(cp);
  652. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  653. tor_free(esc);
  654. return -1;
  655. }
  656. if (separator_char != (nospace ? 'T' : ' ')) {
  657. char *esc = esc_for_log(cp);
  658. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  659. tor_free(esc);
  660. return -1;
  661. }
  662. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  663. hour > 23 || minute > 59 || second > 60 || year >= INT32_MAX) {
  664. char *esc = esc_for_log(cp);
  665. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  666. tor_free(esc);
  667. return -1;
  668. }
  669. st_tm.tm_year = (int)year-1900;
  670. st_tm.tm_mon = month-1;
  671. st_tm.tm_mday = day;
  672. st_tm.tm_hour = hour;
  673. st_tm.tm_min = minute;
  674. st_tm.tm_sec = second;
  675. st_tm.tm_wday = 0; /* Should be ignored. */
  676. if (st_tm.tm_year < 70) {
  677. /* LCOV_EXCL_START
  678. * XXXX I think this is dead code; we already checked for
  679. * year < 1970 above. */
  680. tor_assert_nonfatal_unreached();
  681. char *esc = esc_for_log(cp);
  682. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  683. tor_free(esc);
  684. return -1;
  685. /* LCOV_EXCL_STOP */
  686. }
  687. return tor_timegm(&st_tm, t);
  688. }
  689. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  690. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  691. * failure. Reject the string if any characters are present after the time.
  692. */
  693. int
  694. parse_iso_time(const char *cp, time_t *t)
  695. {
  696. return parse_iso_time_(cp, t, 1, 0);
  697. }
  698. /**
  699. * As parse_iso_time, but parses a time encoded by format_iso_time_nospace().
  700. */
  701. int
  702. parse_iso_time_nospace(const char *cp, time_t *t)
  703. {
  704. return parse_iso_time_(cp, t, 1, 1);
  705. }
  706. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  707. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  708. int
  709. parse_http_time(const char *date, struct tm *tm)
  710. {
  711. const char *cp;
  712. char month[4];
  713. char wkday[4];
  714. int i;
  715. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  716. tor_assert(tm);
  717. memset(tm, 0, sizeof(*tm));
  718. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  719. if ((cp = strchr(date, ','))) {
  720. ++cp;
  721. if (*cp != ' ')
  722. return -1;
  723. ++cp;
  724. if (tor_sscanf(cp, "%2u %3s %4u %2u:%2u:%2u GMT",
  725. &tm_mday, month, &tm_year,
  726. &tm_hour, &tm_min, &tm_sec) == 6) {
  727. /* rfc1123-date */
  728. tm_year -= 1900;
  729. } else if (tor_sscanf(cp, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  730. &tm_mday, month, &tm_year,
  731. &tm_hour, &tm_min, &tm_sec) == 6) {
  732. /* rfc850-date */
  733. } else {
  734. return -1;
  735. }
  736. } else {
  737. /* No comma; possibly asctime() format. */
  738. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  739. wkday, month, &tm_mday,
  740. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  741. tm_year -= 1900;
  742. } else {
  743. return -1;
  744. }
  745. }
  746. tm->tm_mday = (int)tm_mday;
  747. tm->tm_year = (int)tm_year;
  748. tm->tm_hour = (int)tm_hour;
  749. tm->tm_min = (int)tm_min;
  750. tm->tm_sec = (int)tm_sec;
  751. tm->tm_wday = 0; /* Leave this unset. */
  752. month[3] = '\0';
  753. /* Okay, now decode the month. */
  754. /* set tm->tm_mon to dummy value so the check below fails. */
  755. tm->tm_mon = -1;
  756. for (i = 0; i < 12; ++i) {
  757. if (!strcasecmp(MONTH_NAMES[i], month)) {
  758. tm->tm_mon = i;
  759. }
  760. }
  761. if (tm->tm_year < 0 ||
  762. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  763. tm->tm_mday < 1 || tm->tm_mday > 31 ||
  764. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  765. tm->tm_min < 0 || tm->tm_min > 59 ||
  766. tm->tm_sec < 0 || tm->tm_sec > 60)
  767. return -1; /* Out of range, or bad month. */
  768. return 0;
  769. }
  770. /** Given an <b>interval</b> in seconds, try to write it to the
  771. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  772. * Returns a non-negative integer on success, -1 on failure.
  773. */
  774. int
  775. format_time_interval(char *out, size_t out_len, long interval)
  776. {
  777. /* We only report seconds if there's no hours. */
  778. long sec = 0, min = 0, hour = 0, day = 0;
  779. /* -LONG_MIN is LONG_MAX + 1, which causes signed overflow */
  780. if (interval < -LONG_MAX)
  781. interval = LONG_MAX;
  782. else if (interval < 0)
  783. interval = -interval;
  784. if (interval >= 86400) {
  785. day = interval / 86400;
  786. interval %= 86400;
  787. }
  788. if (interval >= 3600) {
  789. hour = interval / 3600;
  790. interval %= 3600;
  791. }
  792. if (interval >= 60) {
  793. min = interval / 60;
  794. interval %= 60;
  795. }
  796. sec = interval;
  797. if (day) {
  798. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  799. day, hour, min);
  800. } else if (hour) {
  801. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  802. } else if (min) {
  803. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  804. } else {
  805. return tor_snprintf(out, out_len, "%ld seconds", sec);
  806. }
  807. }
  808. /* =====
  809. * File helpers
  810. * ===== */
  811. /*
  812. * Filesystem operations.
  813. */
  814. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  815. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  816. * decode its contents into a newly allocated string. On success, assign this
  817. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  818. * provided), and return a pointer to the position in <b>s</b> immediately
  819. * after the string. On failure, return NULL.
  820. */
  821. const char *
  822. unescape_string(const char *s, char **result, size_t *size_out)
  823. {
  824. const char *cp;
  825. char *out;
  826. if (s[0] != '\"')
  827. return NULL;
  828. cp = s+1;
  829. while (1) {
  830. switch (*cp) {
  831. case '\0':
  832. case '\n':
  833. return NULL;
  834. case '\"':
  835. goto end_of_loop;
  836. case '\\':
  837. if (cp[1] == 'x' || cp[1] == 'X') {
  838. if (!(TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])))
  839. return NULL;
  840. cp += 4;
  841. } else if (TOR_ISODIGIT(cp[1])) {
  842. cp += 2;
  843. if (TOR_ISODIGIT(*cp)) ++cp;
  844. if (TOR_ISODIGIT(*cp)) ++cp;
  845. } else if (cp[1] == 'n' || cp[1] == 'r' || cp[1] == 't' || cp[1] == '"'
  846. || cp[1] == '\\' || cp[1] == '\'') {
  847. cp += 2;
  848. } else {
  849. return NULL;
  850. }
  851. break;
  852. default:
  853. ++cp;
  854. break;
  855. }
  856. }
  857. end_of_loop:
  858. out = *result = tor_malloc(cp-s + 1);
  859. cp = s+1;
  860. while (1) {
  861. switch (*cp)
  862. {
  863. case '\"':
  864. *out = '\0';
  865. if (size_out) *size_out = out - *result;
  866. return cp+1;
  867. /* LCOV_EXCL_START -- we caught this in parse_config_from_line. */
  868. case '\0':
  869. tor_fragile_assert();
  870. tor_free(*result);
  871. return NULL;
  872. /* LCOV_EXCL_STOP */
  873. case '\\':
  874. switch (cp[1])
  875. {
  876. case 'n': *out++ = '\n'; cp += 2; break;
  877. case 'r': *out++ = '\r'; cp += 2; break;
  878. case 't': *out++ = '\t'; cp += 2; break;
  879. case 'x': case 'X':
  880. {
  881. int x1, x2;
  882. x1 = hex_decode_digit(cp[2]);
  883. x2 = hex_decode_digit(cp[3]);
  884. if (x1 == -1 || x2 == -1) {
  885. /* LCOV_EXCL_START */
  886. /* we caught this above in the initial loop. */
  887. tor_assert_nonfatal_unreached();
  888. tor_free(*result);
  889. return NULL;
  890. /* LCOV_EXCL_STOP */
  891. }
  892. *out++ = ((x1<<4) + x2);
  893. cp += 4;
  894. }
  895. break;
  896. case '0': case '1': case '2': case '3': case '4': case '5':
  897. case '6': case '7':
  898. {
  899. int n = cp[1]-'0';
  900. cp += 2;
  901. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  902. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  903. if (n > 255) { tor_free(*result); return NULL; }
  904. *out++ = (char)n;
  905. }
  906. break;
  907. case '\'':
  908. case '\"':
  909. case '\\':
  910. case '\?':
  911. *out++ = cp[1];
  912. cp += 2;
  913. break;
  914. /* LCOV_EXCL_START */
  915. default:
  916. /* we caught this above in the initial loop. */
  917. tor_assert_nonfatal_unreached();
  918. tor_free(*result); return NULL;
  919. /* LCOV_EXCL_STOP */
  920. }
  921. break;
  922. default:
  923. *out++ = *cp++;
  924. }
  925. }
  926. }
  927. /* =====
  928. * Process helpers
  929. * ===== */
  930. #ifndef _WIN32
  931. /* Based on code contributed by christian grothoff */
  932. /** True iff we've called start_daemon(). */
  933. static int start_daemon_called = 0;
  934. /** True iff we've called finish_daemon(). */
  935. static int finish_daemon_called = 0;
  936. /** Socketpair used to communicate between parent and child process while
  937. * daemonizing. */
  938. static int daemon_filedes[2];
  939. /** Start putting the process into daemon mode: fork and drop all resources
  940. * except standard fds. The parent process never returns, but stays around
  941. * until finish_daemon is called. (Note: it's safe to call this more
  942. * than once: calls after the first are ignored.)
  943. */
  944. void
  945. start_daemon(void)
  946. {
  947. pid_t pid;
  948. if (start_daemon_called)
  949. return;
  950. start_daemon_called = 1;
  951. if (pipe(daemon_filedes)) {
  952. /* LCOV_EXCL_START */
  953. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  954. exit(1); // exit ok: during daemonize, pipe failed.
  955. /* LCOV_EXCL_STOP */
  956. }
  957. pid = fork();
  958. if (pid < 0) {
  959. /* LCOV_EXCL_START */
  960. log_err(LD_GENERAL,"fork failed. Exiting.");
  961. exit(1); // exit ok: during daemonize, fork failed
  962. /* LCOV_EXCL_STOP */
  963. }
  964. if (pid) { /* Parent */
  965. int ok;
  966. char c;
  967. close(daemon_filedes[1]); /* we only read */
  968. ok = -1;
  969. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  970. if (c == '.')
  971. ok = 1;
  972. }
  973. fflush(stdout);
  974. if (ok == 1)
  975. exit(0); // exit ok: during daemonize, daemonizing.
  976. else
  977. exit(1); /* child reported error. exit ok: daemonize failed. */
  978. } else { /* Child */
  979. close(daemon_filedes[0]); /* we only write */
  980. (void) setsid(); /* Detach from controlling terminal */
  981. /*
  982. * Fork one more time, so the parent (the session group leader) can exit.
  983. * This means that we, as a non-session group leader, can never regain a
  984. * controlling terminal. This part is recommended by Stevens's
  985. * _Advanced Programming in the Unix Environment_.
  986. */
  987. if (fork() != 0) {
  988. exit(0); // exit ok: during daemonize, fork failed (2)
  989. }
  990. set_main_thread(); /* We are now the main thread. */
  991. return;
  992. }
  993. }
  994. /** Finish putting the process into daemon mode: drop standard fds, and tell
  995. * the parent process to exit. (Note: it's safe to call this more than once:
  996. * calls after the first are ignored. Calls start_daemon first if it hasn't
  997. * been called already.)
  998. */
  999. void
  1000. finish_daemon(const char *desired_cwd)
  1001. {
  1002. int nullfd;
  1003. char c = '.';
  1004. if (finish_daemon_called)
  1005. return;
  1006. if (!start_daemon_called)
  1007. start_daemon();
  1008. finish_daemon_called = 1;
  1009. if (!desired_cwd)
  1010. desired_cwd = "/";
  1011. /* Don't hold the wrong FS mounted */
  1012. if (chdir(desired_cwd) < 0) {
  1013. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  1014. exit(1); // exit ok: during daemonize, chdir failed.
  1015. }
  1016. nullfd = tor_open_cloexec("/dev/null", O_RDWR, 0);
  1017. if (nullfd < 0) {
  1018. /* LCOV_EXCL_START */
  1019. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  1020. exit(1); // exit ok: during daemonize, couldn't open /dev/null
  1021. /* LCOV_EXCL_STOP */
  1022. }
  1023. /* close fds linking to invoking terminal, but
  1024. * close usual incoming fds, but redirect them somewhere
  1025. * useful so the fds don't get reallocated elsewhere.
  1026. */
  1027. if (dup2(nullfd,0) < 0 ||
  1028. dup2(nullfd,1) < 0 ||
  1029. dup2(nullfd,2) < 0) {
  1030. /* LCOV_EXCL_START */
  1031. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  1032. exit(1); // exit ok: during daemonize, dup2 failed.
  1033. /* LCOV_EXCL_STOP */
  1034. }
  1035. if (nullfd > 2)
  1036. close(nullfd);
  1037. /* signal success */
  1038. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  1039. log_err(LD_GENERAL,"write failed. Exiting.");
  1040. }
  1041. close(daemon_filedes[1]);
  1042. }
  1043. #else /* !(!defined(_WIN32)) */
  1044. /* defined(_WIN32) */
  1045. void
  1046. start_daemon(void)
  1047. {
  1048. }
  1049. void
  1050. finish_daemon(const char *cp)
  1051. {
  1052. (void)cp;
  1053. }
  1054. #endif /* !defined(_WIN32) */
  1055. /** Write the current process ID, followed by NL, into <b>filename</b>.
  1056. * Return 0 on success, -1 on failure.
  1057. */
  1058. int
  1059. write_pidfile(const char *filename)
  1060. {
  1061. FILE *pidfile;
  1062. if ((pidfile = fopen(filename, "w")) == NULL) {
  1063. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  1064. strerror(errno));
  1065. return -1;
  1066. } else {
  1067. #ifdef _WIN32
  1068. int pid = (int)_getpid();
  1069. #else
  1070. int pid = (int)getpid();
  1071. #endif
  1072. int rv = 0;
  1073. if (fprintf(pidfile, "%d\n", pid) < 0)
  1074. rv = -1;
  1075. if (fclose(pidfile) < 0)
  1076. rv = -1;
  1077. return rv;
  1078. }
  1079. }
  1080. #ifdef _WIN32
  1081. HANDLE
  1082. load_windows_system_library(const TCHAR *library_name)
  1083. {
  1084. TCHAR path[MAX_PATH];
  1085. unsigned n;
  1086. n = GetSystemDirectory(path, MAX_PATH);
  1087. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  1088. return 0;
  1089. _tcscat(path, TEXT("\\"));
  1090. _tcscat(path, library_name);
  1091. return LoadLibrary(path);
  1092. }
  1093. #endif /* defined(_WIN32) */
  1094. /** Format a single argument for being put on a Windows command line.
  1095. * Returns a newly allocated string */
  1096. static char *
  1097. format_win_cmdline_argument(const char *arg)
  1098. {
  1099. char *formatted_arg;
  1100. char need_quotes;
  1101. const char *c;
  1102. int i;
  1103. int bs_counter = 0;
  1104. /* Backslash we can point to when one is inserted into the string */
  1105. const char backslash = '\\';
  1106. /* Smartlist of *char */
  1107. smartlist_t *arg_chars;
  1108. arg_chars = smartlist_new();
  1109. /* Quote string if it contains whitespace or is empty */
  1110. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  1111. /* Build up smartlist of *chars */
  1112. for (c=arg; *c != '\0'; c++) {
  1113. if ('"' == *c) {
  1114. /* Double up backslashes preceding a quote */
  1115. for (i=0; i<(bs_counter*2); i++)
  1116. smartlist_add(arg_chars, (void*)&backslash);
  1117. bs_counter = 0;
  1118. /* Escape the quote */
  1119. smartlist_add(arg_chars, (void*)&backslash);
  1120. smartlist_add(arg_chars, (void*)c);
  1121. } else if ('\\' == *c) {
  1122. /* Count backslashes until we know whether to double up */
  1123. bs_counter++;
  1124. } else {
  1125. /* Don't double up slashes preceding a non-quote */
  1126. for (i=0; i<bs_counter; i++)
  1127. smartlist_add(arg_chars, (void*)&backslash);
  1128. bs_counter = 0;
  1129. smartlist_add(arg_chars, (void*)c);
  1130. }
  1131. }
  1132. /* Don't double up trailing backslashes */
  1133. for (i=0; i<bs_counter; i++)
  1134. smartlist_add(arg_chars, (void*)&backslash);
  1135. /* Allocate space for argument, quotes (if needed), and terminator */
  1136. const size_t formatted_arg_len = smartlist_len(arg_chars) +
  1137. (need_quotes ? 2 : 0) + 1;
  1138. formatted_arg = tor_malloc_zero(formatted_arg_len);
  1139. /* Add leading quote */
  1140. i=0;
  1141. if (need_quotes)
  1142. formatted_arg[i++] = '"';
  1143. /* Add characters */
  1144. SMARTLIST_FOREACH(arg_chars, char*, ch,
  1145. {
  1146. formatted_arg[i++] = *ch;
  1147. });
  1148. /* Add trailing quote */
  1149. if (need_quotes)
  1150. formatted_arg[i++] = '"';
  1151. formatted_arg[i] = '\0';
  1152. smartlist_free(arg_chars);
  1153. return formatted_arg;
  1154. }
  1155. /** Format a command line for use on Windows, which takes the command as a
  1156. * string rather than string array. Follows the rules from "Parsing C++
  1157. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  1158. * Python subprocess module. Returns a newly allocated string */
  1159. char *
  1160. tor_join_win_cmdline(const char *argv[])
  1161. {
  1162. smartlist_t *argv_list;
  1163. char *joined_argv;
  1164. int i;
  1165. /* Format each argument and put the result in a smartlist */
  1166. argv_list = smartlist_new();
  1167. for (i=0; argv[i] != NULL; i++) {
  1168. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  1169. }
  1170. /* Join the arguments with whitespace */
  1171. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  1172. /* Free the newly allocated arguments, and the smartlist */
  1173. SMARTLIST_FOREACH(argv_list, char *, arg,
  1174. {
  1175. tor_free(arg);
  1176. });
  1177. smartlist_free(argv_list);
  1178. return joined_argv;
  1179. }
  1180. #ifndef _WIN32
  1181. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  1182. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  1183. * safe.
  1184. *
  1185. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE+1 bytes available.
  1186. *
  1187. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  1188. * with spaces. CHILD_STATE indicates where
  1189. * in the process of starting the child process did the failure occur (see
  1190. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  1191. * errno when the failure occurred.
  1192. *
  1193. * On success return the number of characters added to hex_errno, not counting
  1194. * the terminating NUL; return -1 on error.
  1195. */
  1196. STATIC int
  1197. format_helper_exit_status(unsigned char child_state, int saved_errno,
  1198. char *hex_errno)
  1199. {
  1200. unsigned int unsigned_errno;
  1201. int written, left;
  1202. char *cur;
  1203. size_t i;
  1204. int res = -1;
  1205. /* Fill hex_errno with spaces, and a trailing newline (memset may
  1206. not be signal handler safe, so we can't use it) */
  1207. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  1208. hex_errno[i] = ' ';
  1209. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  1210. /* Convert errno to be unsigned for hex conversion */
  1211. if (saved_errno < 0) {
  1212. // Avoid overflow on the cast to unsigned int when result is INT_MIN
  1213. // by adding 1 to the signed int negative value,
  1214. // then, after it has been negated and cast to unsigned,
  1215. // adding the original 1 back (the double-addition is intentional).
  1216. // Otherwise, the cast to signed could cause a temporary int
  1217. // to equal INT_MAX + 1, which is undefined.
  1218. unsigned_errno = ((unsigned int) -(saved_errno + 1)) + 1;
  1219. } else {
  1220. unsigned_errno = (unsigned int) saved_errno;
  1221. }
  1222. /*
  1223. * Count how many chars of space we have left, and keep a pointer into the
  1224. * current point in the buffer.
  1225. */
  1226. left = HEX_ERRNO_SIZE+1;
  1227. cur = hex_errno;
  1228. /* Emit child_state */
  1229. written = format_hex_number_sigsafe(child_state, cur, left);
  1230. if (written <= 0)
  1231. goto err;
  1232. /* Adjust left and cur */
  1233. left -= written;
  1234. cur += written;
  1235. if (left <= 0)
  1236. goto err;
  1237. /* Now the '/' */
  1238. *cur = '/';
  1239. /* Adjust left and cur */
  1240. ++cur;
  1241. --left;
  1242. if (left <= 0)
  1243. goto err;
  1244. /* Need minus? */
  1245. if (saved_errno < 0) {
  1246. *cur = '-';
  1247. ++cur;
  1248. --left;
  1249. if (left <= 0)
  1250. goto err;
  1251. }
  1252. /* Emit unsigned_errno */
  1253. written = format_hex_number_sigsafe(unsigned_errno, cur, left);
  1254. if (written <= 0)
  1255. goto err;
  1256. /* Adjust left and cur */
  1257. left -= written;
  1258. cur += written;
  1259. /* Check that we have enough space left for a newline and a NUL */
  1260. if (left <= 1)
  1261. goto err;
  1262. /* Emit the newline and NUL */
  1263. *cur++ = '\n';
  1264. *cur++ = '\0';
  1265. res = (int)(cur - hex_errno - 1);
  1266. goto done;
  1267. err:
  1268. /*
  1269. * In error exit, just write a '\0' in the first char so whatever called
  1270. * this at least won't fall off the end.
  1271. */
  1272. *hex_errno = '\0';
  1273. done:
  1274. return res;
  1275. }
  1276. #endif /* !defined(_WIN32) */
  1277. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  1278. #define DEFAULT_MAX_FD 256
  1279. /** Terminate the process of <b>process_handle</b>, if that process has not
  1280. * already exited.
  1281. *
  1282. * Return 0 if we succeeded in terminating the process (or if the process
  1283. * already exited), and -1 if we tried to kill the process but failed.
  1284. *
  1285. * Based on code originally borrowed from Python's os.kill. */
  1286. int
  1287. tor_terminate_process(process_handle_t *process_handle)
  1288. {
  1289. #ifdef _WIN32
  1290. if (tor_get_exit_code(process_handle, 0, NULL) == PROCESS_EXIT_RUNNING) {
  1291. HANDLE handle = process_handle->pid.hProcess;
  1292. if (!TerminateProcess(handle, 0))
  1293. return -1;
  1294. else
  1295. return 0;
  1296. }
  1297. #else /* !(defined(_WIN32)) */
  1298. if (process_handle->waitpid_cb) {
  1299. /* We haven't got a waitpid yet, so we can just kill off the process. */
  1300. return kill(process_handle->pid, SIGTERM);
  1301. }
  1302. #endif /* defined(_WIN32) */
  1303. return 0; /* We didn't need to kill the process, so report success */
  1304. }
  1305. /** Return the Process ID of <b>process_handle</b>. */
  1306. int
  1307. tor_process_get_pid(process_handle_t *process_handle)
  1308. {
  1309. #ifdef _WIN32
  1310. return (int) process_handle->pid.dwProcessId;
  1311. #else
  1312. return (int) process_handle->pid;
  1313. #endif
  1314. }
  1315. #ifdef _WIN32
  1316. HANDLE
  1317. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  1318. {
  1319. return process_handle->stdout_pipe;
  1320. }
  1321. #else /* !(defined(_WIN32)) */
  1322. /* DOCDOC tor_process_get_stdout_pipe */
  1323. int
  1324. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  1325. {
  1326. return process_handle->stdout_pipe;
  1327. }
  1328. #endif /* defined(_WIN32) */
  1329. /* DOCDOC process_handle_new */
  1330. static process_handle_t *
  1331. process_handle_new(void)
  1332. {
  1333. process_handle_t *out = tor_malloc_zero(sizeof(process_handle_t));
  1334. #ifdef _WIN32
  1335. out->stdin_pipe = INVALID_HANDLE_VALUE;
  1336. out->stdout_pipe = INVALID_HANDLE_VALUE;
  1337. out->stderr_pipe = INVALID_HANDLE_VALUE;
  1338. #else
  1339. out->stdin_pipe = -1;
  1340. out->stdout_pipe = -1;
  1341. out->stderr_pipe = -1;
  1342. #endif /* defined(_WIN32) */
  1343. return out;
  1344. }
  1345. #ifndef _WIN32
  1346. /** Invoked when a process that we've launched via tor_spawn_background() has
  1347. * been found to have terminated.
  1348. */
  1349. static void
  1350. process_handle_waitpid_cb(int status, void *arg)
  1351. {
  1352. process_handle_t *process_handle = arg;
  1353. process_handle->waitpid_exit_status = status;
  1354. clear_waitpid_callback(process_handle->waitpid_cb);
  1355. if (process_handle->status == PROCESS_STATUS_RUNNING)
  1356. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  1357. process_handle->waitpid_cb = 0;
  1358. }
  1359. #endif /* !defined(_WIN32) */
  1360. /**
  1361. * @name child-process states
  1362. *
  1363. * Each of these values represents a possible state that a child process can
  1364. * be in. They're used to determine what to say when telling the parent how
  1365. * far along we were before failure.
  1366. *
  1367. * @{
  1368. */
  1369. #define CHILD_STATE_INIT 0
  1370. #define CHILD_STATE_PIPE 1
  1371. #define CHILD_STATE_MAXFD 2
  1372. #define CHILD_STATE_FORK 3
  1373. #define CHILD_STATE_DUPOUT 4
  1374. #define CHILD_STATE_DUPERR 5
  1375. #define CHILD_STATE_DUPIN 6
  1376. #define CHILD_STATE_CLOSEFD 7
  1377. #define CHILD_STATE_EXEC 8
  1378. #define CHILD_STATE_FAILEXEC 9
  1379. /** @} */
  1380. /**
  1381. * Boolean. If true, then Tor may call execve or CreateProcess via
  1382. * tor_spawn_background.
  1383. **/
  1384. static int may_spawn_background_process = 1;
  1385. /**
  1386. * Turn off may_spawn_background_process, so that all future calls to
  1387. * tor_spawn_background are guaranteed to fail.
  1388. **/
  1389. void
  1390. tor_disable_spawning_background_processes(void)
  1391. {
  1392. may_spawn_background_process = 0;
  1393. }
  1394. /** Start a program in the background. If <b>filename</b> contains a '/', then
  1395. * it will be treated as an absolute or relative path. Otherwise, on
  1396. * non-Windows systems, the system path will be searched for <b>filename</b>.
  1397. * On Windows, only the current directory will be searched. Here, to search the
  1398. * system path (as well as the application directory, current working
  1399. * directory, and system directories), set filename to NULL.
  1400. *
  1401. * The strings in <b>argv</b> will be passed as the command line arguments of
  1402. * the child program (following convention, argv[0] should normally be the
  1403. * filename of the executable, and this must be the case if <b>filename</b> is
  1404. * NULL). The last element of argv must be NULL. A handle to the child process
  1405. * will be returned in process_handle (which must be non-NULL). Read
  1406. * process_handle.status to find out if the process was successfully launched.
  1407. * For convenience, process_handle.status is returned by this function.
  1408. *
  1409. * Some parts of this code are based on the POSIX subprocess module from
  1410. * Python, and example code from
  1411. * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
  1412. */
  1413. int
  1414. tor_spawn_background(const char *const filename, const char **argv,
  1415. process_environment_t *env,
  1416. process_handle_t **process_handle_out)
  1417. {
  1418. if (BUG(may_spawn_background_process == 0)) {
  1419. /* We should never reach this point if we're forbidden to spawn
  1420. * processes. Instead we should have caught the attempt earlier. */
  1421. return PROCESS_STATUS_ERROR;
  1422. }
  1423. #ifdef _WIN32
  1424. HANDLE stdout_pipe_read = NULL;
  1425. HANDLE stdout_pipe_write = NULL;
  1426. HANDLE stderr_pipe_read = NULL;
  1427. HANDLE stderr_pipe_write = NULL;
  1428. HANDLE stdin_pipe_read = NULL;
  1429. HANDLE stdin_pipe_write = NULL;
  1430. process_handle_t *process_handle;
  1431. int status;
  1432. STARTUPINFOA siStartInfo;
  1433. BOOL retval = FALSE;
  1434. SECURITY_ATTRIBUTES saAttr;
  1435. char *joined_argv;
  1436. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  1437. saAttr.bInheritHandle = TRUE;
  1438. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  1439. saAttr.lpSecurityDescriptor = NULL;
  1440. /* Assume failure to start process */
  1441. status = PROCESS_STATUS_ERROR;
  1442. /* Set up pipe for stdout */
  1443. if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, &saAttr, 0)) {
  1444. log_warn(LD_GENERAL,
  1445. "Failed to create pipe for stdout communication with child process: %s",
  1446. format_win32_error(GetLastError()));
  1447. return status;
  1448. }
  1449. if (!SetHandleInformation(stdout_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  1450. log_warn(LD_GENERAL,
  1451. "Failed to configure pipe for stdout communication with child "
  1452. "process: %s", format_win32_error(GetLastError()));
  1453. return status;
  1454. }
  1455. /* Set up pipe for stderr */
  1456. if (!CreatePipe(&stderr_pipe_read, &stderr_pipe_write, &saAttr, 0)) {
  1457. log_warn(LD_GENERAL,
  1458. "Failed to create pipe for stderr communication with child process: %s",
  1459. format_win32_error(GetLastError()));
  1460. return status;
  1461. }
  1462. if (!SetHandleInformation(stderr_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  1463. log_warn(LD_GENERAL,
  1464. "Failed to configure pipe for stderr communication with child "
  1465. "process: %s", format_win32_error(GetLastError()));
  1466. return status;
  1467. }
  1468. /* Set up pipe for stdin */
  1469. if (!CreatePipe(&stdin_pipe_read, &stdin_pipe_write, &saAttr, 0)) {
  1470. log_warn(LD_GENERAL,
  1471. "Failed to create pipe for stdin communication with child process: %s",
  1472. format_win32_error(GetLastError()));
  1473. return status;
  1474. }
  1475. if (!SetHandleInformation(stdin_pipe_write, HANDLE_FLAG_INHERIT, 0)) {
  1476. log_warn(LD_GENERAL,
  1477. "Failed to configure pipe for stdin communication with child "
  1478. "process: %s", format_win32_error(GetLastError()));
  1479. return status;
  1480. }
  1481. /* Create the child process */
  1482. /* Windows expects argv to be a whitespace delimited string, so join argv up
  1483. */
  1484. joined_argv = tor_join_win_cmdline(argv);
  1485. process_handle = process_handle_new();
  1486. process_handle->status = status;
  1487. ZeroMemory(&(process_handle->pid), sizeof(PROCESS_INFORMATION));
  1488. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  1489. siStartInfo.cb = sizeof(STARTUPINFO);
  1490. siStartInfo.hStdError = stderr_pipe_write;
  1491. siStartInfo.hStdOutput = stdout_pipe_write;
  1492. siStartInfo.hStdInput = stdin_pipe_read;
  1493. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  1494. /* Create the child process */
  1495. retval = CreateProcessA(filename, // module name
  1496. joined_argv, // command line
  1497. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  1498. NULL, // process security attributes
  1499. NULL, // primary thread security attributes
  1500. TRUE, // handles are inherited
  1501. /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
  1502. * work?) */
  1503. CREATE_NO_WINDOW, // creation flags
  1504. (env==NULL) ? NULL : env->windows_environment_block,
  1505. NULL, // use parent's current directory
  1506. &siStartInfo, // STARTUPINFO pointer
  1507. &(process_handle->pid)); // receives PROCESS_INFORMATION
  1508. tor_free(joined_argv);
  1509. if (!retval) {
  1510. log_warn(LD_GENERAL,
  1511. "Failed to create child process %s: %s", filename?filename:argv[0],
  1512. format_win32_error(GetLastError()));
  1513. tor_free(process_handle);
  1514. } else {
  1515. /* TODO: Close hProcess and hThread in process_handle->pid? */
  1516. process_handle->stdout_pipe = stdout_pipe_read;
  1517. process_handle->stderr_pipe = stderr_pipe_read;
  1518. process_handle->stdin_pipe = stdin_pipe_write;
  1519. status = process_handle->status = PROCESS_STATUS_RUNNING;
  1520. }
  1521. /* TODO: Close pipes on exit */
  1522. *process_handle_out = process_handle;
  1523. return status;
  1524. #else /* !(defined(_WIN32)) */
  1525. pid_t pid;
  1526. int stdout_pipe[2];
  1527. int stderr_pipe[2];
  1528. int stdin_pipe[2];
  1529. int fd, retval;
  1530. process_handle_t *process_handle;
  1531. int status;
  1532. const char *error_message = SPAWN_ERROR_MESSAGE;
  1533. size_t error_message_length;
  1534. /* Represents where in the process of spawning the program is;
  1535. this is used for printing out the error message */
  1536. unsigned char child_state = CHILD_STATE_INIT;
  1537. char hex_errno[HEX_ERRNO_SIZE + 2]; /* + 1 should be sufficient actually */
  1538. static int max_fd = -1;
  1539. status = PROCESS_STATUS_ERROR;
  1540. /* We do the strlen here because strlen() is not signal handler safe,
  1541. and we are not allowed to use unsafe functions between fork and exec */
  1542. error_message_length = strlen(error_message);
  1543. // child_state = CHILD_STATE_PIPE;
  1544. /* Set up pipe for redirecting stdout, stderr, and stdin of child */
  1545. retval = pipe(stdout_pipe);
  1546. if (-1 == retval) {
  1547. log_warn(LD_GENERAL,
  1548. "Failed to set up pipe for stdout communication with child process: %s",
  1549. strerror(errno));
  1550. return status;
  1551. }
  1552. retval = pipe(stderr_pipe);
  1553. if (-1 == retval) {
  1554. log_warn(LD_GENERAL,
  1555. "Failed to set up pipe for stderr communication with child process: %s",
  1556. strerror(errno));
  1557. close(stdout_pipe[0]);
  1558. close(stdout_pipe[1]);
  1559. return status;
  1560. }
  1561. retval = pipe(stdin_pipe);
  1562. if (-1 == retval) {
  1563. log_warn(LD_GENERAL,
  1564. "Failed to set up pipe for stdin communication with child process: %s",
  1565. strerror(errno));
  1566. close(stdout_pipe[0]);
  1567. close(stdout_pipe[1]);
  1568. close(stderr_pipe[0]);
  1569. close(stderr_pipe[1]);
  1570. return status;
  1571. }
  1572. // child_state = CHILD_STATE_MAXFD;
  1573. #ifdef _SC_OPEN_MAX
  1574. if (-1 == max_fd) {
  1575. max_fd = (int) sysconf(_SC_OPEN_MAX);
  1576. if (max_fd == -1) {
  1577. max_fd = DEFAULT_MAX_FD;
  1578. log_warn(LD_GENERAL,
  1579. "Cannot find maximum file descriptor, assuming %d", max_fd);
  1580. }
  1581. }
  1582. #else /* !(defined(_SC_OPEN_MAX)) */
  1583. max_fd = DEFAULT_MAX_FD;
  1584. #endif /* defined(_SC_OPEN_MAX) */
  1585. // child_state = CHILD_STATE_FORK;
  1586. pid = fork();
  1587. if (0 == pid) {
  1588. /* In child */
  1589. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  1590. /* Attempt to have the kernel issue a SIGTERM if the parent
  1591. * goes away. Certain attributes of the binary being execve()ed
  1592. * will clear this during the execve() call, but it's better
  1593. * than nothing.
  1594. */
  1595. prctl(PR_SET_PDEATHSIG, SIGTERM);
  1596. #endif /* defined(HAVE_SYS_PRCTL_H) && defined(__linux__) */
  1597. child_state = CHILD_STATE_DUPOUT;
  1598. /* Link child stdout to the write end of the pipe */
  1599. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  1600. if (-1 == retval)
  1601. goto error;
  1602. child_state = CHILD_STATE_DUPERR;
  1603. /* Link child stderr to the write end of the pipe */
  1604. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  1605. if (-1 == retval)
  1606. goto error;
  1607. child_state = CHILD_STATE_DUPIN;
  1608. /* Link child stdin to the read end of the pipe */
  1609. retval = dup2(stdin_pipe[0], STDIN_FILENO);
  1610. if (-1 == retval)
  1611. goto error;
  1612. // child_state = CHILD_STATE_CLOSEFD;
  1613. close(stderr_pipe[0]);
  1614. close(stderr_pipe[1]);
  1615. close(stdout_pipe[0]);
  1616. close(stdout_pipe[1]);
  1617. close(stdin_pipe[0]);
  1618. close(stdin_pipe[1]);
  1619. /* Close all other fds, including the read end of the pipe */
  1620. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  1621. * this needless. */
  1622. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  1623. close(fd);
  1624. }
  1625. // child_state = CHILD_STATE_EXEC;
  1626. /* Call the requested program. We need the cast because
  1627. execvp doesn't define argv as const, even though it
  1628. does not modify the arguments */
  1629. if (env)
  1630. execve(filename, (char *const *) argv, env->unixoid_environment_block);
  1631. else {
  1632. static char *new_env[] = { NULL };
  1633. execve(filename, (char *const *) argv, new_env);
  1634. }
  1635. /* If we got here, the exec or open(/dev/null) failed */
  1636. child_state = CHILD_STATE_FAILEXEC;
  1637. error:
  1638. {
  1639. /* XXX: are we leaking fds from the pipe? */
  1640. int n, err=0;
  1641. ssize_t nbytes;
  1642. n = format_helper_exit_status(child_state, errno, hex_errno);
  1643. if (n >= 0) {
  1644. /* Write the error message. GCC requires that we check the return
  1645. value, but there is nothing we can do if it fails */
  1646. /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
  1647. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  1648. err = (nbytes < 0);
  1649. nbytes = write(STDOUT_FILENO, hex_errno, n);
  1650. err += (nbytes < 0);
  1651. }
  1652. _exit(err?254:255); // exit ok: in child.
  1653. }
  1654. /* Never reached, but avoids compiler warning */
  1655. return status; // LCOV_EXCL_LINE
  1656. }
  1657. /* In parent */
  1658. if (-1 == pid) {
  1659. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  1660. close(stdin_pipe[0]);
  1661. close(stdin_pipe[1]);
  1662. close(stdout_pipe[0]);
  1663. close(stdout_pipe[1]);
  1664. close(stderr_pipe[0]);
  1665. close(stderr_pipe[1]);
  1666. return status;
  1667. }
  1668. process_handle = process_handle_new();
  1669. process_handle->status = status;
  1670. process_handle->pid = pid;
  1671. /* TODO: If the child process forked but failed to exec, waitpid it */
  1672. /* Return read end of the pipes to caller, and close write end */
  1673. process_handle->stdout_pipe = stdout_pipe[0];
  1674. retval = close(stdout_pipe[1]);
  1675. if (-1 == retval) {
  1676. log_warn(LD_GENERAL,
  1677. "Failed to close write end of stdout pipe in parent process: %s",
  1678. strerror(errno));
  1679. }
  1680. process_handle->waitpid_cb = set_waitpid_callback(pid,
  1681. process_handle_waitpid_cb,
  1682. process_handle);
  1683. process_handle->stderr_pipe = stderr_pipe[0];
  1684. retval = close(stderr_pipe[1]);
  1685. if (-1 == retval) {
  1686. log_warn(LD_GENERAL,
  1687. "Failed to close write end of stderr pipe in parent process: %s",
  1688. strerror(errno));
  1689. }
  1690. /* Return write end of the stdin pipe to caller, and close the read end */
  1691. process_handle->stdin_pipe = stdin_pipe[1];
  1692. retval = close(stdin_pipe[0]);
  1693. if (-1 == retval) {
  1694. log_warn(LD_GENERAL,
  1695. "Failed to close read end of stdin pipe in parent process: %s",
  1696. strerror(errno));
  1697. }
  1698. status = process_handle->status = PROCESS_STATUS_RUNNING;
  1699. /* Set stdin/stdout/stderr pipes to be non-blocking */
  1700. if (fcntl(process_handle->stdout_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  1701. fcntl(process_handle->stderr_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  1702. fcntl(process_handle->stdin_pipe, F_SETFL, O_NONBLOCK) < 0) {
  1703. log_warn(LD_GENERAL, "Failed to set stderror/stdout/stdin pipes "
  1704. "nonblocking in parent process: %s", strerror(errno));
  1705. }
  1706. *process_handle_out = process_handle;
  1707. return status;
  1708. #endif /* defined(_WIN32) */
  1709. }
  1710. /** Destroy all resources allocated by the process handle in
  1711. * <b>process_handle</b>.
  1712. * If <b>also_terminate_process</b> is true, also terminate the
  1713. * process of the process handle. */
  1714. MOCK_IMPL(void,
  1715. tor_process_handle_destroy,(process_handle_t *process_handle,
  1716. int also_terminate_process))
  1717. {
  1718. if (!process_handle)
  1719. return;
  1720. if (also_terminate_process) {
  1721. if (tor_terminate_process(process_handle) < 0) {
  1722. const char *errstr =
  1723. #ifdef _WIN32
  1724. format_win32_error(GetLastError());
  1725. #else
  1726. strerror(errno);
  1727. #endif
  1728. log_notice(LD_GENERAL, "Failed to terminate process with "
  1729. "PID '%d' ('%s').", tor_process_get_pid(process_handle),
  1730. errstr);
  1731. } else {
  1732. log_info(LD_GENERAL, "Terminated process with PID '%d'.",
  1733. tor_process_get_pid(process_handle));
  1734. }
  1735. }
  1736. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  1737. #ifdef _WIN32
  1738. if (process_handle->stdout_pipe)
  1739. CloseHandle(process_handle->stdout_pipe);
  1740. if (process_handle->stderr_pipe)
  1741. CloseHandle(process_handle->stderr_pipe);
  1742. if (process_handle->stdin_pipe)
  1743. CloseHandle(process_handle->stdin_pipe);
  1744. #else /* !(defined(_WIN32)) */
  1745. close(process_handle->stdout_pipe);
  1746. close(process_handle->stderr_pipe);
  1747. close(process_handle->stdin_pipe);
  1748. clear_waitpid_callback(process_handle->waitpid_cb);
  1749. #endif /* defined(_WIN32) */
  1750. memset(process_handle, 0x0f, sizeof(process_handle_t));
  1751. tor_free(process_handle);
  1752. }
  1753. /** Get the exit code of a process specified by <b>process_handle</b> and store
  1754. * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
  1755. * to true, the call will block until the process has exited. Otherwise if
  1756. * the process is still running, the function will return
  1757. * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
  1758. * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
  1759. * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
  1760. * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
  1761. * probably not work in Tor, because waitpid() is called in main.c to reap any
  1762. * terminated child processes.*/
  1763. int
  1764. tor_get_exit_code(process_handle_t *process_handle,
  1765. int block, int *exit_code)
  1766. {
  1767. #ifdef _WIN32
  1768. DWORD retval;
  1769. BOOL success;
  1770. if (block) {
  1771. /* Wait for the process to exit */
  1772. retval = WaitForSingleObject(process_handle->pid.hProcess, INFINITE);
  1773. if (retval != WAIT_OBJECT_0) {
  1774. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  1775. (int)retval, format_win32_error(GetLastError()));
  1776. return PROCESS_EXIT_ERROR;
  1777. }
  1778. } else {
  1779. retval = WaitForSingleObject(process_handle->pid.hProcess, 0);
  1780. if (WAIT_TIMEOUT == retval) {
  1781. /* Process has not exited */
  1782. return PROCESS_EXIT_RUNNING;
  1783. } else if (retval != WAIT_OBJECT_0) {
  1784. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  1785. (int)retval, format_win32_error(GetLastError()));
  1786. return PROCESS_EXIT_ERROR;
  1787. }
  1788. }
  1789. if (exit_code != NULL) {
  1790. success = GetExitCodeProcess(process_handle->pid.hProcess,
  1791. (PDWORD)exit_code);
  1792. if (!success) {
  1793. log_warn(LD_GENERAL, "GetExitCodeProcess() failed: %s",
  1794. format_win32_error(GetLastError()));
  1795. return PROCESS_EXIT_ERROR;
  1796. }
  1797. }
  1798. #else /* !(defined(_WIN32)) */
  1799. int stat_loc;
  1800. int retval;
  1801. if (process_handle->waitpid_cb) {
  1802. /* We haven't processed a SIGCHLD yet. */
  1803. retval = waitpid(process_handle->pid, &stat_loc, block?0:WNOHANG);
  1804. if (retval == process_handle->pid) {
  1805. clear_waitpid_callback(process_handle->waitpid_cb);
  1806. process_handle->waitpid_cb = NULL;
  1807. process_handle->waitpid_exit_status = stat_loc;
  1808. }
  1809. } else {
  1810. /* We already got a SIGCHLD for this process, and handled it. */
  1811. retval = process_handle->pid;
  1812. stat_loc = process_handle->waitpid_exit_status;
  1813. }
  1814. if (!block && 0 == retval) {
  1815. /* Process has not exited */
  1816. return PROCESS_EXIT_RUNNING;
  1817. } else if (retval != process_handle->pid) {
  1818. log_warn(LD_GENERAL, "waitpid() failed for PID %d: %s",
  1819. (int)process_handle->pid, strerror(errno));
  1820. return PROCESS_EXIT_ERROR;
  1821. }
  1822. if (!WIFEXITED(stat_loc)) {
  1823. log_warn(LD_GENERAL, "Process %d did not exit normally",
  1824. (int)process_handle->pid);
  1825. return PROCESS_EXIT_ERROR;
  1826. }
  1827. if (exit_code != NULL)
  1828. *exit_code = WEXITSTATUS(stat_loc);
  1829. #endif /* defined(_WIN32) */
  1830. return PROCESS_EXIT_EXITED;
  1831. }
  1832. /** Helper: return the number of characters in <b>s</b> preceding the first
  1833. * occurrence of <b>ch</b>. If <b>ch</b> does not occur in <b>s</b>, return
  1834. * the length of <b>s</b>. Should be equivalent to strspn(s, "ch"). */
  1835. static inline size_t
  1836. str_num_before(const char *s, char ch)
  1837. {
  1838. const char *cp = strchr(s, ch);
  1839. if (cp)
  1840. return cp - s;
  1841. else
  1842. return strlen(s);
  1843. }
  1844. /** Return non-zero iff getenv would consider <b>s1</b> and <b>s2</b>
  1845. * to have the same name as strings in a process's environment. */
  1846. int
  1847. environment_variable_names_equal(const char *s1, const char *s2)
  1848. {
  1849. size_t s1_name_len = str_num_before(s1, '=');
  1850. size_t s2_name_len = str_num_before(s2, '=');
  1851. return (s1_name_len == s2_name_len &&
  1852. tor_memeq(s1, s2, s1_name_len));
  1853. }
  1854. /** Free <b>env</b> (assuming it was produced by
  1855. * process_environment_make). */
  1856. void
  1857. process_environment_free_(process_environment_t *env)
  1858. {
  1859. if (env == NULL) return;
  1860. /* As both an optimization hack to reduce consing on Unixoid systems
  1861. * and a nice way to ensure that some otherwise-Windows-specific
  1862. * code will always get tested before changes to it get merged, the
  1863. * strings which env->unixoid_environment_block points to are packed
  1864. * into env->windows_environment_block. */
  1865. tor_free(env->unixoid_environment_block);
  1866. tor_free(env->windows_environment_block);
  1867. tor_free(env);
  1868. }
  1869. /** Make a process_environment_t containing the environment variables
  1870. * specified in <b>env_vars</b> (as C strings of the form
  1871. * "NAME=VALUE"). */
  1872. process_environment_t *
  1873. process_environment_make(struct smartlist_t *env_vars)
  1874. {
  1875. process_environment_t *env = tor_malloc_zero(sizeof(process_environment_t));
  1876. int n_env_vars = smartlist_len(env_vars);
  1877. int i;
  1878. size_t total_env_length;
  1879. smartlist_t *env_vars_sorted;
  1880. tor_assert(n_env_vars + 1 != 0);
  1881. env->unixoid_environment_block = tor_calloc(n_env_vars + 1, sizeof(char *));
  1882. /* env->unixoid_environment_block is already NULL-terminated,
  1883. * because we assume that NULL == 0 (and check that during compilation). */
  1884. total_env_length = 1; /* terminating NUL of terminating empty string */
  1885. for (i = 0; i < n_env_vars; ++i) {
  1886. const char *s = smartlist_get(env_vars, (int)i);
  1887. size_t slen = strlen(s);
  1888. tor_assert(slen + 1 != 0);
  1889. tor_assert(slen + 1 < SIZE_MAX - total_env_length);
  1890. total_env_length += slen + 1;
  1891. }
  1892. env->windows_environment_block = tor_malloc_zero(total_env_length);
  1893. /* env->windows_environment_block is already
  1894. * (NUL-terminated-empty-string)-terminated. */
  1895. /* Some versions of Windows supposedly require that environment
  1896. * blocks be sorted. Or maybe some Windows programs (or their
  1897. * runtime libraries) fail to look up strings in non-sorted
  1898. * environment blocks.
  1899. *
  1900. * Also, sorting strings makes it easy to find duplicate environment
  1901. * variables and environment-variable strings without an '=' on all
  1902. * OSes, and they can cause badness. Let's complain about those. */
  1903. env_vars_sorted = smartlist_new();
  1904. smartlist_add_all(env_vars_sorted, env_vars);
  1905. smartlist_sort_strings(env_vars_sorted);
  1906. /* Now copy the strings into the environment blocks. */
  1907. {
  1908. char *cp = env->windows_environment_block;
  1909. const char *prev_env_var = NULL;
  1910. for (i = 0; i < n_env_vars; ++i) {
  1911. const char *s = smartlist_get(env_vars_sorted, (int)i);
  1912. size_t slen = strlen(s);
  1913. size_t s_name_len = str_num_before(s, '=');
  1914. if (s_name_len == slen) {
  1915. log_warn(LD_GENERAL,
  1916. "Preparing an environment containing a variable "
  1917. "without a value: %s",
  1918. s);
  1919. }
  1920. if (prev_env_var != NULL &&
  1921. environment_variable_names_equal(s, prev_env_var)) {
  1922. log_warn(LD_GENERAL,
  1923. "Preparing an environment containing two variables "
  1924. "with the same name: %s and %s",
  1925. prev_env_var, s);
  1926. }
  1927. prev_env_var = s;
  1928. /* Actually copy the string into the environment. */
  1929. memcpy(cp, s, slen+1);
  1930. env->unixoid_environment_block[i] = cp;
  1931. cp += slen+1;
  1932. }
  1933. tor_assert(cp == env->windows_environment_block + total_env_length - 1);
  1934. }
  1935. smartlist_free(env_vars_sorted);
  1936. return env;
  1937. }
  1938. /** Return a newly allocated smartlist containing every variable in
  1939. * this process's environment, as a NUL-terminated string of the form
  1940. * "NAME=VALUE". Note that on some/many/most/all OSes, the parent
  1941. * process can put strings not of that form in our environment;
  1942. * callers should try to not get crashed by that.
  1943. *
  1944. * The returned strings are heap-allocated, and must be freed by the
  1945. * caller. */
  1946. struct smartlist_t *
  1947. get_current_process_environment_variables(void)
  1948. {
  1949. smartlist_t *sl = smartlist_new();
  1950. char **environ_tmp; /* Not const char ** ? Really? */
  1951. for (environ_tmp = get_environment(); *environ_tmp; ++environ_tmp) {
  1952. smartlist_add_strdup(sl, *environ_tmp);
  1953. }
  1954. return sl;
  1955. }
  1956. /** For each string s in <b>env_vars</b> such that
  1957. * environment_variable_names_equal(s, <b>new_var</b>), remove it; if
  1958. * <b>free_p</b> is non-zero, call <b>free_old</b>(s). If
  1959. * <b>new_var</b> contains '=', insert it into <b>env_vars</b>. */
  1960. void
  1961. set_environment_variable_in_smartlist(struct smartlist_t *env_vars,
  1962. const char *new_var,
  1963. void (*free_old)(void*),
  1964. int free_p)
  1965. {
  1966. SMARTLIST_FOREACH_BEGIN(env_vars, const char *, s) {
  1967. if (environment_variable_names_equal(s, new_var)) {
  1968. SMARTLIST_DEL_CURRENT(env_vars, s);
  1969. if (free_p) {
  1970. free_old((void *)s);
  1971. }
  1972. }
  1973. } SMARTLIST_FOREACH_END(s);
  1974. if (strchr(new_var, '=') != NULL) {
  1975. smartlist_add(env_vars, (void *)new_var);
  1976. }
  1977. }
  1978. #ifdef _WIN32
  1979. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  1980. * <b>hProcess</b> is NULL, the function will return immediately if there is
  1981. * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
  1982. * to the process owning the <b>h</b>. In this case, the function will exit
  1983. * only once the process has exited, or <b>count</b> bytes are read. Returns
  1984. * the number of bytes read, or -1 on error. */
  1985. ssize_t
  1986. tor_read_all_handle(HANDLE h, char *buf, size_t count,
  1987. const process_handle_t *process)
  1988. {
  1989. size_t numread = 0;
  1990. BOOL retval;
  1991. DWORD byte_count;
  1992. BOOL process_exited = FALSE;
  1993. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  1994. return -1;
  1995. while (numread < count) {
  1996. /* Check if there is anything to read */
  1997. retval = PeekNamedPipe(h, NULL, 0, NULL, &byte_count, NULL);
  1998. if (!retval) {
  1999. log_warn(LD_GENERAL,
  2000. "Failed to peek from handle: %s",
  2001. format_win32_error(GetLastError()));
  2002. return -1;
  2003. } else if (0 == byte_count) {
  2004. /* Nothing available: process exited or it is busy */
  2005. /* Exit if we don't know whether the process is running */
  2006. if (NULL == process)
  2007. break;
  2008. /* The process exited and there's nothing left to read from it */
  2009. if (process_exited)
  2010. break;
  2011. /* If process is not running, check for output one more time in case
  2012. it wrote something after the peek was performed. Otherwise keep on
  2013. waiting for output */
  2014. tor_assert(process != NULL);
  2015. byte_count = WaitForSingleObject(process->pid.hProcess, 0);
  2016. if (WAIT_TIMEOUT != byte_count)
  2017. process_exited = TRUE;
  2018. continue;
  2019. }
  2020. /* There is data to read; read it */
  2021. retval = ReadFile(h, buf+numread, count-numread, &byte_count, NULL);
  2022. tor_assert(byte_count + numread <= count);
  2023. if (!retval) {
  2024. log_warn(LD_GENERAL, "Failed to read from handle: %s",
  2025. format_win32_error(GetLastError()));
  2026. return -1;
  2027. } else if (0 == byte_count) {
  2028. /* End of file */
  2029. break;
  2030. }
  2031. numread += byte_count;
  2032. }
  2033. return (ssize_t)numread;
  2034. }
  2035. #else /* !(defined(_WIN32)) */
  2036. /** Read from a handle <b>fd</b> into <b>buf</b>, up to <b>count</b> bytes. If
  2037. * <b>process</b> is NULL, the function will return immediately if there is
  2038. * nothing more to read. Otherwise data will be read until end of file, or
  2039. * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
  2040. * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
  2041. * file has been reached. */
  2042. ssize_t
  2043. tor_read_all_handle(int fd, char *buf, size_t count,
  2044. const process_handle_t *process,
  2045. int *eof)
  2046. {
  2047. size_t numread = 0;
  2048. ssize_t result;
  2049. if (eof)
  2050. *eof = 0;
  2051. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  2052. return -1;
  2053. while (numread < count) {
  2054. result = read(fd, buf+numread, count-numread);
  2055. if (result == 0) {
  2056. log_debug(LD_GENERAL, "read() reached end of file");
  2057. if (eof)
  2058. *eof = 1;
  2059. break;
  2060. } else if (result < 0 && errno == EAGAIN) {
  2061. if (process)
  2062. continue;
  2063. else
  2064. break;
  2065. } else if (result < 0) {
  2066. log_warn(LD_GENERAL, "read() failed: %s", strerror(errno));
  2067. return -1;
  2068. }
  2069. numread += result;
  2070. }
  2071. log_debug(LD_GENERAL, "read() read %d bytes from handle", (int)numread);
  2072. return (ssize_t)numread;
  2073. }
  2074. #endif /* defined(_WIN32) */
  2075. /** Read from stdout of a process until the process exits. */
  2076. ssize_t
  2077. tor_read_all_from_process_stdout(const process_handle_t *process_handle,
  2078. char *buf, size_t count)
  2079. {
  2080. #ifdef _WIN32
  2081. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  2082. process_handle);
  2083. #else
  2084. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  2085. process_handle, NULL);
  2086. #endif /* defined(_WIN32) */
  2087. }
  2088. /** Read from stdout of a process until the process exits. */
  2089. ssize_t
  2090. tor_read_all_from_process_stderr(const process_handle_t *process_handle,
  2091. char *buf, size_t count)
  2092. {
  2093. #ifdef _WIN32
  2094. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  2095. process_handle);
  2096. #else
  2097. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  2098. process_handle, NULL);
  2099. #endif /* defined(_WIN32) */
  2100. }
  2101. /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
  2102. * modified. The resulting smartlist will consist of pointers to buf, so there
  2103. * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
  2104. * string. <b>len</b> should be set to the length of the buffer excluding the
  2105. * NUL. Non-printable characters (including NUL) will be replaced with "." */
  2106. int
  2107. tor_split_lines(smartlist_t *sl, char *buf, int len)
  2108. {
  2109. /* Index in buf of the start of the current line */
  2110. int start = 0;
  2111. /* Index in buf of the current character being processed */
  2112. int cur = 0;
  2113. /* Are we currently in a line */
  2114. char in_line = 0;
  2115. /* Loop over string */
  2116. while (cur < len) {
  2117. /* Loop until end of line or end of string */
  2118. for (; cur < len; cur++) {
  2119. if (in_line) {
  2120. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  2121. /* End of line */
  2122. buf[cur] = '\0';
  2123. /* Point cur to the next line */
  2124. cur++;
  2125. /* Line starts at start and ends with a nul */
  2126. break;
  2127. } else {
  2128. if (!TOR_ISPRINT(buf[cur]))
  2129. buf[cur] = '.';
  2130. }
  2131. } else {
  2132. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  2133. /* Skip leading vertical space */
  2134. ;
  2135. } else {
  2136. in_line = 1;
  2137. start = cur;
  2138. if (!TOR_ISPRINT(buf[cur]))
  2139. buf[cur] = '.';
  2140. }
  2141. }
  2142. }
  2143. /* We are at the end of the line or end of string. If in_line is true there
  2144. * is a line which starts at buf+start and ends at a NUL. cur points to
  2145. * the character after the NUL. */
  2146. if (in_line)
  2147. smartlist_add(sl, (void *)(buf+start));
  2148. in_line = 0;
  2149. }
  2150. return smartlist_len(sl);
  2151. }
  2152. /** Return a string corresponding to <b>stream_status</b>. */
  2153. const char *
  2154. stream_status_to_string(enum stream_status stream_status)
  2155. {
  2156. switch (stream_status) {
  2157. case IO_STREAM_OKAY:
  2158. return "okay";
  2159. case IO_STREAM_EAGAIN:
  2160. return "temporarily unavailable";
  2161. case IO_STREAM_TERM:
  2162. return "terminated";
  2163. case IO_STREAM_CLOSED:
  2164. return "closed";
  2165. default:
  2166. tor_fragile_assert();
  2167. return "unknown";
  2168. }
  2169. }
  2170. #ifdef _WIN32
  2171. /** Return a smartlist containing lines outputted from
  2172. * <b>handle</b>. Return NULL on error, and set
  2173. * <b>stream_status_out</b> appropriately. */
  2174. MOCK_IMPL(smartlist_t *,
  2175. tor_get_lines_from_handle, (HANDLE *handle,
  2176. enum stream_status *stream_status_out))
  2177. {
  2178. int pos;
  2179. char stdout_buf[600] = {0};
  2180. smartlist_t *lines = NULL;
  2181. tor_assert(stream_status_out);
  2182. *stream_status_out = IO_STREAM_TERM;
  2183. pos = tor_read_all_handle(handle, stdout_buf, sizeof(stdout_buf) - 1, NULL);
  2184. if (pos < 0) {
  2185. *stream_status_out = IO_STREAM_TERM;
  2186. return NULL;
  2187. }
  2188. if (pos == 0) {
  2189. *stream_status_out = IO_STREAM_EAGAIN;
  2190. return NULL;
  2191. }
  2192. /* End with a null even if there isn't a \r\n at the end */
  2193. /* TODO: What if this is a partial line? */
  2194. stdout_buf[pos] = '\0';
  2195. /* Split up the buffer */
  2196. lines = smartlist_new();
  2197. tor_split_lines(lines, stdout_buf, pos);
  2198. /* Currently 'lines' is populated with strings residing on the
  2199. stack. Replace them with their exact copies on the heap: */
  2200. SMARTLIST_FOREACH(lines, char *, line,
  2201. SMARTLIST_REPLACE_CURRENT(lines, line, tor_strdup(line)));
  2202. *stream_status_out = IO_STREAM_OKAY;
  2203. return lines;
  2204. }
  2205. #else /* !(defined(_WIN32)) */
  2206. /** Return a smartlist containing lines outputted from
  2207. * <b>fd</b>. Return NULL on error, and set
  2208. * <b>stream_status_out</b> appropriately. */
  2209. MOCK_IMPL(smartlist_t *,
  2210. tor_get_lines_from_handle, (int fd, enum stream_status *stream_status_out))
  2211. {
  2212. enum stream_status stream_status;
  2213. char stdout_buf[400];
  2214. smartlist_t *lines = NULL;
  2215. while (1) {
  2216. memset(stdout_buf, 0, sizeof(stdout_buf));
  2217. stream_status = get_string_from_pipe(fd,
  2218. stdout_buf, sizeof(stdout_buf) - 1);
  2219. if (stream_status != IO_STREAM_OKAY)
  2220. goto done;
  2221. if (!lines) lines = smartlist_new();
  2222. smartlist_split_string(lines, stdout_buf, "\n", 0, 0);
  2223. }
  2224. done:
  2225. *stream_status_out = stream_status;
  2226. return lines;
  2227. }
  2228. #endif /* defined(_WIN32) */
  2229. /** Reads from <b>fd</b> and stores input in <b>buf_out</b> making
  2230. * sure it's below <b>count</b> bytes.
  2231. * If the string has a trailing newline, we strip it off.
  2232. *
  2233. * This function is specifically created to handle input from managed
  2234. * proxies, according to the pluggable transports spec. Make sure it
  2235. * fits your needs before using it.
  2236. *
  2237. * Returns:
  2238. * IO_STREAM_CLOSED: If the stream is closed.
  2239. * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
  2240. * later.
  2241. * IO_STREAM_TERM: If something is wrong with the stream.
  2242. * IO_STREAM_OKAY: If everything went okay and we got a string
  2243. * in <b>buf_out</b>. */
  2244. enum stream_status
  2245. get_string_from_pipe(int fd, char *buf_out, size_t count)
  2246. {
  2247. ssize_t ret;
  2248. tor_assert(count <= INT_MAX);
  2249. ret = read(fd, buf_out, count);
  2250. if (ret == 0)
  2251. return IO_STREAM_CLOSED;
  2252. else if (ret < 0 && errno == EAGAIN)
  2253. return IO_STREAM_EAGAIN;
  2254. else if (ret < 0)
  2255. return IO_STREAM_TERM;
  2256. if (buf_out[ret - 1] == '\n') {
  2257. /* Remove the trailing newline */
  2258. buf_out[ret - 1] = '\0';
  2259. } else
  2260. buf_out[ret] = '\0';
  2261. return IO_STREAM_OKAY;
  2262. }
  2263. /** Initialize the insecure RNG <b>rng</b> from a seed value <b>seed</b>. */
  2264. void
  2265. tor_init_weak_random(tor_weak_rng_t *rng, unsigned seed)
  2266. {
  2267. rng->state = (uint32_t)(seed & 0x7fffffff);
  2268. }
  2269. /** Return a randomly chosen value in the range 0..TOR_WEAK_RANDOM_MAX based
  2270. * on the RNG state of <b>rng</b>. This entropy will not be cryptographically
  2271. * strong; do not rely on it for anything an adversary should not be able to
  2272. * predict. */
  2273. int32_t
  2274. tor_weak_random(tor_weak_rng_t *rng)
  2275. {
  2276. /* Here's a linear congruential generator. OpenBSD and glibc use these
  2277. * parameters; they aren't too bad, and should have maximal period over the
  2278. * range 0..INT32_MAX. We don't want to use the platform rand() or random(),
  2279. * since some platforms have bad weak RNGs that only return values in the
  2280. * range 0..INT16_MAX, which just isn't enough. */
  2281. rng->state = (rng->state * 1103515245 + 12345) & 0x7fffffff;
  2282. return (int32_t) rng->state;
  2283. }
  2284. /** Return a random number in the range [0 , <b>top</b>). {That is, the range
  2285. * of integers i such that 0 <= i < top.} Chooses uniformly. Requires that
  2286. * top is greater than 0. This randomness is not cryptographically strong; do
  2287. * not rely on it for anything an adversary should not be able to predict. */
  2288. int32_t
  2289. tor_weak_random_range(tor_weak_rng_t *rng, int32_t top)
  2290. {
  2291. /* We don't want to just do tor_weak_random() % top, since random() is often
  2292. * implemented with an LCG whose modulus is a power of 2, and those are
  2293. * cyclic in their low-order bits. */
  2294. int divisor, result;
  2295. tor_assert(top > 0);
  2296. divisor = TOR_WEAK_RANDOM_MAX / top;
  2297. do {
  2298. result = (int32_t)(tor_weak_random(rng) / divisor);
  2299. } while (result >= top);
  2300. return result;
  2301. }
  2302. /** Cast a given double value to a int64_t. Return 0 if number is NaN.
  2303. * Returns either INT64_MIN or INT64_MAX if number is outside of the int64_t
  2304. * range. */
  2305. int64_t
  2306. clamp_double_to_int64(double number)
  2307. {
  2308. int exponent;
  2309. #if defined(MINGW_ANY) && GCC_VERSION >= 409
  2310. /*
  2311. Mingw's math.h uses gcc's __builtin_choose_expr() facility to declare
  2312. isnan, isfinite, and signbit. But as implemented in at least some
  2313. versions of gcc, __builtin_choose_expr() can generate type warnings
  2314. even from branches that are not taken. So, suppress those warnings.
  2315. */
  2316. #define PROBLEMATIC_FLOAT_CONVERSION_WARNING
  2317. DISABLE_GCC_WARNING(float-conversion)
  2318. #endif /* defined(MINGW_ANY) && GCC_VERSION >= 409 */
  2319. /*
  2320. With clang 4.0 we apparently run into "double promotion" warnings here,
  2321. since clang thinks we're promoting a double to a long double.
  2322. */
  2323. #if defined(__clang__)
  2324. #if __has_warning("-Wdouble-promotion")
  2325. #define PROBLEMATIC_DOUBLE_PROMOTION_WARNING
  2326. DISABLE_GCC_WARNING(double-promotion)
  2327. #endif
  2328. #endif /* defined(__clang__) */
  2329. /* NaN is a special case that can't be used with the logic below. */
  2330. if (isnan(number)) {
  2331. return 0;
  2332. }
  2333. /* Time to validate if result can overflows a int64_t value. Fun with
  2334. * float! Find that exponent exp such that
  2335. * number == x * 2^exp
  2336. * for some x with abs(x) in [0.5, 1.0). Note that this implies that the
  2337. * magnitude of number is strictly less than 2^exp.
  2338. *
  2339. * If number is infinite, the call to frexp is legal but the contents of
  2340. * are exponent unspecified. */
  2341. frexp(number, &exponent);
  2342. /* If the magnitude of number is strictly less than 2^63, the truncated
  2343. * version of number is guaranteed to be representable. The only
  2344. * representable integer for which this is not the case is INT64_MIN, but
  2345. * it is covered by the logic below. */
  2346. if (isfinite(number) && exponent <= 63) {
  2347. return (int64_t)number;
  2348. }
  2349. /* Handle infinities and finite numbers with magnitude >= 2^63. */
  2350. return signbit(number) ? INT64_MIN : INT64_MAX;
  2351. #ifdef PROBLEMATIC_DOUBLE_PROMOTION_WARNING
  2352. ENABLE_GCC_WARNING(double-promotion)
  2353. #endif
  2354. #ifdef PROBLEMATIC_FLOAT_CONVERSION_WARNING
  2355. ENABLE_GCC_WARNING(float-conversion)
  2356. #endif
  2357. }