util.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. /* Copyright 2003 Roger Dingledine */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. const char util_c_id[] = "$Id$";
  5. /**
  6. * \file util.c
  7. *
  8. * \brief Common functions for strings, IO, network, data structures,
  9. * process control.
  10. **/
  11. /* This is required on rh7 to make strptime not complain.
  12. */
  13. #define _GNU_SOURCE
  14. #include "orconfig.h"
  15. #include "util.h"
  16. #include "log.h"
  17. #include "crypto.h"
  18. #ifdef MS_WINDOWS
  19. #include <io.h>
  20. #include <direct.h>
  21. #endif
  22. #ifdef HAVE_CTYPE_H
  23. #include <ctype.h>
  24. #endif
  25. #include <stdlib.h>
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <assert.h>
  29. #ifdef HAVE_NETINET_IN_H
  30. #include <netinet/in.h>
  31. #endif
  32. #ifdef HAVE_ARPA_INET_H
  33. #include <arpa/inet.h>
  34. #endif
  35. #ifdef HAVE_ERRNO_H
  36. #include <errno.h>
  37. #endif
  38. #ifdef HAVE_LIMITS_H
  39. #include <limits.h>
  40. #endif
  41. #ifdef HAVE_SYS_LIMITS_H
  42. #include <sys/limits.h>
  43. #endif
  44. #ifdef HAVE_MACHINE_LIMITS_H
  45. #ifndef __FreeBSD__
  46. /* FreeBSD has a bug where it complains that this file is obsolete,
  47. and I should migrate to using sys/limits. It complains even when
  48. I include both. */
  49. #include <machine/limits.h>
  50. #endif
  51. #endif
  52. #ifdef HAVE_SYS_TYPES_H
  53. #include <sys/types.h> /* Must be included before sys/stat.h for Ultrix */
  54. #endif
  55. #ifdef HAVE_SYS_SOCKET_H
  56. #include <sys/socket.h>
  57. #endif
  58. #ifdef HAVE_NETDB_H
  59. #include <netdb.h>
  60. #endif
  61. #ifdef HAVE_SYS_TIME_H
  62. #include <sys/time.h>
  63. #endif
  64. #ifdef HAVE_UNISTD_H
  65. #include <unistd.h>
  66. #endif
  67. #ifdef HAVE_SYS_STAT_H
  68. #include <sys/stat.h>
  69. #endif
  70. #ifdef HAVE_SYS_FCNTL_H
  71. #include <sys/fcntl.h>
  72. #endif
  73. #ifdef HAVE_FCNTL_H
  74. #include <fcntl.h>
  75. #endif
  76. /* used by inet_addr, not defined on solaris anywhere!? */
  77. #ifndef INADDR_NONE
  78. #define INADDR_NONE ((unsigned long) -1)
  79. #endif
  80. #ifndef O_BINARY
  81. #define O_BINARY 0
  82. #endif
  83. #ifndef O_TEXT
  84. #define O_TEXT 0
  85. #endif
  86. /* =====
  87. * Memory management
  88. * ===== */
  89. /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
  90. * result. On error, log and terminate the process. (Same as malloc(size),
  91. * but never returns NULL.)
  92. */
  93. void *tor_malloc(size_t size) {
  94. void *result;
  95. /* Some libcs don't do the right thing on size==0. Override them. */
  96. if (size==0) {
  97. size=1;
  98. }
  99. result = malloc(size);
  100. if (!result) {
  101. log_fn(LOG_ERR, "Out of memory. Dying.");
  102. exit(1);
  103. }
  104. // memset(result,'X',size); /* deadbeef to encourage bugs */
  105. return result;
  106. }
  107. /* Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
  108. * zero bytes, and return a pointer to the result. Log and terminate
  109. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  110. */
  111. void *tor_malloc_zero(size_t size) {
  112. void *result = tor_malloc(size);
  113. memset(result, 0, size);
  114. return result;
  115. }
  116. /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
  117. * bytes long; return the new memory block. On error, log and
  118. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  119. */
  120. void *tor_realloc(void *ptr, size_t size) {
  121. void *result;
  122. result = realloc(ptr, size);
  123. if (!result) {
  124. log_fn(LOG_ERR, "Out of memory. Dying.");
  125. exit(1);
  126. }
  127. return result;
  128. }
  129. /** Return a newly allocated copy of the NUL-terminated string s. On
  130. * error, log and terminate. (Like strdup(s), but never returns
  131. * NULL.)
  132. */
  133. char *tor_strdup(const char *s) {
  134. char *dup;
  135. tor_assert(s);
  136. dup = strdup(s);
  137. if (!dup) {
  138. log_fn(LOG_ERR,"Out of memory. Dying.");
  139. exit(1);
  140. }
  141. return dup;
  142. }
  143. /** Allocate and return a new string containing the first <b>n</b>
  144. * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
  145. * characters, only the first <b>n</b> are copied. The result is
  146. * always NUL-terminated. (Like strndup(s,n), but never returns
  147. * NULL.)
  148. */
  149. char *tor_strndup(const char *s, size_t n) {
  150. char *dup;
  151. tor_assert(s);
  152. dup = tor_malloc(n+1);
  153. /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
  154. * this function gets called a whole lot, and platform strncpy is
  155. * much faster than strlcpy when strlen(s) is much longer than n.
  156. */
  157. strncpy(dup, s, n);
  158. dup[n]='\0';
  159. return dup;
  160. }
  161. /* =====
  162. * String manipulation
  163. * ===== */
  164. /** Remove from the string <b>s</b> every character which appears in
  165. * <b>strip</b>. Return the number of characters removed. */
  166. int tor_strstrip(char *s, const char *strip)
  167. {
  168. char *read = s;
  169. while (*read) {
  170. if (strchr(strip, *read)) {
  171. ++read;
  172. } else {
  173. *s++ = *read++;
  174. }
  175. }
  176. *s = '\0';
  177. return read-s;
  178. }
  179. /** Set the <b>dest_len</b>-byte buffer <b>buf</b> to contain the
  180. * string <b>s</b>, with the string <b>insert</b> inserted after every
  181. * <b>n</b> characters. Return 0 on success, -1 on failure.
  182. *
  183. * If <b>rule</b> is ALWAYS_TERMINATE, then always end the string with
  184. * <b>insert</b>, even if its length is not a multiple of <b>n</b>. If
  185. * <b>rule</b> is NEVER_TERMINATE, then never end the string with
  186. * <b>insert</b>, even if its length <i>is</i> a multiple of <b>n</b>.
  187. * If <b>rule</b> is TERMINATE_IF_EVEN, then end the string with <b>insert</b>
  188. * exactly when its length <i>is</i> a multiple of <b>n</b>.
  189. */
  190. int tor_strpartition(char *dest, size_t dest_len,
  191. const char *s, const char *insert, size_t n,
  192. part_finish_rule_t rule)
  193. {
  194. char *destp;
  195. size_t len_in, len_out, len_ins;
  196. int is_even, remaining;
  197. tor_assert(s);
  198. tor_assert(insert);
  199. tor_assert(n > 0);
  200. len_in = strlen(s);
  201. len_ins = strlen(insert);
  202. len_out = len_in + (len_in/n)*len_ins;
  203. is_even = (len_in%n) == 0;
  204. switch (rule)
  205. {
  206. case ALWAYS_TERMINATE:
  207. if (!is_even) len_out += len_ins;
  208. break;
  209. case NEVER_TERMINATE:
  210. if (is_even && len_in) len_out -= len_ins;
  211. break;
  212. case TERMINATE_IF_EVEN:
  213. break;
  214. }
  215. if (dest_len < len_out+1)
  216. return -1;
  217. destp = dest;
  218. remaining = len_in;
  219. while (remaining) {
  220. strncpy(destp, s, n);
  221. remaining -= n;
  222. if (remaining < 0) {
  223. if (rule == ALWAYS_TERMINATE)
  224. strcpy(destp+n+remaining,insert);
  225. break;
  226. } else if (remaining == 0 && rule == NEVER_TERMINATE) {
  227. *(destp+n) = '\0';
  228. break;
  229. }
  230. strcpy(destp+n, insert);
  231. s += n;
  232. destp += n+len_ins;
  233. }
  234. tor_assert(len_out == strlen(dest));
  235. return 0;
  236. }
  237. /** Return a pointer to a NUL-terminated hexadecimal string encoding
  238. * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
  239. * result does not need to be deallocated, but repeated calls to
  240. * hex_str will trash old results.
  241. */
  242. const char *hex_str(const char *from, size_t fromlen)
  243. {
  244. static char buf[65];
  245. if (fromlen>(sizeof(buf)-1)/2)
  246. fromlen = (sizeof(buf)-1)/2;
  247. base16_encode(buf,sizeof(buf),from,fromlen);
  248. return buf;
  249. }
  250. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  251. * lowercase. */
  252. void tor_strlower(char *s)
  253. {
  254. while (*s) {
  255. *s = tolower(*s);
  256. ++s;
  257. }
  258. }
  259. /* Compares the first strlen(s2) characters of s1 with s2. Returns as for
  260. * strcmp.
  261. */
  262. int strcmpstart(const char *s1, const char *s2)
  263. {
  264. size_t n = strlen(s2);
  265. return strncmp(s1, s2, n);
  266. }
  267. /* Compares the first strlen(s2) characters of s1 with s2. Returns as for
  268. * strcasecmp.
  269. */
  270. int strcasecmpstart(const char *s1, const char *s2)
  271. {
  272. size_t n = strlen(s2);
  273. return strncasecmp(s1, s2, n);
  274. }
  275. /* Compares the last strlen(s2) characters of s1 with s2. Returns as for
  276. * strcmp.
  277. */
  278. int strcmpend(const char *s1, const char *s2)
  279. {
  280. size_t n1 = strlen(s1), n2 = strlen(s2);
  281. if (n2>n1)
  282. return strcmp(s1,s2);
  283. else
  284. return strncmp(s1+(n1-n2), s2, n2);
  285. }
  286. /* Compares the last strlen(s2) characters of s1 with s2. Returns as for
  287. * strcasecmp.
  288. */
  289. int strcasecmpend(const char *s1, const char *s2)
  290. {
  291. size_t n1 = strlen(s1), n2 = strlen(s2);
  292. if (n2>n1) /* then they can't be the same; figure out which is bigger */
  293. return strcasecmp(s1,s2);
  294. else
  295. return strncasecmp(s1+(n1-n2), s2, n2);
  296. }
  297. /** Return a pointer to the first char of s that is not whitespace and
  298. * not a comment, or to the terminating NUL if no such character exists.
  299. */
  300. const char *eat_whitespace(const char *s) {
  301. tor_assert(s);
  302. while (isspace((int)*s) || *s == '#') {
  303. while (isspace((int)*s))
  304. s++;
  305. if (*s == '#') { /* read to a \n or \0 */
  306. while (*s && *s != '\n')
  307. s++;
  308. if (!*s)
  309. return s;
  310. }
  311. }
  312. return s;
  313. }
  314. /** Return a pointer to the first char of s that is not a space or a tab,
  315. * or to the terminating NUL if no such character exists. */
  316. const char *eat_whitespace_no_nl(const char *s) {
  317. while (*s == ' ' || *s == '\t')
  318. ++s;
  319. return s;
  320. }
  321. /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
  322. * or to the terminating NUL if no such character exists.
  323. */
  324. const char *find_whitespace(const char *s) {
  325. tor_assert(s);
  326. while (*s && !isspace((int)*s) && *s != '#')
  327. s++;
  328. return s;
  329. }
  330. #define CHECK_STRTOX_RESULT() \
  331. /* Was at least one character converted? */ \
  332. if (endptr == s) \
  333. goto err; \
  334. /* Were there unexpected unconverted characters? */ \
  335. if (!next && *endptr) \
  336. goto err; \
  337. /* Is r within limits? */ \
  338. if (r < min || r > max) \
  339. goto err; \
  340. if (ok) *ok = 1; \
  341. if (next) *next = endptr; \
  342. return r; \
  343. err: \
  344. if (ok) *ok = 0; \
  345. if (next) *next = endptr; \
  346. return 0;
  347. /** Extract a long from the start of s, in the given numeric base. If
  348. * there is unconverted data and next is provided, set *next to the
  349. * first unconverted character. An error has occurred if no characters
  350. * are converted; or if there are unconverted characters and next is NULL; or
  351. * if the parsed value is not between min and max. When no error occurs,
  352. * return the parsed value and set *ok (if provided) to 1. When an error
  353. * occurs, return 0 and set *ok (if provided) to 0.
  354. */
  355. long
  356. tor_parse_long(const char *s, int base, long min, long max,
  357. int *ok, char **next)
  358. {
  359. char *endptr;
  360. long r;
  361. r = strtol(s, &endptr, base);
  362. CHECK_STRTOX_RESULT();
  363. }
  364. unsigned long
  365. tor_parse_ulong(const char *s, int base, unsigned long min,
  366. unsigned long max, int *ok, char **next)
  367. {
  368. char *endptr;
  369. unsigned long r;
  370. r = strtoul(s, &endptr, base);
  371. CHECK_STRTOX_RESULT();
  372. }
  373. /** Only base 10 is guaranteed to work for now. */
  374. uint64_t
  375. tor_parse_uint64(const char *s, int base, uint64_t min,
  376. uint64_t max, int *ok, char **next)
  377. {
  378. char *endptr;
  379. uint64_t r;
  380. #ifdef HAVE_STRTOULL
  381. r = (uint64_t)strtoull(s, &endptr, base);
  382. #elif defined(MS_WINDOWS)
  383. #if _MSC_VER < 1300
  384. tor_assert(base <= 10);
  385. r = (uint64_t)_atoi64(s);
  386. endptr = (char*)s;
  387. while (isspace(*endptr)) endptr++;
  388. while (isdigit(*endptr)) endptr++;
  389. #else
  390. r = (uint64_t)_strtoui64(s, &endptr, base);
  391. #endif
  392. #elif SIZEOF_LONG == 8
  393. r = (uint64_t)strtoul(s, &endptr, base);
  394. #else
  395. #error "I don't know how to parse 64-bit numbers."
  396. #endif
  397. CHECK_STRTOX_RESULT();
  398. }
  399. void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  400. {
  401. const char *end;
  402. char *cp;
  403. tor_assert(destlen >= srclen*2+1);
  404. cp = dest;
  405. end = src+srclen;
  406. while (src<end) {
  407. sprintf(cp,"%02X",*(const uint8_t*)src);
  408. ++src;
  409. cp += 2;
  410. }
  411. *cp = '\0';
  412. }
  413. static const char HEX_DIGITS[] = "0123456789ABCDEFabcdef";
  414. static INLINE int hex_decode_digit(char c)
  415. {
  416. const char *cp;
  417. int n;
  418. cp = strchr(HEX_DIGITS, c);
  419. if (!cp)
  420. return -1;
  421. n = cp-HEX_DIGITS;
  422. if (n<=15)
  423. return n; /* digit or uppercase */
  424. else
  425. return n-6; /* lowercase */
  426. }
  427. int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  428. {
  429. const char *end;
  430. int v1,v2;
  431. if ((srclen % 2) != 0)
  432. return -1;
  433. if (destlen < srclen/2)
  434. return -1;
  435. end = src+srclen;
  436. while (src<end) {
  437. v1 = hex_decode_digit(*src);
  438. v2 = hex_decode_digit(*(src+1));
  439. if (v1<0||v2<0)
  440. return -1;
  441. *(uint8_t*)dest = (v1<<4)|v2;
  442. ++dest;
  443. src+=2;
  444. }
  445. return 0;
  446. }
  447. /* =====
  448. * Time
  449. * ===== */
  450. /** Return the number of microseconds elapsed between *start and *end.
  451. */
  452. long
  453. tv_udiff(struct timeval *start, struct timeval *end)
  454. {
  455. long udiff;
  456. long secdiff = end->tv_sec - start->tv_sec;
  457. if (labs(secdiff+1) > LONG_MAX/1000000) {
  458. log_fn(LOG_WARN, "comparing times too far apart.");
  459. return LONG_MAX;
  460. }
  461. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  462. return udiff;
  463. }
  464. /** Return -1 if *a \< *b, 0 if *a==*b, and 1 if *a \> *b.
  465. */
  466. int tv_cmp(struct timeval *a, struct timeval *b) {
  467. if (a->tv_sec > b->tv_sec)
  468. return 1;
  469. if (a->tv_sec < b->tv_sec)
  470. return -1;
  471. if (a->tv_usec > b->tv_usec)
  472. return 1;
  473. if (a->tv_usec < b->tv_usec)
  474. return -1;
  475. return 0;
  476. }
  477. /** Increment *a by the number of seconds and microseconds in *b.
  478. */
  479. void tv_add(struct timeval *a, struct timeval *b) {
  480. a->tv_usec += b->tv_usec;
  481. a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
  482. a->tv_usec %= 1000000;
  483. }
  484. /** Increment *a by <b>ms</b> milliseconds.
  485. */
  486. void tv_addms(struct timeval *a, long ms) {
  487. a->tv_usec += (ms * 1000) % 1000000;
  488. a->tv_sec += ((ms * 1000) / 1000000) + (a->tv_usec / 1000000);
  489. a->tv_usec %= 1000000;
  490. }
  491. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  492. static int n_leapdays(int y1, int y2) {
  493. --y1;
  494. --y2;
  495. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  496. }
  497. /** Number of days per month in non-leap year; used by tor_timegm. */
  498. static const int days_per_month[] =
  499. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  500. /** Return a time_t given a struct tm. The result is given in GMT, and
  501. * does not account for leap seconds.
  502. */
  503. time_t
  504. tor_timegm(struct tm *tm) {
  505. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  506. * It's way more brute-force than fiddling with tzset().
  507. */
  508. time_t ret;
  509. unsigned long year, days, hours, minutes;
  510. int i;
  511. year = tm->tm_year + 1900;
  512. tor_assert(year >= 1970);
  513. tor_assert(tm->tm_mon >= 0);
  514. tor_assert(tm->tm_mon <= 11);
  515. days = 365 * (year-1970) + n_leapdays(1970,year);
  516. for (i = 0; i < tm->tm_mon; ++i)
  517. days += days_per_month[i];
  518. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  519. ++days;
  520. days += tm->tm_mday - 1;
  521. hours = days*24 + tm->tm_hour;
  522. minutes = hours*60 + tm->tm_min;
  523. ret = minutes*60 + tm->tm_sec;
  524. return ret;
  525. }
  526. /* strftime is locale-specific, so we need to replace those parts */
  527. static const char *WEEKDAY_NAMES[] =
  528. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  529. static const char *MONTH_NAMES[] =
  530. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  531. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  532. void format_rfc1123_time(char *buf, time_t t) {
  533. struct tm *tm = gmtime(&t);
  534. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", tm);
  535. tor_assert(tm->tm_wday >= 0);
  536. tor_assert(tm->tm_wday <= 6);
  537. memcpy(buf, WEEKDAY_NAMES[tm->tm_wday], 3);
  538. tor_assert(tm->tm_wday >= 0);
  539. tor_assert(tm->tm_mon <= 11);
  540. memcpy(buf+8, MONTH_NAMES[tm->tm_mon], 3);
  541. }
  542. int parse_rfc1123_time(const char *buf, time_t *t) {
  543. struct tm tm;
  544. char month[4];
  545. char weekday[4];
  546. int i, m;
  547. if (strlen(buf) != RFC1123_TIME_LEN)
  548. return -1;
  549. memset(&tm, 0, sizeof(tm));
  550. if (sscanf(buf, "%3s, %d %3s %d %d:%d:%d GMT", weekday,
  551. &tm.tm_mday, month, &tm.tm_year, &tm.tm_hour,
  552. &tm.tm_min, &tm.tm_sec) < 7) {
  553. log_fn(LOG_WARN, "Got invalid RFC1123 time \"%s\"", buf);
  554. return -1;
  555. }
  556. m = -1;
  557. for (i = 0; i < 12; ++i) {
  558. if (!strcmp(month, MONTH_NAMES[i])) {
  559. m = i;
  560. break;
  561. }
  562. }
  563. if (m<0) {
  564. log_fn(LOG_WARN, "Got invalid RFC1123 time \"%s\"", buf);
  565. return -1;
  566. }
  567. tm.tm_mon = m;
  568. tm.tm_year -= 1900;
  569. *t = tor_timegm(&tm);
  570. return 0;
  571. }
  572. void format_local_iso_time(char *buf, time_t t) {
  573. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", localtime(&t));
  574. }
  575. void format_iso_time(char *buf, time_t t) {
  576. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", gmtime(&t));
  577. }
  578. int parse_iso_time(const char *cp, time_t *t) {
  579. struct tm st_tm;
  580. #ifdef HAVE_STRPTIME
  581. if (!strptime(cp, "%Y-%m-%d %H:%M:%S", &st_tm)) {
  582. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  583. }
  584. #else
  585. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  586. if (sscanf(cp, "%u-%u-%u %u:%u:%u", &year, &month,
  587. &day, &hour, &minute, &second) < 6) {
  588. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  589. }
  590. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  591. hour > 23 || minute > 59 || second > 61) {
  592. log_fn(LOG_WARN, "Published time was nonsensical"); return -1;
  593. }
  594. st_tm.tm_year = year;
  595. st_tm.tm_mon = month-1;
  596. st_tm.tm_mday = day;
  597. st_tm.tm_hour = hour;
  598. st_tm.tm_min = minute;
  599. st_tm.tm_sec = second;
  600. #endif
  601. *t = tor_timegm(&st_tm);
  602. return 0;
  603. }
  604. /* =====
  605. * File helpers
  606. * ===== */
  607. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  608. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  609. * was returned by open(). Return the number of bytes written, or -1
  610. * on error. Only use if fd is a blocking fd. */
  611. int write_all(int fd, const char *buf, size_t count, int isSocket) {
  612. size_t written = 0;
  613. int result;
  614. while (written != count) {
  615. if (isSocket)
  616. result = send(fd, buf+written, count-written, 0);
  617. else
  618. result = write(fd, buf+written, count-written);
  619. if (result<0)
  620. return -1;
  621. written += result;
  622. }
  623. return count;
  624. }
  625. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  626. * or reach the end of the file.
  627. * isSocket must be 1 if fd
  628. * was returned by socket() or accept(), and 0 if fd was returned by
  629. * open(). Return the number of bytes read, or -1 on error. Only use
  630. * if fd is a blocking fd. */
  631. int read_all(int fd, char *buf, size_t count, int isSocket) {
  632. size_t numread = 0;
  633. int result;
  634. while (numread != count) {
  635. if (isSocket)
  636. result = recv(fd, buf+numread, count-numread, 0);
  637. else
  638. result = read(fd, buf+numread, count-numread);
  639. if (result<0)
  640. return -1;
  641. else if (result == 0)
  642. break;
  643. numread += result;
  644. }
  645. return numread;
  646. }
  647. /*
  648. * Filesystem operations.
  649. */
  650. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  651. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  652. * directory. */
  653. file_status_t file_status(const char *fname)
  654. {
  655. struct stat st;
  656. if (stat(fname, &st)) {
  657. if (errno == ENOENT) {
  658. return FN_NOENT;
  659. }
  660. return FN_ERROR;
  661. }
  662. if (st.st_mode & S_IFDIR)
  663. return FN_DIR;
  664. else if (st.st_mode & S_IFREG)
  665. return FN_FILE;
  666. else
  667. return FN_ERROR;
  668. }
  669. /** Check whether dirname exists and is private. If yes return 0. If
  670. * it does not exist, and check==CPD_CREATE is set, try to create it
  671. * and return 0 on success. If it does not exist, and
  672. * check==CPD_CHECK, and we think we can create it, return 0. Else
  673. * return -1. */
  674. int check_private_dir(const char *dirname, cpd_check_t check)
  675. {
  676. int r;
  677. struct stat st;
  678. tor_assert(dirname);
  679. if (stat(dirname, &st)) {
  680. if (errno != ENOENT) {
  681. log(LOG_WARN, "Directory %s cannot be read: %s", dirname,
  682. strerror(errno));
  683. return -1;
  684. }
  685. if (check == CPD_NONE) {
  686. log(LOG_WARN, "Directory %s does not exist.", dirname);
  687. return -1;
  688. } else if (check == CPD_CREATE) {
  689. log(LOG_INFO, "Creating directory %s", dirname);
  690. #ifdef MS_WINDOWS
  691. r = mkdir(dirname);
  692. #else
  693. r = mkdir(dirname, 0700);
  694. #endif
  695. if (r) {
  696. log(LOG_WARN, "Error creating directory %s: %s", dirname,
  697. strerror(errno));
  698. return -1;
  699. }
  700. }
  701. /* XXXX In the case where check==CPD_CHECK, we should look at the
  702. * parent directory a little harder. */
  703. return 0;
  704. }
  705. if (!(st.st_mode & S_IFDIR)) {
  706. log(LOG_WARN, "%s is not a directory", dirname);
  707. return -1;
  708. }
  709. #ifndef MS_WINDOWS
  710. if (st.st_uid != getuid()) {
  711. log(LOG_WARN, "%s is not owned by this UID (%d). You must fix this to proceed.", dirname, (int)getuid());
  712. return -1;
  713. }
  714. if (st.st_mode & 0077) {
  715. log(LOG_WARN, "Fixing permissions on directory %s", dirname);
  716. if (chmod(dirname, 0700)) {
  717. log(LOG_WARN, "Could not chmod directory %s: %s", dirname,
  718. strerror(errno));
  719. return -1;
  720. } else {
  721. return 0;
  722. }
  723. }
  724. #endif
  725. return 0;
  726. }
  727. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite the
  728. * previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  729. *
  730. * This function replaces the old file atomically, if possible.
  731. */
  732. int
  733. write_str_to_file(const char *fname, const char *str, int bin)
  734. {
  735. #ifdef MS_WINDOWS
  736. if (!bin && strchr(str, '\r')) {
  737. log_fn(LOG_WARN,
  738. "How odd. Writing a string that does contain CR already.");
  739. }
  740. #endif
  741. return write_bytes_to_file(fname, str, strlen(str), bin);
  742. }
  743. /** As write_str_to_file, but does not assume a NUL-terminated *
  744. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  745. int write_bytes_to_file(const char *fname, const char *str, size_t len,
  746. int bin)
  747. {
  748. char tempname[1024];
  749. int fd;
  750. int result;
  751. if ((strlcpy(tempname,fname,1024) >= 1024) ||
  752. (strlcat(tempname,".tmp",1024) >= 1024)) {
  753. log(LOG_WARN, "Filename %s.tmp too long (>1024 chars)", fname);
  754. return -1;
  755. }
  756. if ((fd = open(tempname, O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:O_TEXT), 0600))
  757. < 0) {
  758. log(LOG_WARN, "Couldn't open %s for writing: %s", tempname,
  759. strerror(errno));
  760. return -1;
  761. }
  762. result = write_all(fd, str, len, 0);
  763. if (result < 0 || (size_t)result != len) {
  764. log(LOG_WARN, "Error writing to %s: %s", tempname, strerror(errno));
  765. close(fd);
  766. return -1;
  767. }
  768. if (close(fd)) {
  769. log(LOG_WARN,"Error flushing to %s: %s", tempname, strerror(errno));
  770. return -1;
  771. }
  772. if (replace_file(tempname, fname)) {
  773. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  774. return -1;
  775. }
  776. return 0;
  777. }
  778. /** Read the contents of <b>filename</b> into a newly allocated string; return the
  779. * string on success or NULL on failure.
  780. */
  781. char *read_file_to_str(const char *filename, int bin) {
  782. int fd; /* router file */
  783. struct stat statbuf;
  784. char *string;
  785. int r;
  786. tor_assert(filename);
  787. if (stat(filename, &statbuf) < 0) {
  788. log_fn(LOG_INFO,"Could not stat %s.",filename);
  789. return NULL;
  790. }
  791. fd = open(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  792. if (fd<0) {
  793. log_fn(LOG_WARN,"Could not open %s.",filename);
  794. return NULL;
  795. }
  796. string = tor_malloc(statbuf.st_size+1);
  797. r = read_all(fd,string,statbuf.st_size,0);
  798. if (r<0) {
  799. log_fn(LOG_WARN,"Error reading from file '%s': %s", filename,
  800. strerror(errno));
  801. tor_free(string);
  802. close(fd);
  803. return NULL;
  804. }
  805. string[r] = '\0'; /* NUL-terminate the result. */
  806. if (bin && r != statbuf.st_size) {
  807. /* If we're in binary mode, then we'd better have an exact match for
  808. * size. Otherwise, win32 encoding may throw us off, and that's okay. */
  809. log_fn(LOG_WARN,"Could read only %d of %ld bytes of file '%s'.",
  810. r, (long)statbuf.st_size,filename);
  811. tor_free(string);
  812. close(fd);
  813. return NULL;
  814. }
  815. #ifdef MS_WINDOWS
  816. if (!bin && strchr(string, '\r')) {
  817. log_fn(LOG_DEBUG, "We didn't convert CRLF to LF as well as we hoped when reading %s. Coping.",
  818. filename);
  819. tor_strstrip(string, "\r");
  820. }
  821. #endif
  822. close(fd);
  823. return string;
  824. }
  825. /** Given a string containing part of a configuration file or similar format,
  826. * advance past comments and whitespace and try to parse a single line. If we
  827. * parse a line successfully, set *<b>key_out</b> to the key portion and
  828. * *<b>value_out</b> to the value portion of the line, and return a pointer to
  829. * the start of the next line. If we run out of data, return a pointer to the
  830. * end of the string. If we encounter an error, return NULL.
  831. *
  832. * NOTE: We modify <b>line</b> as we parse it, by inserting NULs to terminate
  833. * the key and value.
  834. */
  835. char *
  836. parse_line_from_str(char *line, char **key_out, char **value_out)
  837. {
  838. char *key, *val, *cp;
  839. tor_assert(key_out);
  840. tor_assert(value_out);
  841. *key_out = *value_out = key = val = NULL;
  842. /* Skip until the first keyword. */
  843. while (1) {
  844. while (isspace(*line))
  845. ++line;
  846. if (*line == '#') {
  847. while (*line && *line != '\n')
  848. ++line;
  849. } else {
  850. break;
  851. }
  852. }
  853. if (!*line) { /* End of string? */
  854. *key_out = *value_out = NULL;
  855. return line;
  856. }
  857. /* Skip until the next space. */
  858. key = line;
  859. while (*line && !isspace(*line) && *line != '#')
  860. ++line;
  861. /* Skip until the value */
  862. while (*line == ' ' || *line == '\t')
  863. *line++ = '\0';
  864. val = line;
  865. /* Find the end of the line. */
  866. while (*line && *line != '\n' && *line != '#')
  867. ++line;
  868. if (*line == '\n')
  869. cp = line++;
  870. else {
  871. cp = line-1;
  872. }
  873. while (cp>=val && isspace(*cp))
  874. *cp-- = '\0';
  875. if (*line == '#') {
  876. do {
  877. *line++ = '\0';
  878. } while (*line && *line != '\n');
  879. if (*line == '\n')
  880. ++line;
  881. }
  882. *key_out = key;
  883. *value_out = val;
  884. return line;
  885. }
  886. /** Expand any homedir prefix on 'filename'; return a newly allocated
  887. * string. */
  888. char *expand_filename(const char *filename)
  889. {
  890. tor_assert(filename);
  891. if (*filename == '~') {
  892. size_t len;
  893. char *home, *result;
  894. const char *rest;
  895. if (filename[1] == '/' || filename[1] == '\0') {
  896. home = getenv("HOME");
  897. if (!home) {
  898. log_fn(LOG_WARN, "Couldn't find $HOME environment variable while expanding %s", filename);
  899. return NULL;
  900. }
  901. home = tor_strdup(home);
  902. rest = strlen(filename)>=2?(filename+2):NULL;
  903. } else {
  904. #ifdef HAVE_PWD_H
  905. char *username, *slash;
  906. slash = strchr(filename, '/');
  907. if (slash)
  908. username = tor_strndup(filename+1,slash-filename-1);
  909. else
  910. username = tor_strdup(filename+1);
  911. if (!(home = get_user_homedir(username))) {
  912. log_fn(LOG_WARN,"Couldn't get homedir for %s",username);
  913. tor_free(username);
  914. return NULL;
  915. }
  916. tor_free(username);
  917. rest = slash ? (slash+1) : NULL;
  918. #else
  919. log_fn(LOG_WARN, "Couldn't expend homedir on system without pwd.h");
  920. return tor_strdup(filename);
  921. #endif
  922. }
  923. tor_assert(home);
  924. /* Remove trailing slash. */
  925. if (strlen(home)>1 && !strcmpend(home,"/")) {
  926. home[strlen(home)-1] = '\0';
  927. }
  928. /* Plus one for /, plus one for NUL.
  929. * Round up to 16 in case we can't do math. */
  930. len = strlen(home)+strlen(rest)+16;
  931. result = tor_malloc(len);
  932. tor_snprintf(result,len,"%s/%s",home,rest?rest:"");
  933. tor_free(home);
  934. return result;
  935. } else {
  936. return tor_strdup(filename);
  937. }
  938. }
  939. /* =====
  940. * Net helpers
  941. * ===== */
  942. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  943. * or reserved for local networks by RFC 1918.
  944. */
  945. int is_internal_IP(uint32_t ip) {
  946. if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
  947. ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
  948. ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
  949. ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  950. ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  951. ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  952. return 1;
  953. return 0;
  954. }
  955. /** Return true iff <b>ip</b> (in host order) is judged to be on the
  956. * same network as us. For now, check if it's an internal IP.
  957. *
  958. * XXX Also check if it's on the same class C network as our public IP.
  959. */
  960. int is_local_IP(uint32_t ip) {
  961. return is_internal_IP(ip);
  962. }
  963. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  964. * *addr to the proper IP address, in network byte order. Returns 0
  965. * on success, -1 on failure; 1 on transient failure.
  966. *
  967. * (This function exists because standard windows gethostbyname
  968. * doesn't treat raw IP addresses properly.)
  969. */
  970. int tor_lookup_hostname(const char *name, uint32_t *addr)
  971. {
  972. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  973. * something.
  974. */
  975. struct in_addr iaddr;
  976. struct hostent *ent;
  977. tor_assert(addr);
  978. if (!*name) {
  979. /* Empty address is an error. */
  980. return -1;
  981. } else if (tor_inet_aton(name, &iaddr)) {
  982. /* It's an IP. */
  983. memcpy(addr, &iaddr.s_addr, 4);
  984. return 0;
  985. } else {
  986. ent = gethostbyname(name);
  987. if (ent) {
  988. /* break to remind us if we move away from IPv4 */
  989. tor_assert(ent->h_length == 4);
  990. memcpy(addr, ent->h_addr, 4);
  991. return 0;
  992. }
  993. memset(addr, 0, 4);
  994. #ifdef MS_WINDOWS
  995. return (WSAGetLastError() == WSATRY_AGAIN) ? 1 : -1;
  996. #else
  997. return (h_errno == TRY_AGAIN) ? 1 : -1;
  998. #endif
  999. }
  1000. }
  1001. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  1002. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  1003. * host portion of the string. If <b>addr</b> is provided, try to
  1004. * resolve the host portion of the string and store it into
  1005. * *<b>addr</b> (in host byte order). If <b>port</b> is provided,
  1006. * store the port number into *<b>port</b>, or 0 if no port is given.
  1007. * Return 0 on success, -1 on failure.
  1008. */
  1009. int
  1010. parse_addr_port(const char *addrport, char **address, uint32_t *addr,
  1011. uint16_t *port)
  1012. {
  1013. const char *colon;
  1014. char *_address = NULL;
  1015. int _port;
  1016. int ok = 1;
  1017. tor_assert(addrport);
  1018. tor_assert(port);
  1019. colon = strchr(addrport, ':');
  1020. if (colon) {
  1021. _address = tor_strndup(addrport, colon-addrport);
  1022. _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  1023. if (!_port) {
  1024. log_fn(LOG_WARN, "Port '%s' out of range", colon+1);
  1025. ok = 0;
  1026. }
  1027. } else {
  1028. _address = tor_strdup(addrport);
  1029. _port = 0;
  1030. }
  1031. if (addr) {
  1032. /* There's an addr pointer, so we need to resolve the hostname. */
  1033. if (tor_lookup_hostname(_address,addr)) {
  1034. log_fn(LOG_WARN, "Couldn't look up '%s'", _address);
  1035. ok = 0;
  1036. *addr = 0;
  1037. }
  1038. *addr = ntohl(*addr);
  1039. }
  1040. if (address && ok) {
  1041. *address = _address;
  1042. } else {
  1043. if (address)
  1044. *address = NULL;
  1045. tor_free(_address);
  1046. }
  1047. if (port)
  1048. *port = ok ? ((uint16_t) _port) : 0;
  1049. return ok ? 0 : -1;
  1050. }
  1051. /** Parse a string <b>s</b> in the format of
  1052. * (IP(/mask|/mask-bits)?|*):(*|port(-maxport)?), setting the various
  1053. * *out pointers as appropriate. Return 0 on success, -1 on failure.
  1054. */
  1055. int
  1056. parse_addr_and_port_range(const char *s, uint32_t *addr_out,
  1057. uint32_t *mask_out, uint16_t *port_min_out,
  1058. uint16_t *port_max_out)
  1059. {
  1060. char *address;
  1061. char *mask, *port, *endptr;
  1062. struct in_addr in;
  1063. int bits;
  1064. tor_assert(s);
  1065. tor_assert(addr_out);
  1066. tor_assert(mask_out);
  1067. tor_assert(port_min_out);
  1068. tor_assert(port_max_out);
  1069. address = tor_strdup(s);
  1070. /* Break 'address' into separate strings.
  1071. */
  1072. mask = strchr(address,'/');
  1073. port = strchr(mask?mask:address,':');
  1074. if (mask)
  1075. *mask++ = '\0';
  1076. if (port)
  1077. *port++ = '\0';
  1078. /* Now "address" is the IP|'*' part...
  1079. * "mask" is the Mask|Maskbits part...
  1080. * and "port" is the *|port|min-max part.
  1081. */
  1082. if (strcmp(address,"*")==0) {
  1083. *addr_out = 0;
  1084. } else if (tor_inet_aton(address, &in) != 0) {
  1085. *addr_out = ntohl(in.s_addr);
  1086. } else {
  1087. log_fn(LOG_WARN, "Malformed IP %s in address pattern; rejecting.",address);
  1088. goto err;
  1089. }
  1090. if (!mask) {
  1091. if (strcmp(address,"*")==0)
  1092. *mask_out = 0;
  1093. else
  1094. *mask_out = 0xFFFFFFFFu;
  1095. } else {
  1096. endptr = NULL;
  1097. bits = (int) strtol(mask, &endptr, 10);
  1098. if (!*endptr) {
  1099. /* strtol handled the whole mask. */
  1100. if (bits < 0 || bits > 32) {
  1101. log_fn(LOG_WARN, "Bad number of mask bits on address range; rejecting.");
  1102. goto err;
  1103. }
  1104. *mask_out = ~((1<<(32-bits))-1);
  1105. } else if (tor_inet_aton(mask, &in) != 0) {
  1106. *mask_out = ntohl(in.s_addr);
  1107. } else {
  1108. log_fn(LOG_WARN, "Malformed mask %s on address range; rejecting.",
  1109. mask);
  1110. goto err;
  1111. }
  1112. }
  1113. if (!port || strcmp(port, "*") == 0) {
  1114. *port_min_out = 1;
  1115. *port_max_out = 65535;
  1116. } else {
  1117. endptr = NULL;
  1118. *port_min_out = (uint16_t) tor_parse_long(port, 10, 1, 65535,
  1119. NULL, &endptr);
  1120. if (*endptr == '-') {
  1121. port = endptr+1;
  1122. endptr = NULL;
  1123. *port_max_out = (uint16_t) tor_parse_long(port, 10, 1, 65535, NULL,
  1124. &endptr);
  1125. if (*endptr || !*port_max_out) {
  1126. log_fn(LOG_WARN, "Malformed port %s on address range rejecting.",
  1127. port);
  1128. }
  1129. } else if (*endptr || !*port_min_out) {
  1130. log_fn(LOG_WARN, "Malformed port %s on address range; rejecting.",
  1131. port);
  1132. goto err;
  1133. } else {
  1134. *port_max_out = *port_min_out;
  1135. }
  1136. if (*port_min_out > *port_max_out) {
  1137. log_fn(LOG_WARN,"Insane port range on address policy; rejecting.");
  1138. goto err;
  1139. }
  1140. }
  1141. tor_free(address);
  1142. return 0;
  1143. err:
  1144. tor_free(address);
  1145. return -1;
  1146. }
  1147. /* =====
  1148. * Process helpers
  1149. * ===== */
  1150. #ifndef MS_WINDOWS
  1151. /* Based on code contributed by christian grothoff */
  1152. static int start_daemon_called = 0;
  1153. static int finish_daemon_called = 0;
  1154. static int daemon_filedes[2];
  1155. /** Start putting the process into daemon mode: fork and drop all resources
  1156. * except standard fds. The parent process never returns, but stays around
  1157. * until finish_daemon is called. (Note: it's safe to call this more
  1158. * than once: calls after the first are ignored.)
  1159. */
  1160. void start_daemon(const char *desired_cwd)
  1161. {
  1162. pid_t pid;
  1163. if (start_daemon_called)
  1164. return;
  1165. start_daemon_called = 1;
  1166. if (!desired_cwd)
  1167. desired_cwd = "/";
  1168. /* Don't hold the wrong FS mounted */
  1169. if (chdir(desired_cwd) < 0) {
  1170. log_fn(LOG_ERR,"chdir to %s failed. Exiting.",desired_cwd);
  1171. exit(1);
  1172. }
  1173. pipe(daemon_filedes);
  1174. pid = fork();
  1175. if (pid < 0) {
  1176. log_fn(LOG_ERR,"fork failed. Exiting.");
  1177. exit(1);
  1178. }
  1179. if (pid) { /* Parent */
  1180. int ok;
  1181. char c;
  1182. close(daemon_filedes[1]); /* we only read */
  1183. ok = -1;
  1184. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  1185. if (c == '.')
  1186. ok = 1;
  1187. }
  1188. fflush(stdout);
  1189. if (ok == 1)
  1190. exit(0);
  1191. else
  1192. exit(1); /* child reported error */
  1193. } else { /* Child */
  1194. close(daemon_filedes[0]); /* we only write */
  1195. pid = setsid(); /* Detach from controlling terminal */
  1196. /*
  1197. * Fork one more time, so the parent (the session group leader) can exit.
  1198. * This means that we, as a non-session group leader, can never regain a
  1199. * controlling terminal. This part is recommended by Stevens's
  1200. * _Advanced Programming in the Unix Environment_.
  1201. */
  1202. if (fork() != 0) {
  1203. exit(0);
  1204. }
  1205. return;
  1206. }
  1207. }
  1208. /** Finish putting the process into daemon mode: drop standard fds, and tell
  1209. * the parent process to exit. (Note: it's safe to call this more than once:
  1210. * calls after the first are ignored. Calls start_daemon first if it hasn't
  1211. * been called already.)
  1212. */
  1213. void finish_daemon(void)
  1214. {
  1215. int nullfd;
  1216. char c = '.';
  1217. if (finish_daemon_called)
  1218. return;
  1219. if (!start_daemon_called)
  1220. start_daemon(NULL);
  1221. finish_daemon_called = 1;
  1222. nullfd = open("/dev/null",
  1223. O_CREAT | O_RDWR | O_APPEND);
  1224. if (nullfd < 0) {
  1225. log_fn(LOG_ERR,"/dev/null can't be opened. Exiting.");
  1226. exit(1);
  1227. }
  1228. /* close fds linking to invoking terminal, but
  1229. * close usual incoming fds, but redirect them somewhere
  1230. * useful so the fds don't get reallocated elsewhere.
  1231. */
  1232. if (dup2(nullfd,0) < 0 ||
  1233. dup2(nullfd,1) < 0 ||
  1234. dup2(nullfd,2) < 0) {
  1235. log_fn(LOG_ERR,"dup2 failed. Exiting.");
  1236. exit(1);
  1237. }
  1238. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  1239. close(daemon_filedes[1]);
  1240. }
  1241. #else
  1242. /* defined(MS_WINDOWS) */
  1243. void start_daemon(const char *cp) {}
  1244. void finish_daemon(void) {}
  1245. #endif
  1246. /** Write the current process ID, followed by NL, into <b>filename</b>.
  1247. */
  1248. void write_pidfile(char *filename) {
  1249. #ifndef MS_WINDOWS
  1250. FILE *pidfile;
  1251. if ((pidfile = fopen(filename, "w")) == NULL) {
  1252. log_fn(LOG_WARN, "Unable to open %s for writing: %s", filename,
  1253. strerror(errno));
  1254. } else {
  1255. fprintf(pidfile, "%d\n", (int)getpid());
  1256. fclose(pidfile);
  1257. }
  1258. #endif
  1259. }