util.c 66 KB

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