util.c 12 KB

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