util.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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. /* used by inet_addr, not defined on solaris anywhere!? */
  9. #ifndef INADDR_NONE
  10. #define INADDR_NONE ((unsigned long) -1)
  11. #endif
  12. /* in-line the strl functions */
  13. #ifndef HAVE_STRLCPY
  14. #include "strlcpy.c"
  15. #endif
  16. #ifndef HAVE_STRLCAT
  17. #include "strlcat.c"
  18. #endif
  19. /*
  20. * Memory wrappers
  21. */
  22. void *tor_malloc(size_t size) {
  23. void *result;
  24. result = malloc(size);
  25. if(!result) {
  26. log_fn(LOG_ERR, "Out of memory. Dying.");
  27. exit(1);
  28. }
  29. // memset(result,'X',size); /* deadbeef to encourage bugs */
  30. return result;
  31. }
  32. void *tor_malloc_zero(size_t size) {
  33. void *result = tor_malloc(size);
  34. memset(result, 0, size);
  35. return result;
  36. }
  37. void *tor_realloc(void *ptr, size_t size) {
  38. void *result;
  39. result = realloc(ptr, size);
  40. if (!result) {
  41. log_fn(LOG_ERR, "Out of memory. Dying.");
  42. exit(1);
  43. }
  44. return result;
  45. }
  46. char *tor_strdup(const char *s) {
  47. char *dup;
  48. assert(s);
  49. dup = strdup(s);
  50. if(!dup) {
  51. log_fn(LOG_ERR,"Out of memory. Dying.");
  52. exit(1);
  53. }
  54. return dup;
  55. }
  56. char *tor_strndup(const char *s, size_t n) {
  57. char *dup;
  58. assert(s);
  59. dup = tor_malloc(n+1);
  60. strncpy(dup, s, n);
  61. dup[n] = 0;
  62. return dup;
  63. }
  64. /*
  65. * A simple smartlist interface to make an unordered list of acceptable
  66. * nodes and then choose a random one.
  67. * smartlist_create() mallocs the list, _free() frees the list,
  68. * _add() adds an element, _remove() removes an element if it's there,
  69. * _choose() returns a random element.
  70. */
  71. smartlist_t *smartlist_create(int max_elements) {
  72. smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
  73. sl->list = tor_malloc(sizeof(void *) * max_elements);
  74. sl->num_used = 0;
  75. sl->max = max_elements;
  76. return sl;
  77. }
  78. void smartlist_free(smartlist_t *sl) {
  79. free(sl->list);
  80. free(sl);
  81. }
  82. /* add element to the list, but only if there's room */
  83. void smartlist_add(smartlist_t *sl, void *element) {
  84. if(sl->num_used < sl->max)
  85. sl->list[sl->num_used++] = element;
  86. else
  87. log_fn(LOG_WARN,"We've already got %d elements, discarding.",sl->max);
  88. }
  89. void smartlist_remove(smartlist_t *sl, void *element) {
  90. int i;
  91. if(element == NULL)
  92. return;
  93. for(i=0; i < sl->num_used; i++)
  94. if(sl->list[i] == element) {
  95. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  96. i--; /* so we process the new i'th element */
  97. }
  98. }
  99. int smartlist_isin(smartlist_t *sl, void *element) {
  100. int i;
  101. for(i=0; i < sl->num_used; i++)
  102. if(sl->list[i] == element)
  103. return 1;
  104. return 0;
  105. }
  106. int smartlist_overlap(smartlist_t *sl1, smartlist_t *sl2) {
  107. int i;
  108. for(i=0; i < sl2->num_used; i++)
  109. if(smartlist_isin(sl1, sl2->list[i]))
  110. return 1;
  111. return 0;
  112. }
  113. /* remove elements of sl1 that aren't in sl2 */
  114. void smartlist_intersect(smartlist_t *sl1, smartlist_t *sl2) {
  115. int i;
  116. for(i=0; i < sl1->num_used; i++)
  117. if(!smartlist_isin(sl2, sl1->list[i])) {
  118. sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
  119. i--; /* so we process the new i'th element */
  120. }
  121. }
  122. /* remove all elements of sl2 from sl1 */
  123. void smartlist_subtract(smartlist_t *sl1, smartlist_t *sl2) {
  124. int i;
  125. for(i=0; i < sl2->num_used; i++)
  126. smartlist_remove(sl1, sl2->list[i]);
  127. }
  128. void *smartlist_choose(smartlist_t *sl) {
  129. if(sl->num_used)
  130. return sl->list[crypto_pseudo_rand_int(sl->num_used)];
  131. return NULL; /* no elements to choose from */
  132. }
  133. /*
  134. * String manipulation
  135. */
  136. /* return the first char of s that is not whitespace and not a comment */
  137. const char *eat_whitespace(const char *s) {
  138. assert(s);
  139. while(isspace((int)*s) || *s == '#') {
  140. while(isspace((int)*s))
  141. s++;
  142. if(*s == '#') { /* read to a \n or \0 */
  143. while(*s && *s != '\n')
  144. s++;
  145. if(!*s)
  146. return s;
  147. }
  148. }
  149. return s;
  150. }
  151. const char *eat_whitespace_no_nl(const char *s) {
  152. while(*s == ' ' || *s == '\t')
  153. ++s;
  154. return s;
  155. }
  156. /* return the first char of s that is whitespace or '#' or '\0 */
  157. const char *find_whitespace(const char *s) {
  158. assert(s);
  159. while(*s && !isspace((int)*s) && *s != '#')
  160. s++;
  161. return s;
  162. }
  163. /*
  164. * Time
  165. */
  166. void tor_gettimeofday(struct timeval *timeval) {
  167. #ifdef HAVE_GETTIMEOFDAY
  168. if (gettimeofday(timeval, NULL)) {
  169. log_fn(LOG_ERR, "gettimeofday failed.");
  170. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  171. or segfaulted.*/
  172. exit(1);
  173. }
  174. #elif defined(HAVE_FTIME)
  175. ftime(timeval);
  176. #else
  177. #error "No way to get time."
  178. #endif
  179. return;
  180. }
  181. long
  182. tv_udiff(struct timeval *start, struct timeval *end)
  183. {
  184. long udiff;
  185. long secdiff = end->tv_sec - start->tv_sec;
  186. if (secdiff+1 > LONG_MAX/1000000) {
  187. log_fn(LOG_WARN, "comparing times too far apart.");
  188. return LONG_MAX;
  189. }
  190. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  191. if(udiff < 0) {
  192. log_fn(LOG_INFO, "start (%ld.%ld) is after end (%ld.%ld). Returning 0.",
  193. (long)start->tv_sec, (long)start->tv_usec, (long)end->tv_sec, (long)end->tv_usec);
  194. return 0;
  195. }
  196. return udiff;
  197. }
  198. int tv_cmp(struct timeval *a, struct timeval *b) {
  199. if (a->tv_sec > b->tv_sec)
  200. return 1;
  201. if (a->tv_sec < b->tv_sec)
  202. return -1;
  203. if (a->tv_usec > b->tv_usec)
  204. return 1;
  205. if (a->tv_usec < b->tv_usec)
  206. return -1;
  207. return 0;
  208. }
  209. void tv_add(struct timeval *a, struct timeval *b) {
  210. a->tv_usec += b->tv_usec;
  211. a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
  212. a->tv_usec %= 1000000;
  213. }
  214. void tv_addms(struct timeval *a, long ms) {
  215. a->tv_usec += (ms * 1000) % 1000000;
  216. a->tv_sec += ((ms * 1000) / 1000000) + (a->tv_usec / 1000000);
  217. a->tv_usec %= 1000000;
  218. }
  219. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  220. static int n_leapdays(int y1, int y2) {
  221. --y1;
  222. --y2;
  223. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  224. }
  225. static const int days_per_month[] =
  226. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  227. time_t tor_timegm (struct tm *tm) {
  228. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  229. * It's way more brute-force than fiddling with tzset().
  230. */
  231. time_t ret;
  232. unsigned long year, days, hours, minutes;
  233. int i;
  234. year = tm->tm_year + 1900;
  235. assert(year >= 1970);
  236. assert(tm->tm_mon >= 0 && tm->tm_mon <= 11);
  237. days = 365 * (year-1970) + n_leapdays(1970,year);
  238. for (i = 0; i < tm->tm_mon; ++i)
  239. days += days_per_month[i];
  240. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  241. ++days;
  242. days += tm->tm_mday - 1;
  243. hours = days*24 + tm->tm_hour;
  244. minutes = hours*60 + tm->tm_min;
  245. ret = minutes*60 + tm->tm_sec;
  246. return ret;
  247. }
  248. /*
  249. * Low-level I/O.
  250. */
  251. /* a wrapper for write(2) that makes sure to write all count bytes.
  252. * Only use if fd is a blocking fd. */
  253. int write_all(int fd, const char *buf, size_t count, int isSocket) {
  254. size_t written = 0;
  255. int result;
  256. while(written != count) {
  257. if (isSocket)
  258. result = send(fd, buf+written, count-written, 0);
  259. else
  260. result = write(fd, buf+written, count-written);
  261. if(result<0)
  262. return -1;
  263. written += result;
  264. }
  265. return count;
  266. }
  267. /* a wrapper for read(2) that makes sure to read all count bytes.
  268. * Only use if fd is a blocking fd. */
  269. int read_all(int fd, char *buf, size_t count, int isSocket) {
  270. size_t numread = 0;
  271. int result;
  272. while(numread != count) {
  273. if (isSocket)
  274. result = recv(fd, buf+numread, count-numread, 0);
  275. else
  276. result = read(fd, buf+numread, count-numread);
  277. if(result<=0)
  278. return -1;
  279. numread += result;
  280. }
  281. return count;
  282. }
  283. void set_socket_nonblocking(int socket)
  284. {
  285. #ifdef MS_WINDOWS
  286. /* Yes means no and no means yes. Do you not want to be nonblocking? */
  287. int nonblocking = 0;
  288. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  289. #else
  290. fcntl(socket, F_SETFL, O_NONBLOCK);
  291. #endif
  292. }
  293. /*
  294. * Process control
  295. */
  296. /* Minimalist interface to run a void function in the background. On
  297. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  298. * func should not return, but rather should call spawn_exit.
  299. */
  300. int spawn_func(int (*func)(void *), void *data)
  301. {
  302. #ifdef MS_WINDOWS
  303. int rv;
  304. rv = _beginthread(func, 0, data);
  305. if (rv == (unsigned long) -1)
  306. return -1;
  307. return 0;
  308. #else
  309. pid_t pid;
  310. pid = fork();
  311. if (pid<0)
  312. return -1;
  313. if (pid==0) {
  314. /* Child */
  315. func(data);
  316. assert(0); /* Should never reach here. */
  317. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  318. } else {
  319. /* Parent */
  320. return 0;
  321. }
  322. #endif
  323. }
  324. void spawn_exit()
  325. {
  326. #ifdef MS_WINDOWS
  327. _endthread();
  328. #else
  329. exit(0);
  330. #endif
  331. }
  332. /*
  333. * Windows compatibility.
  334. */
  335. int
  336. tor_socketpair(int family, int type, int protocol, int fd[2])
  337. {
  338. #ifdef HAVE_SOCKETPAIR_XXXX
  339. /* For testing purposes, we never fall back to real socketpairs. */
  340. return socketpair(family, type, protocol, fd);
  341. #else
  342. int listener = -1;
  343. int connector = -1;
  344. int acceptor = -1;
  345. struct sockaddr_in listen_addr;
  346. struct sockaddr_in connect_addr;
  347. int size;
  348. if (protocol
  349. #ifdef AF_UNIX
  350. || family != AF_UNIX
  351. #endif
  352. ) {
  353. #ifdef MS_WINDOWS
  354. errno = WSAEAFNOSUPPORT;
  355. #else
  356. errno = EAFNOSUPPORT;
  357. #endif
  358. return -1;
  359. }
  360. if (!fd) {
  361. errno = EINVAL;
  362. return -1;
  363. }
  364. listener = socket(AF_INET, type, 0);
  365. if (listener == -1)
  366. return -1;
  367. memset (&listen_addr, 0, sizeof (listen_addr));
  368. listen_addr.sin_family = AF_INET;
  369. listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
  370. listen_addr.sin_port = 0; /* kernel choses port. */
  371. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  372. == -1)
  373. goto tidy_up_and_fail;
  374. if (listen(listener, 1) == -1)
  375. goto tidy_up_and_fail;
  376. connector = socket(AF_INET, type, 0);
  377. if (connector == -1)
  378. goto tidy_up_and_fail;
  379. /* We want to find out the port number to connect to. */
  380. size = sizeof (connect_addr);
  381. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  382. goto tidy_up_and_fail;
  383. if (size != sizeof (connect_addr))
  384. goto abort_tidy_up_and_fail;
  385. if (connect(connector, (struct sockaddr *) &connect_addr,
  386. sizeof (connect_addr)) == -1)
  387. goto tidy_up_and_fail;
  388. size = sizeof (listen_addr);
  389. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  390. if (acceptor == -1)
  391. goto tidy_up_and_fail;
  392. if (size != sizeof(listen_addr))
  393. goto abort_tidy_up_and_fail;
  394. close(listener);
  395. /* Now check we are talking to ourself by matching port and host on the
  396. two sockets. */
  397. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  398. goto tidy_up_and_fail;
  399. if (size != sizeof (connect_addr)
  400. || listen_addr.sin_family != connect_addr.sin_family
  401. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  402. || listen_addr.sin_port != connect_addr.sin_port) {
  403. goto abort_tidy_up_and_fail;
  404. }
  405. fd[0] = connector;
  406. fd[1] = acceptor;
  407. return 0;
  408. abort_tidy_up_and_fail:
  409. #ifdef MS_WINDOWS
  410. errno = WSAECONNABORTED;
  411. #else
  412. errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  413. #endif
  414. tidy_up_and_fail:
  415. {
  416. int save_errno = errno;
  417. if (listener != -1)
  418. close(listener);
  419. if (connector != -1)
  420. close(connector);
  421. if (acceptor != -1)
  422. close(acceptor);
  423. errno = save_errno;
  424. return -1;
  425. }
  426. #endif
  427. }
  428. #ifdef MS_WINDOWS
  429. int correct_socket_errno(int s)
  430. {
  431. int optval, optvallen=sizeof(optval);
  432. assert(errno == WSAEWOULDBLOCK);
  433. if (getsockopt(s, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  434. return errno;
  435. if (optval)
  436. return optval;
  437. return WSAEWOULDBLOCK;
  438. }
  439. #endif
  440. /*
  441. * Filesystem operations.
  442. */
  443. /* Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  444. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  445. * directory. */
  446. file_status_t file_status(const char *fname)
  447. {
  448. struct stat st;
  449. if (stat(fname, &st)) {
  450. if (errno == ENOENT) {
  451. return FN_NOENT;
  452. }
  453. return FN_ERROR;
  454. }
  455. if (st.st_mode & S_IFDIR)
  456. return FN_DIR;
  457. else if (st.st_mode & S_IFREG)
  458. return FN_FILE;
  459. else
  460. return FN_ERROR;
  461. }
  462. /* Check whether dirname exists and is private. If yes returns
  463. 0. Else returns -1. */
  464. int check_private_dir(const char *dirname, int create)
  465. {
  466. int r;
  467. struct stat st;
  468. if (stat(dirname, &st)) {
  469. if (errno != ENOENT) {
  470. log(LOG_WARN, "Directory %s cannot be read: %s", dirname,
  471. strerror(errno));
  472. return -1;
  473. }
  474. if (!create) {
  475. log(LOG_WARN, "Directory %s does not exist.", dirname);
  476. return -1;
  477. }
  478. log(LOG_INFO, "Creating directory %s", dirname);
  479. #ifdef MS_WINDOWS
  480. r = mkdir(dirname);
  481. #else
  482. r = mkdir(dirname, 0700);
  483. #endif
  484. if (r) {
  485. log(LOG_WARN, "Error creating directory %s: %s", dirname,
  486. strerror(errno));
  487. return -1;
  488. } else {
  489. return 0;
  490. }
  491. }
  492. if (!(st.st_mode & S_IFDIR)) {
  493. log(LOG_WARN, "%s is not a directory", dirname);
  494. return -1;
  495. }
  496. #ifndef MS_WINDOWS
  497. if (st.st_uid != getuid()) {
  498. log(LOG_WARN, "%s is not owned by this UID (%d)", dirname, (int)getuid());
  499. return -1;
  500. }
  501. if (st.st_mode & 0077) {
  502. log(LOG_WARN, "Fixing permissions on directory %s", dirname);
  503. if (chmod(dirname, 0700)) {
  504. log(LOG_WARN, "Could not chmod directory %s: %s", dirname,
  505. strerror(errno));
  506. return -1;
  507. } else {
  508. return 0;
  509. }
  510. }
  511. #endif
  512. return 0;
  513. }
  514. int
  515. write_str_to_file(const char *fname, const char *str)
  516. {
  517. char tempname[1024];
  518. int fd;
  519. FILE *file;
  520. if ((strlcpy(tempname,fname,1024) >= 1024) ||
  521. (strlcat(tempname,".tmp",1024) >= 1024)) {
  522. log(LOG_WARN, "Filename %s.tmp too long (>1024 chars)", fname);
  523. return -1;
  524. }
  525. if ((fd = open(tempname, O_WRONLY|O_CREAT|O_TRUNC, 0600)) < 0) {
  526. log(LOG_WARN, "Couldn't open %s for writing: %s", tempname,
  527. strerror(errno));
  528. return -1;
  529. }
  530. if (!(file = fdopen(fd, "w"))) {
  531. log(LOG_WARN, "Couldn't fdopen %s for writing: %s", tempname,
  532. strerror(errno));
  533. close(fd); return -1;
  534. }
  535. if (fputs(str,file) == EOF) {
  536. log(LOG_WARN, "Error writing to %s: %s", tempname, strerror(errno));
  537. fclose(file); return -1;
  538. }
  539. fclose(file);
  540. if (rename(tempname, fname)) {
  541. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  542. return -1;
  543. }
  544. return 0;
  545. }
  546. char *read_file_to_str(const char *filename) {
  547. int fd; /* router file */
  548. struct stat statbuf;
  549. char *string;
  550. assert(filename);
  551. if(strcspn(filename,CONFIG_LEGAL_FILENAME_CHARACTERS) != 0) {
  552. log_fn(LOG_WARN,"Filename %s contains illegal characters.",filename);
  553. return NULL;
  554. }
  555. if(stat(filename, &statbuf) < 0) {
  556. log_fn(LOG_INFO,"Could not stat %s.",filename);
  557. return NULL;
  558. }
  559. fd = open(filename,O_RDONLY,0);
  560. if (fd<0) {
  561. log_fn(LOG_WARN,"Could not open %s.",filename);
  562. return NULL;
  563. }
  564. string = tor_malloc(statbuf.st_size+1);
  565. if(read_all(fd,string,statbuf.st_size,0) != statbuf.st_size) {
  566. log_fn(LOG_WARN,"Couldn't read all %ld bytes of file '%s'.",
  567. (long)statbuf.st_size,filename);
  568. free(string);
  569. close(fd);
  570. return NULL;
  571. }
  572. close(fd);
  573. string[statbuf.st_size] = 0; /* null terminate it */
  574. return string;
  575. }
  576. /* read lines from f (no more than maxlen-1 bytes each) until we
  577. * get a non-whitespace line. If it isn't of the form "key value"
  578. * (value can have spaces), return -1.
  579. * Point *key to the first word in line, point *value * to the second.
  580. * Put a \0 at the end of key, remove everything at the end of value
  581. * that is whitespace or comment.
  582. * Return 1 if success, 0 if no more lines, -1 if error.
  583. */
  584. int parse_line_from_file(char *line, int maxlen, FILE *f, char **key_out, char **value_out) {
  585. char *s, *key, *end, *value;
  586. try_next_line:
  587. if(!fgets(line, maxlen, f)) {
  588. if(feof(f))
  589. return 0;
  590. return -1; /* real error */
  591. }
  592. if((s = strchr(line,'#'))) /* strip comments */
  593. *s = 0; /* stop the line there */
  594. /* remove end whitespace */
  595. s = strchr(line, 0); /* now we're at the null */
  596. do {
  597. *s = 0;
  598. s--;
  599. } while (s >= line && isspace((int)*s));
  600. key = line;
  601. while(isspace((int)*key))
  602. key++;
  603. if(*key == 0)
  604. goto try_next_line; /* this line has nothing on it */
  605. end = key;
  606. while(*end && !isspace((int)*end))
  607. end++;
  608. value = end;
  609. while(*value && isspace((int)*value))
  610. value++;
  611. if(!*end || !*value) { /* only a key on this line. no value. */
  612. *end = 0;
  613. log_fn(LOG_WARN,"Line has keyword '%s' but no value. Failing.",key);
  614. return -1;
  615. }
  616. *end = 0; /* null it out */
  617. log_fn(LOG_DEBUG,"got keyword '%s', value '%s'", key, value);
  618. *key_out = key, *value_out = value;
  619. return 1;
  620. }
  621. int is_internal_IP(uint32_t ip) {
  622. if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
  623. ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
  624. ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
  625. ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  626. ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  627. ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  628. return 1;
  629. return 0;
  630. }
  631. static char uname_result[256];
  632. static int uname_result_is_set = 0;
  633. const char *
  634. get_uname(void)
  635. {
  636. #ifdef HAVE_UNAME
  637. struct utsname u;
  638. #endif
  639. if (!uname_result_is_set) {
  640. #ifdef HAVE_UNAME
  641. if (!uname((&u))) {
  642. snprintf(uname_result, 255, "%s %s %s",
  643. u.sysname, u.nodename, u.machine);
  644. uname_result[255] = '\0';
  645. } else
  646. #endif
  647. {
  648. strcpy(uname_result, "Unknown platform");
  649. }
  650. uname_result_is_set = 1;
  651. }
  652. return uname_result;
  653. }
  654. #ifndef MS_WINDOWS
  655. /* Based on code contributed by christian grothoff */
  656. static int start_daemon_called = 0;
  657. static int finish_daemon_called = 0;
  658. static int daemon_filedes[2];
  659. void start_daemon(char *desired_cwd)
  660. {
  661. pid_t pid;
  662. if (start_daemon_called)
  663. return;
  664. start_daemon_called = 1;
  665. if(!desired_cwd)
  666. desired_cwd = "/";
  667. /* Don't hold the wrong FS mounted */
  668. if (chdir(desired_cwd) < 0) {
  669. log_fn(LOG_ERR,"chdir to %s failed. Exiting.",desired_cwd);
  670. exit(1);
  671. }
  672. pipe(daemon_filedes);
  673. pid = fork();
  674. if (pid < 0) {
  675. log_fn(LOG_ERR,"fork failed. Exiting.");
  676. exit(1);
  677. }
  678. if (pid) { /* Parent */
  679. int ok;
  680. char c;
  681. close(daemon_filedes[1]); /* we only read */
  682. ok = -1;
  683. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  684. if (c == '.')
  685. ok = 1;
  686. }
  687. fflush(stdout);
  688. if (ok == 1)
  689. exit(0);
  690. else
  691. exit(1); /* child reported error */
  692. } else { /* Child */
  693. close(daemon_filedes[0]); /* we only write */
  694. pid = setsid(); /* Detach from controlling terminal */
  695. /*
  696. * Fork one more time, so the parent (the session group leader) can exit.
  697. * This means that we, as a non-session group leader, can never regain a
  698. * controlling terminal. This part is recommended by Stevens's
  699. * _Advanced Programming in the Unix Environment_.
  700. */
  701. if (fork() != 0) {
  702. exit(0);
  703. }
  704. return;
  705. }
  706. }
  707. void finish_daemon(void)
  708. {
  709. int nullfd;
  710. char c = '.';
  711. if (finish_daemon_called)
  712. return;
  713. if (!start_daemon_called)
  714. start_daemon(NULL);
  715. finish_daemon_called = 1;
  716. nullfd = open("/dev/null",
  717. O_CREAT | O_RDWR | O_APPEND);
  718. if (nullfd < 0) {
  719. log_fn(LOG_ERR,"/dev/null can't be opened. Exiting.");
  720. exit(1);
  721. }
  722. /* close fds linking to invoking terminal, but
  723. * close usual incoming fds, but redirect them somewhere
  724. * useful so the fds don't get reallocated elsewhere.
  725. */
  726. if (dup2(nullfd,0) < 0 ||
  727. dup2(nullfd,1) < 0 ||
  728. dup2(nullfd,2) < 0) {
  729. log_fn(LOG_ERR,"dup2 failed. Exiting.");
  730. exit(1);
  731. }
  732. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  733. close(daemon_filedes[1]);
  734. }
  735. #else
  736. /* defined(MS_WINDOWS) */
  737. void start_daemon(char *cp) {}
  738. void finish_daemon(void) {}
  739. #endif
  740. void write_pidfile(char *filename) {
  741. #ifndef MS_WINDOWS
  742. FILE *pidfile;
  743. if ((pidfile = fopen(filename, "w")) == NULL) {
  744. log_fn(LOG_WARN, "unable to open %s for writing: %s", filename,
  745. strerror(errno));
  746. } else {
  747. fprintf(pidfile, "%d", (int)getpid());
  748. fclose(pidfile);
  749. }
  750. #endif
  751. }
  752. int switch_id(char *user, char *group) {
  753. #ifndef MS_WINDOWS
  754. struct passwd *pw = NULL;
  755. struct group *gr = NULL;
  756. if (user) {
  757. pw = getpwnam(user);
  758. if (pw == NULL) {
  759. log_fn(LOG_ERR,"User '%s' not found.", user);
  760. return -1;
  761. }
  762. }
  763. /* switch the group first, while we still have the privileges to do so */
  764. if (group) {
  765. gr = getgrnam(group);
  766. if (gr == NULL) {
  767. log_fn(LOG_ERR,"Group '%s' not found.", group);
  768. return -1;
  769. }
  770. if (setgid(gr->gr_gid) != 0) {
  771. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  772. return -1;
  773. }
  774. } else if (user) {
  775. if (setgid(pw->pw_gid) != 0) {
  776. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  777. return -1;
  778. }
  779. }
  780. /* now that the group is switched, we can switch users and lose
  781. privileges */
  782. if (user) {
  783. if (setuid(pw->pw_uid) != 0) {
  784. log_fn(LOG_ERR,"Error setting UID: %s", strerror(errno));
  785. return -1;
  786. }
  787. }
  788. return 0;
  789. #endif
  790. log_fn(LOG_ERR,
  791. "User or group specified, but switching users is not supported.");
  792. return -1;
  793. }
  794. int tor_inet_aton(const char *c, struct in_addr* addr)
  795. {
  796. #ifdef HAVE_INET_ATON
  797. return inet_aton(c, addr);
  798. #else
  799. uint32_t r;
  800. assert(c && addr);
  801. if (strcmp(c, "255.255.255.255") == 0) {
  802. addr->s_addr = 0xFFFFFFFFu;
  803. return 1;
  804. }
  805. r = inet_addr(c);
  806. if (r == INADDR_NONE)
  807. return 0;
  808. addr->s_addr = r;
  809. return 1;
  810. #endif
  811. }