util.c 34 KB

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