util.c 35 KB

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