util.c 36 KB

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