util.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. /* Copyright 2003 Roger Dingledine */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "../or/or.h"
  5. #ifdef HAVE_UNAME
  6. #include <sys/utsname.h>
  7. #endif
  8. /*
  9. * Memory wrappers
  10. */
  11. void *tor_malloc(size_t size) {
  12. void *result;
  13. result = malloc(size);
  14. if(!result) {
  15. log_fn(LOG_ERR, "Out of memory. Dying.");
  16. exit(1);
  17. }
  18. // memset(result,'X',size); /* deadbeef to encourage bugs */
  19. return result;
  20. }
  21. void *tor_malloc_zero(size_t size) {
  22. void *result = tor_malloc(size);
  23. memset(result, 0, size);
  24. return result;
  25. }
  26. void *tor_realloc(void *ptr, size_t size) {
  27. void *result;
  28. result = realloc(ptr, size);
  29. if (!result) {
  30. log_fn(LOG_ERR, "Out of memory. Dying.");
  31. exit(1);
  32. }
  33. return result;
  34. }
  35. char *tor_strdup(const char *s) {
  36. char *dup;
  37. assert(s);
  38. dup = strdup(s);
  39. if(!dup) {
  40. log_fn(LOG_ERR,"Out of memory. Dying.");
  41. exit(1);
  42. }
  43. return dup;
  44. }
  45. char *tor_strndup(const char *s, size_t n) {
  46. char *dup;
  47. assert(s);
  48. dup = tor_malloc(n+1);
  49. strncpy(dup, s, n);
  50. dup[n] = 0;
  51. return dup;
  52. }
  53. /*
  54. * A simple smartlist interface to make an unordered list of acceptable
  55. * nodes and then choose a random one.
  56. * smartlist_create() mallocs the list, _free() frees the list,
  57. * _add() adds an element, _remove() removes an element if it's there,
  58. * _choose() returns a random element.
  59. */
  60. smartlist_t *smartlist_create(int max_elements) {
  61. smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
  62. sl->list = tor_malloc(sizeof(void *) * max_elements);
  63. sl->num_used = 0;
  64. sl->max = max_elements;
  65. return sl;
  66. }
  67. void smartlist_free(smartlist_t *sl) {
  68. free(sl->list);
  69. free(sl);
  70. }
  71. /* add element to the list, but only if there's room */
  72. void smartlist_add(smartlist_t *sl, void *element) {
  73. if(sl->num_used < sl->max)
  74. sl->list[sl->num_used++] = element;
  75. else
  76. log_fn(LOG_WARN,"We've already got %d elements, discarding.",sl->max);
  77. }
  78. void smartlist_remove(smartlist_t *sl, void *element) {
  79. int i;
  80. if(element == NULL)
  81. return;
  82. for(i=0; i < sl->num_used; i++)
  83. if(sl->list[i] == element) {
  84. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  85. i--; /* so we process the new i'th element */
  86. }
  87. }
  88. int smartlist_isin(smartlist_t *sl, void *element) {
  89. int i;
  90. for(i=0; i < sl->num_used; i++)
  91. if(sl->list[i] == element)
  92. return 1;
  93. return 0;
  94. }
  95. int smartlist_overlap(smartlist_t *sl1, smartlist_t *sl2) {
  96. int i;
  97. for(i=0; i < sl2->num_used; i++)
  98. if(smartlist_isin(sl1, sl2->list[i]))
  99. return 1;
  100. return 0;
  101. }
  102. /* remove elements of sl1 that aren't in sl2 */
  103. void smartlist_intersect(smartlist_t *sl1, smartlist_t *sl2) {
  104. int i;
  105. for(i=0; i < sl1->num_used; i++)
  106. if(!smartlist_isin(sl2, sl1->list[i])) {
  107. sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
  108. i--; /* so we process the new i'th element */
  109. }
  110. }
  111. /* remove all elements of sl2 from sl1 */
  112. void smartlist_subtract(smartlist_t *sl1, smartlist_t *sl2) {
  113. int i;
  114. for(i=0; i < sl2->num_used; i++)
  115. smartlist_remove(sl1, sl2->list[i]);
  116. }
  117. void *smartlist_choose(smartlist_t *sl) {
  118. if(sl->num_used)
  119. return sl->list[crypto_pseudo_rand_int(sl->num_used)];
  120. return NULL; /* no elements to choose from */
  121. }
  122. /*
  123. * String manipulation
  124. */
  125. /* return the first char of s that is not whitespace and not a comment */
  126. const char *eat_whitespace(const char *s) {
  127. assert(s);
  128. while(isspace(*s) || *s == '#') {
  129. while(isspace(*s))
  130. s++;
  131. if(*s == '#') { /* read to a \n or \0 */
  132. while(*s && *s != '\n')
  133. s++;
  134. if(!*s)
  135. return s;
  136. }
  137. }
  138. return s;
  139. }
  140. const char *eat_whitespace_no_nl(const char *s) {
  141. while(*s == ' ' || *s == '\t')
  142. ++s;
  143. return s;
  144. }
  145. /* return the first char of s that is whitespace or '#' or '\0 */
  146. const char *find_whitespace(const char *s) {
  147. assert(s);
  148. while(*s && !isspace(*s) && *s != '#')
  149. s++;
  150. return s;
  151. }
  152. /*
  153. * Time
  154. */
  155. void tor_gettimeofday(struct timeval *timeval) {
  156. #ifdef HAVE_GETTIMEOFDAY
  157. if (gettimeofday(timeval, NULL)) {
  158. log_fn(LOG_ERR, "gettimeofday failed.");
  159. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  160. or segfaulted.*/
  161. exit(1);
  162. }
  163. #elif defined(HAVE_FTIME)
  164. ftime(timeval);
  165. #else
  166. #error "No way to get time."
  167. #endif
  168. return;
  169. }
  170. long
  171. tv_udiff(struct timeval *start, struct timeval *end)
  172. {
  173. long udiff;
  174. long secdiff = end->tv_sec - start->tv_sec;
  175. if (secdiff+1 > LONG_MAX/1000000) {
  176. log_fn(LOG_WARN, "comparing times too far apart.");
  177. return LONG_MAX;
  178. }
  179. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  180. if(udiff < 0) {
  181. log_fn(LOG_INFO, "start (%ld.%ld) is after end (%ld.%ld). Returning 0.",
  182. (long)start->tv_sec, (long)start->tv_usec, (long)end->tv_sec, (long)end->tv_usec);
  183. return 0;
  184. }
  185. return udiff;
  186. }
  187. int tv_cmp(struct timeval *a, struct timeval *b) {
  188. if (a->tv_sec > b->tv_sec)
  189. return 1;
  190. if (a->tv_sec < b->tv_sec)
  191. return -1;
  192. if (a->tv_usec > b->tv_usec)
  193. return 1;
  194. if (a->tv_usec < b->tv_usec)
  195. return -1;
  196. return 0;
  197. }
  198. void tv_add(struct timeval *a, struct timeval *b) {
  199. a->tv_usec += b->tv_usec;
  200. a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
  201. a->tv_usec %= 1000000;
  202. }
  203. void tv_addms(struct timeval *a, long ms) {
  204. a->tv_usec += (ms * 1000) % 1000000;
  205. a->tv_sec += ((ms * 1000) / 1000000) + (a->tv_usec / 1000000);
  206. a->tv_usec %= 1000000;
  207. }
  208. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  209. static int n_leapdays(int y1, int y2) {
  210. --y1;
  211. --y2;
  212. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  213. }
  214. static const int days_per_month[] =
  215. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  216. time_t tor_timegm (struct tm *tm) {
  217. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  218. * It's way more brute-force than fiddling with tzset().
  219. */
  220. time_t ret;
  221. unsigned long year, days, hours, minutes;
  222. int i;
  223. year = tm->tm_year + 1900;
  224. assert(year >= 1970);
  225. assert(tm->tm_mon >= 0 && tm->tm_mon <= 11);
  226. days = 365 * (year-1970) + n_leapdays(1970,year);
  227. for (i = 0; i < tm->tm_mon; ++i)
  228. days += days_per_month[i];
  229. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  230. ++days;
  231. days += tm->tm_mday - 1;
  232. hours = days*24 + tm->tm_hour;
  233. minutes = hours*60 + tm->tm_min;
  234. ret = minutes*60 + tm->tm_sec;
  235. return ret;
  236. }
  237. /*
  238. * Low-level I/O.
  239. */
  240. /* a wrapper for write(2) that makes sure to write all count bytes.
  241. * Only use if fd is a blocking fd. */
  242. int write_all(int fd, const char *buf, size_t count) {
  243. int written = 0;
  244. int result;
  245. while(written != count) {
  246. result = write(fd, buf+written, count-written);
  247. if(result<0)
  248. return -1;
  249. written += result;
  250. }
  251. return count;
  252. }
  253. /* a wrapper for read(2) that makes sure to read all count bytes.
  254. * Only use if fd is a blocking fd. */
  255. int read_all(int fd, char *buf, size_t count) {
  256. int numread = 0;
  257. int result;
  258. while(numread != count) {
  259. result = read(fd, buf+numread, count-numread);
  260. if(result<=0)
  261. return -1;
  262. numread += result;
  263. }
  264. return count;
  265. }
  266. void set_socket_nonblocking(int socket)
  267. {
  268. #ifdef MS_WINDOWS
  269. /* Yes means no and no means yes. Do you not want to be nonblocking? */
  270. int nonblocking = 0;
  271. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  272. #else
  273. fcntl(socket, F_SETFL, O_NONBLOCK);
  274. #endif
  275. }
  276. /*
  277. * Process control
  278. */
  279. /* Minimalist interface to run a void function in the background. On
  280. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  281. * func should not return, but rather should call spawn_exit.
  282. */
  283. int spawn_func(int (*func)(void *), void *data)
  284. {
  285. #ifdef MS_WINDOWS
  286. int rv;
  287. rv = _beginthread(func, 0, data);
  288. if (rv == (unsigned long) -1)
  289. return -1;
  290. return 0;
  291. #else
  292. pid_t pid;
  293. pid = fork();
  294. if (pid<0)
  295. return -1;
  296. if (pid==0) {
  297. /* Child */
  298. func(data);
  299. assert(0); /* Should never reach here. */
  300. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  301. } else {
  302. /* Parent */
  303. return 0;
  304. }
  305. #endif
  306. }
  307. void spawn_exit()
  308. {
  309. #ifdef MS_WINDOWS
  310. _endthread();
  311. #else
  312. exit(0);
  313. #endif
  314. }
  315. /*
  316. * Windows compatibility.
  317. */
  318. int
  319. tor_socketpair(int family, int type, int protocol, int fd[2])
  320. {
  321. #ifdef HAVE_SOCKETPAIR_XXXX
  322. /* For testing purposes, we never fall back to real socketpairs. */
  323. return socketpair(family, type, protocol, fd);
  324. #else
  325. int listener = -1;
  326. int connector = -1;
  327. int acceptor = -1;
  328. struct sockaddr_in listen_addr;
  329. struct sockaddr_in connect_addr;
  330. int size;
  331. if (protocol
  332. #ifdef AF_UNIX
  333. || family != AF_UNIX
  334. #endif
  335. ) {
  336. #ifdef MS_WINDOWS
  337. errno = WSAEAFNOSUPPORT;
  338. #else
  339. errno = EAFNOSUPPORT;
  340. #endif
  341. return -1;
  342. }
  343. if (!fd) {
  344. errno = EINVAL;
  345. return -1;
  346. }
  347. listener = socket(AF_INET, type, 0);
  348. if (listener == -1)
  349. return -1;
  350. memset (&listen_addr, 0, sizeof (listen_addr));
  351. listen_addr.sin_family = AF_INET;
  352. listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
  353. listen_addr.sin_port = 0; /* kernel choses port. */
  354. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  355. == -1)
  356. goto tidy_up_and_fail;
  357. if (listen(listener, 1) == -1)
  358. goto tidy_up_and_fail;
  359. connector = socket(AF_INET, type, 0);
  360. if (connector == -1)
  361. goto tidy_up_and_fail;
  362. /* We want to find out the port number to connect to. */
  363. size = sizeof (connect_addr);
  364. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  365. goto tidy_up_and_fail;
  366. if (size != sizeof (connect_addr))
  367. goto abort_tidy_up_and_fail;
  368. if (connect(connector, (struct sockaddr *) &connect_addr,
  369. sizeof (connect_addr)) == -1)
  370. goto tidy_up_and_fail;
  371. size = sizeof (listen_addr);
  372. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  373. if (acceptor == -1)
  374. goto tidy_up_and_fail;
  375. if (size != sizeof(listen_addr))
  376. goto abort_tidy_up_and_fail;
  377. close(listener);
  378. /* Now check we are talking to ourself by matching port and host on the
  379. two sockets. */
  380. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  381. goto tidy_up_and_fail;
  382. if (size != sizeof (connect_addr)
  383. || listen_addr.sin_family != connect_addr.sin_family
  384. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  385. || listen_addr.sin_port != connect_addr.sin_port) {
  386. goto abort_tidy_up_and_fail;
  387. }
  388. fd[0] = connector;
  389. fd[1] = acceptor;
  390. return 0;
  391. abort_tidy_up_and_fail:
  392. #ifdef MS_WINDOWS
  393. errno = WSAECONNABORTED;
  394. #else
  395. errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  396. #endif
  397. tidy_up_and_fail:
  398. {
  399. int save_errno = errno;
  400. if (listener != -1)
  401. close(listener);
  402. if (connector != -1)
  403. close(connector);
  404. if (acceptor != -1)
  405. close(acceptor);
  406. errno = save_errno;
  407. return -1;
  408. }
  409. #endif
  410. }
  411. #ifdef MS_WINDOWS
  412. int correct_socket_errno(int s)
  413. {
  414. int optval, optvallen=sizeof(optval);
  415. assert(errno == WSAEWOULDBLOCK);
  416. if (getsockopt(s, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  417. return errno;
  418. if (optval)
  419. return optval;
  420. return WSAEWOULDBLOCK;
  421. }
  422. #endif
  423. /*
  424. * Filesystem operations.
  425. */
  426. /* Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  427. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  428. * directory. */
  429. file_status_t file_status(const char *fname)
  430. {
  431. struct stat st;
  432. if (stat(fname, &st)) {
  433. if (errno == ENOENT) {
  434. return FN_NOENT;
  435. }
  436. return FN_ERROR;
  437. }
  438. if (st.st_mode & S_IFDIR)
  439. return FN_DIR;
  440. else if (st.st_mode & S_IFREG)
  441. return FN_FILE;
  442. else
  443. return FN_ERROR;
  444. }
  445. /* Check whether dirname exists and is private. If yes returns
  446. 0. Else returns -1. */
  447. int check_private_dir(const char *dirname, int create)
  448. {
  449. struct stat st;
  450. if (stat(dirname, &st)) {
  451. if (errno != ENOENT) {
  452. log(LOG_WARN, "Directory %s cannot be read: %s", dirname,
  453. strerror(errno));
  454. return -1;
  455. }
  456. if (!create) {
  457. log(LOG_WARN, "Directory %s does not exist.", dirname);
  458. return -1;
  459. }
  460. log(LOG_INFO, "Creating directory %s", dirname);
  461. if (mkdir(dirname, 0700)) {
  462. log(LOG_WARN, "Error creating directory %s: %s", dirname,
  463. strerror(errno));
  464. return -1;
  465. } else {
  466. return 0;
  467. }
  468. }
  469. if (!(st.st_mode & S_IFDIR)) {
  470. log(LOG_WARN, "%s is not a directory", dirname);
  471. return -1;
  472. }
  473. if (st.st_uid != getuid()) {
  474. log(LOG_WARN, "%s is not owned by this UID (%d)", dirname, (int)getuid());
  475. return -1;
  476. }
  477. if (st.st_mode & 0077) {
  478. log(LOG_WARN, "Fixing permissions on directory %s", dirname);
  479. if (chmod(dirname, 0700)) {
  480. log(LOG_WARN, "Could not chmod directory %s: %s", dirname,
  481. strerror(errno));
  482. return -1;
  483. } else {
  484. return 0;
  485. }
  486. }
  487. return 0;
  488. }
  489. int
  490. write_str_to_file(const char *fname, const char *str)
  491. {
  492. char tempname[1024];
  493. int fd;
  494. FILE *file;
  495. if (strlen(fname) > 1000) {
  496. log(LOG_WARN, "Filename %s is too long.", fname);
  497. return -1;
  498. }
  499. strcpy(tempname,fname);
  500. strcat(tempname,".tmp");
  501. if ((fd = open(tempname, O_WRONLY|O_CREAT|O_TRUNC, 0600)) < 0) {
  502. log(LOG_WARN, "Couldn't open %s for writing: %s", tempname,
  503. strerror(errno));
  504. return -1;
  505. }
  506. if (!(file = fdopen(fd, "w"))) {
  507. log(LOG_WARN, "Couldn't fdopen %s for writing: %s", tempname,
  508. strerror(errno));
  509. close(fd); return -1;
  510. }
  511. if (fputs(str,file) == EOF) {
  512. log(LOG_WARN, "Error writing to %s: %s", tempname, strerror(errno));
  513. fclose(file); return -1;
  514. }
  515. fclose(file);
  516. if (rename(tempname, fname)) {
  517. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  518. return -1;
  519. }
  520. return 0;
  521. }
  522. char *read_file_to_str(const char *filename) {
  523. int fd; /* router file */
  524. struct stat statbuf;
  525. char *string;
  526. assert(filename);
  527. if(strcspn(filename,CONFIG_LEGAL_FILENAME_CHARACTERS) != 0) {
  528. log_fn(LOG_WARN,"Filename %s contains illegal characters.",filename);
  529. return NULL;
  530. }
  531. if(stat(filename, &statbuf) < 0) {
  532. log_fn(LOG_INFO,"Could not stat %s.",filename);
  533. return NULL;
  534. }
  535. fd = open(filename,O_RDONLY,0);
  536. if (fd<0) {
  537. log_fn(LOG_WARN,"Could not open %s.",filename);
  538. return NULL;
  539. }
  540. string = tor_malloc(statbuf.st_size+1);
  541. if(read_all(fd,string,statbuf.st_size) != statbuf.st_size) {
  542. log_fn(LOG_WARN,"Couldn't read all %ld bytes of file '%s'.",
  543. (long)statbuf.st_size,filename);
  544. free(string);
  545. close(fd);
  546. return NULL;
  547. }
  548. close(fd);
  549. string[statbuf.st_size] = 0; /* null terminate it */
  550. return string;
  551. }
  552. /* read lines from f (no more than maxlen-1 bytes each) until we
  553. * get one with a well-formed "key value".
  554. * point *key to the first word in line, point *value to the second.
  555. * Put a \0 at the end of key, remove everything at the end of value
  556. * that is whitespace or comment.
  557. * Return 1 if success, 0 if no more lines, -1 if error.
  558. */
  559. int parse_line_from_file(char *line, int maxlen, FILE *f, char **key_out, char **value_out) {
  560. char *s, *key, *end, *value;
  561. try_next_line:
  562. if(!fgets(line, maxlen, f)) {
  563. if(feof(f))
  564. return 0;
  565. return -1; /* real error */
  566. }
  567. if((s = strchr(line,'#'))) /* strip comments */
  568. *s = 0; /* stop the line there */
  569. /* remove end whitespace */
  570. s = strchr(line, 0); /* now we're at the null */
  571. do {
  572. *s = 0;
  573. s--;
  574. } while (s >= line && isspace(*s));
  575. key = line;
  576. while(isspace(*key))
  577. key++;
  578. if(*key == 0)
  579. goto try_next_line; /* this line has nothing on it */
  580. end = key;
  581. while(*end && !isspace(*end))
  582. end++;
  583. value = end;
  584. while(*value && isspace(*value))
  585. value++;
  586. if(!*end || !*value) { /* only a key on this line. no value. */
  587. *end = 0;
  588. log_fn(LOG_WARN,"Line has keyword '%s' but no value. Skipping.",key);
  589. goto try_next_line;
  590. }
  591. *end = 0; /* null it out */
  592. log_fn(LOG_DEBUG,"got keyword '%s', value '%s'", key, value);
  593. *key_out = key, *value_out = value;
  594. return 1;
  595. }
  596. static char uname_result[256];
  597. static int uname_result_is_set = 0;
  598. const char *
  599. get_uname(void)
  600. {
  601. #ifdef HAVE_UNAME
  602. struct utsname u;
  603. #endif
  604. if (!uname_result_is_set) {
  605. #ifdef HAVE_UNAME
  606. if (!uname((&u))) {
  607. snprintf(uname_result, 255, "%s %s %s %s %s",
  608. u.sysname, u.nodename, u.release, u.version, u.machine);
  609. uname_result[255] = '\0';
  610. } else
  611. #endif
  612. {
  613. strcpy(uname_result, "Unknown platform");
  614. }
  615. uname_result_is_set = 1;
  616. }
  617. return uname_result;
  618. }
  619. void daemonize(void) {
  620. #ifdef HAVE_DAEMON
  621. if (daemon(0 /* chdir to / */,
  622. 0 /* Redirect std* to /dev/null */)) {
  623. log_fn(LOG_ERR, "Daemon returned an error: %s", strerror(errno));
  624. exit(1);
  625. }
  626. #elif ! defined(MS_WINDOWS)
  627. /* Fork; parent exits. */
  628. if (fork())
  629. exit(0);
  630. /* Create new session; make sure we never get a terminal */
  631. setsid();
  632. if (fork())
  633. exit(0);
  634. chdir("/");
  635. umask(000);
  636. fclose(stdin);
  637. fclose(stdout);
  638. fclose(stderr);
  639. #endif
  640. }
  641. void write_pidfile(char *filename) {
  642. #ifndef MS_WINDOWS
  643. FILE *pidfile;
  644. if ((pidfile = fopen(filename, "w")) == NULL) {
  645. log_fn(LOG_WARN, "unable to open %s for writing: %s", filename,
  646. strerror(errno));
  647. } else {
  648. fprintf(pidfile, "%d", getpid());
  649. fclose(pidfile);
  650. }
  651. #endif
  652. }
  653. int switch_id(char *user, char *group) {
  654. #ifndef MS_WINDOWS
  655. struct passwd *pw = NULL;
  656. struct group *gr = NULL;
  657. if (user) {
  658. pw = getpwnam(user);
  659. if (pw == NULL) {
  660. log_fn(LOG_ERR,"User '%s' not found.", user);
  661. return -1;
  662. }
  663. }
  664. /* switch the group first, while we still have the privileges to do so */
  665. if (group) {
  666. gr = getgrnam(group);
  667. if (gr == NULL) {
  668. log_fn(LOG_ERR,"Group '%s' not found.", group);
  669. return -1;
  670. }
  671. if (setgid(gr->gr_gid) != 0) {
  672. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  673. return -1;
  674. }
  675. } else if (user) {
  676. if (setgid(pw->pw_gid) != 0) {
  677. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  678. return -1;
  679. }
  680. }
  681. /* now that the group is switched, we can switch users and lose
  682. privileges */
  683. if (user) {
  684. if (setuid(pw->pw_uid) != 0) {
  685. log_fn(LOG_ERR,"Error setting UID: %s", strerror(errno));
  686. return -1;
  687. }
  688. }
  689. return 0;
  690. #endif
  691. log_fn(LOG_ERR,
  692. "User or group specified, but switching users is not supported.");
  693. return -1;
  694. }