util.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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, int isSocket) {
  243. size_t written = 0;
  244. int result;
  245. while(written != count) {
  246. if (isSocket)
  247. result = send(fd, buf+written, count-written, 0);
  248. else
  249. result = write(fd, buf+written, count-written);
  250. if(result<0)
  251. return -1;
  252. written += result;
  253. }
  254. return count;
  255. }
  256. /* a wrapper for read(2) that makes sure to read all count bytes.
  257. * Only use if fd is a blocking fd. */
  258. int read_all(int fd, char *buf, size_t count, int isSocket) {
  259. size_t numread = 0;
  260. int result;
  261. while(numread != count) {
  262. if (isSocket)
  263. result = recv(fd, buf+numread, count-numread, 0);
  264. else
  265. result = read(fd, buf+numread, count-numread);
  266. if(result<=0)
  267. return -1;
  268. numread += result;
  269. }
  270. return count;
  271. }
  272. void set_socket_nonblocking(int socket)
  273. {
  274. #ifdef MS_WINDOWS
  275. /* Yes means no and no means yes. Do you not want to be nonblocking? */
  276. int nonblocking = 0;
  277. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  278. #else
  279. fcntl(socket, F_SETFL, O_NONBLOCK);
  280. #endif
  281. }
  282. /*
  283. * Process control
  284. */
  285. /* Minimalist interface to run a void function in the background. On
  286. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  287. * func should not return, but rather should call spawn_exit.
  288. */
  289. int spawn_func(int (*func)(void *), void *data)
  290. {
  291. #ifdef MS_WINDOWS
  292. int rv;
  293. rv = _beginthread(func, 0, data);
  294. if (rv == (unsigned long) -1)
  295. return -1;
  296. return 0;
  297. #else
  298. pid_t pid;
  299. pid = fork();
  300. if (pid<0)
  301. return -1;
  302. if (pid==0) {
  303. /* Child */
  304. func(data);
  305. assert(0); /* Should never reach here. */
  306. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  307. } else {
  308. /* Parent */
  309. return 0;
  310. }
  311. #endif
  312. }
  313. void spawn_exit()
  314. {
  315. #ifdef MS_WINDOWS
  316. _endthread();
  317. #else
  318. exit(0);
  319. #endif
  320. }
  321. /*
  322. * Windows compatibility.
  323. */
  324. int
  325. tor_socketpair(int family, int type, int protocol, int fd[2])
  326. {
  327. #ifdef HAVE_SOCKETPAIR_XXXX
  328. /* For testing purposes, we never fall back to real socketpairs. */
  329. return socketpair(family, type, protocol, fd);
  330. #else
  331. int listener = -1;
  332. int connector = -1;
  333. int acceptor = -1;
  334. struct sockaddr_in listen_addr;
  335. struct sockaddr_in connect_addr;
  336. int size;
  337. if (protocol
  338. #ifdef AF_UNIX
  339. || family != AF_UNIX
  340. #endif
  341. ) {
  342. #ifdef MS_WINDOWS
  343. errno = WSAEAFNOSUPPORT;
  344. #else
  345. errno = EAFNOSUPPORT;
  346. #endif
  347. return -1;
  348. }
  349. if (!fd) {
  350. errno = EINVAL;
  351. return -1;
  352. }
  353. listener = socket(AF_INET, type, 0);
  354. if (listener == -1)
  355. return -1;
  356. memset (&listen_addr, 0, sizeof (listen_addr));
  357. listen_addr.sin_family = AF_INET;
  358. listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
  359. listen_addr.sin_port = 0; /* kernel choses port. */
  360. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  361. == -1)
  362. goto tidy_up_and_fail;
  363. if (listen(listener, 1) == -1)
  364. goto tidy_up_and_fail;
  365. connector = socket(AF_INET, type, 0);
  366. if (connector == -1)
  367. goto tidy_up_and_fail;
  368. /* We want to find out the port number to connect to. */
  369. size = sizeof (connect_addr);
  370. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  371. goto tidy_up_and_fail;
  372. if (size != sizeof (connect_addr))
  373. goto abort_tidy_up_and_fail;
  374. if (connect(connector, (struct sockaddr *) &connect_addr,
  375. sizeof (connect_addr)) == -1)
  376. goto tidy_up_and_fail;
  377. size = sizeof (listen_addr);
  378. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  379. if (acceptor == -1)
  380. goto tidy_up_and_fail;
  381. if (size != sizeof(listen_addr))
  382. goto abort_tidy_up_and_fail;
  383. close(listener);
  384. /* Now check we are talking to ourself by matching port and host on the
  385. two sockets. */
  386. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  387. goto tidy_up_and_fail;
  388. if (size != sizeof (connect_addr)
  389. || listen_addr.sin_family != connect_addr.sin_family
  390. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  391. || listen_addr.sin_port != connect_addr.sin_port) {
  392. goto abort_tidy_up_and_fail;
  393. }
  394. fd[0] = connector;
  395. fd[1] = acceptor;
  396. return 0;
  397. abort_tidy_up_and_fail:
  398. #ifdef MS_WINDOWS
  399. errno = WSAECONNABORTED;
  400. #else
  401. errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  402. #endif
  403. tidy_up_and_fail:
  404. {
  405. int save_errno = errno;
  406. if (listener != -1)
  407. close(listener);
  408. if (connector != -1)
  409. close(connector);
  410. if (acceptor != -1)
  411. close(acceptor);
  412. errno = save_errno;
  413. return -1;
  414. }
  415. #endif
  416. }
  417. #ifdef MS_WINDOWS
  418. int correct_socket_errno(int s)
  419. {
  420. int optval, optvallen=sizeof(optval);
  421. assert(errno == WSAEWOULDBLOCK);
  422. if (getsockopt(s, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  423. return errno;
  424. if (optval)
  425. return optval;
  426. return WSAEWOULDBLOCK;
  427. }
  428. #endif
  429. /*
  430. * Filesystem operations.
  431. */
  432. /* Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  433. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  434. * directory. */
  435. file_status_t file_status(const char *fname)
  436. {
  437. struct stat st;
  438. if (stat(fname, &st)) {
  439. if (errno == ENOENT) {
  440. return FN_NOENT;
  441. }
  442. return FN_ERROR;
  443. }
  444. if (st.st_mode & S_IFDIR)
  445. return FN_DIR;
  446. else if (st.st_mode & S_IFREG)
  447. return FN_FILE;
  448. else
  449. return FN_ERROR;
  450. }
  451. /* Check whether dirname exists and is private. If yes returns
  452. 0. Else returns -1. */
  453. int check_private_dir(const char *dirname, int create)
  454. {
  455. int r;
  456. struct stat st;
  457. if (stat(dirname, &st)) {
  458. if (errno != ENOENT) {
  459. log(LOG_WARN, "Directory %s cannot be read: %s", dirname,
  460. strerror(errno));
  461. return -1;
  462. }
  463. if (!create) {
  464. log(LOG_WARN, "Directory %s does not exist.", dirname);
  465. return -1;
  466. }
  467. log(LOG_INFO, "Creating directory %s", dirname);
  468. #ifdef MS_WINDOWS
  469. r = mkdir(dirname);
  470. #else
  471. r = mkdir(dirname, 0700);
  472. #endif
  473. if (r) {
  474. log(LOG_WARN, "Error creating directory %s: %s", dirname,
  475. strerror(errno));
  476. return -1;
  477. } else {
  478. return 0;
  479. }
  480. }
  481. if (!(st.st_mode & S_IFDIR)) {
  482. log(LOG_WARN, "%s is not a directory", dirname);
  483. return -1;
  484. }
  485. #ifndef MS_WINDOWS
  486. if (st.st_uid != getuid()) {
  487. log(LOG_WARN, "%s is not owned by this UID (%d)", dirname, (int)getuid());
  488. return -1;
  489. }
  490. if (st.st_mode & 0077) {
  491. log(LOG_WARN, "Fixing permissions on directory %s", dirname);
  492. if (chmod(dirname, 0700)) {
  493. log(LOG_WARN, "Could not chmod directory %s: %s", dirname,
  494. strerror(errno));
  495. return -1;
  496. } else {
  497. return 0;
  498. }
  499. }
  500. #endif
  501. return 0;
  502. }
  503. int
  504. write_str_to_file(const char *fname, const char *str)
  505. {
  506. char tempname[1024];
  507. int fd;
  508. FILE *file;
  509. if (strlen(fname) > 1000) {
  510. log(LOG_WARN, "Filename %s is too long.", fname);
  511. return -1;
  512. }
  513. strcpy(tempname,fname);
  514. strcat(tempname,".tmp");
  515. if ((fd = open(tempname, O_WRONLY|O_CREAT|O_TRUNC, 0600)) < 0) {
  516. log(LOG_WARN, "Couldn't open %s for writing: %s", tempname,
  517. strerror(errno));
  518. return -1;
  519. }
  520. if (!(file = fdopen(fd, "w"))) {
  521. log(LOG_WARN, "Couldn't fdopen %s for writing: %s", tempname,
  522. strerror(errno));
  523. close(fd); return -1;
  524. }
  525. if (fputs(str,file) == EOF) {
  526. log(LOG_WARN, "Error writing to %s: %s", tempname, strerror(errno));
  527. fclose(file); return -1;
  528. }
  529. fclose(file);
  530. if (rename(tempname, fname)) {
  531. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  532. return -1;
  533. }
  534. return 0;
  535. }
  536. char *read_file_to_str(const char *filename) {
  537. int fd; /* router file */
  538. struct stat statbuf;
  539. char *string;
  540. assert(filename);
  541. if(strcspn(filename,CONFIG_LEGAL_FILENAME_CHARACTERS) != 0) {
  542. log_fn(LOG_WARN,"Filename %s contains illegal characters.",filename);
  543. return NULL;
  544. }
  545. if(stat(filename, &statbuf) < 0) {
  546. log_fn(LOG_INFO,"Could not stat %s.",filename);
  547. return NULL;
  548. }
  549. fd = open(filename,O_RDONLY,0);
  550. if (fd<0) {
  551. log_fn(LOG_WARN,"Could not open %s.",filename);
  552. return NULL;
  553. }
  554. string = tor_malloc(statbuf.st_size+1);
  555. if(read_all(fd,string,statbuf.st_size,0) != statbuf.st_size) {
  556. log_fn(LOG_WARN,"Couldn't read all %ld bytes of file '%s'.",
  557. (long)statbuf.st_size,filename);
  558. free(string);
  559. close(fd);
  560. return NULL;
  561. }
  562. close(fd);
  563. string[statbuf.st_size] = 0; /* null terminate it */
  564. return string;
  565. }
  566. /* read lines from f (no more than maxlen-1 bytes each) until we
  567. * get a non-whitespace line. If it isn't of the form "key value"
  568. * (value can have spaces), return -1.
  569. * Point *key to the first word in line, point *value * to the second.
  570. * Put a \0 at the end of key, remove everything at the end of value
  571. * that is whitespace or comment.
  572. * Return 1 if success, 0 if no more lines, -1 if error.
  573. */
  574. int parse_line_from_file(char *line, int maxlen, FILE *f, char **key_out, char **value_out) {
  575. char *s, *key, *end, *value;
  576. try_next_line:
  577. if(!fgets(line, maxlen, f)) {
  578. if(feof(f))
  579. return 0;
  580. return -1; /* real error */
  581. }
  582. if((s = strchr(line,'#'))) /* strip comments */
  583. *s = 0; /* stop the line there */
  584. /* remove end whitespace */
  585. s = strchr(line, 0); /* now we're at the null */
  586. do {
  587. *s = 0;
  588. s--;
  589. } while (s >= line && isspace(*s));
  590. key = line;
  591. while(isspace(*key))
  592. key++;
  593. if(*key == 0)
  594. goto try_next_line; /* this line has nothing on it */
  595. end = key;
  596. while(*end && !isspace(*end))
  597. end++;
  598. value = end;
  599. while(*value && isspace(*value))
  600. value++;
  601. if(!*end || !*value) { /* only a key on this line. no value. */
  602. *end = 0;
  603. log_fn(LOG_WARN,"Line has keyword '%s' but no value. Failing.",key);
  604. return -1;
  605. }
  606. *end = 0; /* null it out */
  607. log_fn(LOG_DEBUG,"got keyword '%s', value '%s'", key, value);
  608. *key_out = key, *value_out = value;
  609. return 1;
  610. }
  611. int is_internal_IP(uint32_t ip) {
  612. if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
  613. ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
  614. ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
  615. ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  616. ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  617. ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  618. return 1;
  619. return 0;
  620. }
  621. static char uname_result[256];
  622. static int uname_result_is_set = 0;
  623. const char *
  624. get_uname(void)
  625. {
  626. #ifdef HAVE_UNAME
  627. struct utsname u;
  628. #endif
  629. if (!uname_result_is_set) {
  630. #ifdef HAVE_UNAME
  631. if (!uname((&u))) {
  632. snprintf(uname_result, 255, "%s %s %s",
  633. u.sysname, u.nodename, u.machine);
  634. uname_result[255] = '\0';
  635. } else
  636. #endif
  637. {
  638. strcpy(uname_result, "Unknown platform");
  639. }
  640. uname_result_is_set = 1;
  641. }
  642. return uname_result;
  643. }
  644. #ifndef MS_WINDOWS
  645. /* Based on code contributed by christian grothoff */
  646. static int start_daemon_called = 0;
  647. static int finish_daemon_called = 0;
  648. static int daemon_filedes[2];
  649. void start_daemon(char *desired_cwd)
  650. {
  651. pid_t pid;
  652. if (start_daemon_called)
  653. return;
  654. start_daemon_called = 1;
  655. if(!desired_cwd)
  656. desired_cwd = "/";
  657. /* Don't hold the wrong FS mounted */
  658. if (chdir(desired_cwd) < 0) {
  659. log_fn(LOG_ERR,"chdir to %s failed. Exiting.",desired_cwd);
  660. exit(1);
  661. }
  662. pipe(daemon_filedes);
  663. pid = fork();
  664. if (pid < 0) {
  665. log_fn(LOG_ERR,"fork failed. Exiting.");
  666. exit(1);
  667. }
  668. if (pid) { /* Parent */
  669. int ok;
  670. char c;
  671. close(daemon_filedes[1]); /* we only read */
  672. ok = -1;
  673. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  674. if (c == '.')
  675. ok = 1;
  676. }
  677. fflush(stdout);
  678. if (ok == 1)
  679. exit(0);
  680. else
  681. exit(1); /* child reported error */
  682. } else { /* Child */
  683. close(daemon_filedes[0]); /* we only write */
  684. pid = setsid(); /* Detach from controlling terminal */
  685. /*
  686. * Fork one more time, so the parent (the session group leader) can exit.
  687. * This means that we, as a non-session group leader, can never regain a
  688. * controlling terminal. This part is recommended by Stevens's
  689. * _Advanced Programming in the Unix Environment_.
  690. */
  691. if (fork() != 0) {
  692. exit(0);
  693. }
  694. return;
  695. }
  696. }
  697. void finish_daemon(void)
  698. {
  699. int nullfd;
  700. char c = '.';
  701. if (finish_daemon_called)
  702. return;
  703. if (!start_daemon_called)
  704. start_daemon(NULL);
  705. finish_daemon_called = 1;
  706. nullfd = open("/dev/null",
  707. O_CREAT | O_RDWR | O_APPEND);
  708. if (nullfd < 0) {
  709. log_fn(LOG_ERR,"/dev/null can't be opened. Exiting.");
  710. exit(1);
  711. }
  712. /* close fds linking to invoking terminal, but
  713. * close usual incoming fds, but redirect them somewhere
  714. * useful so the fds don't get reallocated elsewhere.
  715. */
  716. if (dup2(nullfd,0) < 0 ||
  717. dup2(nullfd,1) < 0 ||
  718. dup2(nullfd,2) < 0) {
  719. log_fn(LOG_ERR,"dup2 failed. Exiting.");
  720. exit(1);
  721. }
  722. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  723. close(daemon_filedes[1]);
  724. }
  725. #else
  726. /* defined(MS_WINDOWS) */
  727. void start_daemon(char *cp) {}
  728. void finish_daemon(void) {}
  729. #endif
  730. void write_pidfile(char *filename) {
  731. #ifndef MS_WINDOWS
  732. FILE *pidfile;
  733. if ((pidfile = fopen(filename, "w")) == NULL) {
  734. log_fn(LOG_WARN, "unable to open %s for writing: %s", filename,
  735. strerror(errno));
  736. } else {
  737. fprintf(pidfile, "%d", getpid());
  738. fclose(pidfile);
  739. }
  740. #endif
  741. }
  742. int switch_id(char *user, char *group) {
  743. #ifndef MS_WINDOWS
  744. struct passwd *pw = NULL;
  745. struct group *gr = NULL;
  746. if (user) {
  747. pw = getpwnam(user);
  748. if (pw == NULL) {
  749. log_fn(LOG_ERR,"User '%s' not found.", user);
  750. return -1;
  751. }
  752. }
  753. /* switch the group first, while we still have the privileges to do so */
  754. if (group) {
  755. gr = getgrnam(group);
  756. if (gr == NULL) {
  757. log_fn(LOG_ERR,"Group '%s' not found.", group);
  758. return -1;
  759. }
  760. if (setgid(gr->gr_gid) != 0) {
  761. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  762. return -1;
  763. }
  764. } else if (user) {
  765. if (setgid(pw->pw_gid) != 0) {
  766. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  767. return -1;
  768. }
  769. }
  770. /* now that the group is switched, we can switch users and lose
  771. privileges */
  772. if (user) {
  773. if (setuid(pw->pw_uid) != 0) {
  774. log_fn(LOG_ERR,"Error setting UID: %s", strerror(errno));
  775. return -1;
  776. }
  777. }
  778. return 0;
  779. #endif
  780. log_fn(LOG_ERR,
  781. "User or group specified, but switching users is not supported.");
  782. return -1;
  783. }
  784. int tor_inet_aton(const char *c, struct in_addr* addr)
  785. {
  786. #ifdef HAVE_INET_ATON
  787. return inet_aton(c, addr);
  788. #else
  789. uint32_t r;
  790. assert(c && addr);
  791. if (strcmp(c, "255.255.255.255") == 0) {
  792. addr->s_addr = 0xFFFFFFFFu;
  793. return 1;
  794. }
  795. r = inet_addr(c);
  796. if (r == INADDR_NONE)
  797. return 0;
  798. addr->s_addr = r;
  799. return 1;
  800. #endif
  801. }