util.c 31 KB

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