util.c 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104
  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 true if <b>string</b> is a valid 'key=[value]' string.
  208. * "value" is optional, to indicate the empty string. Log at logging
  209. * <b>severity</b> if something ugly happens. */
  210. int
  211. string_is_key_value(int severity, const char *string)
  212. {
  213. /* position of equal sign in string */
  214. const char *equal_sign_pos = NULL;
  215. tor_assert(string);
  216. if (strlen(string) < 2) { /* "x=" is shortest args string */
  217. tor_log(severity, LD_GENERAL, "'%s' is too short to be a k=v value.",
  218. escaped(string));
  219. return 0;
  220. }
  221. equal_sign_pos = strchr(string, '=');
  222. if (!equal_sign_pos) {
  223. tor_log(severity, LD_GENERAL, "'%s' is not a k=v value.", escaped(string));
  224. return 0;
  225. }
  226. /* validate that the '=' is not in the beginning of the string. */
  227. if (equal_sign_pos == string) {
  228. tor_log(severity, LD_GENERAL, "'%s' is not a valid k=v value.",
  229. escaped(string));
  230. return 0;
  231. }
  232. return 1;
  233. }
  234. /** Return a newly allocated string equal to <b>string</b>, except that every
  235. * character in <b>chars_to_escape</b> is preceded by a backslash. */
  236. char *
  237. tor_escape_str_for_pt_args(const char *string, const char *chars_to_escape)
  238. {
  239. char *new_string = NULL;
  240. char *new_cp = NULL;
  241. size_t length, new_length;
  242. tor_assert(string);
  243. length = strlen(string);
  244. if (!length) /* If we were given the empty string, return the same. */
  245. return tor_strdup("");
  246. /* (new_length > SIZE_MAX) => ((length * 2) + 1 > SIZE_MAX) =>
  247. (length*2 > SIZE_MAX - 1) => (length > (SIZE_MAX - 1)/2) */
  248. if (length > (SIZE_MAX - 1)/2) /* check for overflow */
  249. return NULL;
  250. /* this should be enough even if all characters must be escaped */
  251. new_length = (length * 2) + 1;
  252. new_string = new_cp = tor_malloc(new_length);
  253. while (*string) {
  254. if (strchr(chars_to_escape, *string))
  255. *new_cp++ = '\\';
  256. *new_cp++ = *string++;
  257. }
  258. *new_cp = '\0'; /* NUL-terminate the new string */
  259. return new_string;
  260. }
  261. /* =====
  262. * Time
  263. * ===== */
  264. #define TOR_USEC_PER_SEC 1000000
  265. /** Return the difference between start->tv_sec and end->tv_sec.
  266. * Returns INT64_MAX on overflow and underflow.
  267. */
  268. static int64_t
  269. tv_secdiff_impl(const struct timeval *start, const struct timeval *end)
  270. {
  271. const int64_t s = (int64_t)start->tv_sec;
  272. const int64_t e = (int64_t)end->tv_sec;
  273. /* This may not be the most efficient way of implemeting this check,
  274. * but it's easy to see that it's correct and doesn't overflow */
  275. if (s > 0 && e < INT64_MIN + s) {
  276. /* s is positive: equivalent to e - s < INT64_MIN, but without any
  277. * overflow */
  278. return INT64_MAX;
  279. } else if (s < 0 && e > INT64_MAX + s) {
  280. /* s is negative: equivalent to e - s > INT64_MAX, but without any
  281. * overflow */
  282. return INT64_MAX;
  283. }
  284. return e - s;
  285. }
  286. /** Return the number of microseconds elapsed between *start and *end.
  287. * Returns LONG_MAX on overflow and underflow.
  288. */
  289. long
  290. tv_udiff(const struct timeval *start, const struct timeval *end)
  291. {
  292. /* Sanity check tv_usec */
  293. if (start->tv_usec > TOR_USEC_PER_SEC || start->tv_usec < 0) {
  294. log_warn(LD_GENERAL, "comparing times on microsecond detail with bad "
  295. "start tv_usec: " I64_FORMAT " microseconds",
  296. I64_PRINTF_ARG(start->tv_usec));
  297. return LONG_MAX;
  298. }
  299. if (end->tv_usec > TOR_USEC_PER_SEC || end->tv_usec < 0) {
  300. log_warn(LD_GENERAL, "comparing times on microsecond detail with bad "
  301. "end tv_usec: " I64_FORMAT " microseconds",
  302. I64_PRINTF_ARG(end->tv_usec));
  303. return LONG_MAX;
  304. }
  305. /* Some BSDs have struct timeval.tv_sec 64-bit, but time_t (and long) 32-bit
  306. */
  307. int64_t udiff;
  308. const int64_t secdiff = tv_secdiff_impl(start, end);
  309. /* end->tv_usec - start->tv_usec can be up to 1 second either way */
  310. if (secdiff > (int64_t)(LONG_MAX/1000000 - 1) ||
  311. secdiff < (int64_t)(LONG_MIN/1000000 + 1)) {
  312. log_warn(LD_GENERAL, "comparing times on microsecond detail too far "
  313. "apart: " I64_FORMAT " seconds", I64_PRINTF_ARG(secdiff));
  314. return LONG_MAX;
  315. }
  316. /* we'll never get an overflow here, because we check that both usecs are
  317. * between 0 and TV_USEC_PER_SEC. */
  318. udiff = secdiff*1000000 + ((int64_t)end->tv_usec - (int64_t)start->tv_usec);
  319. /* Some compilers are smart enough to work out this is a no-op on L64 */
  320. #if SIZEOF_LONG < 8
  321. if (udiff > (int64_t)LONG_MAX || udiff < (int64_t)LONG_MIN) {
  322. return LONG_MAX;
  323. }
  324. #endif
  325. return (long)udiff;
  326. }
  327. /** Return the number of milliseconds elapsed between *start and *end.
  328. * If the tv_usec difference is 500, rounds away from zero.
  329. * Returns LONG_MAX on overflow and underflow.
  330. */
  331. long
  332. tv_mdiff(const struct timeval *start, const struct timeval *end)
  333. {
  334. /* Sanity check tv_usec */
  335. if (start->tv_usec > TOR_USEC_PER_SEC || start->tv_usec < 0) {
  336. log_warn(LD_GENERAL, "comparing times on millisecond detail with bad "
  337. "start tv_usec: " I64_FORMAT " microseconds",
  338. I64_PRINTF_ARG(start->tv_usec));
  339. return LONG_MAX;
  340. }
  341. if (end->tv_usec > TOR_USEC_PER_SEC || end->tv_usec < 0) {
  342. log_warn(LD_GENERAL, "comparing times on millisecond detail with bad "
  343. "end tv_usec: " I64_FORMAT " microseconds",
  344. I64_PRINTF_ARG(end->tv_usec));
  345. return LONG_MAX;
  346. }
  347. /* Some BSDs have struct timeval.tv_sec 64-bit, but time_t (and long) 32-bit
  348. */
  349. int64_t mdiff;
  350. const int64_t secdiff = tv_secdiff_impl(start, end);
  351. /* end->tv_usec - start->tv_usec can be up to 1 second either way, but the
  352. * mdiff calculation may add another temporary second for rounding.
  353. * Whether this actually causes overflow depends on the compiler's constant
  354. * folding and order of operations. */
  355. if (secdiff > (int64_t)(LONG_MAX/1000 - 2) ||
  356. secdiff < (int64_t)(LONG_MIN/1000 + 1)) {
  357. log_warn(LD_GENERAL, "comparing times on millisecond detail too far "
  358. "apart: " I64_FORMAT " seconds", I64_PRINTF_ARG(secdiff));
  359. return LONG_MAX;
  360. }
  361. /* Subtract and round */
  362. mdiff = secdiff*1000 +
  363. /* We add a million usec here to ensure that the result is positive,
  364. * so that the round-towards-zero behavior of the division will give
  365. * the right result for rounding to the nearest msec. Later we subtract
  366. * 1000 in order to get the correct result.
  367. * We'll never get an overflow here, because we check that both usecs are
  368. * between 0 and TV_USEC_PER_SEC. */
  369. ((int64_t)end->tv_usec - (int64_t)start->tv_usec + 500 + 1000000) / 1000
  370. - 1000;
  371. /* Some compilers are smart enough to work out this is a no-op on L64 */
  372. #if SIZEOF_LONG < 8
  373. if (mdiff > (int64_t)LONG_MAX || mdiff < (int64_t)LONG_MIN) {
  374. return LONG_MAX;
  375. }
  376. #endif
  377. return (long)mdiff;
  378. }
  379. /**
  380. * Converts timeval to milliseconds.
  381. */
  382. int64_t
  383. tv_to_msec(const struct timeval *tv)
  384. {
  385. int64_t conv = ((int64_t)tv->tv_sec)*1000L;
  386. /* Round ghetto-style */
  387. conv += ((int64_t)tv->tv_usec+500)/1000L;
  388. return conv;
  389. }
  390. /* =====
  391. * File helpers
  392. * ===== */
  393. /*
  394. * Filesystem operations.
  395. */
  396. /* =====
  397. * Process helpers
  398. * ===== */
  399. #ifndef _WIN32
  400. /* Based on code contributed by christian grothoff */
  401. /** True iff we've called start_daemon(). */
  402. static int start_daemon_called = 0;
  403. /** True iff we've called finish_daemon(). */
  404. static int finish_daemon_called = 0;
  405. /** Socketpair used to communicate between parent and child process while
  406. * daemonizing. */
  407. static int daemon_filedes[2];
  408. /** Start putting the process into daemon mode: fork and drop all resources
  409. * except standard fds. The parent process never returns, but stays around
  410. * until finish_daemon is called. (Note: it's safe to call this more
  411. * than once: calls after the first are ignored.)
  412. */
  413. void
  414. start_daemon(void)
  415. {
  416. pid_t pid;
  417. if (start_daemon_called)
  418. return;
  419. start_daemon_called = 1;
  420. if (pipe(daemon_filedes)) {
  421. /* LCOV_EXCL_START */
  422. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  423. exit(1); // exit ok: during daemonize, pipe failed.
  424. /* LCOV_EXCL_STOP */
  425. }
  426. pid = fork();
  427. if (pid < 0) {
  428. /* LCOV_EXCL_START */
  429. log_err(LD_GENERAL,"fork failed. Exiting.");
  430. exit(1); // exit ok: during daemonize, fork failed
  431. /* LCOV_EXCL_STOP */
  432. }
  433. if (pid) { /* Parent */
  434. int ok;
  435. char c;
  436. close(daemon_filedes[1]); /* we only read */
  437. ok = -1;
  438. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  439. if (c == '.')
  440. ok = 1;
  441. }
  442. fflush(stdout);
  443. if (ok == 1)
  444. exit(0); // exit ok: during daemonize, daemonizing.
  445. else
  446. exit(1); /* child reported error. exit ok: daemonize failed. */
  447. } else { /* Child */
  448. close(daemon_filedes[0]); /* we only write */
  449. (void) setsid(); /* Detach from controlling terminal */
  450. /*
  451. * Fork one more time, so the parent (the session group leader) can exit.
  452. * This means that we, as a non-session group leader, can never regain a
  453. * controlling terminal. This part is recommended by Stevens's
  454. * _Advanced Programming in the Unix Environment_.
  455. */
  456. if (fork() != 0) {
  457. exit(0); // exit ok: during daemonize, fork failed (2)
  458. }
  459. set_main_thread(); /* We are now the main thread. */
  460. return;
  461. }
  462. }
  463. /** Finish putting the process into daemon mode: drop standard fds, and tell
  464. * the parent process to exit. (Note: it's safe to call this more than once:
  465. * calls after the first are ignored. Calls start_daemon first if it hasn't
  466. * been called already.)
  467. */
  468. void
  469. finish_daemon(const char *desired_cwd)
  470. {
  471. int nullfd;
  472. char c = '.';
  473. if (finish_daemon_called)
  474. return;
  475. if (!start_daemon_called)
  476. start_daemon();
  477. finish_daemon_called = 1;
  478. if (!desired_cwd)
  479. desired_cwd = "/";
  480. /* Don't hold the wrong FS mounted */
  481. if (chdir(desired_cwd) < 0) {
  482. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  483. exit(1); // exit ok: during daemonize, chdir failed.
  484. }
  485. nullfd = tor_open_cloexec("/dev/null", O_RDWR, 0);
  486. if (nullfd < 0) {
  487. /* LCOV_EXCL_START */
  488. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  489. exit(1); // exit ok: during daemonize, couldn't open /dev/null
  490. /* LCOV_EXCL_STOP */
  491. }
  492. /* close fds linking to invoking terminal, but
  493. * close usual incoming fds, but redirect them somewhere
  494. * useful so the fds don't get reallocated elsewhere.
  495. */
  496. if (dup2(nullfd,0) < 0 ||
  497. dup2(nullfd,1) < 0 ||
  498. dup2(nullfd,2) < 0) {
  499. /* LCOV_EXCL_START */
  500. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  501. exit(1); // exit ok: during daemonize, dup2 failed.
  502. /* LCOV_EXCL_STOP */
  503. }
  504. if (nullfd > 2)
  505. close(nullfd);
  506. /* signal success */
  507. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  508. log_err(LD_GENERAL,"write failed. Exiting.");
  509. }
  510. close(daemon_filedes[1]);
  511. }
  512. #else /* !(!defined(_WIN32)) */
  513. /* defined(_WIN32) */
  514. void
  515. start_daemon(void)
  516. {
  517. }
  518. void
  519. finish_daemon(const char *cp)
  520. {
  521. (void)cp;
  522. }
  523. #endif /* !defined(_WIN32) */
  524. /** Write the current process ID, followed by NL, into <b>filename</b>.
  525. * Return 0 on success, -1 on failure.
  526. */
  527. int
  528. write_pidfile(const char *filename)
  529. {
  530. FILE *pidfile;
  531. if ((pidfile = fopen(filename, "w")) == NULL) {
  532. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  533. strerror(errno));
  534. return -1;
  535. } else {
  536. #ifdef _WIN32
  537. int pid = (int)_getpid();
  538. #else
  539. int pid = (int)getpid();
  540. #endif
  541. int rv = 0;
  542. if (fprintf(pidfile, "%d\n", pid) < 0)
  543. rv = -1;
  544. if (fclose(pidfile) < 0)
  545. rv = -1;
  546. return rv;
  547. }
  548. }
  549. #ifdef _WIN32
  550. HANDLE
  551. load_windows_system_library(const TCHAR *library_name)
  552. {
  553. TCHAR path[MAX_PATH];
  554. unsigned n;
  555. n = GetSystemDirectory(path, MAX_PATH);
  556. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  557. return 0;
  558. _tcscat(path, TEXT("\\"));
  559. _tcscat(path, library_name);
  560. return LoadLibrary(path);
  561. }
  562. #endif /* defined(_WIN32) */
  563. /** Format a single argument for being put on a Windows command line.
  564. * Returns a newly allocated string */
  565. static char *
  566. format_win_cmdline_argument(const char *arg)
  567. {
  568. char *formatted_arg;
  569. char need_quotes;
  570. const char *c;
  571. int i;
  572. int bs_counter = 0;
  573. /* Backslash we can point to when one is inserted into the string */
  574. const char backslash = '\\';
  575. /* Smartlist of *char */
  576. smartlist_t *arg_chars;
  577. arg_chars = smartlist_new();
  578. /* Quote string if it contains whitespace or is empty */
  579. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  580. /* Build up smartlist of *chars */
  581. for (c=arg; *c != '\0'; c++) {
  582. if ('"' == *c) {
  583. /* Double up backslashes preceding a quote */
  584. for (i=0; i<(bs_counter*2); i++)
  585. smartlist_add(arg_chars, (void*)&backslash);
  586. bs_counter = 0;
  587. /* Escape the quote */
  588. smartlist_add(arg_chars, (void*)&backslash);
  589. smartlist_add(arg_chars, (void*)c);
  590. } else if ('\\' == *c) {
  591. /* Count backslashes until we know whether to double up */
  592. bs_counter++;
  593. } else {
  594. /* Don't double up slashes preceding a non-quote */
  595. for (i=0; i<bs_counter; i++)
  596. smartlist_add(arg_chars, (void*)&backslash);
  597. bs_counter = 0;
  598. smartlist_add(arg_chars, (void*)c);
  599. }
  600. }
  601. /* Don't double up trailing backslashes */
  602. for (i=0; i<bs_counter; i++)
  603. smartlist_add(arg_chars, (void*)&backslash);
  604. /* Allocate space for argument, quotes (if needed), and terminator */
  605. const size_t formatted_arg_len = smartlist_len(arg_chars) +
  606. (need_quotes ? 2 : 0) + 1;
  607. formatted_arg = tor_malloc_zero(formatted_arg_len);
  608. /* Add leading quote */
  609. i=0;
  610. if (need_quotes)
  611. formatted_arg[i++] = '"';
  612. /* Add characters */
  613. SMARTLIST_FOREACH(arg_chars, char*, ch,
  614. {
  615. formatted_arg[i++] = *ch;
  616. });
  617. /* Add trailing quote */
  618. if (need_quotes)
  619. formatted_arg[i++] = '"';
  620. formatted_arg[i] = '\0';
  621. smartlist_free(arg_chars);
  622. return formatted_arg;
  623. }
  624. /** Format a command line for use on Windows, which takes the command as a
  625. * string rather than string array. Follows the rules from "Parsing C++
  626. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  627. * Python subprocess module. Returns a newly allocated string */
  628. char *
  629. tor_join_win_cmdline(const char *argv[])
  630. {
  631. smartlist_t *argv_list;
  632. char *joined_argv;
  633. int i;
  634. /* Format each argument and put the result in a smartlist */
  635. argv_list = smartlist_new();
  636. for (i=0; argv[i] != NULL; i++) {
  637. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  638. }
  639. /* Join the arguments with whitespace */
  640. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  641. /* Free the newly allocated arguments, and the smartlist */
  642. SMARTLIST_FOREACH(argv_list, char *, arg,
  643. {
  644. tor_free(arg);
  645. });
  646. smartlist_free(argv_list);
  647. return joined_argv;
  648. }
  649. #ifndef _WIN32
  650. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  651. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  652. * safe.
  653. *
  654. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE+1 bytes available.
  655. *
  656. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  657. * with spaces. CHILD_STATE indicates where
  658. * in the process of starting the child process did the failure occur (see
  659. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  660. * errno when the failure occurred.
  661. *
  662. * On success return the number of characters added to hex_errno, not counting
  663. * the terminating NUL; return -1 on error.
  664. */
  665. STATIC int
  666. format_helper_exit_status(unsigned char child_state, int saved_errno,
  667. char *hex_errno)
  668. {
  669. unsigned int unsigned_errno;
  670. int written, left;
  671. char *cur;
  672. size_t i;
  673. int res = -1;
  674. /* Fill hex_errno with spaces, and a trailing newline (memset may
  675. not be signal handler safe, so we can't use it) */
  676. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  677. hex_errno[i] = ' ';
  678. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  679. /* Convert errno to be unsigned for hex conversion */
  680. if (saved_errno < 0) {
  681. // Avoid overflow on the cast to unsigned int when result is INT_MIN
  682. // by adding 1 to the signed int negative value,
  683. // then, after it has been negated and cast to unsigned,
  684. // adding the original 1 back (the double-addition is intentional).
  685. // Otherwise, the cast to signed could cause a temporary int
  686. // to equal INT_MAX + 1, which is undefined.
  687. unsigned_errno = ((unsigned int) -(saved_errno + 1)) + 1;
  688. } else {
  689. unsigned_errno = (unsigned int) saved_errno;
  690. }
  691. /*
  692. * Count how many chars of space we have left, and keep a pointer into the
  693. * current point in the buffer.
  694. */
  695. left = HEX_ERRNO_SIZE+1;
  696. cur = hex_errno;
  697. /* Emit child_state */
  698. written = format_hex_number_sigsafe(child_state, cur, left);
  699. if (written <= 0)
  700. goto err;
  701. /* Adjust left and cur */
  702. left -= written;
  703. cur += written;
  704. if (left <= 0)
  705. goto err;
  706. /* Now the '/' */
  707. *cur = '/';
  708. /* Adjust left and cur */
  709. ++cur;
  710. --left;
  711. if (left <= 0)
  712. goto err;
  713. /* Need minus? */
  714. if (saved_errno < 0) {
  715. *cur = '-';
  716. ++cur;
  717. --left;
  718. if (left <= 0)
  719. goto err;
  720. }
  721. /* Emit unsigned_errno */
  722. written = format_hex_number_sigsafe(unsigned_errno, cur, left);
  723. if (written <= 0)
  724. goto err;
  725. /* Adjust left and cur */
  726. left -= written;
  727. cur += written;
  728. /* Check that we have enough space left for a newline and a NUL */
  729. if (left <= 1)
  730. goto err;
  731. /* Emit the newline and NUL */
  732. *cur++ = '\n';
  733. *cur++ = '\0';
  734. res = (int)(cur - hex_errno - 1);
  735. goto done;
  736. err:
  737. /*
  738. * In error exit, just write a '\0' in the first char so whatever called
  739. * this at least won't fall off the end.
  740. */
  741. *hex_errno = '\0';
  742. done:
  743. return res;
  744. }
  745. #endif /* !defined(_WIN32) */
  746. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  747. #define DEFAULT_MAX_FD 256
  748. /** Terminate the process of <b>process_handle</b>, if that process has not
  749. * already exited.
  750. *
  751. * Return 0 if we succeeded in terminating the process (or if the process
  752. * already exited), and -1 if we tried to kill the process but failed.
  753. *
  754. * Based on code originally borrowed from Python's os.kill. */
  755. int
  756. tor_terminate_process(process_handle_t *process_handle)
  757. {
  758. #ifdef _WIN32
  759. if (tor_get_exit_code(process_handle, 0, NULL) == PROCESS_EXIT_RUNNING) {
  760. HANDLE handle = process_handle->pid.hProcess;
  761. if (!TerminateProcess(handle, 0))
  762. return -1;
  763. else
  764. return 0;
  765. }
  766. #else /* !(defined(_WIN32)) */
  767. if (process_handle->waitpid_cb) {
  768. /* We haven't got a waitpid yet, so we can just kill off the process. */
  769. return kill(process_handle->pid, SIGTERM);
  770. }
  771. #endif /* defined(_WIN32) */
  772. return 0; /* We didn't need to kill the process, so report success */
  773. }
  774. /** Return the Process ID of <b>process_handle</b>. */
  775. int
  776. tor_process_get_pid(process_handle_t *process_handle)
  777. {
  778. #ifdef _WIN32
  779. return (int) process_handle->pid.dwProcessId;
  780. #else
  781. return (int) process_handle->pid;
  782. #endif
  783. }
  784. #ifdef _WIN32
  785. HANDLE
  786. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  787. {
  788. return process_handle->stdout_pipe;
  789. }
  790. #else /* !(defined(_WIN32)) */
  791. /* DOCDOC tor_process_get_stdout_pipe */
  792. int
  793. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  794. {
  795. return process_handle->stdout_pipe;
  796. }
  797. #endif /* defined(_WIN32) */
  798. /* DOCDOC process_handle_new */
  799. static process_handle_t *
  800. process_handle_new(void)
  801. {
  802. process_handle_t *out = tor_malloc_zero(sizeof(process_handle_t));
  803. #ifdef _WIN32
  804. out->stdin_pipe = INVALID_HANDLE_VALUE;
  805. out->stdout_pipe = INVALID_HANDLE_VALUE;
  806. out->stderr_pipe = INVALID_HANDLE_VALUE;
  807. #else
  808. out->stdin_pipe = -1;
  809. out->stdout_pipe = -1;
  810. out->stderr_pipe = -1;
  811. #endif /* defined(_WIN32) */
  812. return out;
  813. }
  814. #ifndef _WIN32
  815. /** Invoked when a process that we've launched via tor_spawn_background() has
  816. * been found to have terminated.
  817. */
  818. static void
  819. process_handle_waitpid_cb(int status, void *arg)
  820. {
  821. process_handle_t *process_handle = arg;
  822. process_handle->waitpid_exit_status = status;
  823. clear_waitpid_callback(process_handle->waitpid_cb);
  824. if (process_handle->status == PROCESS_STATUS_RUNNING)
  825. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  826. process_handle->waitpid_cb = 0;
  827. }
  828. #endif /* !defined(_WIN32) */
  829. /**
  830. * @name child-process states
  831. *
  832. * Each of these values represents a possible state that a child process can
  833. * be in. They're used to determine what to say when telling the parent how
  834. * far along we were before failure.
  835. *
  836. * @{
  837. */
  838. #define CHILD_STATE_INIT 0
  839. #define CHILD_STATE_PIPE 1
  840. #define CHILD_STATE_MAXFD 2
  841. #define CHILD_STATE_FORK 3
  842. #define CHILD_STATE_DUPOUT 4
  843. #define CHILD_STATE_DUPERR 5
  844. #define CHILD_STATE_DUPIN 6
  845. #define CHILD_STATE_CLOSEFD 7
  846. #define CHILD_STATE_EXEC 8
  847. #define CHILD_STATE_FAILEXEC 9
  848. /** @} */
  849. /**
  850. * Boolean. If true, then Tor may call execve or CreateProcess via
  851. * tor_spawn_background.
  852. **/
  853. static int may_spawn_background_process = 1;
  854. /**
  855. * Turn off may_spawn_background_process, so that all future calls to
  856. * tor_spawn_background are guaranteed to fail.
  857. **/
  858. void
  859. tor_disable_spawning_background_processes(void)
  860. {
  861. may_spawn_background_process = 0;
  862. }
  863. /** Start a program in the background. If <b>filename</b> contains a '/', then
  864. * it will be treated as an absolute or relative path. Otherwise, on
  865. * non-Windows systems, the system path will be searched for <b>filename</b>.
  866. * On Windows, only the current directory will be searched. Here, to search the
  867. * system path (as well as the application directory, current working
  868. * directory, and system directories), set filename to NULL.
  869. *
  870. * The strings in <b>argv</b> will be passed as the command line arguments of
  871. * the child program (following convention, argv[0] should normally be the
  872. * filename of the executable, and this must be the case if <b>filename</b> is
  873. * NULL). The last element of argv must be NULL. A handle to the child process
  874. * will be returned in process_handle (which must be non-NULL). Read
  875. * process_handle.status to find out if the process was successfully launched.
  876. * For convenience, process_handle.status is returned by this function.
  877. *
  878. * Some parts of this code are based on the POSIX subprocess module from
  879. * Python, and example code from
  880. * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
  881. */
  882. int
  883. tor_spawn_background(const char *const filename, const char **argv,
  884. process_environment_t *env,
  885. process_handle_t **process_handle_out)
  886. {
  887. if (BUG(may_spawn_background_process == 0)) {
  888. /* We should never reach this point if we're forbidden to spawn
  889. * processes. Instead we should have caught the attempt earlier. */
  890. return PROCESS_STATUS_ERROR;
  891. }
  892. #ifdef _WIN32
  893. HANDLE stdout_pipe_read = NULL;
  894. HANDLE stdout_pipe_write = NULL;
  895. HANDLE stderr_pipe_read = NULL;
  896. HANDLE stderr_pipe_write = NULL;
  897. HANDLE stdin_pipe_read = NULL;
  898. HANDLE stdin_pipe_write = NULL;
  899. process_handle_t *process_handle;
  900. int status;
  901. STARTUPINFOA siStartInfo;
  902. BOOL retval = FALSE;
  903. SECURITY_ATTRIBUTES saAttr;
  904. char *joined_argv;
  905. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  906. saAttr.bInheritHandle = TRUE;
  907. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  908. saAttr.lpSecurityDescriptor = NULL;
  909. /* Assume failure to start process */
  910. status = PROCESS_STATUS_ERROR;
  911. /* Set up pipe for stdout */
  912. if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, &saAttr, 0)) {
  913. log_warn(LD_GENERAL,
  914. "Failed to create pipe for stdout communication with child process: %s",
  915. format_win32_error(GetLastError()));
  916. return status;
  917. }
  918. if (!SetHandleInformation(stdout_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  919. log_warn(LD_GENERAL,
  920. "Failed to configure pipe for stdout communication with child "
  921. "process: %s", format_win32_error(GetLastError()));
  922. return status;
  923. }
  924. /* Set up pipe for stderr */
  925. if (!CreatePipe(&stderr_pipe_read, &stderr_pipe_write, &saAttr, 0)) {
  926. log_warn(LD_GENERAL,
  927. "Failed to create pipe for stderr communication with child process: %s",
  928. format_win32_error(GetLastError()));
  929. return status;
  930. }
  931. if (!SetHandleInformation(stderr_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  932. log_warn(LD_GENERAL,
  933. "Failed to configure pipe for stderr communication with child "
  934. "process: %s", format_win32_error(GetLastError()));
  935. return status;
  936. }
  937. /* Set up pipe for stdin */
  938. if (!CreatePipe(&stdin_pipe_read, &stdin_pipe_write, &saAttr, 0)) {
  939. log_warn(LD_GENERAL,
  940. "Failed to create pipe for stdin communication with child process: %s",
  941. format_win32_error(GetLastError()));
  942. return status;
  943. }
  944. if (!SetHandleInformation(stdin_pipe_write, HANDLE_FLAG_INHERIT, 0)) {
  945. log_warn(LD_GENERAL,
  946. "Failed to configure pipe for stdin communication with child "
  947. "process: %s", format_win32_error(GetLastError()));
  948. return status;
  949. }
  950. /* Create the child process */
  951. /* Windows expects argv to be a whitespace delimited string, so join argv up
  952. */
  953. joined_argv = tor_join_win_cmdline(argv);
  954. process_handle = process_handle_new();
  955. process_handle->status = status;
  956. ZeroMemory(&(process_handle->pid), sizeof(PROCESS_INFORMATION));
  957. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  958. siStartInfo.cb = sizeof(STARTUPINFO);
  959. siStartInfo.hStdError = stderr_pipe_write;
  960. siStartInfo.hStdOutput = stdout_pipe_write;
  961. siStartInfo.hStdInput = stdin_pipe_read;
  962. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  963. /* Create the child process */
  964. retval = CreateProcessA(filename, // module name
  965. joined_argv, // command line
  966. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  967. NULL, // process security attributes
  968. NULL, // primary thread security attributes
  969. TRUE, // handles are inherited
  970. /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
  971. * work?) */
  972. CREATE_NO_WINDOW, // creation flags
  973. (env==NULL) ? NULL : env->windows_environment_block,
  974. NULL, // use parent's current directory
  975. &siStartInfo, // STARTUPINFO pointer
  976. &(process_handle->pid)); // receives PROCESS_INFORMATION
  977. tor_free(joined_argv);
  978. if (!retval) {
  979. log_warn(LD_GENERAL,
  980. "Failed to create child process %s: %s", filename?filename:argv[0],
  981. format_win32_error(GetLastError()));
  982. tor_free(process_handle);
  983. } else {
  984. /* TODO: Close hProcess and hThread in process_handle->pid? */
  985. process_handle->stdout_pipe = stdout_pipe_read;
  986. process_handle->stderr_pipe = stderr_pipe_read;
  987. process_handle->stdin_pipe = stdin_pipe_write;
  988. status = process_handle->status = PROCESS_STATUS_RUNNING;
  989. }
  990. /* TODO: Close pipes on exit */
  991. *process_handle_out = process_handle;
  992. return status;
  993. #else /* !(defined(_WIN32)) */
  994. pid_t pid;
  995. int stdout_pipe[2];
  996. int stderr_pipe[2];
  997. int stdin_pipe[2];
  998. int fd, retval;
  999. process_handle_t *process_handle;
  1000. int status;
  1001. const char *error_message = SPAWN_ERROR_MESSAGE;
  1002. size_t error_message_length;
  1003. /* Represents where in the process of spawning the program is;
  1004. this is used for printing out the error message */
  1005. unsigned char child_state = CHILD_STATE_INIT;
  1006. char hex_errno[HEX_ERRNO_SIZE + 2]; /* + 1 should be sufficient actually */
  1007. static int max_fd = -1;
  1008. status = PROCESS_STATUS_ERROR;
  1009. /* We do the strlen here because strlen() is not signal handler safe,
  1010. and we are not allowed to use unsafe functions between fork and exec */
  1011. error_message_length = strlen(error_message);
  1012. // child_state = CHILD_STATE_PIPE;
  1013. /* Set up pipe for redirecting stdout, stderr, and stdin of child */
  1014. retval = pipe(stdout_pipe);
  1015. if (-1 == retval) {
  1016. log_warn(LD_GENERAL,
  1017. "Failed to set up pipe for stdout communication with child process: %s",
  1018. strerror(errno));
  1019. return status;
  1020. }
  1021. retval = pipe(stderr_pipe);
  1022. if (-1 == retval) {
  1023. log_warn(LD_GENERAL,
  1024. "Failed to set up pipe for stderr communication with child process: %s",
  1025. strerror(errno));
  1026. close(stdout_pipe[0]);
  1027. close(stdout_pipe[1]);
  1028. return status;
  1029. }
  1030. retval = pipe(stdin_pipe);
  1031. if (-1 == retval) {
  1032. log_warn(LD_GENERAL,
  1033. "Failed to set up pipe for stdin communication with child process: %s",
  1034. strerror(errno));
  1035. close(stdout_pipe[0]);
  1036. close(stdout_pipe[1]);
  1037. close(stderr_pipe[0]);
  1038. close(stderr_pipe[1]);
  1039. return status;
  1040. }
  1041. // child_state = CHILD_STATE_MAXFD;
  1042. #ifdef _SC_OPEN_MAX
  1043. if (-1 == max_fd) {
  1044. max_fd = (int) sysconf(_SC_OPEN_MAX);
  1045. if (max_fd == -1) {
  1046. max_fd = DEFAULT_MAX_FD;
  1047. log_warn(LD_GENERAL,
  1048. "Cannot find maximum file descriptor, assuming %d", max_fd);
  1049. }
  1050. }
  1051. #else /* !(defined(_SC_OPEN_MAX)) */
  1052. max_fd = DEFAULT_MAX_FD;
  1053. #endif /* defined(_SC_OPEN_MAX) */
  1054. // child_state = CHILD_STATE_FORK;
  1055. pid = fork();
  1056. if (0 == pid) {
  1057. /* In child */
  1058. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  1059. /* Attempt to have the kernel issue a SIGTERM if the parent
  1060. * goes away. Certain attributes of the binary being execve()ed
  1061. * will clear this during the execve() call, but it's better
  1062. * than nothing.
  1063. */
  1064. prctl(PR_SET_PDEATHSIG, SIGTERM);
  1065. #endif /* defined(HAVE_SYS_PRCTL_H) && defined(__linux__) */
  1066. child_state = CHILD_STATE_DUPOUT;
  1067. /* Link child stdout to the write end of the pipe */
  1068. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  1069. if (-1 == retval)
  1070. goto error;
  1071. child_state = CHILD_STATE_DUPERR;
  1072. /* Link child stderr to the write end of the pipe */
  1073. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  1074. if (-1 == retval)
  1075. goto error;
  1076. child_state = CHILD_STATE_DUPIN;
  1077. /* Link child stdin to the read end of the pipe */
  1078. retval = dup2(stdin_pipe[0], STDIN_FILENO);
  1079. if (-1 == retval)
  1080. goto error;
  1081. // child_state = CHILD_STATE_CLOSEFD;
  1082. close(stderr_pipe[0]);
  1083. close(stderr_pipe[1]);
  1084. close(stdout_pipe[0]);
  1085. close(stdout_pipe[1]);
  1086. close(stdin_pipe[0]);
  1087. close(stdin_pipe[1]);
  1088. /* Close all other fds, including the read end of the pipe */
  1089. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  1090. * this needless. */
  1091. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  1092. close(fd);
  1093. }
  1094. // child_state = CHILD_STATE_EXEC;
  1095. /* Call the requested program. We need the cast because
  1096. execvp doesn't define argv as const, even though it
  1097. does not modify the arguments */
  1098. if (env)
  1099. execve(filename, (char *const *) argv, env->unixoid_environment_block);
  1100. else {
  1101. static char *new_env[] = { NULL };
  1102. execve(filename, (char *const *) argv, new_env);
  1103. }
  1104. /* If we got here, the exec or open(/dev/null) failed */
  1105. child_state = CHILD_STATE_FAILEXEC;
  1106. error:
  1107. {
  1108. /* XXX: are we leaking fds from the pipe? */
  1109. int n, err=0;
  1110. ssize_t nbytes;
  1111. n = format_helper_exit_status(child_state, errno, hex_errno);
  1112. if (n >= 0) {
  1113. /* Write the error message. GCC requires that we check the return
  1114. value, but there is nothing we can do if it fails */
  1115. /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
  1116. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  1117. err = (nbytes < 0);
  1118. nbytes = write(STDOUT_FILENO, hex_errno, n);
  1119. err += (nbytes < 0);
  1120. }
  1121. _exit(err?254:255); // exit ok: in child.
  1122. }
  1123. /* Never reached, but avoids compiler warning */
  1124. return status; // LCOV_EXCL_LINE
  1125. }
  1126. /* In parent */
  1127. if (-1 == pid) {
  1128. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  1129. close(stdin_pipe[0]);
  1130. close(stdin_pipe[1]);
  1131. close(stdout_pipe[0]);
  1132. close(stdout_pipe[1]);
  1133. close(stderr_pipe[0]);
  1134. close(stderr_pipe[1]);
  1135. return status;
  1136. }
  1137. process_handle = process_handle_new();
  1138. process_handle->status = status;
  1139. process_handle->pid = pid;
  1140. /* TODO: If the child process forked but failed to exec, waitpid it */
  1141. /* Return read end of the pipes to caller, and close write end */
  1142. process_handle->stdout_pipe = stdout_pipe[0];
  1143. retval = close(stdout_pipe[1]);
  1144. if (-1 == retval) {
  1145. log_warn(LD_GENERAL,
  1146. "Failed to close write end of stdout pipe in parent process: %s",
  1147. strerror(errno));
  1148. }
  1149. process_handle->waitpid_cb = set_waitpid_callback(pid,
  1150. process_handle_waitpid_cb,
  1151. process_handle);
  1152. process_handle->stderr_pipe = stderr_pipe[0];
  1153. retval = close(stderr_pipe[1]);
  1154. if (-1 == retval) {
  1155. log_warn(LD_GENERAL,
  1156. "Failed to close write end of stderr pipe in parent process: %s",
  1157. strerror(errno));
  1158. }
  1159. /* Return write end of the stdin pipe to caller, and close the read end */
  1160. process_handle->stdin_pipe = stdin_pipe[1];
  1161. retval = close(stdin_pipe[0]);
  1162. if (-1 == retval) {
  1163. log_warn(LD_GENERAL,
  1164. "Failed to close read end of stdin pipe in parent process: %s",
  1165. strerror(errno));
  1166. }
  1167. status = process_handle->status = PROCESS_STATUS_RUNNING;
  1168. /* Set stdin/stdout/stderr pipes to be non-blocking */
  1169. if (fcntl(process_handle->stdout_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  1170. fcntl(process_handle->stderr_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  1171. fcntl(process_handle->stdin_pipe, F_SETFL, O_NONBLOCK) < 0) {
  1172. log_warn(LD_GENERAL, "Failed to set stderror/stdout/stdin pipes "
  1173. "nonblocking in parent process: %s", strerror(errno));
  1174. }
  1175. *process_handle_out = process_handle;
  1176. return status;
  1177. #endif /* defined(_WIN32) */
  1178. }
  1179. /** Destroy all resources allocated by the process handle in
  1180. * <b>process_handle</b>.
  1181. * If <b>also_terminate_process</b> is true, also terminate the
  1182. * process of the process handle. */
  1183. MOCK_IMPL(void,
  1184. tor_process_handle_destroy,(process_handle_t *process_handle,
  1185. int also_terminate_process))
  1186. {
  1187. if (!process_handle)
  1188. return;
  1189. if (also_terminate_process) {
  1190. if (tor_terminate_process(process_handle) < 0) {
  1191. const char *errstr =
  1192. #ifdef _WIN32
  1193. format_win32_error(GetLastError());
  1194. #else
  1195. strerror(errno);
  1196. #endif
  1197. log_notice(LD_GENERAL, "Failed to terminate process with "
  1198. "PID '%d' ('%s').", tor_process_get_pid(process_handle),
  1199. errstr);
  1200. } else {
  1201. log_info(LD_GENERAL, "Terminated process with PID '%d'.",
  1202. tor_process_get_pid(process_handle));
  1203. }
  1204. }
  1205. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  1206. #ifdef _WIN32
  1207. if (process_handle->stdout_pipe)
  1208. CloseHandle(process_handle->stdout_pipe);
  1209. if (process_handle->stderr_pipe)
  1210. CloseHandle(process_handle->stderr_pipe);
  1211. if (process_handle->stdin_pipe)
  1212. CloseHandle(process_handle->stdin_pipe);
  1213. #else /* !(defined(_WIN32)) */
  1214. close(process_handle->stdout_pipe);
  1215. close(process_handle->stderr_pipe);
  1216. close(process_handle->stdin_pipe);
  1217. clear_waitpid_callback(process_handle->waitpid_cb);
  1218. #endif /* defined(_WIN32) */
  1219. memset(process_handle, 0x0f, sizeof(process_handle_t));
  1220. tor_free(process_handle);
  1221. }
  1222. /** Get the exit code of a process specified by <b>process_handle</b> and store
  1223. * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
  1224. * to true, the call will block until the process has exited. Otherwise if
  1225. * the process is still running, the function will return
  1226. * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
  1227. * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
  1228. * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
  1229. * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
  1230. * probably not work in Tor, because waitpid() is called in main.c to reap any
  1231. * terminated child processes.*/
  1232. int
  1233. tor_get_exit_code(process_handle_t *process_handle,
  1234. int block, int *exit_code)
  1235. {
  1236. #ifdef _WIN32
  1237. DWORD retval;
  1238. BOOL success;
  1239. if (block) {
  1240. /* Wait for the process to exit */
  1241. retval = WaitForSingleObject(process_handle->pid.hProcess, INFINITE);
  1242. if (retval != WAIT_OBJECT_0) {
  1243. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  1244. (int)retval, format_win32_error(GetLastError()));
  1245. return PROCESS_EXIT_ERROR;
  1246. }
  1247. } else {
  1248. retval = WaitForSingleObject(process_handle->pid.hProcess, 0);
  1249. if (WAIT_TIMEOUT == retval) {
  1250. /* Process has not exited */
  1251. return PROCESS_EXIT_RUNNING;
  1252. } else if (retval != WAIT_OBJECT_0) {
  1253. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  1254. (int)retval, format_win32_error(GetLastError()));
  1255. return PROCESS_EXIT_ERROR;
  1256. }
  1257. }
  1258. if (exit_code != NULL) {
  1259. success = GetExitCodeProcess(process_handle->pid.hProcess,
  1260. (PDWORD)exit_code);
  1261. if (!success) {
  1262. log_warn(LD_GENERAL, "GetExitCodeProcess() failed: %s",
  1263. format_win32_error(GetLastError()));
  1264. return PROCESS_EXIT_ERROR;
  1265. }
  1266. }
  1267. #else /* !(defined(_WIN32)) */
  1268. int stat_loc;
  1269. int retval;
  1270. if (process_handle->waitpid_cb) {
  1271. /* We haven't processed a SIGCHLD yet. */
  1272. retval = waitpid(process_handle->pid, &stat_loc, block?0:WNOHANG);
  1273. if (retval == process_handle->pid) {
  1274. clear_waitpid_callback(process_handle->waitpid_cb);
  1275. process_handle->waitpid_cb = NULL;
  1276. process_handle->waitpid_exit_status = stat_loc;
  1277. }
  1278. } else {
  1279. /* We already got a SIGCHLD for this process, and handled it. */
  1280. retval = process_handle->pid;
  1281. stat_loc = process_handle->waitpid_exit_status;
  1282. }
  1283. if (!block && 0 == retval) {
  1284. /* Process has not exited */
  1285. return PROCESS_EXIT_RUNNING;
  1286. } else if (retval != process_handle->pid) {
  1287. log_warn(LD_GENERAL, "waitpid() failed for PID %d: %s",
  1288. (int)process_handle->pid, strerror(errno));
  1289. return PROCESS_EXIT_ERROR;
  1290. }
  1291. if (!WIFEXITED(stat_loc)) {
  1292. log_warn(LD_GENERAL, "Process %d did not exit normally",
  1293. (int)process_handle->pid);
  1294. return PROCESS_EXIT_ERROR;
  1295. }
  1296. if (exit_code != NULL)
  1297. *exit_code = WEXITSTATUS(stat_loc);
  1298. #endif /* defined(_WIN32) */
  1299. return PROCESS_EXIT_EXITED;
  1300. }
  1301. /** Helper: return the number of characters in <b>s</b> preceding the first
  1302. * occurrence of <b>ch</b>. If <b>ch</b> does not occur in <b>s</b>, return
  1303. * the length of <b>s</b>. Should be equivalent to strspn(s, "ch"). */
  1304. static inline size_t
  1305. str_num_before(const char *s, char ch)
  1306. {
  1307. const char *cp = strchr(s, ch);
  1308. if (cp)
  1309. return cp - s;
  1310. else
  1311. return strlen(s);
  1312. }
  1313. /** Return non-zero iff getenv would consider <b>s1</b> and <b>s2</b>
  1314. * to have the same name as strings in a process's environment. */
  1315. int
  1316. environment_variable_names_equal(const char *s1, const char *s2)
  1317. {
  1318. size_t s1_name_len = str_num_before(s1, '=');
  1319. size_t s2_name_len = str_num_before(s2, '=');
  1320. return (s1_name_len == s2_name_len &&
  1321. tor_memeq(s1, s2, s1_name_len));
  1322. }
  1323. /** Free <b>env</b> (assuming it was produced by
  1324. * process_environment_make). */
  1325. void
  1326. process_environment_free_(process_environment_t *env)
  1327. {
  1328. if (env == NULL) return;
  1329. /* As both an optimization hack to reduce consing on Unixoid systems
  1330. * and a nice way to ensure that some otherwise-Windows-specific
  1331. * code will always get tested before changes to it get merged, the
  1332. * strings which env->unixoid_environment_block points to are packed
  1333. * into env->windows_environment_block. */
  1334. tor_free(env->unixoid_environment_block);
  1335. tor_free(env->windows_environment_block);
  1336. tor_free(env);
  1337. }
  1338. /** Make a process_environment_t containing the environment variables
  1339. * specified in <b>env_vars</b> (as C strings of the form
  1340. * "NAME=VALUE"). */
  1341. process_environment_t *
  1342. process_environment_make(struct smartlist_t *env_vars)
  1343. {
  1344. process_environment_t *env = tor_malloc_zero(sizeof(process_environment_t));
  1345. int n_env_vars = smartlist_len(env_vars);
  1346. int i;
  1347. size_t total_env_length;
  1348. smartlist_t *env_vars_sorted;
  1349. tor_assert(n_env_vars + 1 != 0);
  1350. env->unixoid_environment_block = tor_calloc(n_env_vars + 1, sizeof(char *));
  1351. /* env->unixoid_environment_block is already NULL-terminated,
  1352. * because we assume that NULL == 0 (and check that during compilation). */
  1353. total_env_length = 1; /* terminating NUL of terminating empty string */
  1354. for (i = 0; i < n_env_vars; ++i) {
  1355. const char *s = smartlist_get(env_vars, (int)i);
  1356. size_t slen = strlen(s);
  1357. tor_assert(slen + 1 != 0);
  1358. tor_assert(slen + 1 < SIZE_MAX - total_env_length);
  1359. total_env_length += slen + 1;
  1360. }
  1361. env->windows_environment_block = tor_malloc_zero(total_env_length);
  1362. /* env->windows_environment_block is already
  1363. * (NUL-terminated-empty-string)-terminated. */
  1364. /* Some versions of Windows supposedly require that environment
  1365. * blocks be sorted. Or maybe some Windows programs (or their
  1366. * runtime libraries) fail to look up strings in non-sorted
  1367. * environment blocks.
  1368. *
  1369. * Also, sorting strings makes it easy to find duplicate environment
  1370. * variables and environment-variable strings without an '=' on all
  1371. * OSes, and they can cause badness. Let's complain about those. */
  1372. env_vars_sorted = smartlist_new();
  1373. smartlist_add_all(env_vars_sorted, env_vars);
  1374. smartlist_sort_strings(env_vars_sorted);
  1375. /* Now copy the strings into the environment blocks. */
  1376. {
  1377. char *cp = env->windows_environment_block;
  1378. const char *prev_env_var = NULL;
  1379. for (i = 0; i < n_env_vars; ++i) {
  1380. const char *s = smartlist_get(env_vars_sorted, (int)i);
  1381. size_t slen = strlen(s);
  1382. size_t s_name_len = str_num_before(s, '=');
  1383. if (s_name_len == slen) {
  1384. log_warn(LD_GENERAL,
  1385. "Preparing an environment containing a variable "
  1386. "without a value: %s",
  1387. s);
  1388. }
  1389. if (prev_env_var != NULL &&
  1390. environment_variable_names_equal(s, prev_env_var)) {
  1391. log_warn(LD_GENERAL,
  1392. "Preparing an environment containing two variables "
  1393. "with the same name: %s and %s",
  1394. prev_env_var, s);
  1395. }
  1396. prev_env_var = s;
  1397. /* Actually copy the string into the environment. */
  1398. memcpy(cp, s, slen+1);
  1399. env->unixoid_environment_block[i] = cp;
  1400. cp += slen+1;
  1401. }
  1402. tor_assert(cp == env->windows_environment_block + total_env_length - 1);
  1403. }
  1404. smartlist_free(env_vars_sorted);
  1405. return env;
  1406. }
  1407. /** Return a newly allocated smartlist containing every variable in
  1408. * this process's environment, as a NUL-terminated string of the form
  1409. * "NAME=VALUE". Note that on some/many/most/all OSes, the parent
  1410. * process can put strings not of that form in our environment;
  1411. * callers should try to not get crashed by that.
  1412. *
  1413. * The returned strings are heap-allocated, and must be freed by the
  1414. * caller. */
  1415. struct smartlist_t *
  1416. get_current_process_environment_variables(void)
  1417. {
  1418. smartlist_t *sl = smartlist_new();
  1419. char **environ_tmp; /* Not const char ** ? Really? */
  1420. for (environ_tmp = get_environment(); *environ_tmp; ++environ_tmp) {
  1421. smartlist_add_strdup(sl, *environ_tmp);
  1422. }
  1423. return sl;
  1424. }
  1425. /** For each string s in <b>env_vars</b> such that
  1426. * environment_variable_names_equal(s, <b>new_var</b>), remove it; if
  1427. * <b>free_p</b> is non-zero, call <b>free_old</b>(s). If
  1428. * <b>new_var</b> contains '=', insert it into <b>env_vars</b>. */
  1429. void
  1430. set_environment_variable_in_smartlist(struct smartlist_t *env_vars,
  1431. const char *new_var,
  1432. void (*free_old)(void*),
  1433. int free_p)
  1434. {
  1435. SMARTLIST_FOREACH_BEGIN(env_vars, const char *, s) {
  1436. if (environment_variable_names_equal(s, new_var)) {
  1437. SMARTLIST_DEL_CURRENT(env_vars, s);
  1438. if (free_p) {
  1439. free_old((void *)s);
  1440. }
  1441. }
  1442. } SMARTLIST_FOREACH_END(s);
  1443. if (strchr(new_var, '=') != NULL) {
  1444. smartlist_add(env_vars, (void *)new_var);
  1445. }
  1446. }
  1447. #ifdef _WIN32
  1448. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  1449. * <b>hProcess</b> is NULL, the function will return immediately if there is
  1450. * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
  1451. * to the process owning the <b>h</b>. In this case, the function will exit
  1452. * only once the process has exited, or <b>count</b> bytes are read. Returns
  1453. * the number of bytes read, or -1 on error. */
  1454. ssize_t
  1455. tor_read_all_handle(HANDLE h, char *buf, size_t count,
  1456. const process_handle_t *process)
  1457. {
  1458. size_t numread = 0;
  1459. BOOL retval;
  1460. DWORD byte_count;
  1461. BOOL process_exited = FALSE;
  1462. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  1463. return -1;
  1464. while (numread < count) {
  1465. /* Check if there is anything to read */
  1466. retval = PeekNamedPipe(h, NULL, 0, NULL, &byte_count, NULL);
  1467. if (!retval) {
  1468. log_warn(LD_GENERAL,
  1469. "Failed to peek from handle: %s",
  1470. format_win32_error(GetLastError()));
  1471. return -1;
  1472. } else if (0 == byte_count) {
  1473. /* Nothing available: process exited or it is busy */
  1474. /* Exit if we don't know whether the process is running */
  1475. if (NULL == process)
  1476. break;
  1477. /* The process exited and there's nothing left to read from it */
  1478. if (process_exited)
  1479. break;
  1480. /* If process is not running, check for output one more time in case
  1481. it wrote something after the peek was performed. Otherwise keep on
  1482. waiting for output */
  1483. tor_assert(process != NULL);
  1484. byte_count = WaitForSingleObject(process->pid.hProcess, 0);
  1485. if (WAIT_TIMEOUT != byte_count)
  1486. process_exited = TRUE;
  1487. continue;
  1488. }
  1489. /* There is data to read; read it */
  1490. retval = ReadFile(h, buf+numread, count-numread, &byte_count, NULL);
  1491. tor_assert(byte_count + numread <= count);
  1492. if (!retval) {
  1493. log_warn(LD_GENERAL, "Failed to read from handle: %s",
  1494. format_win32_error(GetLastError()));
  1495. return -1;
  1496. } else if (0 == byte_count) {
  1497. /* End of file */
  1498. break;
  1499. }
  1500. numread += byte_count;
  1501. }
  1502. return (ssize_t)numread;
  1503. }
  1504. #else /* !(defined(_WIN32)) */
  1505. /** Read from a handle <b>fd</b> into <b>buf</b>, up to <b>count</b> bytes. If
  1506. * <b>process</b> is NULL, the function will return immediately if there is
  1507. * nothing more to read. Otherwise data will be read until end of file, or
  1508. * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
  1509. * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
  1510. * file has been reached. */
  1511. ssize_t
  1512. tor_read_all_handle(int fd, char *buf, size_t count,
  1513. const process_handle_t *process,
  1514. int *eof)
  1515. {
  1516. size_t numread = 0;
  1517. ssize_t result;
  1518. if (eof)
  1519. *eof = 0;
  1520. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  1521. return -1;
  1522. while (numread < count) {
  1523. result = read(fd, buf+numread, count-numread);
  1524. if (result == 0) {
  1525. log_debug(LD_GENERAL, "read() reached end of file");
  1526. if (eof)
  1527. *eof = 1;
  1528. break;
  1529. } else if (result < 0 && errno == EAGAIN) {
  1530. if (process)
  1531. continue;
  1532. else
  1533. break;
  1534. } else if (result < 0) {
  1535. log_warn(LD_GENERAL, "read() failed: %s", strerror(errno));
  1536. return -1;
  1537. }
  1538. numread += result;
  1539. }
  1540. log_debug(LD_GENERAL, "read() read %d bytes from handle", (int)numread);
  1541. return (ssize_t)numread;
  1542. }
  1543. #endif /* defined(_WIN32) */
  1544. /** Read from stdout of a process until the process exits. */
  1545. ssize_t
  1546. tor_read_all_from_process_stdout(const process_handle_t *process_handle,
  1547. char *buf, size_t count)
  1548. {
  1549. #ifdef _WIN32
  1550. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  1551. process_handle);
  1552. #else
  1553. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  1554. process_handle, NULL);
  1555. #endif /* defined(_WIN32) */
  1556. }
  1557. /** Read from stdout of a process until the process exits. */
  1558. ssize_t
  1559. tor_read_all_from_process_stderr(const process_handle_t *process_handle,
  1560. char *buf, size_t count)
  1561. {
  1562. #ifdef _WIN32
  1563. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  1564. process_handle);
  1565. #else
  1566. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  1567. process_handle, NULL);
  1568. #endif /* defined(_WIN32) */
  1569. }
  1570. /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
  1571. * modified. The resulting smartlist will consist of pointers to buf, so there
  1572. * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
  1573. * string. <b>len</b> should be set to the length of the buffer excluding the
  1574. * NUL. Non-printable characters (including NUL) will be replaced with "." */
  1575. int
  1576. tor_split_lines(smartlist_t *sl, char *buf, int len)
  1577. {
  1578. /* Index in buf of the start of the current line */
  1579. int start = 0;
  1580. /* Index in buf of the current character being processed */
  1581. int cur = 0;
  1582. /* Are we currently in a line */
  1583. char in_line = 0;
  1584. /* Loop over string */
  1585. while (cur < len) {
  1586. /* Loop until end of line or end of string */
  1587. for (; cur < len; cur++) {
  1588. if (in_line) {
  1589. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  1590. /* End of line */
  1591. buf[cur] = '\0';
  1592. /* Point cur to the next line */
  1593. cur++;
  1594. /* Line starts at start and ends with a nul */
  1595. break;
  1596. } else {
  1597. if (!TOR_ISPRINT(buf[cur]))
  1598. buf[cur] = '.';
  1599. }
  1600. } else {
  1601. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  1602. /* Skip leading vertical space */
  1603. ;
  1604. } else {
  1605. in_line = 1;
  1606. start = cur;
  1607. if (!TOR_ISPRINT(buf[cur]))
  1608. buf[cur] = '.';
  1609. }
  1610. }
  1611. }
  1612. /* We are at the end of the line or end of string. If in_line is true there
  1613. * is a line which starts at buf+start and ends at a NUL. cur points to
  1614. * the character after the NUL. */
  1615. if (in_line)
  1616. smartlist_add(sl, (void *)(buf+start));
  1617. in_line = 0;
  1618. }
  1619. return smartlist_len(sl);
  1620. }
  1621. /** Return a string corresponding to <b>stream_status</b>. */
  1622. const char *
  1623. stream_status_to_string(enum stream_status stream_status)
  1624. {
  1625. switch (stream_status) {
  1626. case IO_STREAM_OKAY:
  1627. return "okay";
  1628. case IO_STREAM_EAGAIN:
  1629. return "temporarily unavailable";
  1630. case IO_STREAM_TERM:
  1631. return "terminated";
  1632. case IO_STREAM_CLOSED:
  1633. return "closed";
  1634. default:
  1635. tor_fragile_assert();
  1636. return "unknown";
  1637. }
  1638. }
  1639. #ifdef _WIN32
  1640. /** Return a smartlist containing lines outputted from
  1641. * <b>handle</b>. Return NULL on error, and set
  1642. * <b>stream_status_out</b> appropriately. */
  1643. MOCK_IMPL(smartlist_t *,
  1644. tor_get_lines_from_handle, (HANDLE *handle,
  1645. enum stream_status *stream_status_out))
  1646. {
  1647. int pos;
  1648. char stdout_buf[600] = {0};
  1649. smartlist_t *lines = NULL;
  1650. tor_assert(stream_status_out);
  1651. *stream_status_out = IO_STREAM_TERM;
  1652. pos = tor_read_all_handle(handle, stdout_buf, sizeof(stdout_buf) - 1, NULL);
  1653. if (pos < 0) {
  1654. *stream_status_out = IO_STREAM_TERM;
  1655. return NULL;
  1656. }
  1657. if (pos == 0) {
  1658. *stream_status_out = IO_STREAM_EAGAIN;
  1659. return NULL;
  1660. }
  1661. /* End with a null even if there isn't a \r\n at the end */
  1662. /* TODO: What if this is a partial line? */
  1663. stdout_buf[pos] = '\0';
  1664. /* Split up the buffer */
  1665. lines = smartlist_new();
  1666. tor_split_lines(lines, stdout_buf, pos);
  1667. /* Currently 'lines' is populated with strings residing on the
  1668. stack. Replace them with their exact copies on the heap: */
  1669. SMARTLIST_FOREACH(lines, char *, line,
  1670. SMARTLIST_REPLACE_CURRENT(lines, line, tor_strdup(line)));
  1671. *stream_status_out = IO_STREAM_OKAY;
  1672. return lines;
  1673. }
  1674. #else /* !(defined(_WIN32)) */
  1675. /** Return a smartlist containing lines outputted from
  1676. * <b>fd</b>. Return NULL on error, and set
  1677. * <b>stream_status_out</b> appropriately. */
  1678. MOCK_IMPL(smartlist_t *,
  1679. tor_get_lines_from_handle, (int fd, enum stream_status *stream_status_out))
  1680. {
  1681. enum stream_status stream_status;
  1682. char stdout_buf[400];
  1683. smartlist_t *lines = NULL;
  1684. while (1) {
  1685. memset(stdout_buf, 0, sizeof(stdout_buf));
  1686. stream_status = get_string_from_pipe(fd,
  1687. stdout_buf, sizeof(stdout_buf) - 1);
  1688. if (stream_status != IO_STREAM_OKAY)
  1689. goto done;
  1690. if (!lines) lines = smartlist_new();
  1691. smartlist_split_string(lines, stdout_buf, "\n", 0, 0);
  1692. }
  1693. done:
  1694. *stream_status_out = stream_status;
  1695. return lines;
  1696. }
  1697. #endif /* defined(_WIN32) */
  1698. /** Reads from <b>fd</b> and stores input in <b>buf_out</b> making
  1699. * sure it's below <b>count</b> bytes.
  1700. * If the string has a trailing newline, we strip it off.
  1701. *
  1702. * This function is specifically created to handle input from managed
  1703. * proxies, according to the pluggable transports spec. Make sure it
  1704. * fits your needs before using it.
  1705. *
  1706. * Returns:
  1707. * IO_STREAM_CLOSED: If the stream is closed.
  1708. * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
  1709. * later.
  1710. * IO_STREAM_TERM: If something is wrong with the stream.
  1711. * IO_STREAM_OKAY: If everything went okay and we got a string
  1712. * in <b>buf_out</b>. */
  1713. enum stream_status
  1714. get_string_from_pipe(int fd, char *buf_out, size_t count)
  1715. {
  1716. ssize_t ret;
  1717. tor_assert(count <= INT_MAX);
  1718. ret = read(fd, buf_out, count);
  1719. if (ret == 0)
  1720. return IO_STREAM_CLOSED;
  1721. else if (ret < 0 && errno == EAGAIN)
  1722. return IO_STREAM_EAGAIN;
  1723. else if (ret < 0)
  1724. return IO_STREAM_TERM;
  1725. if (buf_out[ret - 1] == '\n') {
  1726. /* Remove the trailing newline */
  1727. buf_out[ret - 1] = '\0';
  1728. } else
  1729. buf_out[ret] = '\0';
  1730. return IO_STREAM_OKAY;
  1731. }
  1732. /** Initialize the insecure RNG <b>rng</b> from a seed value <b>seed</b>. */
  1733. void
  1734. tor_init_weak_random(tor_weak_rng_t *rng, unsigned seed)
  1735. {
  1736. rng->state = (uint32_t)(seed & 0x7fffffff);
  1737. }
  1738. /** Return a randomly chosen value in the range 0..TOR_WEAK_RANDOM_MAX based
  1739. * on the RNG state of <b>rng</b>. This entropy will not be cryptographically
  1740. * strong; do not rely on it for anything an adversary should not be able to
  1741. * predict. */
  1742. int32_t
  1743. tor_weak_random(tor_weak_rng_t *rng)
  1744. {
  1745. /* Here's a linear congruential generator. OpenBSD and glibc use these
  1746. * parameters; they aren't too bad, and should have maximal period over the
  1747. * range 0..INT32_MAX. We don't want to use the platform rand() or random(),
  1748. * since some platforms have bad weak RNGs that only return values in the
  1749. * range 0..INT16_MAX, which just isn't enough. */
  1750. rng->state = (rng->state * 1103515245 + 12345) & 0x7fffffff;
  1751. return (int32_t) rng->state;
  1752. }
  1753. /** Return a random number in the range [0 , <b>top</b>). {That is, the range
  1754. * of integers i such that 0 <= i < top.} Chooses uniformly. Requires that
  1755. * top is greater than 0. This randomness is not cryptographically strong; do
  1756. * not rely on it for anything an adversary should not be able to predict. */
  1757. int32_t
  1758. tor_weak_random_range(tor_weak_rng_t *rng, int32_t top)
  1759. {
  1760. /* We don't want to just do tor_weak_random() % top, since random() is often
  1761. * implemented with an LCG whose modulus is a power of 2, and those are
  1762. * cyclic in their low-order bits. */
  1763. int divisor, result;
  1764. tor_assert(top > 0);
  1765. divisor = TOR_WEAK_RANDOM_MAX / top;
  1766. do {
  1767. result = (int32_t)(tor_weak_random(rng) / divisor);
  1768. } while (result >= top);
  1769. return result;
  1770. }
  1771. /** Cast a given double value to a int64_t. Return 0 if number is NaN.
  1772. * Returns either INT64_MIN or INT64_MAX if number is outside of the int64_t
  1773. * range. */
  1774. int64_t
  1775. clamp_double_to_int64(double number)
  1776. {
  1777. int exponent;
  1778. #if defined(MINGW_ANY) && GCC_VERSION >= 409
  1779. /*
  1780. Mingw's math.h uses gcc's __builtin_choose_expr() facility to declare
  1781. isnan, isfinite, and signbit. But as implemented in at least some
  1782. versions of gcc, __builtin_choose_expr() can generate type warnings
  1783. even from branches that are not taken. So, suppress those warnings.
  1784. */
  1785. #define PROBLEMATIC_FLOAT_CONVERSION_WARNING
  1786. DISABLE_GCC_WARNING(float-conversion)
  1787. #endif /* defined(MINGW_ANY) && GCC_VERSION >= 409 */
  1788. /*
  1789. With clang 4.0 we apparently run into "double promotion" warnings here,
  1790. since clang thinks we're promoting a double to a long double.
  1791. */
  1792. #if defined(__clang__)
  1793. #if __has_warning("-Wdouble-promotion")
  1794. #define PROBLEMATIC_DOUBLE_PROMOTION_WARNING
  1795. DISABLE_GCC_WARNING(double-promotion)
  1796. #endif
  1797. #endif /* defined(__clang__) */
  1798. /* NaN is a special case that can't be used with the logic below. */
  1799. if (isnan(number)) {
  1800. return 0;
  1801. }
  1802. /* Time to validate if result can overflows a int64_t value. Fun with
  1803. * float! Find that exponent exp such that
  1804. * number == x * 2^exp
  1805. * for some x with abs(x) in [0.5, 1.0). Note that this implies that the
  1806. * magnitude of number is strictly less than 2^exp.
  1807. *
  1808. * If number is infinite, the call to frexp is legal but the contents of
  1809. * are exponent unspecified. */
  1810. frexp(number, &exponent);
  1811. /* If the magnitude of number is strictly less than 2^63, the truncated
  1812. * version of number is guaranteed to be representable. The only
  1813. * representable integer for which this is not the case is INT64_MIN, but
  1814. * it is covered by the logic below. */
  1815. if (isfinite(number) && exponent <= 63) {
  1816. return (int64_t)number;
  1817. }
  1818. /* Handle infinities and finite numbers with magnitude >= 2^63. */
  1819. return signbit(number) ? INT64_MIN : INT64_MAX;
  1820. #ifdef PROBLEMATIC_DOUBLE_PROMOTION_WARNING
  1821. ENABLE_GCC_WARNING(double-promotion)
  1822. #endif
  1823. #ifdef PROBLEMATIC_FLOAT_CONVERSION_WARNING
  1824. ENABLE_GCC_WARNING(float-conversion)
  1825. #endif
  1826. }