util.c 35 KB

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