util.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  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);
  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. */
  432. long
  433. tv_udiff(struct timeval *start, struct timeval *end)
  434. {
  435. long udiff;
  436. long secdiff = end->tv_sec - start->tv_sec;
  437. if (labs(secdiff+1) > LONG_MAX/1000000) {
  438. log_fn(LOG_WARN, "comparing times too far apart.");
  439. return LONG_MAX;
  440. }
  441. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  442. return udiff;
  443. }
  444. /** Return -1 if *a \< *b, 0 if *a==*b, and 1 if *a \> *b.
  445. */
  446. int tv_cmp(struct timeval *a, struct timeval *b) {
  447. if (a->tv_sec > b->tv_sec)
  448. return 1;
  449. if (a->tv_sec < b->tv_sec)
  450. return -1;
  451. if (a->tv_usec > b->tv_usec)
  452. return 1;
  453. if (a->tv_usec < b->tv_usec)
  454. return -1;
  455. return 0;
  456. }
  457. /** Increment *a by the number of seconds and microseconds in *b.
  458. */
  459. void tv_add(struct timeval *a, struct timeval *b) {
  460. a->tv_usec += b->tv_usec;
  461. a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
  462. a->tv_usec %= 1000000;
  463. }
  464. /** Increment *a by <b>ms</b> milliseconds.
  465. */
  466. void tv_addms(struct timeval *a, long ms) {
  467. a->tv_usec += (ms * 1000) % 1000000;
  468. a->tv_sec += ((ms * 1000) / 1000000) + (a->tv_usec / 1000000);
  469. a->tv_usec %= 1000000;
  470. }
  471. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  472. static int n_leapdays(int y1, int y2) {
  473. --y1;
  474. --y2;
  475. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  476. }
  477. /** Number of days per month in non-leap year; used by tor_timegm. */
  478. static const int days_per_month[] =
  479. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  480. /** Return a time_t given a struct tm. The result is given in GMT, and
  481. * does not account for leap seconds.
  482. */
  483. time_t
  484. 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_local_iso_time(char *buf, time_t t) {
  553. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", localtime(&t));
  554. }
  555. void format_iso_time(char *buf, time_t t) {
  556. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", gmtime(&t));
  557. }
  558. int parse_iso_time(const char *cp, time_t *t) {
  559. struct tm st_tm;
  560. #ifdef HAVE_STRPTIME
  561. if (!strptime(cp, "%Y-%m-%d %H:%M:%S", &st_tm)) {
  562. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  563. }
  564. #else
  565. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  566. if (sscanf(cp, "%u-%u-%u %u:%u:%u", &year, &month,
  567. &day, &hour, &minute, &second) < 6) {
  568. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  569. }
  570. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  571. hour > 23 || minute > 59 || second > 61) {
  572. log_fn(LOG_WARN, "Published time was nonsensical"); return -1;
  573. }
  574. st_tm.tm_year = year;
  575. st_tm.tm_mon = month-1;
  576. st_tm.tm_mday = day;
  577. st_tm.tm_hour = hour;
  578. st_tm.tm_min = minute;
  579. st_tm.tm_sec = second;
  580. #endif
  581. *t = tor_timegm(&st_tm);
  582. return 0;
  583. }
  584. /* =====
  585. * File helpers
  586. * ===== */
  587. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  588. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  589. * was returned by open(). Return the number of bytes written, or -1
  590. * on error. Only use if fd is a blocking fd. */
  591. int write_all(int fd, const char *buf, size_t count, int isSocket) {
  592. size_t written = 0;
  593. int result;
  594. while(written != count) {
  595. if (isSocket)
  596. result = send(fd, buf+written, count-written, 0);
  597. else
  598. result = write(fd, buf+written, count-written);
  599. if(result<0)
  600. return -1;
  601. written += result;
  602. }
  603. return count;
  604. }
  605. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  606. * or reach the end of the file.
  607. * isSocket must be 1 if fd
  608. * was returned by socket() or accept(), and 0 if fd was returned by
  609. * open(). Return the number of bytes read, or -1 on error. Only use
  610. * if fd is a blocking fd. */
  611. int read_all(int fd, char *buf, size_t count, int isSocket) {
  612. size_t numread = 0;
  613. int result;
  614. while(numread != count) {
  615. if (isSocket)
  616. result = recv(fd, buf+numread, count-numread, 0);
  617. else
  618. result = read(fd, buf+numread, count-numread);
  619. if(result<0)
  620. return -1;
  621. else if (result == 0)
  622. break;
  623. numread += result;
  624. }
  625. return numread;
  626. }
  627. /*
  628. * Filesystem operations.
  629. */
  630. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  631. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  632. * directory. */
  633. file_status_t file_status(const char *fname)
  634. {
  635. struct stat st;
  636. if (stat(fname, &st)) {
  637. if (errno == ENOENT) {
  638. return FN_NOENT;
  639. }
  640. return FN_ERROR;
  641. }
  642. if (st.st_mode & S_IFDIR)
  643. return FN_DIR;
  644. else if (st.st_mode & S_IFREG)
  645. return FN_FILE;
  646. else
  647. return FN_ERROR;
  648. }
  649. /** Check whether dirname exists and is private. If yes return 0. If
  650. * it does not exist, and check==CPD_CREATE is set, try to create it
  651. * and return 0 on success. If it does not exist, and
  652. * check==CPD_CHECK, and we think we can create it, return 0. Else
  653. * return -1. */
  654. int check_private_dir(const char *dirname, cpd_check_t check)
  655. {
  656. int r;
  657. struct stat st;
  658. tor_assert(dirname);
  659. if (stat(dirname, &st)) {
  660. if (errno != ENOENT) {
  661. log(LOG_WARN, "Directory %s cannot be read: %s", dirname,
  662. strerror(errno));
  663. return -1;
  664. }
  665. if (check == CPD_NONE) {
  666. log(LOG_WARN, "Directory %s does not exist.", dirname);
  667. return -1;
  668. } else if (check == CPD_CREATE) {
  669. log(LOG_INFO, "Creating directory %s", dirname);
  670. #ifdef MS_WINDOWS
  671. r = mkdir(dirname);
  672. #else
  673. r = mkdir(dirname, 0700);
  674. #endif
  675. if (r) {
  676. log(LOG_WARN, "Error creating directory %s: %s", dirname,
  677. strerror(errno));
  678. return -1;
  679. }
  680. }
  681. /* XXXX In the case where check==CPD_CHECK, we should look at the
  682. * parent directory a little harder. */
  683. return 0;
  684. }
  685. if (!(st.st_mode & S_IFDIR)) {
  686. log(LOG_WARN, "%s is not a directory", dirname);
  687. return -1;
  688. }
  689. #ifndef MS_WINDOWS
  690. if (st.st_uid != getuid()) {
  691. log(LOG_WARN, "%s is not owned by this UID (%d). You must fix this to proceed.", dirname, (int)getuid());
  692. return -1;
  693. }
  694. if (st.st_mode & 0077) {
  695. log(LOG_WARN, "Fixing permissions on directory %s", dirname);
  696. if (chmod(dirname, 0700)) {
  697. log(LOG_WARN, "Could not chmod directory %s: %s", dirname,
  698. strerror(errno));
  699. return -1;
  700. } else {
  701. return 0;
  702. }
  703. }
  704. #endif
  705. return 0;
  706. }
  707. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite the
  708. * previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  709. *
  710. * This function replaces the old file atomically, if possible.
  711. */
  712. int
  713. write_str_to_file(const char *fname, const char *str, int bin)
  714. {
  715. #ifdef MS_WINDOWS
  716. if (!bin && strchr(str, '\r')) {
  717. log_fn(LOG_WARN,
  718. "How odd. Writing a string that does contain CR already.");
  719. }
  720. #endif
  721. return write_bytes_to_file(fname, str, strlen(str), bin);
  722. }
  723. /** As write_str_to_file, but does not assume a NUL-terminated *
  724. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  725. int write_bytes_to_file(const char *fname, const char *str, size_t len,
  726. int bin)
  727. {
  728. char tempname[1024];
  729. int fd;
  730. int result;
  731. if ((strlcpy(tempname,fname,1024) >= 1024) ||
  732. (strlcat(tempname,".tmp",1024) >= 1024)) {
  733. log(LOG_WARN, "Filename %s.tmp too long (>1024 chars)", fname);
  734. return -1;
  735. }
  736. if ((fd = open(tempname, O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:O_TEXT), 0600))
  737. < 0) {
  738. log(LOG_WARN, "Couldn't open %s for writing: %s", tempname,
  739. strerror(errno));
  740. return -1;
  741. }
  742. result = write_all(fd, str, len, 0);
  743. if(result < 0 || (size_t)result != len) {
  744. log(LOG_WARN, "Error writing to %s: %s", tempname, strerror(errno));
  745. close(fd);
  746. return -1;
  747. }
  748. if (close(fd)) {
  749. log(LOG_WARN,"Error flushing to %s: %s", tempname, strerror(errno));
  750. return -1;
  751. }
  752. if (replace_file(tempname, fname)) {
  753. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  754. return -1;
  755. }
  756. return 0;
  757. }
  758. /** Read the contents of <b>filename</b> into a newly allocated string; return the
  759. * string on success or NULL on failure.
  760. */
  761. char *read_file_to_str(const char *filename, int bin) {
  762. int fd; /* router file */
  763. struct stat statbuf;
  764. char *string;
  765. int r;
  766. tor_assert(filename);
  767. if(stat(filename, &statbuf) < 0) {
  768. log_fn(LOG_INFO,"Could not stat %s.",filename);
  769. return NULL;
  770. }
  771. fd = open(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  772. if (fd<0) {
  773. log_fn(LOG_WARN,"Could not open %s.",filename);
  774. return NULL;
  775. }
  776. string = tor_malloc(statbuf.st_size+1);
  777. r = read_all(fd,string,statbuf.st_size,0);
  778. if (r<0) {
  779. log_fn(LOG_WARN,"Error reading from file '%s': %s", filename,
  780. strerror(errno));
  781. tor_free(string);
  782. close(fd);
  783. return NULL;
  784. }
  785. string[r] = '\0'; /* NUL-terminate the result. */
  786. if (bin && r != statbuf.st_size) {
  787. /* If we're in binary mode, then we'd better have an exact match for
  788. * size. Otherwise, win32 encoding may throw us off, and that's okay. */
  789. log_fn(LOG_WARN,"Could read only %d of %ld bytes of file '%s'.",
  790. r, (long)statbuf.st_size,filename);
  791. tor_free(string);
  792. close(fd);
  793. return NULL;
  794. }
  795. #ifdef MS_WINDOWS
  796. if (!bin && strchr(string, '\r')) {
  797. log_fn(LOG_DEBUG, "We didn't convert CRLF to LF as well as we hoped when reading %s. Coping.",
  798. filename);
  799. tor_strstrip(string, "\r");
  800. }
  801. #endif
  802. close(fd);
  803. return string;
  804. }
  805. /** Given a string containing part of a configuration file or similar format,
  806. * advance past comments and whitespace and try to parse a single line. If we
  807. * parse a line successfully, set *<b>key_out</b> to the key portion and
  808. * *<b>value_out</b> to the value portion of the line, and return a pointer to
  809. * the start of the next line. If we run out of data, return a pointer to the
  810. * end of the string. If we encounter an error, return NULL.
  811. *
  812. * NOTE: We modify <b>line</b> as we parse it, by inserting NULs to terminate
  813. * the key and value.
  814. */
  815. char *
  816. parse_line_from_str(char *line, char **key_out, char **value_out)
  817. {
  818. char *key, *val, *cp;
  819. tor_assert(key_out);
  820. tor_assert(value_out);
  821. *key_out = *value_out = key = val = NULL;
  822. /* Skip until the first keyword. */
  823. while (1) {
  824. while (isspace(*line))
  825. ++line;
  826. if (*line == '#') {
  827. while (*line && *line != '\n')
  828. ++line;
  829. } else {
  830. break;
  831. }
  832. }
  833. if (!*line) { /* End of string? */
  834. *key_out = *value_out = NULL;
  835. return line;
  836. }
  837. /* Skip until the next space. */
  838. key = line;
  839. while (*line && !isspace(*line) && *line != '#')
  840. ++line;
  841. /* Skip until the value */
  842. while (*line == ' ' || *line == '\t')
  843. *line++ = '\0';
  844. val = line;
  845. /* Find the end of the line. */
  846. while (*line && *line != '\n' && *line != '#')
  847. ++line;
  848. if (*line == '\n')
  849. cp = line++;
  850. else {
  851. cp = line-1;
  852. }
  853. while (cp>=val && isspace(*cp))
  854. *cp-- = '\0';
  855. if (*line == '#') {
  856. do {
  857. *line++ = '\0';
  858. } while (*line && *line != '\n');
  859. if (*line == '\n')
  860. ++line;
  861. }
  862. *key_out = key;
  863. *value_out = val;
  864. return line;
  865. }
  866. /** Expand any homedir prefix on 'filename'; return a newly allocated
  867. * string. */
  868. char *expand_filename(const char *filename)
  869. {
  870. tor_assert(filename);
  871. if (*filename == '~') {
  872. size_t len;
  873. char *home, *result;
  874. const char *rest;
  875. if (filename[1] == '/' || filename[1] == '\0') {
  876. home = getenv("HOME");
  877. if (!home) {
  878. log_fn(LOG_WARN, "Couldn't find $HOME environment variable while expanding %s", filename);
  879. return NULL;
  880. }
  881. home = tor_strdup(home);
  882. rest = strlen(filename)>=2?(filename+2):NULL;
  883. } else {
  884. #ifdef HAVE_PWD_H
  885. char *username, *slash;
  886. slash = strchr(filename, '/');
  887. if (slash)
  888. username = tor_strndup(filename+1,slash-filename-1);
  889. else
  890. username = tor_strdup(filename+1);
  891. if (!(home = get_user_homedir(username))) {
  892. log_fn(LOG_WARN,"Couldn't get homedir for %s",username);
  893. tor_free(username);
  894. return NULL;
  895. }
  896. tor_free(username);
  897. rest = slash ? (slash+1) : NULL;
  898. #else
  899. log_fn(LOG_WARN, "Couldn't expend homedir on system without pwd.h");
  900. return tor_strdup(filename);
  901. #endif
  902. }
  903. tor_assert(home);
  904. /* Remove trailing slash. */
  905. if (strlen(home)>1 && !strcmpend(home,"/")) {
  906. home[strlen(home)-1] = '\0';
  907. }
  908. /* Plus one for /, plus one for NUL.
  909. * Round up to 16 in case we can't do math. */
  910. len = strlen(home)+strlen(rest)+16;
  911. result = tor_malloc(len);
  912. tor_snprintf(result,len,"%s/%s",home,rest?rest:"");
  913. tor_free(home);
  914. return result;
  915. } else {
  916. return tor_strdup(filename);
  917. }
  918. }
  919. /* =====
  920. * Net helpers
  921. * ===== */
  922. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  923. * or reserved for local networks by RFC 1918.
  924. */
  925. int is_internal_IP(uint32_t ip) {
  926. if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
  927. ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
  928. ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
  929. ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  930. ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  931. ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  932. return 1;
  933. return 0;
  934. }
  935. /** Return true iff <b>ip</b> (in host order) is judged to be on the
  936. * same network as us. For now, check if it's an internal IP.
  937. *
  938. * XXX Also check if it's on the same class C network as our public IP.
  939. */
  940. int is_local_IP(uint32_t ip) {
  941. return is_internal_IP(ip);
  942. }
  943. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  944. * *addr to the proper IP address, in network byte order. Returns 0
  945. * on success, -1 on failure; 1 on transient failure.
  946. *
  947. * (This function exists because standard windows gethostbyname
  948. * doesn't treat raw IP addresses properly.)
  949. */
  950. int tor_lookup_hostname(const char *name, uint32_t *addr)
  951. {
  952. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  953. * something.
  954. */
  955. struct in_addr iaddr;
  956. struct hostent *ent;
  957. tor_assert(addr);
  958. if (!*name) {
  959. /* Empty address is an error. */
  960. return -1;
  961. } else if (tor_inet_aton(name, &iaddr)) {
  962. /* It's an IP. */
  963. memcpy(addr, &iaddr.s_addr, 4);
  964. return 0;
  965. } else {
  966. ent = gethostbyname(name);
  967. if (ent) {
  968. /* break to remind us if we move away from IPv4 */
  969. tor_assert(ent->h_length == 4);
  970. memcpy(addr, ent->h_addr, 4);
  971. return 0;
  972. }
  973. memset(addr, 0, 4);
  974. #ifdef MS_WINDOWS
  975. return (WSAGetLastError() == WSATRY_AGAIN) ? 1 : -1;
  976. #else
  977. return (h_errno == TRY_AGAIN) ? 1 : -1;
  978. #endif
  979. }
  980. }
  981. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  982. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  983. * host portion of the string. If <b>addr</b> is provided, try to
  984. * resolve the host portion of the string and store it into
  985. * *<b>addr</b> (in host byte order). If <b>port</b> is provided,
  986. * store the port number into *<b>port</b>, or 0 if no port is given.
  987. * Return 0 on success, -1 on failure.
  988. */
  989. int
  990. parse_addr_port(const char *addrport, char **address, uint32_t *addr,
  991. uint16_t *port)
  992. {
  993. const char *colon;
  994. char *_address = NULL;
  995. int _port;
  996. int ok = 1;
  997. tor_assert(addrport);
  998. tor_assert(port);
  999. colon = strchr(addrport, ':');
  1000. if (colon) {
  1001. _address = tor_strndup(addrport, colon-addrport);
  1002. _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  1003. if (!_port) {
  1004. log_fn(LOG_WARN, "Port '%s' out of range", colon+1);
  1005. ok = 0;
  1006. }
  1007. } else {
  1008. _address = tor_strdup(addrport);
  1009. _port = 0;
  1010. }
  1011. if (addr) {
  1012. /* There's an addr pointer, so we need to resolve the hostname. */
  1013. if (tor_lookup_hostname(_address,addr)) {
  1014. log_fn(LOG_WARN, "Couldn't look up '%s'", _address);
  1015. ok = 0;
  1016. *addr = 0;
  1017. }
  1018. *addr = ntohl(*addr);
  1019. }
  1020. if (address && ok) {
  1021. *address = _address;
  1022. } else {
  1023. if (address)
  1024. *address = NULL;
  1025. tor_free(_address);
  1026. }
  1027. if (port)
  1028. *port = ok ? ((uint16_t) _port) : 0;
  1029. return ok ? 0 : -1;
  1030. }
  1031. /** Parse a string <b>s</b> in the format of
  1032. * (IP(/mask|/mask-bits)?|*):(*|port(-maxport)?), setting the various
  1033. * *out pointers as appropriate. Return 0 on success, -1 on failure.
  1034. */
  1035. int
  1036. parse_addr_and_port_range(const char *s, uint32_t *addr_out,
  1037. uint32_t *mask_out, uint16_t *port_min_out,
  1038. uint16_t *port_max_out)
  1039. {
  1040. char *address;
  1041. char *mask, *port, *endptr;
  1042. struct in_addr in;
  1043. int bits;
  1044. tor_assert(s);
  1045. tor_assert(addr_out);
  1046. tor_assert(mask_out);
  1047. tor_assert(port_min_out);
  1048. tor_assert(port_max_out);
  1049. address = tor_strdup(s);
  1050. /* Break 'address' into separate strings.
  1051. */
  1052. mask = strchr(address,'/');
  1053. port = strchr(mask?mask:address,':');
  1054. if (mask)
  1055. *mask++ = '\0';
  1056. if (port)
  1057. *port++ = '\0';
  1058. /* Now "address" is the IP|'*' part...
  1059. * "mask" is the Mask|Maskbits part...
  1060. * and "port" is the *|port|min-max part.
  1061. */
  1062. if (strcmp(address,"*")==0) {
  1063. *addr_out = 0;
  1064. } else if (tor_inet_aton(address, &in) != 0) {
  1065. *addr_out = ntohl(in.s_addr);
  1066. } else {
  1067. log_fn(LOG_WARN, "Malformed IP %s in address pattern; rejecting.",address);
  1068. goto err;
  1069. }
  1070. if (!mask) {
  1071. if (strcmp(address,"*")==0)
  1072. *mask_out = 0;
  1073. else
  1074. *mask_out = 0xFFFFFFFFu;
  1075. } else {
  1076. endptr = NULL;
  1077. bits = (int) strtol(mask, &endptr, 10);
  1078. if (!*endptr) {
  1079. /* strtol handled the whole mask. */
  1080. if (bits < 0 || bits > 32) {
  1081. log_fn(LOG_WARN, "Bad number of mask bits on address range; rejecting.");
  1082. goto err;
  1083. }
  1084. *mask_out = ~((1<<(32-bits))-1);
  1085. } else if (tor_inet_aton(mask, &in) != 0) {
  1086. *mask_out = ntohl(in.s_addr);
  1087. } else {
  1088. log_fn(LOG_WARN, "Malformed mask %s on address range; rejecting.",
  1089. mask);
  1090. goto err;
  1091. }
  1092. }
  1093. if (!port || strcmp(port, "*") == 0) {
  1094. *port_min_out = 1;
  1095. *port_max_out = 65535;
  1096. } else {
  1097. endptr = NULL;
  1098. *port_min_out = (uint16_t) tor_parse_long(port, 10, 1, 65535,
  1099. NULL, &endptr);
  1100. if (*endptr == '-') {
  1101. port = endptr+1;
  1102. endptr = NULL;
  1103. *port_max_out = (uint16_t) tor_parse_long(port, 10, 1, 65535, NULL,
  1104. &endptr);
  1105. if (*endptr || !*port_max_out) {
  1106. log_fn(LOG_WARN, "Malformed port %s on address range rejecting.",
  1107. port);
  1108. }
  1109. } else if (*endptr || !*port_min_out) {
  1110. log_fn(LOG_WARN, "Malformed port %s on address range; rejecting.",
  1111. port);
  1112. goto err;
  1113. } else {
  1114. *port_max_out = *port_min_out;
  1115. }
  1116. if (*port_min_out > *port_max_out) {
  1117. log_fn(LOG_WARN,"Insane port range on address policy; rejecting.");
  1118. goto err;
  1119. }
  1120. }
  1121. tor_free(address);
  1122. return 0;
  1123. err:
  1124. tor_free(address);
  1125. return -1;
  1126. }
  1127. /* =====
  1128. * Process helpers
  1129. * ===== */
  1130. #ifndef MS_WINDOWS
  1131. /* Based on code contributed by christian grothoff */
  1132. static int start_daemon_called = 0;
  1133. static int finish_daemon_called = 0;
  1134. static int daemon_filedes[2];
  1135. /** Start putting the process into daemon mode: fork and drop all resources
  1136. * except standard fds. The parent process never returns, but stays around
  1137. * until finish_daemon is called. (Note: it's safe to call this more
  1138. * than once: calls after the first are ignored.)
  1139. */
  1140. void start_daemon(const char *desired_cwd)
  1141. {
  1142. pid_t pid;
  1143. if (start_daemon_called)
  1144. return;
  1145. start_daemon_called = 1;
  1146. if(!desired_cwd)
  1147. desired_cwd = "/";
  1148. /* Don't hold the wrong FS mounted */
  1149. if (chdir(desired_cwd) < 0) {
  1150. log_fn(LOG_ERR,"chdir to %s failed. Exiting.",desired_cwd);
  1151. exit(1);
  1152. }
  1153. pipe(daemon_filedes);
  1154. pid = fork();
  1155. if (pid < 0) {
  1156. log_fn(LOG_ERR,"fork failed. Exiting.");
  1157. exit(1);
  1158. }
  1159. if (pid) { /* Parent */
  1160. int ok;
  1161. char c;
  1162. close(daemon_filedes[1]); /* we only read */
  1163. ok = -1;
  1164. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  1165. if (c == '.')
  1166. ok = 1;
  1167. }
  1168. fflush(stdout);
  1169. if (ok == 1)
  1170. exit(0);
  1171. else
  1172. exit(1); /* child reported error */
  1173. } else { /* Child */
  1174. close(daemon_filedes[0]); /* we only write */
  1175. pid = setsid(); /* Detach from controlling terminal */
  1176. /*
  1177. * Fork one more time, so the parent (the session group leader) can exit.
  1178. * This means that we, as a non-session group leader, can never regain a
  1179. * controlling terminal. This part is recommended by Stevens's
  1180. * _Advanced Programming in the Unix Environment_.
  1181. */
  1182. if (fork() != 0) {
  1183. exit(0);
  1184. }
  1185. return;
  1186. }
  1187. }
  1188. /** Finish putting the process into daemon mode: drop standard fds, and tell
  1189. * the parent process to exit. (Note: it's safe to call this more than once:
  1190. * calls after the first are ignored. Calls start_daemon first if it hasn't
  1191. * been called already.)
  1192. */
  1193. void finish_daemon(void)
  1194. {
  1195. int nullfd;
  1196. char c = '.';
  1197. if (finish_daemon_called)
  1198. return;
  1199. if (!start_daemon_called)
  1200. start_daemon(NULL);
  1201. finish_daemon_called = 1;
  1202. nullfd = open("/dev/null",
  1203. O_CREAT | O_RDWR | O_APPEND);
  1204. if (nullfd < 0) {
  1205. log_fn(LOG_ERR,"/dev/null can't be opened. Exiting.");
  1206. exit(1);
  1207. }
  1208. /* close fds linking to invoking terminal, but
  1209. * close usual incoming fds, but redirect them somewhere
  1210. * useful so the fds don't get reallocated elsewhere.
  1211. */
  1212. if (dup2(nullfd,0) < 0 ||
  1213. dup2(nullfd,1) < 0 ||
  1214. dup2(nullfd,2) < 0) {
  1215. log_fn(LOG_ERR,"dup2 failed. Exiting.");
  1216. exit(1);
  1217. }
  1218. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  1219. close(daemon_filedes[1]);
  1220. }
  1221. #else
  1222. /* defined(MS_WINDOWS) */
  1223. void start_daemon(const char *cp) {}
  1224. void finish_daemon(void) {}
  1225. #endif
  1226. /** Write the current process ID, followed by NL, into <b>filename</b>.
  1227. */
  1228. void write_pidfile(char *filename) {
  1229. #ifndef MS_WINDOWS
  1230. FILE *pidfile;
  1231. if ((pidfile = fopen(filename, "w")) == NULL) {
  1232. log_fn(LOG_WARN, "Unable to open %s for writing: %s", filename,
  1233. strerror(errno));
  1234. } else {
  1235. fprintf(pidfile, "%d\n", (int)getpid());
  1236. fclose(pidfile);
  1237. }
  1238. #endif
  1239. }