util.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602
  1. /* Copyright 2003 Roger Dingledine */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /*****
  5. * util.c: Common functions for strings, IO, network, data structures,
  6. * process control, and cross-platform portability.
  7. *****/
  8. #include "orconfig.h"
  9. #ifdef MS_WINDOWS
  10. #define WIN32_WINNT 0x400
  11. #define _WIN32_WINNT 0x400
  12. #define WIN32_LEAN_AND_MEAN
  13. #if _MSC_VER > 1300
  14. #include <winsock2.h>
  15. #include <ws2tcpip.h>
  16. #elif defined(_MSC_VER)
  17. #include <winsock.h>
  18. #endif
  19. #include <io.h>
  20. #include <process.h>
  21. #include <direct.h>
  22. #include <windows.h>
  23. #endif
  24. #include <stdlib.h>
  25. #include <stdio.h>
  26. #include <string.h>
  27. #include <assert.h>
  28. #include "util.h"
  29. #include "log.h"
  30. #include "crypto.h"
  31. #include "../or/tree.h"
  32. #ifdef HAVE_UNAME
  33. #include <sys/utsname.h>
  34. #endif
  35. #ifdef HAVE_CTYPE_H
  36. #include <ctype.h>
  37. #endif
  38. #ifdef HAVE_NETINET_IN_H
  39. #include <netinet/in.h>
  40. #endif
  41. #ifdef HAVE_ARPA_INET_H
  42. #include <arpa/inet.h>
  43. #endif
  44. #ifdef HAVE_ERRNO_H
  45. #include <errno.h>
  46. #endif
  47. #ifdef HAVE_LIMITS_H
  48. #include <limits.h>
  49. #endif
  50. #ifdef HAVE_SYS_LIMITS_H
  51. #include <sys/limits.h>
  52. #endif
  53. #ifdef HAVE_MACHINE_LIMITS_H
  54. #include <machine/limits.h>
  55. #endif
  56. #ifdef HAVE_SYS_TYPES_H
  57. #include <sys/types.h> /* Must be included before sys/stat.h for Ultrix */
  58. #endif
  59. #ifdef HAVE_SYS_SOCKET_H
  60. #include <sys/socket.h>
  61. #endif
  62. #ifdef HAVE_NETDB_H
  63. #include <netdb.h>
  64. #endif
  65. #ifdef HAVE_UNISTD_H
  66. #include <unistd.h>
  67. #endif
  68. #ifdef HAVE_SYS_STAT_H
  69. #include <sys/stat.h>
  70. #endif
  71. #ifdef HAVE_SYS_FCNTL_H
  72. #include <sys/fcntl.h>
  73. #endif
  74. #ifdef HAVE_PWD_H
  75. #include <pwd.h>
  76. #endif
  77. #ifdef HAVE_GRP_H
  78. #include <grp.h>
  79. #endif
  80. #ifdef HAVE_FCNTL_H
  81. #include <fcntl.h>
  82. #endif
  83. /* used by inet_addr, not defined on solaris anywhere!? */
  84. #ifndef INADDR_NONE
  85. #define INADDR_NONE ((unsigned long) -1)
  86. #endif
  87. /* Inline the strl functions if the plaform doesn't have them. */
  88. #ifndef HAVE_STRLCPY
  89. #include "strlcpy.c"
  90. #endif
  91. #ifndef HAVE_STRLCAT
  92. #include "strlcat.c"
  93. #endif
  94. /*****
  95. * Memory wrappers
  96. *****/
  97. /* Allocate a chunk of 'size' bytes of memory, and return a pointer to
  98. * result. On error, log and terminate the process. (Same as malloc(size),
  99. * but never returns NULL.)
  100. */
  101. void *tor_malloc(size_t size) {
  102. void *result;
  103. /* Some libcs don't do the right thing on size==0. Override them. */
  104. if (size==0) {
  105. size=1;
  106. }
  107. result = malloc(size);
  108. if(!result) {
  109. log_fn(LOG_ERR, "Out of memory. Dying.");
  110. exit(1);
  111. }
  112. // memset(result,'X',size); /* deadbeef to encourage bugs */
  113. return result;
  114. }
  115. /* Allocate a chunk of 'size' bytes of memory, fill the memory with
  116. * zero bytes, and return a pointer to the result. Log and terminate
  117. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  118. */
  119. void *tor_malloc_zero(size_t size) {
  120. void *result = tor_malloc(size);
  121. memset(result, 0, size);
  122. return result;
  123. }
  124. /* Change the size of the memory block pointed to by 'ptr' to 'size'
  125. * bytes long; return the new memory block. On error, log and
  126. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  127. */
  128. void *tor_realloc(void *ptr, size_t size) {
  129. void *result;
  130. result = realloc(ptr, size);
  131. if (!result) {
  132. log_fn(LOG_ERR, "Out of memory. Dying.");
  133. exit(1);
  134. }
  135. return result;
  136. }
  137. /* Return a newly allocated copy of the NUL-terminated string s. On
  138. * error, log and terminate. (Like strdup(s), but never returns
  139. * NULL.)
  140. */
  141. char *tor_strdup(const char *s) {
  142. char *dup;
  143. tor_assert(s);
  144. dup = strdup(s);
  145. if(!dup) {
  146. log_fn(LOG_ERR,"Out of memory. Dying.");
  147. exit(1);
  148. }
  149. return dup;
  150. }
  151. /* Allocate and return a new string containing the first 'n'
  152. * characters of 's'. If 's' is longer than 'n' characters, only the
  153. * first 'n' are copied. The result is always NUL-terminated. (Like
  154. * strndup(s,n), but never returns NULL.)
  155. */
  156. char *tor_strndup(const char *s, size_t n) {
  157. char *dup;
  158. tor_assert(s);
  159. dup = tor_malloc(n+1);
  160. strncpy(dup, s, n);
  161. dup[n] = 0;
  162. return dup;
  163. }
  164. /* Convert all alphabetic characters in the nul-terminated string 's' to
  165. * lowercase. */
  166. void tor_strlower(char *s)
  167. {
  168. while (*s) {
  169. *s = tolower(*s);
  170. ++s;
  171. }
  172. }
  173. #ifndef UNALIGNED_INT_ACCESS_OK
  174. uint16_t get_uint16(const char *cp)
  175. {
  176. uint16_t v;
  177. memcpy(&v,cp,2);
  178. return v;
  179. }
  180. uint32_t get_uint32(const char *cp)
  181. {
  182. uint32_t v;
  183. memcpy(&v,cp,4);
  184. return v;
  185. }
  186. void set_uint16(char *cp, uint16_t v)
  187. {
  188. memcpy(cp,&v,2);
  189. }
  190. void set_uint32(char *cp, uint32_t v)
  191. {
  192. memcpy(cp,&v,4);
  193. }
  194. #endif
  195. /* Encode the first 'fromlen' bytes stored at 'from' in hexidecimal;
  196. * write the result as a NUL-terminated string to 'to'. 'to' must
  197. * have at least (2*fromlen)+1 bytes of free space.
  198. */
  199. void hex_encode(const char *from, int fromlen, char *to)
  200. {
  201. const unsigned char *fp = from;
  202. static const char TABLE[] = "0123456789abcdef";
  203. tor_assert(from && fromlen>=0 && to);
  204. while (fromlen--) {
  205. *to++ = TABLE[*fp >> 4];
  206. *to++ = TABLE[*fp & 7];
  207. ++fp;
  208. }
  209. *to = '\0';
  210. }
  211. /* Return a pointer to a NUL-terminated hexidecimal string encoding
  212. * the first 'fromlen' bytes of 'from'. (fromlen must be <= 32.) The
  213. * result does not need to be deallocated, but repeated calls to
  214. * hex_str will trash old results.
  215. */
  216. const char *hex_str(const char *from, int fromlen)
  217. {
  218. static char buf[65];
  219. if (fromlen>(sizeof(buf)-1)/2)
  220. fromlen = (sizeof(buf)-1)/2;
  221. hex_encode(from,fromlen,buf);
  222. return buf;
  223. }
  224. /*****
  225. * smartlist_t: a simple resizeable array abstraction.
  226. *****/
  227. /* All newly allocated smartlists have this capacity.
  228. */
  229. #define SMARTLIST_DEFAULT_CAPACITY 32
  230. struct smartlist_t {
  231. /* 'list' has enough capacity to store exactly 'capacity' elements
  232. * before it needs to be resized. Only the first 'num_used' (<=
  233. * capacity) elements point to valid data.
  234. */
  235. void **list;
  236. int num_used;
  237. int capacity;
  238. };
  239. /* Allocate and return an empty smartlist.
  240. */
  241. smartlist_t *smartlist_create() {
  242. smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
  243. sl->num_used = 0;
  244. sl->capacity = SMARTLIST_DEFAULT_CAPACITY;
  245. sl->list = tor_malloc(sizeof(void *) * sl->capacity);
  246. return sl;
  247. }
  248. /* Deallocate a smartlist. Does not release storage associated with the
  249. * list's elements.
  250. */
  251. void smartlist_free(smartlist_t *sl) {
  252. free(sl->list);
  253. free(sl);
  254. }
  255. /* Change the capacity of the smartlist to 'n', so that we can grow
  256. * the list upt to'n' elements with no further reallocation or wasted
  257. * space. If 'n' is less than or equal to the number of elements
  258. * currently in the list, reduces the list's capacity as much as
  259. * possible without losing elements.
  260. */
  261. void smartlist_set_capacity(smartlist_t *sl, int n) {
  262. if (n < sl->num_used)
  263. n = sl->num_used;
  264. if (sl->capacity != n) {
  265. sl->capacity = n;
  266. sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
  267. }
  268. }
  269. /* Remove all elements from the list.
  270. */
  271. void smartlist_clear(smartlist_t *sl) {
  272. sl->num_used = 0;
  273. }
  274. /* Set the list's new length to 'len' (which must be <= the list's
  275. * current size). Remove the last smartlist_len(sl)-len elements from the
  276. * list.
  277. */
  278. void smartlist_truncate(smartlist_t *sl, int len)
  279. {
  280. tor_assert(len <= sl->num_used);
  281. sl->num_used = len;
  282. }
  283. /* Append element to the end of the list. */
  284. void smartlist_add(smartlist_t *sl, void *element) {
  285. if (sl->num_used >= sl->capacity) {
  286. sl->capacity *= 2;
  287. sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
  288. }
  289. sl->list[sl->num_used++] = element;
  290. }
  291. /* Append each elements from S2 to the end of S1. */
  292. void smartlist_add_all(smartlist_t *sl, const smartlist_t *s2)
  293. {
  294. SMARTLIST_FOREACH(s2, void *, element, smartlist_add(sl, element));
  295. }
  296. /* Remove all elements E from sl such that E==element. Does not preserve
  297. * the order of s1.
  298. */
  299. void smartlist_remove(smartlist_t *sl, void *element) {
  300. int i;
  301. if(element == NULL)
  302. return;
  303. for(i=0; i < sl->num_used; i++)
  304. if(sl->list[i] == element) {
  305. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  306. i--; /* so we process the new i'th element */
  307. }
  308. }
  309. /* Return true iff some element E of sl has E==element.
  310. */
  311. int smartlist_isin(const smartlist_t *sl, void *element) {
  312. int i;
  313. for(i=0; i < sl->num_used; i++)
  314. if(sl->list[i] == element)
  315. return 1;
  316. return 0;
  317. }
  318. /* Return true iff some element E of sl2 has smartlist_isin(sl1,E).
  319. */
  320. int smartlist_overlap(const smartlist_t *sl1, const smartlist_t *sl2) {
  321. int i;
  322. for(i=0; i < sl2->num_used; i++)
  323. if(smartlist_isin(sl1, sl2->list[i]))
  324. return 1;
  325. return 0;
  326. }
  327. /* Remove every element E of sl1 such that !smartlist_isin(sl2,E).
  328. * Does not preserve the order of sl1.
  329. */
  330. void smartlist_intersect(smartlist_t *sl1, const smartlist_t *sl2) {
  331. int i;
  332. for(i=0; i < sl1->num_used; i++)
  333. if(!smartlist_isin(sl2, sl1->list[i])) {
  334. sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
  335. i--; /* so we process the new i'th element */
  336. }
  337. }
  338. /* Remove every element E of sl1 such that smartlist_isin(sl2,E).
  339. * Does not preserve the order of sl1.
  340. */
  341. void smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2) {
  342. int i;
  343. for(i=0; i < sl2->num_used; i++)
  344. smartlist_remove(sl1, sl2->list[i]);
  345. }
  346. /* Return a randomly chosen element of sl; or NULL if sl is empty.
  347. */
  348. void *smartlist_choose(const smartlist_t *sl) {
  349. if(sl->num_used)
  350. return sl->list[crypto_pseudo_rand_int(sl->num_used)];
  351. return NULL; /* no elements to choose from */
  352. }
  353. /* Return the 'idx'th element of sl.
  354. */
  355. void *smartlist_get(const smartlist_t *sl, int idx)
  356. {
  357. tor_assert(sl && idx>=0 && idx < sl->num_used);
  358. return sl->list[idx];
  359. }
  360. /* Change the value of the 'idx'th element of sl to 'val'; return the old
  361. * value of the 'idx'th element.
  362. */
  363. void *smartlist_set(smartlist_t *sl, int idx, void *val)
  364. {
  365. void *old;
  366. tor_assert(sl && idx>=0 && idx < sl->num_used);
  367. old = sl->list[idx];
  368. sl->list[idx] = val;
  369. return old;
  370. }
  371. /* Remove the 'idx'th element of sl; if idx is not the last element,
  372. * swap the last element of sl into the 'idx'th space. Return the old value
  373. * of the 'idx'th element.
  374. */
  375. void *smartlist_del(smartlist_t *sl, int idx)
  376. {
  377. void *old;
  378. tor_assert(sl && idx>=0 && idx < sl->num_used);
  379. old = sl->list[idx];
  380. sl->list[idx] = sl->list[--sl->num_used];
  381. return old;
  382. }
  383. /* Remove the 'idx'th element of sl; if idx is not the last element,
  384. * moving all subsequent elements back one space. Return the old value
  385. * of the 'idx'th element.
  386. */
  387. void *smartlist_del_keeporder(smartlist_t *sl, int idx)
  388. {
  389. void *old;
  390. tor_assert(sl && idx>=0 && idx < sl->num_used);
  391. old = sl->list[idx];
  392. --sl->num_used;
  393. if (idx < sl->num_used)
  394. memmove(sl->list+idx, sl->list+idx+1, sizeof(void*)*(sl->num_used-idx));
  395. return old;
  396. }
  397. /* Return the number of items in sl.
  398. */
  399. int smartlist_len(const smartlist_t *sl)
  400. {
  401. return sl->num_used;
  402. }
  403. /* Insert the value 'val' as the new 'idx'th element of 'sl', moving all
  404. * items previously at 'idx' or later forward on space.
  405. */
  406. void smartlist_insert(smartlist_t *sl, int idx, void *val)
  407. {
  408. tor_assert(sl && idx >= 0 && idx <= sl->num_used);
  409. if (idx == sl->num_used) {
  410. smartlist_add(sl, val);
  411. } else {
  412. /* Ensure sufficient capacity */
  413. if (sl->num_used >= sl->capacity) {
  414. sl->capacity *= 2;
  415. sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
  416. }
  417. /* Move other elements away */
  418. if (idx < sl->num_used)
  419. memmove(sl->list + idx + 1, sl->list + idx,
  420. sizeof(void*)*(sl->num_used-idx));
  421. sl->num_used++;
  422. sl->list[idx] = val;
  423. }
  424. }
  425. /*****
  426. * Splay-tree implementation of string-to-void* map
  427. *****/
  428. struct strmap_entry_t {
  429. SPLAY_ENTRY(strmap_entry_t) node;
  430. char *key;
  431. void *val;
  432. };
  433. struct strmap_t {
  434. SPLAY_HEAD(strmap_tree, strmap_entry_t) head;
  435. };
  436. static int compare_strmap_entries(struct strmap_entry_t *a,
  437. struct strmap_entry_t *b)
  438. {
  439. return strcmp(a->key, b->key);
  440. }
  441. SPLAY_PROTOTYPE(strmap_tree, strmap_entry_t, node, compare_strmap_entries);
  442. SPLAY_GENERATE(strmap_tree, strmap_entry_t, node, compare_strmap_entries);
  443. /* Create a new empty map from strings to void*'s.
  444. */
  445. strmap_t* strmap_new(void)
  446. {
  447. strmap_t *result;
  448. result = tor_malloc(sizeof(strmap_t));
  449. SPLAY_INIT(&result->head);
  450. return result;
  451. }
  452. /* Set the current value for <key> with <val>. Returns the previous
  453. * value for <key> if one was set, or NULL if one was not.
  454. *
  455. * This function makes a copy of 'key' if necessary, but not of 'val'.
  456. */
  457. void* strmap_set(strmap_t *map, const char *key, void *val)
  458. {
  459. strmap_entry_t *resolve;
  460. strmap_entry_t search;
  461. void *oldval;
  462. tor_assert(map && key && val);
  463. search.key = (char*)key;
  464. resolve = SPLAY_FIND(strmap_tree, &map->head, &search);
  465. if (resolve) {
  466. oldval = resolve->val;
  467. resolve->val = val;
  468. return oldval;
  469. } else {
  470. resolve = tor_malloc_zero(sizeof(strmap_entry_t));
  471. resolve->key = tor_strdup(key);
  472. resolve->val = val;
  473. SPLAY_INSERT(strmap_tree, &map->head, resolve);
  474. return NULL;
  475. }
  476. }
  477. /* Return the current value associated with <key>, or NULL if no
  478. * value is set.
  479. */
  480. void* strmap_get(strmap_t *map, const char *key)
  481. {
  482. strmap_entry_t *resolve;
  483. strmap_entry_t search;
  484. tor_assert(map && key);
  485. search.key = (char*)key;
  486. resolve = SPLAY_FIND(strmap_tree, &map->head, &search);
  487. if (resolve) {
  488. return resolve->val;
  489. } else {
  490. return NULL;
  491. }
  492. }
  493. /* Remove the value currently associated with <key> from the map.
  494. * Return the value if one was set, or NULL if there was no entry for
  495. * <key>.
  496. *
  497. * Note: you must free any storage associated with the returned value.
  498. */
  499. void* strmap_remove(strmap_t *map, const char *key)
  500. {
  501. strmap_entry_t *resolve;
  502. strmap_entry_t search;
  503. void *oldval;
  504. tor_assert(map && key);
  505. search.key = (char*)key;
  506. resolve = SPLAY_FIND(strmap_tree, &map->head, &search);
  507. if (resolve) {
  508. oldval = resolve->val;
  509. SPLAY_REMOVE(strmap_tree, &map->head, resolve);
  510. tor_free(resolve->key);
  511. tor_free(resolve);
  512. return oldval;
  513. } else {
  514. return NULL;
  515. }
  516. }
  517. /* Same as strmap_set, but first converts <key> to lowercase. */
  518. void* strmap_set_lc(strmap_t *map, const char *key, void *val)
  519. {
  520. /* We could be a little faster by using strcasecmp instead, and a separate
  521. * type, but I don't think it matters. */
  522. void *v;
  523. char *lc_key = tor_strdup(key);
  524. tor_strlower(lc_key);
  525. v = strmap_set(map,lc_key,val);
  526. tor_free(lc_key);
  527. return v;
  528. }
  529. /* Same as strmap_get, but first converts <key> to lowercase. */
  530. void* strmap_get_lc(strmap_t *map, const char *key)
  531. {
  532. void *v;
  533. char *lc_key = tor_strdup(key);
  534. tor_strlower(lc_key);
  535. v = strmap_get(map,lc_key);
  536. tor_free(lc_key);
  537. return v;
  538. }
  539. /* Same as strmap_remove, but first converts <key> to lowercase */
  540. void* strmap_remove_lc(strmap_t *map, const char *key)
  541. {
  542. void *v;
  543. char *lc_key = tor_strdup(key);
  544. tor_strlower(lc_key);
  545. v = strmap_remove(map,lc_key);
  546. tor_free(lc_key);
  547. return v;
  548. }
  549. /* Invoke fn() on every entry of the map, in order. For every entry,
  550. * fn() is invoked with that entry's key, that entry's value, and the
  551. * value of <data> supplied to strmap_foreach. fn() must return a new
  552. * (possibly unmodified) value for each entry: if fn() returns NULL, the
  553. * entry is removed.
  554. *
  555. * Example:
  556. * static void* upcase_and_remove_empty_vals(const char *key, void *val,
  557. * void* data) {
  558. * char *cp = (char*)val;
  559. * if (!*cp) { // val is an empty string.
  560. * free(val);
  561. * return NULL;
  562. * } else {
  563. * for (; *cp; cp++)
  564. * *cp = toupper(*cp);
  565. * }
  566. * return val;
  567. * }
  568. * }
  569. *
  570. * ...
  571. *
  572. * strmap_foreach(map, upcase_and_remove_empty_vals, NULL);
  573. */
  574. void strmap_foreach(strmap_t *map,
  575. void* (*fn)(const char *key, void *val, void *data),
  576. void *data)
  577. {
  578. strmap_entry_t *ptr, *next;
  579. tor_assert(map && fn);
  580. for (ptr = SPLAY_MIN(strmap_tree, &map->head); ptr != NULL; ptr = next) {
  581. /* This remove-in-place usage is specifically blessed in tree(3). */
  582. next = SPLAY_NEXT(strmap_tree, &map->head, ptr);
  583. ptr->val = fn(ptr->key, ptr->val, data);
  584. if (!ptr->val) {
  585. SPLAY_REMOVE(strmap_tree, &map->head, ptr);
  586. tor_free(ptr->key);
  587. tor_free(ptr);
  588. }
  589. }
  590. }
  591. /* return an 'iterator' pointer to the front of a map.
  592. *
  593. * Iterator example:
  594. *
  595. * // uppercase values in "map", removing empty values.
  596. *
  597. * strmap_iter_t *iter;
  598. * const char *key;
  599. * void *val;
  600. * char *cp;
  601. *
  602. * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
  603. * strmap_iter_get(iter, &key, &val);
  604. * cp = (char*)val;
  605. * if (!*cp) {
  606. * iter = strmap_iter_next_rmv(iter);
  607. * free(val);
  608. * } else {
  609. * for(;*cp;cp++) *cp = toupper(*cp);
  610. * iter = strmap_iter_next(iter);
  611. * }
  612. * }
  613. *
  614. */
  615. strmap_iter_t *strmap_iter_init(strmap_t *map)
  616. {
  617. tor_assert(map);
  618. return SPLAY_MIN(strmap_tree, &map->head);
  619. }
  620. /* Advance the iterator 'iter' for map a single step to the next entry.
  621. */
  622. strmap_iter_t *strmap_iter_next(strmap_t *map, strmap_iter_t *iter)
  623. {
  624. tor_assert(map && iter);
  625. return SPLAY_NEXT(strmap_tree, &map->head, iter);
  626. }
  627. /* Advance the iterator 'iter' a single step to the next entry, removing
  628. * the current entry.
  629. */
  630. strmap_iter_t *strmap_iter_next_rmv(strmap_t *map, strmap_iter_t *iter)
  631. {
  632. strmap_iter_t *next;
  633. tor_assert(map && iter);
  634. next = SPLAY_NEXT(strmap_tree, &map->head, iter);
  635. SPLAY_REMOVE(strmap_tree, &map->head, iter);
  636. tor_free(iter->key);
  637. tor_free(iter);
  638. return next;
  639. }
  640. /* Set *keyp and *valp to the current entry pointed to by iter.
  641. */
  642. void strmap_iter_get(strmap_iter_t *iter, const char **keyp, void **valp)
  643. {
  644. tor_assert(iter && keyp && valp);
  645. *keyp = iter->key;
  646. *valp = iter->val;
  647. }
  648. /* Return true iff iter has advanced past the last entry of map.
  649. */
  650. int strmap_iter_done(strmap_iter_t *iter)
  651. {
  652. return iter == NULL;
  653. }
  654. /* Remove all entries from <map>, and deallocate storage for those entries.
  655. * If free_val is provided, it is invoked on every value in <map>.
  656. */
  657. void strmap_free(strmap_t *map, void (*free_val)(void*))
  658. {
  659. strmap_entry_t *ent, *next;
  660. for (ent = SPLAY_MIN(strmap_tree, &map->head); ent != NULL; ent = next) {
  661. next = SPLAY_NEXT(strmap_tree, &map->head, ent);
  662. SPLAY_REMOVE(strmap_tree, &map->head, ent);
  663. tor_free(ent->key);
  664. if (free_val)
  665. tor_free(ent->val);
  666. }
  667. tor_assert(SPLAY_EMPTY(&map->head));
  668. tor_free(map);
  669. }
  670. /*
  671. * String manipulation
  672. */
  673. /* Return a pointer to the first char of s that is not whitespace and
  674. * not a comment, or to the terminating NUL if no such character exists.
  675. */
  676. const char *eat_whitespace(const char *s) {
  677. tor_assert(s);
  678. while(isspace((int)*s) || *s == '#') {
  679. while(isspace((int)*s))
  680. s++;
  681. if(*s == '#') { /* read to a \n or \0 */
  682. while(*s && *s != '\n')
  683. s++;
  684. if(!*s)
  685. return s;
  686. }
  687. }
  688. return s;
  689. }
  690. /* Return a pointer to the first char of s that is not a space or a tab,
  691. * or to the terminating NUL if no such character exists. */
  692. const char *eat_whitespace_no_nl(const char *s) {
  693. while(*s == ' ' || *s == '\t')
  694. ++s;
  695. return s;
  696. }
  697. /* Return a pointer to the first char of s that is whitespace or '#',
  698. * or to the terminating NUL if no such character exists. */
  699. */
  700. const char *find_whitespace(const char *s) {
  701. tor_assert(s);
  702. while(*s && !isspace((int)*s) && *s != '#')
  703. s++;
  704. return s;
  705. }
  706. /*****
  707. * Time
  708. *****/
  709. /* Set *timeval to the current time of day. On error, log and terminate.
  710. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  711. */
  712. void tor_gettimeofday(struct timeval *timeval) {
  713. #ifdef HAVE_GETTIMEOFDAY
  714. if (gettimeofday(timeval, NULL)) {
  715. log_fn(LOG_ERR, "gettimeofday failed.");
  716. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  717. or segfaulted.*/
  718. exit(1);
  719. }
  720. #elif defined(HAVE_FTIME)
  721. ftime(timeval);
  722. #else
  723. #error "No way to get time."
  724. #endif
  725. return;
  726. }
  727. /* Returns the number of microseconds elapsed between *start and *end.
  728. */
  729. long
  730. tv_udiff(struct timeval *start, struct timeval *end)
  731. {
  732. long udiff;
  733. long secdiff = end->tv_sec - start->tv_sec;
  734. if (secdiff+1 > LONG_MAX/1000000) {
  735. log_fn(LOG_WARN, "comparing times too far apart.");
  736. return LONG_MAX;
  737. }
  738. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  739. if(udiff < 0) {
  740. log_fn(LOG_INFO, "start (%ld.%ld) is after end (%ld.%ld). Returning 0.",
  741. (long)start->tv_sec, (long)start->tv_usec, (long)end->tv_sec, (long)end->tv_usec);
  742. return 0;
  743. }
  744. return udiff;
  745. }
  746. /* Return -1 if *a<*b, 0 if *a==*b, and 1 if *a>*b.
  747. */
  748. int tv_cmp(struct timeval *a, struct timeval *b) {
  749. if (a->tv_sec > b->tv_sec)
  750. return 1;
  751. if (a->tv_sec < b->tv_sec)
  752. return -1;
  753. if (a->tv_usec > b->tv_usec)
  754. return 1;
  755. if (a->tv_usec < b->tv_usec)
  756. return -1;
  757. return 0;
  758. }
  759. /* Increment *a by the number of seconds and microseconds in *b.
  760. */
  761. void tv_add(struct timeval *a, struct timeval *b) {
  762. a->tv_usec += b->tv_usec;
  763. a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
  764. a->tv_usec %= 1000000;
  765. }
  766. /* Increment *a by 'ms' milliseconds.
  767. */
  768. void tv_addms(struct timeval *a, long ms) {
  769. a->tv_usec += (ms * 1000) % 1000000;
  770. a->tv_sec += ((ms * 1000) / 1000000) + (a->tv_usec / 1000000);
  771. a->tv_usec %= 1000000;
  772. }
  773. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  774. static int n_leapdays(int y1, int y2) {
  775. --y1;
  776. --y2;
  777. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  778. }
  779. static const int days_per_month[] =
  780. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  781. /* Return a time_t given a struct tm. The result is given in GMT, and
  782. * does not account for leap seconds.
  783. */
  784. time_t tor_timegm (struct tm *tm) {
  785. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  786. * It's way more brute-force than fiddling with tzset().
  787. */
  788. time_t ret;
  789. unsigned long year, days, hours, minutes;
  790. int i;
  791. year = tm->tm_year + 1900;
  792. tor_assert(year >= 1970);
  793. tor_assert(tm->tm_mon >= 0 && tm->tm_mon <= 11);
  794. days = 365 * (year-1970) + n_leapdays(1970,year);
  795. for (i = 0; i < tm->tm_mon; ++i)
  796. days += days_per_month[i];
  797. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  798. ++days;
  799. days += tm->tm_mday - 1;
  800. hours = days*24 + tm->tm_hour;
  801. minutes = hours*60 + tm->tm_min;
  802. ret = minutes*60 + tm->tm_sec;
  803. return ret;
  804. }
  805. /*
  806. * Low-level I/O.
  807. */
  808. /* Write 'count' bytes from 'buf' to 'fd'. isSocket must be 1 if fd
  809. * was returned by socket() or accept(), and 0 if fd was returned by
  810. * open(). Return the number of bytes written, or -1 on error. Only
  811. * use if fd is a blocking fd. */
  812. int write_all(int fd, const char *buf, size_t count, int isSocket) {
  813. size_t written = 0;
  814. int result;
  815. while(written != count) {
  816. if (isSocket)
  817. result = send(fd, buf+written, count-written, 0);
  818. else
  819. result = write(fd, buf+written, count-written);
  820. if(result<0)
  821. return -1;
  822. written += result;
  823. }
  824. return count;
  825. }
  826. /* Read 'count' bytes from 'fd' to 'buf'. isSocket must be 1 if fd
  827. * was returned by socket() or accept(), and 0 if fd was returned by
  828. * open(). Return the number of bytes read, or -1 on error. Only use
  829. * if fd is a blocking fd. */
  830. int read_all(int fd, char *buf, size_t count, int isSocket) {
  831. size_t numread = 0;
  832. int result;
  833. while(numread != count) {
  834. if (isSocket)
  835. result = recv(fd, buf+numread, count-numread, 0);
  836. else
  837. result = read(fd, buf+numread, count-numread);
  838. if(result<=0)
  839. return -1;
  840. numread += result;
  841. }
  842. return count;
  843. }
  844. /* Turn 'socket' into a nonblocking socket.
  845. */
  846. void set_socket_nonblocking(int socket)
  847. {
  848. #ifdef MS_WINDOWS
  849. /* Yes means no and no means yes. Do you not want to be nonblocking? */
  850. int nonblocking = 0;
  851. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  852. #else
  853. fcntl(socket, F_SETFL, O_NONBLOCK);
  854. #endif
  855. }
  856. /*
  857. * Process control
  858. */
  859. /* Minimalist interface to run a void function in the background. On
  860. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  861. * func should not return, but rather should call spawn_exit.
  862. */
  863. int spawn_func(int (*func)(void *), void *data)
  864. {
  865. #ifdef MS_WINDOWS
  866. int rv;
  867. rv = _beginthread(func, 0, data);
  868. if (rv == (unsigned long) -1)
  869. return -1;
  870. return 0;
  871. #else
  872. pid_t pid;
  873. pid = fork();
  874. if (pid<0)
  875. return -1;
  876. if (pid==0) {
  877. /* Child */
  878. func(data);
  879. tor_assert(0); /* Should never reach here. */
  880. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  881. } else {
  882. /* Parent */
  883. return 0;
  884. }
  885. #endif
  886. }
  887. /* End the current thread/process.
  888. */
  889. void spawn_exit()
  890. {
  891. #ifdef MS_WINDOWS
  892. _endthread();
  893. #else
  894. exit(0);
  895. #endif
  896. }
  897. /**
  898. * Allocate a pair of connected sockets. (Like socketpair(family,
  899. * type,protocol,fd), but works on systems that don't have
  900. * socketpair.)
  901. *
  902. * Currently, only (AF_UNIX, SOCK_STREAM, 0 ) sockets are supported.
  903. * Note that on systems without socketpair, this call will sometimes
  904. * fail if localhost is inaccessible (for example, if the networking
  905. * stack is down).
  906. **/
  907. int
  908. tor_socketpair(int family, int type, int protocol, int fd[2])
  909. {
  910. #ifdef HAVE_SOCKETPAIR
  911. return socketpair(family, type, protocol, fd);
  912. #else
  913. /* This socketpair does not work when localhost is down. So
  914. * it's really not the same thing at all. But it's close enough
  915. * for now, and really, when localhost is down sometimes, we
  916. * have other problems too.
  917. */
  918. int listener = -1;
  919. int connector = -1;
  920. int acceptor = -1;
  921. struct sockaddr_in listen_addr;
  922. struct sockaddr_in connect_addr;
  923. int size;
  924. if (protocol
  925. #ifdef AF_UNIX
  926. || family != AF_UNIX
  927. #endif
  928. ) {
  929. #ifdef MS_WINDOWS
  930. errno = WSAEAFNOSUPPORT;
  931. #else
  932. errno = EAFNOSUPPORT;
  933. #endif
  934. return -1;
  935. }
  936. if (!fd) {
  937. errno = EINVAL;
  938. return -1;
  939. }
  940. listener = socket(AF_INET, type, 0);
  941. if (listener == -1)
  942. return -1;
  943. memset (&listen_addr, 0, sizeof (listen_addr));
  944. listen_addr.sin_family = AF_INET;
  945. listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
  946. listen_addr.sin_port = 0; /* kernel choses port. */
  947. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  948. == -1)
  949. goto tidy_up_and_fail;
  950. if (listen(listener, 1) == -1)
  951. goto tidy_up_and_fail;
  952. connector = socket(AF_INET, type, 0);
  953. if (connector == -1)
  954. goto tidy_up_and_fail;
  955. /* We want to find out the port number to connect to. */
  956. size = sizeof (connect_addr);
  957. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  958. goto tidy_up_and_fail;
  959. if (size != sizeof (connect_addr))
  960. goto abort_tidy_up_and_fail;
  961. if (connect(connector, (struct sockaddr *) &connect_addr,
  962. sizeof (connect_addr)) == -1)
  963. goto tidy_up_and_fail;
  964. size = sizeof (listen_addr);
  965. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  966. if (acceptor == -1)
  967. goto tidy_up_and_fail;
  968. if (size != sizeof(listen_addr))
  969. goto abort_tidy_up_and_fail;
  970. tor_close_socket(listener);
  971. /* Now check we are talking to ourself by matching port and host on the
  972. two sockets. */
  973. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  974. goto tidy_up_and_fail;
  975. if (size != sizeof (connect_addr)
  976. || listen_addr.sin_family != connect_addr.sin_family
  977. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  978. || listen_addr.sin_port != connect_addr.sin_port) {
  979. goto abort_tidy_up_and_fail;
  980. }
  981. fd[0] = connector;
  982. fd[1] = acceptor;
  983. return 0;
  984. abort_tidy_up_and_fail:
  985. #ifdef MS_WINDOWS
  986. errno = WSAECONNABORTED;
  987. #else
  988. errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  989. #endif
  990. tidy_up_and_fail:
  991. {
  992. int save_errno = errno;
  993. if (listener != -1)
  994. tor_close_socket(listener);
  995. if (connector != -1)
  996. tor_close_socket(connector);
  997. if (acceptor != -1)
  998. tor_close_socket(acceptor);
  999. errno = save_errno;
  1000. return -1;
  1001. }
  1002. #endif
  1003. }
  1004. /* On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  1005. * you need to ask the socket for its actual errno. Also, you need to
  1006. * get your errors from WSAGetLastError, not errno.
  1007. */
  1008. #ifdef MS_WINDOWS
  1009. int tor_socket_errno(int sock)
  1010. {
  1011. int optval, optvallen=sizeof(optval);
  1012. int err = WSAGetLastError();
  1013. if (err == WSAEWOULDBLOCK && sock >= 0) {
  1014. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  1015. return err;
  1016. if (optval)
  1017. return optval;
  1018. }
  1019. return err;
  1020. }
  1021. #endif
  1022. /*
  1023. * Filesystem operations.
  1024. */
  1025. /* Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1026. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1027. * directory. */
  1028. file_status_t file_status(const char *fname)
  1029. {
  1030. struct stat st;
  1031. if (stat(fname, &st)) {
  1032. if (errno == ENOENT) {
  1033. return FN_NOENT;
  1034. }
  1035. return FN_ERROR;
  1036. }
  1037. if (st.st_mode & S_IFDIR)
  1038. return FN_DIR;
  1039. else if (st.st_mode & S_IFREG)
  1040. return FN_FILE;
  1041. else
  1042. return FN_ERROR;
  1043. }
  1044. /* Check whether dirname exists and is private. If yes returns 0. If
  1045. * it does not exist, and create is set, try to creat it and return 0
  1046. * on success. Else return -1. */
  1047. int check_private_dir(const char *dirname, int create)
  1048. {
  1049. int r;
  1050. struct stat st;
  1051. if (stat(dirname, &st)) {
  1052. if (errno != ENOENT) {
  1053. log(LOG_WARN, "Directory %s cannot be read: %s", dirname,
  1054. strerror(errno));
  1055. return -1;
  1056. }
  1057. if (!create) {
  1058. log(LOG_WARN, "Directory %s does not exist.", dirname);
  1059. return -1;
  1060. }
  1061. log(LOG_INFO, "Creating directory %s", dirname);
  1062. #ifdef MS_WINDOWS
  1063. r = mkdir(dirname);
  1064. #else
  1065. r = mkdir(dirname, 0700);
  1066. #endif
  1067. if (r) {
  1068. log(LOG_WARN, "Error creating directory %s: %s", dirname,
  1069. strerror(errno));
  1070. return -1;
  1071. } else {
  1072. return 0;
  1073. }
  1074. }
  1075. if (!(st.st_mode & S_IFDIR)) {
  1076. log(LOG_WARN, "%s is not a directory", dirname);
  1077. return -1;
  1078. }
  1079. #ifndef MS_WINDOWS
  1080. if (st.st_uid != getuid()) {
  1081. log(LOG_WARN, "%s is not owned by this UID (%d)", dirname, (int)getuid());
  1082. return -1;
  1083. }
  1084. if (st.st_mode & 0077) {
  1085. log(LOG_WARN, "Fixing permissions on directory %s", dirname);
  1086. if (chmod(dirname, 0700)) {
  1087. log(LOG_WARN, "Could not chmod directory %s: %s", dirname,
  1088. strerror(errno));
  1089. return -1;
  1090. } else {
  1091. return 0;
  1092. }
  1093. }
  1094. #endif
  1095. return 0;
  1096. }
  1097. /* Create a file named 'fname' with the contents 'str'. Overwrite the
  1098. * previous 'fname' if possible. Return 0 on success, -1 on failure.
  1099. *
  1100. * This function replaces the old file atomically, if possible.
  1101. */
  1102. int
  1103. write_str_to_file(const char *fname, const char *str)
  1104. {
  1105. char tempname[1024];
  1106. int fd;
  1107. FILE *file;
  1108. if ((strlcpy(tempname,fname,1024) >= 1024) ||
  1109. (strlcat(tempname,".tmp",1024) >= 1024)) {
  1110. log(LOG_WARN, "Filename %s.tmp too long (>1024 chars)", fname);
  1111. return -1;
  1112. }
  1113. if ((fd = open(tempname, O_WRONLY|O_CREAT|O_TRUNC, 0600)) < 0) {
  1114. log(LOG_WARN, "Couldn't open %s for writing: %s", tempname,
  1115. strerror(errno));
  1116. return -1;
  1117. }
  1118. if (!(file = fdopen(fd, "w"))) {
  1119. log(LOG_WARN, "Couldn't fdopen %s for writing: %s", tempname,
  1120. strerror(errno));
  1121. close(fd);
  1122. return -1;
  1123. }
  1124. if (fputs(str,file) == EOF) {
  1125. log(LOG_WARN, "Error writing to %s: %s", tempname, strerror(errno));
  1126. fclose(file);
  1127. return -1;
  1128. }
  1129. fclose(file);
  1130. /* XXXX This won't work on windows: you can't use rename to replace a file.*/
  1131. if (rename(tempname, fname)) {
  1132. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  1133. return -1;
  1134. }
  1135. return 0;
  1136. }
  1137. /* Read the contents of 'filename' into a newly allocated string; return the
  1138. * string on success or NULL on failure.
  1139. */
  1140. char *read_file_to_str(const char *filename) {
  1141. int fd; /* router file */
  1142. struct stat statbuf;
  1143. char *string;
  1144. tor_assert(filename);
  1145. if(strcspn(filename,CONFIG_LEGAL_FILENAME_CHARACTERS) != 0) {
  1146. log_fn(LOG_WARN,"Filename %s contains illegal characters.",filename);
  1147. return NULL;
  1148. }
  1149. if(stat(filename, &statbuf) < 0) {
  1150. log_fn(LOG_INFO,"Could not stat %s.",filename);
  1151. return NULL;
  1152. }
  1153. fd = open(filename,O_RDONLY,0);
  1154. if (fd<0) {
  1155. log_fn(LOG_WARN,"Could not open %s.",filename);
  1156. return NULL;
  1157. }
  1158. string = tor_malloc(statbuf.st_size+1);
  1159. if(read_all(fd,string,statbuf.st_size,0) != statbuf.st_size) {
  1160. log_fn(LOG_WARN,"Couldn't read all %ld bytes of file '%s'.",
  1161. (long)statbuf.st_size,filename);
  1162. free(string);
  1163. close(fd);
  1164. return NULL;
  1165. }
  1166. close(fd);
  1167. string[statbuf.st_size] = 0; /* null terminate it */
  1168. return string;
  1169. }
  1170. /* read lines from f (no more than maxlen-1 bytes each) until we
  1171. * get a non-whitespace line. If it isn't of the form "key value"
  1172. * (value can have spaces), return -1.
  1173. * Point *key to the first word in line, point *value * to the second.
  1174. * Put a \0 at the end of key, remove everything at the end of value
  1175. * that is whitespace or comment.
  1176. * Return 1 if success, 0 if no more lines, -1 if error.
  1177. */
  1178. int parse_line_from_file(char *line, int maxlen, FILE *f, char **key_out, char **value_out) {
  1179. char *s, *key, *end, *value;
  1180. try_next_line:
  1181. if(!fgets(line, maxlen, f)) {
  1182. if(feof(f))
  1183. return 0;
  1184. return -1; /* real error */
  1185. }
  1186. if((s = strchr(line,'#'))) /* strip comments */
  1187. *s = 0; /* stop the line there */
  1188. /* remove end whitespace */
  1189. s = strchr(line, 0); /* now we're at the null */
  1190. do {
  1191. *s = 0;
  1192. s--;
  1193. } while (s >= line && isspace((int)*s));
  1194. key = line;
  1195. while(isspace((int)*key))
  1196. key++;
  1197. if(*key == 0)
  1198. goto try_next_line; /* this line has nothing on it */
  1199. end = key;
  1200. while(*end && !isspace((int)*end))
  1201. end++;
  1202. value = end;
  1203. while(*value && isspace((int)*value))
  1204. value++;
  1205. if(!*end || !*value) { /* only a key on this line. no value. */
  1206. *end = 0;
  1207. log_fn(LOG_WARN,"Line has keyword '%s' but no value. Failing.",key);
  1208. return -1;
  1209. }
  1210. *end = 0; /* null it out */
  1211. log_fn(LOG_DEBUG,"got keyword '%s', value '%s'", key, value);
  1212. *key_out = key, *value_out = value;
  1213. return 1;
  1214. }
  1215. /* Return true iff 'ip' (in host order) is an IP reserved to localhost,
  1216. * or reserved for local networks by RFC 1918.
  1217. */
  1218. int is_internal_IP(uint32_t ip) {
  1219. if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
  1220. ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
  1221. ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
  1222. ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  1223. ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  1224. ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  1225. return 1;
  1226. return 0;
  1227. }
  1228. /* Hold the result of our call to 'uname'. */
  1229. static char uname_result[256];
  1230. /* True iff uname_Result is set. */
  1231. static int uname_result_is_set = 0;
  1232. /* Return a pointer to a description of our platform.
  1233. */
  1234. const char *
  1235. get_uname(void)
  1236. {
  1237. #ifdef HAVE_UNAME
  1238. struct utsname u;
  1239. #endif
  1240. if (!uname_result_is_set) {
  1241. #ifdef HAVE_UNAME
  1242. if (uname(&u) != -1) {
  1243. /* (linux says 0 is success, solaris says 1 is success) */
  1244. snprintf(uname_result, 255, "%s %s %s",
  1245. u.sysname, u.nodename, u.machine);
  1246. uname_result[255] = '\0';
  1247. } else
  1248. #endif
  1249. {
  1250. strcpy(uname_result, "Unknown platform");
  1251. }
  1252. uname_result_is_set = 1;
  1253. }
  1254. return uname_result;
  1255. }
  1256. #ifndef MS_WINDOWS
  1257. /* Based on code contributed by christian grothoff */
  1258. static int start_daemon_called = 0;
  1259. static int finish_daemon_called = 0;
  1260. static int daemon_filedes[2];
  1261. /* Begin running this process as a daemon. The child process will return
  1262. * quickly; the parent process will wait around until the child process calls
  1263. * finish_daemon.
  1264. */
  1265. void start_daemon(char *desired_cwd)
  1266. {
  1267. pid_t pid;
  1268. if (start_daemon_called)
  1269. return;
  1270. start_daemon_called = 1;
  1271. if(!desired_cwd)
  1272. desired_cwd = "/";
  1273. /* Don't hold the wrong FS mounted */
  1274. if (chdir(desired_cwd) < 0) {
  1275. log_fn(LOG_ERR,"chdir to %s failed. Exiting.",desired_cwd);
  1276. exit(1);
  1277. }
  1278. pipe(daemon_filedes);
  1279. pid = fork();
  1280. if (pid < 0) {
  1281. log_fn(LOG_ERR,"fork failed. Exiting.");
  1282. exit(1);
  1283. }
  1284. if (pid) { /* Parent */
  1285. int ok;
  1286. char c;
  1287. close(daemon_filedes[1]); /* we only read */
  1288. ok = -1;
  1289. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  1290. if (c == '.')
  1291. ok = 1;
  1292. }
  1293. fflush(stdout);
  1294. if (ok == 1)
  1295. exit(0);
  1296. else
  1297. exit(1); /* child reported error */
  1298. } else { /* Child */
  1299. close(daemon_filedes[0]); /* we only write */
  1300. pid = setsid(); /* Detach from controlling terminal */
  1301. /*
  1302. * Fork one more time, so the parent (the session group leader) can exit.
  1303. * This means that we, as a non-session group leader, can never regain a
  1304. * controlling terminal. This part is recommended by Stevens's
  1305. * _Advanced Programming in the Unix Environment_.
  1306. */
  1307. if (fork() != 0) {
  1308. exit(0);
  1309. }
  1310. return;
  1311. }
  1312. }
  1313. /* Tell the parent process that the child has successfully finished setup,
  1314. * and the daemon is now running.
  1315. */
  1316. void finish_daemon(void)
  1317. {
  1318. int nullfd;
  1319. char c = '.';
  1320. if (finish_daemon_called)
  1321. return;
  1322. if (!start_daemon_called)
  1323. start_daemon(NULL);
  1324. finish_daemon_called = 1;
  1325. nullfd = open("/dev/null",
  1326. O_CREAT | O_RDWR | O_APPEND);
  1327. if (nullfd < 0) {
  1328. log_fn(LOG_ERR,"/dev/null can't be opened. Exiting.");
  1329. exit(1);
  1330. }
  1331. /* close fds linking to invoking terminal, but
  1332. * close usual incoming fds, but redirect them somewhere
  1333. * useful so the fds don't get reallocated elsewhere.
  1334. */
  1335. if (dup2(nullfd,0) < 0 ||
  1336. dup2(nullfd,1) < 0 ||
  1337. dup2(nullfd,2) < 0) {
  1338. log_fn(LOG_ERR,"dup2 failed. Exiting.");
  1339. exit(1);
  1340. }
  1341. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  1342. close(daemon_filedes[1]);
  1343. }
  1344. #else
  1345. /* defined(MS_WINDOWS) */
  1346. void start_daemon(char *cp) {}
  1347. void finish_daemon(void) {}
  1348. #endif
  1349. /* Write the current process ID, followed by NL, into 'filaname',
  1350. */
  1351. void write_pidfile(char *filename) {
  1352. #ifndef MS_WINDOWS
  1353. FILE *pidfile;
  1354. if ((pidfile = fopen(filename, "w")) == NULL) {
  1355. log_fn(LOG_WARN, "unable to open %s for writing: %s", filename,
  1356. strerror(errno));
  1357. } else {
  1358. fprintf(pidfile, "%d\n", (int)getpid());
  1359. fclose(pidfile);
  1360. }
  1361. #endif
  1362. }
  1363. /* Call setuid and setgid to run as 'user':'group'. Return 0 on
  1364. * success. On failure, log and return -1.
  1365. */
  1366. int switch_id(char *user, char *group) {
  1367. #ifndef MS_WINDOWS
  1368. struct passwd *pw = NULL;
  1369. struct group *gr = NULL;
  1370. if (user) {
  1371. pw = getpwnam(user);
  1372. if (pw == NULL) {
  1373. log_fn(LOG_ERR,"User '%s' not found.", user);
  1374. return -1;
  1375. }
  1376. }
  1377. /* switch the group first, while we still have the privileges to do so */
  1378. if (group) {
  1379. gr = getgrnam(group);
  1380. if (gr == NULL) {
  1381. log_fn(LOG_ERR,"Group '%s' not found.", group);
  1382. return -1;
  1383. }
  1384. if (setgid(gr->gr_gid) != 0) {
  1385. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  1386. return -1;
  1387. }
  1388. } else if (user) {
  1389. if (setgid(pw->pw_gid) != 0) {
  1390. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  1391. return -1;
  1392. }
  1393. }
  1394. /* now that the group is switched, we can switch users and lose
  1395. privileges */
  1396. if (user) {
  1397. if (setuid(pw->pw_uid) != 0) {
  1398. log_fn(LOG_ERR,"Error setting UID: %s", strerror(errno));
  1399. return -1;
  1400. }
  1401. }
  1402. return 0;
  1403. #endif
  1404. log_fn(LOG_ERR,
  1405. "User or group specified, but switching users is not supported.");
  1406. return -1;
  1407. }
  1408. /* Set *addr to the IP address (in dotted-quad notation) stored in c.
  1409. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  1410. * but works on Windows.)
  1411. */
  1412. int tor_inet_aton(const char *c, struct in_addr* addr)
  1413. {
  1414. #ifdef HAVE_INET_ATON
  1415. return inet_aton(c, addr);
  1416. #else
  1417. uint32_t r;
  1418. tor_assert(c && addr);
  1419. if (strcmp(c, "255.255.255.255") == 0) {
  1420. addr->s_addr = 0xFFFFFFFFu;
  1421. return 1;
  1422. }
  1423. r = inet_addr(c);
  1424. if (r == INADDR_NONE)
  1425. return 0;
  1426. addr->s_addr = r;
  1427. return 1;
  1428. #endif
  1429. }
  1430. /* Similar behavior to Unix gethostbyname: resolve 'name', and set
  1431. * *addr to the proper IP address, in network byte order. Returns 0
  1432. * on success, -1 on failure; 1 on transient failure.
  1433. *
  1434. * (This function exists because standard windows gethostbyname
  1435. * doesn't treat raw IP addresses properly.)
  1436. */
  1437. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  1438. * something.
  1439. */
  1440. int tor_lookup_hostname(const char *name, uint32_t *addr)
  1441. {
  1442. struct in_addr iaddr;
  1443. struct hostent *ent;
  1444. tor_assert(addr);
  1445. if (tor_inet_aton(name, &iaddr)) {
  1446. /* It's an IP. */
  1447. memcpy(addr, &iaddr.s_addr, 4);
  1448. return 0;
  1449. } else {
  1450. ent = gethostbyname(name);
  1451. if (ent) {
  1452. /* break to remind us if we move away from IPv4 */
  1453. tor_assert(ent->h_length == 4);
  1454. memcpy(addr, ent->h_addr, 4);
  1455. return 0;
  1456. }
  1457. memset(addr, 0, 4);
  1458. #ifdef MS_WINDOWS
  1459. return (WSAGetLastError() == WSATRY_AGAIN) ? 1 : -1;
  1460. #else
  1461. return (h_errno == TRY_AGAIN) ? 1 : -1;
  1462. #endif
  1463. }
  1464. }
  1465. /*
  1466. Local Variables:
  1467. mode:c
  1468. indent-tabs-mode:nil
  1469. c-basic-offset:2
  1470. End:
  1471. */