util.c 15 KB

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