util.c 45 KB

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