bugfix: stop trying to write to a stderr that may not be there
[tor.git] / src / common / util.c
blob6cfe36abfad27bd44fd66b74f349cbb8709ce263
1 /* Copyright 2003 Roger Dingledine */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
5 #include "../or/or.h"
7 #ifdef HAVE_UNAME
8 #include <sys/utsname.h>
9 #endif
12 * Memory wrappers
15 void *tor_malloc(size_t size) {
16 void *result;
18 result = malloc(size);
20 if(!result) {
21 log_fn(LOG_ERR, "Out of memory. Dying.");
22 exit(1);
24 // memset(result,'X',size); /* deadbeef to encourage bugs */
25 return result;
28 void *tor_malloc_zero(size_t size) {
29 void *result = tor_malloc(size);
30 memset(result, 0, size);
31 return result;
34 void *tor_realloc(void *ptr, size_t size) {
35 void *result;
37 result = realloc(ptr, size);
38 if (!result) {
39 log_fn(LOG_ERR, "Out of memory. Dying.");
40 exit(1);
42 return result;
45 char *tor_strdup(const char *s) {
46 char *dup;
47 assert(s);
49 dup = strdup(s);
50 if(!dup) {
51 log_fn(LOG_ERR,"Out of memory. Dying.");
52 exit(1);
54 return dup;
57 char *tor_strndup(const char *s, size_t n) {
58 char *dup;
59 assert(s);
60 dup = tor_malloc(n+1);
61 strncpy(dup, s, n);
62 dup[n] = 0;
63 return dup;
67 * A simple smartlist interface to make an unordered list of acceptable
68 * nodes and then choose a random one.
69 * smartlist_create() mallocs the list, _free() frees the list,
70 * _add() adds an element, _remove() removes an element if it's there,
71 * _choose() returns a random element.
74 smartlist_t *smartlist_create(int max_elements) {
75 smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
76 sl->list = tor_malloc(sizeof(void *) * max_elements);
77 sl->num_used = 0;
78 sl->max = max_elements;
79 return sl;
82 void smartlist_free(smartlist_t *sl) {
83 free(sl->list);
84 free(sl);
87 /* add element to the list, but only if there's room */
88 void smartlist_add(smartlist_t *sl, void *element) {
89 if(sl->num_used < sl->max)
90 sl->list[sl->num_used++] = element;
91 else
92 log_fn(LOG_WARN,"We've already got %d elements, discarding.",sl->max);
95 void smartlist_remove(smartlist_t *sl, void *element) {
96 int i;
97 if(element == NULL)
98 return;
99 for(i=0; i < sl->num_used; i++)
100 if(sl->list[i] == element) {
101 sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
102 i--; /* so we process the new i'th element */
106 int smartlist_isin(smartlist_t *sl, void *element) {
107 int i;
108 for(i=0; i < sl->num_used; i++)
109 if(sl->list[i] == element)
110 return 1;
111 return 0;
114 int smartlist_overlap(smartlist_t *sl1, smartlist_t *sl2) {
115 int i;
116 for(i=0; i < sl2->num_used; i++)
117 if(smartlist_isin(sl1, sl2->list[i]))
118 return 1;
119 return 0;
122 /* remove elements of sl1 that aren't in sl2 */
123 void smartlist_intersect(smartlist_t *sl1, smartlist_t *sl2) {
124 int i;
125 for(i=0; i < sl1->num_used; i++)
126 if(!smartlist_isin(sl2, sl1->list[i])) {
127 sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
128 i--; /* so we process the new i'th element */
132 /* remove all elements of sl2 from sl1 */
133 void smartlist_subtract(smartlist_t *sl1, smartlist_t *sl2) {
134 int i;
135 for(i=0; i < sl2->num_used; i++)
136 smartlist_remove(sl1, sl2->list[i]);
139 void *smartlist_choose(smartlist_t *sl) {
140 if(sl->num_used)
141 return sl->list[crypto_pseudo_rand_int(sl->num_used)];
142 return NULL; /* no elements to choose from */
146 * String manipulation
149 /* return the first char of s that is not whitespace and not a comment */
150 const char *eat_whitespace(const char *s) {
151 assert(s);
153 while(isspace(*s) || *s == '#') {
154 while(isspace(*s))
155 s++;
156 if(*s == '#') { /* read to a \n or \0 */
157 while(*s && *s != '\n')
158 s++;
159 if(!*s)
160 return s;
163 return s;
166 const char *eat_whitespace_no_nl(const char *s) {
167 while(*s == ' ' || *s == '\t')
168 ++s;
169 return s;
172 /* return the first char of s that is whitespace or '#' or '\0 */
173 const char *find_whitespace(const char *s) {
174 assert(s);
176 while(*s && !isspace(*s) && *s != '#')
177 s++;
179 return s;
183 * Time
186 void tor_gettimeofday(struct timeval *timeval) {
187 #ifdef HAVE_GETTIMEOFDAY
188 if (gettimeofday(timeval, NULL)) {
189 log_fn(LOG_ERR, "gettimeofday failed.");
190 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
191 or segfaulted.*/
192 exit(1);
194 #elif defined(HAVE_FTIME)
195 ftime(timeval);
196 #else
197 #error "No way to get time."
198 #endif
199 return;
202 long
203 tv_udiff(struct timeval *start, struct timeval *end)
205 long udiff;
206 long secdiff = end->tv_sec - start->tv_sec;
208 if (secdiff+1 > LONG_MAX/1000000) {
209 log_fn(LOG_WARN, "comparing times too far apart.");
210 return LONG_MAX;
213 udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
214 if(udiff < 0) {
215 log_fn(LOG_INFO, "start (%ld.%ld) is after end (%ld.%ld). Returning 0.",
216 (long)start->tv_sec, (long)start->tv_usec, (long)end->tv_sec, (long)end->tv_usec);
217 return 0;
219 return udiff;
222 int tv_cmp(struct timeval *a, struct timeval *b) {
223 if (a->tv_sec > b->tv_sec)
224 return 1;
225 if (a->tv_sec < b->tv_sec)
226 return -1;
227 if (a->tv_usec > b->tv_usec)
228 return 1;
229 if (a->tv_usec < b->tv_usec)
230 return -1;
231 return 0;
234 void tv_add(struct timeval *a, struct timeval *b) {
235 a->tv_usec += b->tv_usec;
236 a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
237 a->tv_usec %= 1000000;
240 void tv_addms(struct timeval *a, long ms) {
241 a->tv_usec += (ms * 1000) % 1000000;
242 a->tv_sec += ((ms * 1000) / 1000000) + (a->tv_usec / 1000000);
243 a->tv_usec %= 1000000;
247 #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
248 static int n_leapdays(int y1, int y2) {
249 --y1;
250 --y2;
251 return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
253 static const int days_per_month[] =
254 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
256 time_t tor_timegm (struct tm *tm) {
257 /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
258 * It's way more brute-force than fiddling with tzset().
260 time_t ret;
261 unsigned long year, days, hours, minutes;
262 int i;
263 year = tm->tm_year + 1900;
264 assert(year >= 1970);
265 assert(tm->tm_mon >= 0 && tm->tm_mon <= 11);
266 days = 365 * (year-1970) + n_leapdays(1970,year);
267 for (i = 0; i < tm->tm_mon; ++i)
268 days += days_per_month[i];
269 if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
270 ++days;
271 days += tm->tm_mday - 1;
272 hours = days*24 + tm->tm_hour;
274 minutes = hours*60 + tm->tm_min;
275 ret = minutes*60 + tm->tm_sec;
276 return ret;
280 * Low-level I/O.
283 /* a wrapper for write(2) that makes sure to write all count bytes.
284 * Only use if fd is a blocking fd. */
285 int write_all(int fd, const char *buf, size_t count) {
286 int written = 0;
287 int result;
289 while(written != count) {
290 result = write(fd, buf+written, count-written);
291 if(result<0)
292 return -1;
293 written += result;
295 return count;
298 /* a wrapper for read(2) that makes sure to read all count bytes.
299 * Only use if fd is a blocking fd. */
300 int read_all(int fd, char *buf, size_t count) {
301 int numread = 0;
302 int result;
304 while(numread != count) {
305 result = read(fd, buf+numread, count-numread);
306 if(result<=0)
307 return -1;
308 numread += result;
310 return count;
313 void set_socket_nonblocking(int socket)
315 #ifdef MS_WINDOWS
316 /* Yes means no and no means yes. Do you not want to be nonblocking? */
317 int nonblocking = 0;
318 ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
319 #else
320 fcntl(socket, F_SETFL, O_NONBLOCK);
321 #endif
325 * Process control
328 /* Minimalist interface to run a void function in the background. On
329 * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
330 * func should not return, but rather should call spawn_exit.
332 int spawn_func(int (*func)(void *), void *data)
334 #ifdef MS_WINDOWS
335 int rv;
336 rv = _beginthread(func, 0, data);
337 if (rv == (unsigned long) -1)
338 return -1;
339 return 0;
340 #else
341 pid_t pid;
342 pid = fork();
343 if (pid<0)
344 return -1;
345 if (pid==0) {
346 /* Child */
347 func(data);
348 assert(0); /* Should never reach here. */
349 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
350 } else {
351 /* Parent */
352 return 0;
354 #endif
357 void spawn_exit()
359 #ifdef MS_WINDOWS
360 _endthread();
361 #else
362 exit(0);
363 #endif
368 * Windows compatibility.
371 tor_socketpair(int family, int type, int protocol, int fd[2])
373 #ifdef HAVE_SOCKETPAIR_XXXX
374 /* For testing purposes, we never fall back to real socketpairs. */
375 return socketpair(family, type, protocol, fd);
376 #else
377 int listener = -1;
378 int connector = -1;
379 int acceptor = -1;
380 struct sockaddr_in listen_addr;
381 struct sockaddr_in connect_addr;
382 int size;
384 if (protocol
385 #ifdef AF_UNIX
386 || family != AF_UNIX
387 #endif
389 #ifdef MS_WINDOWS
390 errno = WSAEAFNOSUPPORT;
391 #else
392 errno = EAFNOSUPPORT;
393 #endif
394 return -1;
396 if (!fd) {
397 errno = EINVAL;
398 return -1;
401 listener = socket(AF_INET, type, 0);
402 if (listener == -1)
403 return -1;
404 memset (&listen_addr, 0, sizeof (listen_addr));
405 listen_addr.sin_family = AF_INET;
406 listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
407 listen_addr.sin_port = 0; /* kernel choses port. */
408 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
409 == -1)
410 goto tidy_up_and_fail;
411 if (listen(listener, 1) == -1)
412 goto tidy_up_and_fail;
414 connector = socket(AF_INET, type, 0);
415 if (connector == -1)
416 goto tidy_up_and_fail;
417 /* We want to find out the port number to connect to. */
418 size = sizeof (connect_addr);
419 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
420 goto tidy_up_and_fail;
421 if (size != sizeof (connect_addr))
422 goto abort_tidy_up_and_fail;
423 if (connect(connector, (struct sockaddr *) &connect_addr,
424 sizeof (connect_addr)) == -1)
425 goto tidy_up_and_fail;
427 size = sizeof (listen_addr);
428 acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
429 if (acceptor == -1)
430 goto tidy_up_and_fail;
431 if (size != sizeof(listen_addr))
432 goto abort_tidy_up_and_fail;
433 close(listener);
434 /* Now check we are talking to ourself by matching port and host on the
435 two sockets. */
436 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
437 goto tidy_up_and_fail;
438 if (size != sizeof (connect_addr)
439 || listen_addr.sin_family != connect_addr.sin_family
440 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
441 || listen_addr.sin_port != connect_addr.sin_port) {
442 goto abort_tidy_up_and_fail;
444 fd[0] = connector;
445 fd[1] = acceptor;
446 return 0;
448 abort_tidy_up_and_fail:
449 #ifdef MS_WINDOWS
450 errno = WSAECONNABORTED;
451 #else
452 errno = ECONNABORTED; /* I hope this is portable and appropriate. */
453 #endif
454 tidy_up_and_fail:
456 int save_errno = errno;
457 if (listener != -1)
458 close(listener);
459 if (connector != -1)
460 close(connector);
461 if (acceptor != -1)
462 close(acceptor);
463 errno = save_errno;
464 return -1;
466 #endif
469 #ifdef MS_WINDOWS
470 int correct_socket_errno(int s)
472 int optval, optvallen=sizeof(optval);
473 assert(errno == WSAEWOULDBLOCK);
474 if (getsockopt(s, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
475 return errno;
476 if (optval)
477 return optval;
478 return WSAEWOULDBLOCK;
480 #endif
483 * Filesystem operations.
486 /* Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
487 * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
488 * directory. */
489 file_status_t file_status(const char *fname)
491 struct stat st;
492 if (stat(fname, &st)) {
493 if (errno == ENOENT) {
494 return FN_NOENT;
496 return FN_ERROR;
498 if (st.st_mode & S_IFDIR)
499 return FN_DIR;
500 else if (st.st_mode & S_IFREG)
501 return FN_FILE;
502 else
503 return FN_ERROR;
506 /* Check whether dirname exists and is private. If yes returns
507 0. Else returns -1. */
508 int check_private_dir(const char *dirname, int create)
510 struct stat st;
511 if (stat(dirname, &st)) {
512 if (errno != ENOENT) {
513 log(LOG_WARN, "Directory %s cannot be read: %s", dirname,
514 strerror(errno));
515 return -1;
517 if (!create) {
518 log(LOG_WARN, "Directory %s does not exist.", dirname);
519 return -1;
521 log(LOG_INFO, "Creating directory %s", dirname);
522 if (mkdir(dirname, 0700)) {
523 log(LOG_WARN, "Error creating directory %s: %s", dirname,
524 strerror(errno));
525 return -1;
526 } else {
527 return 0;
530 if (!(st.st_mode & S_IFDIR)) {
531 log(LOG_WARN, "%s is not a directory", dirname);
532 return -1;
534 if (st.st_uid != getuid()) {
535 log(LOG_WARN, "%s is not owned by this UID (%d)", dirname, (int)getuid());
536 return -1;
538 if (st.st_mode & 0077) {
539 log(LOG_WARN, "Fixing permissions on directory %s", dirname);
540 if (chmod(dirname, 0700)) {
541 log(LOG_WARN, "Could not chmod directory %s: %s", dirname,
542 strerror(errno));
543 return -1;
544 } else {
545 return 0;
548 return 0;
552 write_str_to_file(const char *fname, const char *str)
554 char tempname[1024];
555 int fd;
556 FILE *file;
557 if (strlen(fname) > 1000) {
558 log(LOG_WARN, "Filename %s is too long.", fname);
559 return -1;
561 strcpy(tempname,fname);
562 strcat(tempname,".tmp");
563 if ((fd = open(tempname, O_WRONLY|O_CREAT|O_TRUNC, 0600)) < 0) {
564 log(LOG_WARN, "Couldn't open %s for writing: %s", tempname,
565 strerror(errno));
566 return -1;
568 if (!(file = fdopen(fd, "w"))) {
569 log(LOG_WARN, "Couldn't fdopen %s for writing: %s", tempname,
570 strerror(errno));
571 close(fd); return -1;
573 if (fputs(str,file) == EOF) {
574 log(LOG_WARN, "Error writing to %s: %s", tempname, strerror(errno));
575 fclose(file); return -1;
577 fclose(file);
578 if (rename(tempname, fname)) {
579 log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
580 return -1;
582 return 0;
585 char *read_file_to_str(const char *filename) {
586 int fd; /* router file */
587 struct stat statbuf;
588 char *string;
590 assert(filename);
592 if(strcspn(filename,CONFIG_LEGAL_FILENAME_CHARACTERS) != 0) {
593 log_fn(LOG_WARN,"Filename %s contains illegal characters.",filename);
594 return NULL;
597 if(stat(filename, &statbuf) < 0) {
598 log_fn(LOG_INFO,"Could not stat %s.",filename);
599 return NULL;
602 fd = open(filename,O_RDONLY,0);
603 if (fd<0) {
604 log_fn(LOG_WARN,"Could not open %s.",filename);
605 return NULL;
608 string = tor_malloc(statbuf.st_size+1);
610 if(read_all(fd,string,statbuf.st_size) != statbuf.st_size) {
611 log_fn(LOG_WARN,"Couldn't read all %ld bytes of file '%s'.",
612 (long)statbuf.st_size,filename);
613 free(string);
614 close(fd);
615 return NULL;
617 close(fd);
619 string[statbuf.st_size] = 0; /* null terminate it */
620 return string;
623 /* read lines from f (no more than maxlen-1 bytes each) until we
624 * get one with a well-formed "key value".
625 * point *key to the first word in line, point *value to the second.
626 * Put a \0 at the end of key, remove everything at the end of value
627 * that is whitespace or comment.
628 * Return 1 if success, 0 if no more lines, -1 if error.
630 int parse_line_from_file(char *line, int maxlen, FILE *f, char **key_out, char **value_out) {
631 char *s, *key, *end, *value;
633 try_next_line:
634 if(!fgets(line, maxlen, f)) {
635 if(feof(f))
636 return 0;
637 return -1; /* real error */
640 if((s = strchr(line,'#'))) /* strip comments */
641 *s = 0; /* stop the line there */
643 /* remove end whitespace */
644 s = strchr(line, 0); /* now we're at the null */
645 do {
646 *s = 0;
647 s--;
648 } while (s >= line && isspace(*s));
650 key = line;
651 while(isspace(*key))
652 key++;
653 if(*key == 0)
654 goto try_next_line; /* this line has nothing on it */
655 end = key;
656 while(*end && !isspace(*end))
657 end++;
658 value = end;
659 while(*value && isspace(*value))
660 value++;
662 if(!*end || !*value) { /* only a key on this line. no value. */
663 *end = 0;
664 log_fn(LOG_WARN,"Line has keyword '%s' but no value. Skipping.",key);
665 goto try_next_line;
667 *end = 0; /* null it out */
669 log_fn(LOG_DEBUG,"got keyword '%s', value '%s'", key, value);
670 *key_out = key, *value_out = value;
671 return 1;
674 static char uname_result[256];
675 static int uname_result_is_set = 0;
677 const char *
678 get_uname(void)
680 #ifdef HAVE_UNAME
681 struct utsname u;
682 #endif
683 if (!uname_result_is_set) {
684 #ifdef HAVE_UNAME
685 if (!uname((&u))) {
686 snprintf(uname_result, 255, "%s %s %s",
687 u.sysname, u.nodename, u.machine);
688 uname_result[255] = '\0';
689 } else
690 #endif
692 strcpy(uname_result, "Unknown platform");
694 uname_result_is_set = 1;
696 return uname_result;
699 #ifndef MS_WINDOWS
700 /* Based on code contributed by christian grothoff */
701 static int start_daemon_called = 0;
702 static int finish_daemon_called = 0;
703 static int daemon_filedes[2];
704 void start_daemon(char *desired_cwd)
706 pid_t pid;
708 if (start_daemon_called)
709 return;
710 start_daemon_called = 1;
712 if(!desired_cwd)
713 desired_cwd = "/";
714 /* Don't hold the wrong FS mounted */
715 if (chdir(desired_cwd) < 0) {
716 log_fn(LOG_ERR,"chdir to %s failed. Exiting.",desired_cwd);
717 exit(1);
720 pipe(daemon_filedes);
721 pid = fork();
722 if (pid < 0) {
723 log_fn(LOG_ERR,"fork failed. Exiting.");
724 exit(1);
726 if (pid) { /* Parent */
727 int ok;
728 char c;
730 close(daemon_filedes[1]); /* we only read */
731 ok = -1;
732 while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
733 if (c == '.')
734 ok = 1;
736 fflush(stdout);
737 if (ok == 1)
738 exit(0);
739 else
740 exit(1); /* child reported error */
741 } else { /* Child */
742 close(daemon_filedes[0]); /* we only write */
744 pid = setsid(); /* Detach from controlling terminal */
746 * Fork one more time, so the parent (the session group leader) can exit.
747 * This means that we, as a non-session group leader, can never regain a
748 * controlling terminal. This part is recommended by Stevens's
749 * _Advanced Programming in the Unix Environment_.
751 if (fork() != 0) {
752 exit(0);
754 return;
758 void finish_daemon(void)
760 int nullfd;
761 char c = '.';
762 if (finish_daemon_called)
763 return;
764 if (!start_daemon_called)
765 start_daemon(NULL);
766 finish_daemon_called = 1;
768 nullfd = open("/dev/null",
769 O_CREAT | O_RDWR | O_APPEND);
770 if (nullfd < 0) {
771 log_fn(LOG_ERR,"/dev/null can't be opened. Exiting.");
772 exit(1);
774 /* close fds linking to invoking terminal, but
775 * close usual incoming fds, but redirect them somewhere
776 * useful so the fds don't get reallocated elsewhere.
778 if (dup2(nullfd,0) < 0 ||
779 dup2(nullfd,1) < 0 ||
780 dup2(nullfd,2) < 0) {
781 log_fn(LOG_ERR,"dup2 failed. Exiting.");
782 exit(1);
784 write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
785 close(daemon_filedes[1]);
787 #else
788 /* defined(MS_WINDOWS) */
789 void start_daemon(void) {}
790 void finish_daemon(void) {}
791 #endif
793 void write_pidfile(char *filename) {
794 #ifndef MS_WINDOWS
795 FILE *pidfile;
797 if ((pidfile = fopen(filename, "w")) == NULL) {
798 log_fn(LOG_WARN, "unable to open %s for writing: %s", filename,
799 strerror(errno));
800 } else {
801 fprintf(pidfile, "%d", getpid());
802 fclose(pidfile);
804 #endif
807 int switch_id(char *user, char *group) {
808 #ifndef MS_WINDOWS
809 struct passwd *pw = NULL;
810 struct group *gr = NULL;
812 if (user) {
813 pw = getpwnam(user);
814 if (pw == NULL) {
815 log_fn(LOG_ERR,"User '%s' not found.", user);
816 return -1;
820 /* switch the group first, while we still have the privileges to do so */
821 if (group) {
822 gr = getgrnam(group);
823 if (gr == NULL) {
824 log_fn(LOG_ERR,"Group '%s' not found.", group);
825 return -1;
828 if (setgid(gr->gr_gid) != 0) {
829 log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
830 return -1;
832 } else if (user) {
833 if (setgid(pw->pw_gid) != 0) {
834 log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
835 return -1;
839 /* now that the group is switched, we can switch users and lose
840 privileges */
841 if (user) {
842 if (setuid(pw->pw_uid) != 0) {
843 log_fn(LOG_ERR,"Error setting UID: %s", strerror(errno));
844 return -1;
848 return 0;
849 #endif
851 log_fn(LOG_ERR,
852 "User or group specified, but switching users is not supported.");
854 return -1;