util.c 47 KB

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