util.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. /*
  97. * Low-level I/O.
  98. */
  99. /* a wrapper for write(2) that makes sure to write all count bytes.
  100. * Only use if fd is a blocking fd. */
  101. int write_all(int fd, const void *buf, size_t count) {
  102. int written = 0;
  103. int result;
  104. while(written != count) {
  105. result = write(fd, buf+written, count-written);
  106. if(result<0)
  107. return -1;
  108. written += result;
  109. }
  110. return count;
  111. }
  112. /* a wrapper for read(2) that makes sure to read all count bytes.
  113. * Only use if fd is a blocking fd. */
  114. int read_all(int fd, void *buf, size_t count) {
  115. int numread = 0;
  116. int result;
  117. while(numread != count) {
  118. result = read(fd, buf+numread, count-numread);
  119. if(result<=0)
  120. return -1;
  121. numread += result;
  122. }
  123. return count;
  124. }
  125. void set_socket_nonblocking(int socket)
  126. {
  127. #ifdef MS_WINDOWS
  128. /* Yes means no and no means yes. Do you not want to be nonblocking? */
  129. int nonblocking = 0;
  130. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  131. #else
  132. fcntl(socket, F_SETFL, O_NONBLOCK);
  133. #endif
  134. }
  135. /*
  136. * Process control
  137. */
  138. /* Minimalist interface to run a void function in the background. On
  139. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  140. * func should not return, but rather should call spawn_exit.
  141. */
  142. int spawn_func(int (*func)(void *), void *data)
  143. {
  144. #ifdef MS_WINDOWS
  145. int rv;
  146. rv = _beginthread(func, 0, data);
  147. if (rv == (unsigned long) -1)
  148. return -1;
  149. return 0;
  150. #else
  151. pid_t pid;
  152. pid = fork();
  153. if (pid<0)
  154. return -1;
  155. if (pid==0) {
  156. /* Child */
  157. func(data);
  158. assert(0); /* Should never reach here. */
  159. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  160. } else {
  161. /* Parent */
  162. return 0;
  163. }
  164. #endif
  165. }
  166. void spawn_exit()
  167. {
  168. #ifdef MS_WINDOWS
  169. _endthread();
  170. #else
  171. exit(0);
  172. #endif
  173. }
  174. /*
  175. * Windows compatibility.
  176. */
  177. int
  178. tor_socketpair(int family, int type, int protocol, int fd[2])
  179. {
  180. #ifdef HAVE_SOCKETPAIR_XXXX
  181. /* For testing purposes, we never fall back to real socketpairs. */
  182. return socketpair(family, type, protocol, fd);
  183. #else
  184. int listener = -1;
  185. int connector = -1;
  186. int acceptor = -1;
  187. struct sockaddr_in listen_addr;
  188. struct sockaddr_in connect_addr;
  189. int size;
  190. if (protocol
  191. #ifdef AF_UNIX
  192. || family != AF_UNIX
  193. #endif
  194. ) {
  195. #ifdef MS_WINDOWS
  196. errno = WSAEAFNOSUPPORT;
  197. #else
  198. errno = EAFNOSUPPORT;
  199. #endif
  200. return -1;
  201. }
  202. if (!fd) {
  203. errno = EINVAL;
  204. return -1;
  205. }
  206. listener = socket(AF_INET, type, 0);
  207. if (listener == -1)
  208. return -1;
  209. memset (&listen_addr, 0, sizeof (listen_addr));
  210. listen_addr.sin_family = AF_INET;
  211. listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
  212. listen_addr.sin_port = 0; /* kernel choses port. */
  213. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  214. == -1)
  215. goto tidy_up_and_fail;
  216. if (listen(listener, 1) == -1)
  217. goto tidy_up_and_fail;
  218. connector = socket(AF_INET, type, 0);
  219. if (connector == -1)
  220. goto tidy_up_and_fail;
  221. /* We want to find out the port number to connect to. */
  222. size = sizeof (connect_addr);
  223. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  224. goto tidy_up_and_fail;
  225. if (size != sizeof (connect_addr))
  226. goto abort_tidy_up_and_fail;
  227. if (connect(connector, (struct sockaddr *) &connect_addr,
  228. sizeof (connect_addr)) == -1)
  229. goto tidy_up_and_fail;
  230. size = sizeof (listen_addr);
  231. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  232. if (acceptor == -1)
  233. goto tidy_up_and_fail;
  234. if (size != sizeof(listen_addr))
  235. goto abort_tidy_up_and_fail;
  236. close(listener);
  237. /* Now check we are talking to ourself by matching port and host on the
  238. two sockets. */
  239. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  240. goto tidy_up_and_fail;
  241. if (size != sizeof (connect_addr)
  242. || listen_addr.sin_family != connect_addr.sin_family
  243. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  244. || listen_addr.sin_port != connect_addr.sin_port) {
  245. goto abort_tidy_up_and_fail;
  246. }
  247. fd[0] = connector;
  248. fd[1] = acceptor;
  249. return 0;
  250. abort_tidy_up_and_fail:
  251. #ifdef MS_WINDOWS
  252. errno = WSAECONNABORTED;
  253. #else
  254. errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  255. #endif
  256. tidy_up_and_fail:
  257. {
  258. int save_errno = errno;
  259. if (listener != -1)
  260. close(listener);
  261. if (connector != -1)
  262. close(connector);
  263. if (acceptor != -1)
  264. close(acceptor);
  265. errno = save_errno;
  266. return -1;
  267. }
  268. #endif
  269. }
  270. #ifdef MS_WINDOWS
  271. int correct_socket_errno(int s)
  272. {
  273. int optval, optvallen=sizeof(optval);
  274. assert(errno == WSAEWOULDBLOCK);
  275. if (getsockopt(s, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  276. return errno;
  277. if (optval)
  278. return optval;
  279. return WSAEWOULDBLOCK;
  280. }
  281. #endif
  282. /*
  283. * Filesystem operations.
  284. */
  285. /* Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  286. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  287. * directory. */
  288. file_status_t file_status(const char *fname)
  289. {
  290. struct stat st;
  291. if (stat(fname, &st)) {
  292. if (errno == ENOENT) {
  293. return FN_NOENT;
  294. }
  295. return FN_ERROR;
  296. }
  297. if (st.st_mode & S_IFDIR)
  298. return FN_DIR;
  299. else if (st.st_mode & S_IFREG)
  300. return FN_FILE;
  301. else
  302. return FN_ERROR;
  303. }
  304. /* Check whether dirname exists and is private. If yes returns
  305. 0. Else returns -1. */
  306. int check_private_dir(const char *dirname, int create)
  307. {
  308. struct stat st;
  309. if (stat(dirname, &st)) {
  310. if (errno != ENOENT) {
  311. log(LOG_WARN, "Directory %s cannot be read: %s", dirname,
  312. strerror(errno));
  313. return -1;
  314. }
  315. if (!create) {
  316. log(LOG_WARN, "Directory %s does not exist.", dirname);
  317. return -1;
  318. }
  319. log(LOG_INFO, "Creating directory %s", dirname);
  320. if (mkdir(dirname, 0700)) {
  321. log(LOG_WARN, "Error creating directory %s: %s", dirname,
  322. strerror(errno));
  323. return -1;
  324. } else {
  325. return 0;
  326. }
  327. }
  328. if (!(st.st_mode & S_IFDIR)) {
  329. log(LOG_WARN, "%s is not a directory", dirname);
  330. return -1;
  331. }
  332. if (st.st_uid != getuid()) {
  333. log(LOG_WARN, "%s is not owned by this UID (%d)", dirname, getuid());
  334. return -1;
  335. }
  336. if (st.st_mode & 0077) {
  337. log(LOG_WARN, "Fixing permissions on directory %s", dirname);
  338. if (chmod(dirname, 0700)) {
  339. log(LOG_WARN, "Could not chmod directory %s: %s", dirname,
  340. strerror(errno));
  341. return -1;
  342. } else {
  343. return 0;
  344. }
  345. }
  346. return 0;
  347. }
  348. int
  349. write_str_to_file(const char *fname, const char *str)
  350. {
  351. char tempname[1024];
  352. int fd;
  353. FILE *file;
  354. if (strlen(fname) > 1000) {
  355. log(LOG_WARN, "Filename %s is too long.", fname);
  356. return -1;
  357. }
  358. strcpy(tempname,fname);
  359. strcat(tempname,".tmp");
  360. if ((fd = open(tempname, O_WRONLY|O_CREAT|O_TRUNC, 0600)) < 0) {
  361. log(LOG_WARN, "Couldn't open %s for writing: %s", tempname,
  362. strerror(errno));
  363. return -1;
  364. }
  365. if (!(file = fdopen(fd, "w"))) {
  366. log(LOG_WARN, "Couldn't fdopen %s for writing: %s", tempname,
  367. strerror(errno));
  368. close(fd); return -1;
  369. }
  370. if (fputs(str,file) == EOF) {
  371. log(LOG_WARN, "Error writing to %s: %s", tempname, strerror(errno));
  372. fclose(file); return -1;
  373. }
  374. fclose(file);
  375. if (rename(tempname, fname)) {
  376. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  377. return -1;
  378. }
  379. return 0;
  380. }
  381. char *read_file_to_str(const char *filename) {
  382. int fd; /* router file */
  383. struct stat statbuf;
  384. char *string;
  385. assert(filename);
  386. if(strcspn(filename,CONFIG_LEGAL_FILENAME_CHARACTERS) != 0) {
  387. log_fn(LOG_WARN,"Filename %s contains illegal characters.",filename);
  388. return NULL;
  389. }
  390. if(stat(filename, &statbuf) < 0) {
  391. log_fn(LOG_INFO,"Could not stat %s.",filename);
  392. return NULL;
  393. }
  394. fd = open(filename,O_RDONLY,0);
  395. if (fd<0) {
  396. log_fn(LOG_WARN,"Could not open %s.",filename);
  397. return NULL;
  398. }
  399. string = tor_malloc(statbuf.st_size+1);
  400. if(read_all(fd,string,statbuf.st_size) != statbuf.st_size) {
  401. log_fn(LOG_WARN,"Couldn't read all %ld bytes of file '%s'.",
  402. (long)statbuf.st_size,filename);
  403. free(string);
  404. close(fd);
  405. return NULL;
  406. }
  407. close(fd);
  408. string[statbuf.st_size] = 0; /* null terminate it */
  409. return string;
  410. }
  411. /* read lines from f (no more than maxlen-1 bytes each) until we
  412. * get one with a well-formed "key value".
  413. * point *key to the first word in line, point *value to the second.
  414. * Put a \0 at the end of key, remove everything at the end of value
  415. * that is whitespace or comment.
  416. * Return 1 if success, 0 if no more lines, -1 if error.
  417. */
  418. int parse_line_from_file(char *line, int maxlen, FILE *f, char **key_out, char **value_out) {
  419. char *s, *key, *end, *value;
  420. try_next_line:
  421. if(!fgets(line, maxlen, f)) {
  422. if(feof(f))
  423. return 0;
  424. return -1; /* real error */
  425. }
  426. if((s = strchr(line,'#'))) /* strip comments */
  427. *s = 0; /* stop the line there */
  428. /* remove end whitespace */
  429. s = strchr(line, 0); /* now we're at the null */
  430. do {
  431. *s = 0;
  432. s--;
  433. } while (isspace(*s));
  434. key = line;
  435. while(isspace(*key))
  436. key++;
  437. if(*key == 0)
  438. goto try_next_line; /* this line has nothing on it */
  439. end = key;
  440. while(*end && !isspace(*end))
  441. end++;
  442. value = end;
  443. while(*value && isspace(*value))
  444. value++;
  445. if(!*end || !*value) { /* only a key on this line. no value. */
  446. log_fn(LOG_WARN,"Line has keyword '%s' but no value. Skipping.",s);
  447. goto try_next_line;
  448. }
  449. *end = 0; /* null it out */
  450. log_fn(LOG_DEBUG,"got keyword '%s', value '%s'", key, value);
  451. *key_out = key, *value_out = value;
  452. return 1;
  453. }
  454. static char uname_result[256];
  455. static int uname_result_is_set = 0;
  456. const char *
  457. get_uname(void)
  458. {
  459. #ifdef HAVE_UNAME
  460. struct utsname u;
  461. #endif
  462. if (!uname_result_is_set) {
  463. #ifdef HAVE_UNAME
  464. if (!uname((&u))) {
  465. snprintf(uname_result, 255, "%s %s %s %s %s",
  466. u.sysname, u.nodename, u.release, u.version, u.machine);
  467. uname_result[255] = '\0';
  468. } else
  469. #endif
  470. {
  471. strcpy(uname_result, "Unknown platform");
  472. }
  473. uname_result_is_set = 1;
  474. }
  475. return uname_result;
  476. }