util.c 27 KB

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