util.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933
  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. /* This is required on rh7 to make strptime not complain.
  11. */
  12. #define _GNU_SOURCE
  13. #include "orconfig.h"
  14. #ifdef MS_WINDOWS
  15. #define WIN32_WINNT 0x400
  16. #define _WIN32_WINNT 0x400
  17. #define WIN32_LEAN_AND_MEAN
  18. #if _MSC_VER > 1300
  19. #include <winsock2.h>
  20. #include <ws2tcpip.h>
  21. #elif defined(_MSC_VER)
  22. #include <winsock.h>
  23. #endif
  24. #include <io.h>
  25. #include <process.h>
  26. #include <direct.h>
  27. #include <windows.h>
  28. #endif
  29. #include <stdlib.h>
  30. #include <stdio.h>
  31. #include <string.h>
  32. #include <assert.h>
  33. #ifndef HAVE_GETTIMEOFDAY
  34. #ifdef HAVE_FTIME
  35. #include <sys/timeb.h>
  36. #endif
  37. #endif
  38. #include "util.h"
  39. #include "log.h"
  40. #include "crypto.h"
  41. #include "../or/tree.h"
  42. #ifdef HAVE_UNAME
  43. #include <sys/utsname.h>
  44. #endif
  45. #ifdef HAVE_CTYPE_H
  46. #include <ctype.h>
  47. #endif
  48. #ifdef HAVE_NETINET_IN_H
  49. #include <netinet/in.h>
  50. #endif
  51. #ifdef HAVE_ARPA_INET_H
  52. #include <arpa/inet.h>
  53. #endif
  54. #ifdef HAVE_ERRNO_H
  55. #include <errno.h>
  56. #endif
  57. #ifdef HAVE_LIMITS_H
  58. #include <limits.h>
  59. #endif
  60. #ifdef HAVE_SYS_PARAM_H
  61. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  62. #endif
  63. #ifdef HAVE_SYS_LIMITS_H
  64. #include <sys/limits.h>
  65. #endif
  66. #ifdef HAVE_MACHINE_LIMITS_H
  67. #ifndef __FreeBSD__
  68. /* FreeBSD has a bug where it complains that this file is obsolete,
  69. and I should migrate to using sys/limits. It complains even when
  70. I include both. */
  71. #include <machine/limits.h>
  72. #endif
  73. #endif
  74. #ifdef HAVE_SYS_TYPES_H
  75. #include <sys/types.h> /* Must be included before sys/stat.h for Ultrix */
  76. #endif
  77. #ifdef HAVE_SYS_SOCKET_H
  78. #include <sys/socket.h>
  79. #endif
  80. #ifdef HAVE_NETDB_H
  81. #include <netdb.h>
  82. #endif
  83. #ifdef HAVE_UNISTD_H
  84. #include <unistd.h>
  85. #endif
  86. #ifdef HAVE_SYS_STAT_H
  87. #include <sys/stat.h>
  88. #endif
  89. #ifdef HAVE_SYS_FCNTL_H
  90. #include <sys/fcntl.h>
  91. #endif
  92. #ifdef HAVE_PWD_H
  93. #include <pwd.h>
  94. #endif
  95. #ifdef HAVE_GRP_H
  96. #include <grp.h>
  97. #endif
  98. #ifdef HAVE_FCNTL_H
  99. #include <fcntl.h>
  100. #endif
  101. /* used by inet_addr, not defined on solaris anywhere!? */
  102. #ifndef INADDR_NONE
  103. #define INADDR_NONE ((unsigned long) -1)
  104. #endif
  105. /* Inline the strl functions if the plaform doesn't have them. */
  106. #ifndef HAVE_STRLCPY
  107. #include "strlcpy.c"
  108. #endif
  109. #ifndef HAVE_STRLCAT
  110. #include "strlcat.c"
  111. #endif
  112. /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
  113. * result. On error, log and terminate the process. (Same as malloc(size),
  114. * but never returns NULL.)
  115. */
  116. void *tor_malloc(size_t size) {
  117. void *result;
  118. /* Some libcs don't do the right thing on size==0. Override them. */
  119. if (size==0) {
  120. size=1;
  121. }
  122. result = malloc(size);
  123. if(!result) {
  124. log_fn(LOG_ERR, "Out of memory. Dying.");
  125. exit(1);
  126. }
  127. // memset(result,'X',size); /* deadbeef to encourage bugs */
  128. return result;
  129. }
  130. /* Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
  131. * zero bytes, and return a pointer to the result. Log and terminate
  132. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  133. */
  134. void *tor_malloc_zero(size_t size) {
  135. void *result = tor_malloc(size);
  136. memset(result, 0, size);
  137. return result;
  138. }
  139. /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
  140. * bytes long; return the new memory block. On error, log and
  141. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  142. */
  143. void *tor_realloc(void *ptr, size_t size) {
  144. void *result;
  145. result = realloc(ptr, size);
  146. if (!result) {
  147. log_fn(LOG_ERR, "Out of memory. Dying.");
  148. exit(1);
  149. }
  150. return result;
  151. }
  152. /** Return a newly allocated copy of the NUL-terminated string s. On
  153. * error, log and terminate. (Like strdup(s), but never returns
  154. * NULL.)
  155. */
  156. char *tor_strdup(const char *s) {
  157. char *dup;
  158. tor_assert(s);
  159. dup = strdup(s);
  160. if(!dup) {
  161. log_fn(LOG_ERR,"Out of memory. Dying.");
  162. exit(1);
  163. }
  164. return dup;
  165. }
  166. /** Allocate and return a new string containing the first <b>n</b>
  167. * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
  168. * characters, only the first <b>n</b> are copied. The result is
  169. * always NUL-terminated. (Like strndup(s,n), but never returns
  170. * NULL.)
  171. */
  172. char *tor_strndup(const char *s, size_t n) {
  173. char *dup;
  174. tor_assert(s);
  175. dup = tor_malloc(n+1);
  176. strncpy(dup, s, n);
  177. dup[n] = 0;
  178. return dup;
  179. }
  180. #ifndef UNALIGNED_INT_ACCESS_OK
  181. /**
  182. * Read a 16-bit value beginning at <b>cp</b>. Equaivalent to
  183. * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
  184. * unaligned memory access.
  185. */
  186. uint16_t get_uint16(const char *cp)
  187. {
  188. uint16_t v;
  189. memcpy(&v,cp,2);
  190. return v;
  191. }
  192. /**
  193. * Read a 32-bit value beginning at <b>cp</b>. Equaivalent to
  194. * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
  195. * unaligned memory access.
  196. */
  197. uint32_t get_uint32(const char *cp)
  198. {
  199. uint32_t v;
  200. memcpy(&v,cp,4);
  201. return v;
  202. }
  203. /**
  204. * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  205. * *(uint16_t)(cp) = v, but will not cause segfaults on platforms that forbid
  206. * unaligned memory access. */
  207. void set_uint16(char *cp, uint16_t v)
  208. {
  209. memcpy(cp,&v,2);
  210. }
  211. /**
  212. * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  213. * *(uint32_t)(cp) = v, but will not cause segfaults on platforms that forbid
  214. * unaligned memory access. */
  215. void set_uint32(char *cp, uint32_t v)
  216. {
  217. memcpy(cp,&v,4);
  218. }
  219. #endif
  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. base16_encode(buf,sizeof(buf),from,fromlen);
  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. struct timeb tb;
  744. ftime(&tb);
  745. timeval->tv_sec = tb.time;
  746. timeval->tv_usec = tb.millitm * 1000;
  747. #else
  748. #error "No way to get time."
  749. #endif
  750. return;
  751. }
  752. /** Return the number of microseconds elapsed between *start and *end.
  753. * If start is after end, return 0.
  754. */
  755. long
  756. tv_udiff(struct timeval *start, struct timeval *end)
  757. {
  758. long udiff;
  759. long secdiff = end->tv_sec - start->tv_sec;
  760. if (secdiff+1 > LONG_MAX/1000000) {
  761. log_fn(LOG_WARN, "comparing times too far apart.");
  762. return LONG_MAX;
  763. }
  764. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  765. if(udiff < 0) {
  766. log_fn(LOG_INFO, "start (%ld.%ld) is after end (%ld.%ld). Returning 0.",
  767. (long)start->tv_sec, (long)start->tv_usec, (long)end->tv_sec, (long)end->tv_usec);
  768. return 0;
  769. }
  770. return udiff;
  771. }
  772. /** Return -1 if *a \< *b, 0 if *a==*b, and 1 if *a \> *b.
  773. */
  774. int tv_cmp(struct timeval *a, struct timeval *b) {
  775. if (a->tv_sec > b->tv_sec)
  776. return 1;
  777. if (a->tv_sec < b->tv_sec)
  778. return -1;
  779. if (a->tv_usec > b->tv_usec)
  780. return 1;
  781. if (a->tv_usec < b->tv_usec)
  782. return -1;
  783. return 0;
  784. }
  785. /** Increment *a by the number of seconds and microseconds in *b.
  786. */
  787. void tv_add(struct timeval *a, struct timeval *b) {
  788. a->tv_usec += b->tv_usec;
  789. a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
  790. a->tv_usec %= 1000000;
  791. }
  792. /** Increment *a by <b>ms</b> milliseconds.
  793. */
  794. void tv_addms(struct timeval *a, long ms) {
  795. a->tv_usec += (ms * 1000) % 1000000;
  796. a->tv_sec += ((ms * 1000) / 1000000) + (a->tv_usec / 1000000);
  797. a->tv_usec %= 1000000;
  798. }
  799. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  800. static int n_leapdays(int y1, int y2) {
  801. --y1;
  802. --y2;
  803. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  804. }
  805. /** Number of days per month in non-leap year; used by tor_timegm. */
  806. static const int days_per_month[] =
  807. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  808. /** Return a time_t given a struct tm. The result is given in GMT, and
  809. * does not account for leap seconds.
  810. */
  811. time_t tor_timegm (struct tm *tm) {
  812. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  813. * It's way more brute-force than fiddling with tzset().
  814. */
  815. time_t ret;
  816. unsigned long year, days, hours, minutes;
  817. int i;
  818. year = tm->tm_year + 1900;
  819. tor_assert(year >= 1970);
  820. tor_assert(tm->tm_mon >= 0 && tm->tm_mon <= 11);
  821. days = 365 * (year-1970) + n_leapdays(1970,year);
  822. for (i = 0; i < tm->tm_mon; ++i)
  823. days += days_per_month[i];
  824. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  825. ++days;
  826. days += tm->tm_mday - 1;
  827. hours = days*24 + tm->tm_hour;
  828. minutes = hours*60 + tm->tm_min;
  829. ret = minutes*60 + tm->tm_sec;
  830. return ret;
  831. }
  832. /* strftime is locale-specific, so we need to replace those parts */
  833. static const char *WEEKDAY_NAMES[] =
  834. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  835. static const char *MONTH_NAMES[] =
  836. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  837. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  838. void format_rfc1123_time(char *buf, time_t t) {
  839. struct tm *tm = gmtime(&t);
  840. strftime(buf, RFC1123_TIME_LEN+1, "XXX, %d XXX %Y %H:%M:%S GMT", tm);
  841. tor_assert(tm->tm_wday >= 0 && tm->tm_wday <= 6);
  842. memcpy(buf, WEEKDAY_NAMES[tm->tm_wday], 3);
  843. tor_assert(tm->tm_wday >= 0 && tm->tm_mon <= 11);
  844. memcpy(buf+8, MONTH_NAMES[tm->tm_mon], 3);
  845. }
  846. int parse_rfc1123_time(const char *buf, time_t *t) {
  847. struct tm tm;
  848. char month[4];
  849. char weekday[4];
  850. int i, m;
  851. if (strlen(buf) != RFC1123_TIME_LEN)
  852. return -1;
  853. memset(&tm, 0, sizeof(tm));
  854. if (sscanf(buf, "%3s, %d %3s %d %d:%d:%d GMT", weekday,
  855. &tm.tm_mday, month, &tm.tm_year, &tm.tm_hour,
  856. &tm.tm_min, &tm.tm_sec) < 7) {
  857. log_fn(LOG_WARN, "Got invalid RFC1123 time \"%s\"", buf);
  858. return -1;
  859. }
  860. m = -1;
  861. for (i = 0; i < 12; ++i) {
  862. if (!strcmp(month, MONTH_NAMES[i])) {
  863. m = i;
  864. break;
  865. }
  866. }
  867. if (m<0) {
  868. log_fn(LOG_WARN, "Got invalid RFC1123 time \"%s\"", buf);
  869. return -1;
  870. }
  871. tm.tm_mon = m;
  872. tm.tm_year -= 1900;
  873. *t = tor_timegm(&tm);
  874. return 0;
  875. }
  876. void format_iso_time(char *buf, time_t t) {
  877. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", gmtime(&t));
  878. }
  879. int parse_iso_time(const char *cp, time_t *t) {
  880. struct tm st_tm;
  881. #ifdef HAVE_STRPTIME
  882. if (!strptime(cp, "%Y-%m-%d %H:%M:%S", &st_tm)) {
  883. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  884. }
  885. #else
  886. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  887. if (sscanf(cp, "%u-%u-%u %u:%u:%u", &year, &month,
  888. &day, &hour, &minute, &second) < 6) {
  889. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  890. }
  891. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  892. hour > 23 || minute > 59 || second > 61) {
  893. log_fn(LOG_WARN, "Published time was nonsensical"); return -1;
  894. }
  895. st_tm.tm_year = year;
  896. st_tm.tm_mon = month-1;
  897. st_tm.tm_mday = day;
  898. st_tm.tm_hour = hour;
  899. st_tm.tm_min = minute;
  900. st_tm.tm_sec = second;
  901. #endif
  902. *t = tor_timegm(&st_tm);
  903. return 0;
  904. }
  905. /*
  906. * Low-level I/O.
  907. */
  908. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  909. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  910. * was returned by open(). Return the number of bytes written, or -1
  911. * on error. Only use if fd is a blocking fd. */
  912. int write_all(int fd, const char *buf, size_t count, int isSocket) {
  913. size_t written = 0;
  914. int result;
  915. while(written != count) {
  916. if (isSocket)
  917. result = send(fd, buf+written, count-written, 0);
  918. else
  919. result = write(fd, buf+written, count-written);
  920. if(result<0)
  921. return -1;
  922. written += result;
  923. }
  924. return count;
  925. }
  926. /** Read <b>count</b> bytes from <b>fd</b> to <b>buf</b>. isSocket must be 1 if fd
  927. * was returned by socket() or accept(), and 0 if fd was returned by
  928. * open(). Return the number of bytes read, or -1 on error. Only use
  929. * if fd is a blocking fd. */
  930. int read_all(int fd, char *buf, size_t count, int isSocket) {
  931. size_t numread = 0;
  932. int result;
  933. while(numread != count) {
  934. if (isSocket)
  935. result = recv(fd, buf+numread, count-numread, 0);
  936. else
  937. result = read(fd, buf+numread, count-numread);
  938. if(result<=0)
  939. return -1;
  940. numread += result;
  941. }
  942. return count;
  943. }
  944. /** Turn <b>socket</b> into a nonblocking socket.
  945. */
  946. void set_socket_nonblocking(int socket)
  947. {
  948. #ifdef MS_WINDOWS
  949. /* Yes means no and no means yes. Do you not want to be nonblocking? */
  950. int nonblocking = 0;
  951. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  952. #else
  953. fcntl(socket, F_SETFL, O_NONBLOCK);
  954. #endif
  955. }
  956. /*
  957. * Process control
  958. */
  959. /** Minimalist interface to run a void function in the background. On
  960. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  961. * func should not return, but rather should call spawn_exit.
  962. */
  963. int spawn_func(int (*func)(void *), void *data)
  964. {
  965. #ifdef MS_WINDOWS
  966. int rv;
  967. rv = _beginthread(func, 0, data);
  968. if (rv == (unsigned long) -1)
  969. return -1;
  970. return 0;
  971. #else
  972. pid_t pid;
  973. pid = fork();
  974. if (pid<0)
  975. return -1;
  976. if (pid==0) {
  977. /* Child */
  978. func(data);
  979. tor_assert(0); /* Should never reach here. */
  980. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  981. } else {
  982. /* Parent */
  983. return 0;
  984. }
  985. #endif
  986. }
  987. /** End the current thread/process.
  988. */
  989. void spawn_exit()
  990. {
  991. #ifdef MS_WINDOWS
  992. _endthread();
  993. #else
  994. exit(0);
  995. #endif
  996. }
  997. /**
  998. * Allocate a pair of connected sockets. (Like socketpair(family,
  999. * type,protocol,fd), but works on systems that don't have
  1000. * socketpair.)
  1001. *
  1002. * Currently, only (AF_UNIX, SOCK_STREAM, 0 ) sockets are supported.
  1003. *
  1004. * Note that on systems without socketpair, this call will fail if
  1005. * localhost is inaccessible (for example, if the networking
  1006. * stack is down). And even if it succeeds, the socket pair will not
  1007. * be able to read while localhost is down later (the socket pair may
  1008. * even close, depending on OS-specific timeouts).
  1009. **/
  1010. int
  1011. tor_socketpair(int family, int type, int protocol, int fd[2])
  1012. {
  1013. #ifdef HAVE_SOCKETPAIR
  1014. return socketpair(family, type, protocol, fd);
  1015. #else
  1016. /* This socketpair does not work when localhost is down. So
  1017. * it's really not the same thing at all. But it's close enough
  1018. * for now, and really, when localhost is down sometimes, we
  1019. * have other problems too.
  1020. */
  1021. int listener = -1;
  1022. int connector = -1;
  1023. int acceptor = -1;
  1024. struct sockaddr_in listen_addr;
  1025. struct sockaddr_in connect_addr;
  1026. int size;
  1027. if (protocol
  1028. #ifdef AF_UNIX
  1029. || family != AF_UNIX
  1030. #endif
  1031. ) {
  1032. #ifdef MS_WINDOWS
  1033. errno = WSAEAFNOSUPPORT;
  1034. #else
  1035. errno = EAFNOSUPPORT;
  1036. #endif
  1037. return -1;
  1038. }
  1039. if (!fd) {
  1040. errno = EINVAL;
  1041. return -1;
  1042. }
  1043. listener = socket(AF_INET, type, 0);
  1044. if (listener == -1)
  1045. return -1;
  1046. memset (&listen_addr, 0, sizeof (listen_addr));
  1047. listen_addr.sin_family = AF_INET;
  1048. listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
  1049. listen_addr.sin_port = 0; /* kernel choses port. */
  1050. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  1051. == -1)
  1052. goto tidy_up_and_fail;
  1053. if (listen(listener, 1) == -1)
  1054. goto tidy_up_and_fail;
  1055. connector = socket(AF_INET, type, 0);
  1056. if (connector == -1)
  1057. goto tidy_up_and_fail;
  1058. /* We want to find out the port number to connect to. */
  1059. size = sizeof (connect_addr);
  1060. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  1061. goto tidy_up_and_fail;
  1062. if (size != sizeof (connect_addr))
  1063. goto abort_tidy_up_and_fail;
  1064. if (connect(connector, (struct sockaddr *) &connect_addr,
  1065. sizeof (connect_addr)) == -1)
  1066. goto tidy_up_and_fail;
  1067. size = sizeof (listen_addr);
  1068. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  1069. if (acceptor == -1)
  1070. goto tidy_up_and_fail;
  1071. if (size != sizeof(listen_addr))
  1072. goto abort_tidy_up_and_fail;
  1073. tor_close_socket(listener);
  1074. /* Now check we are talking to ourself by matching port and host on the
  1075. two sockets. */
  1076. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  1077. goto tidy_up_and_fail;
  1078. if (size != sizeof (connect_addr)
  1079. || listen_addr.sin_family != connect_addr.sin_family
  1080. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  1081. || listen_addr.sin_port != connect_addr.sin_port) {
  1082. goto abort_tidy_up_and_fail;
  1083. }
  1084. fd[0] = connector;
  1085. fd[1] = acceptor;
  1086. return 0;
  1087. abort_tidy_up_and_fail:
  1088. #ifdef MS_WINDOWS
  1089. errno = WSAECONNABORTED;
  1090. #else
  1091. errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  1092. #endif
  1093. tidy_up_and_fail:
  1094. {
  1095. int save_errno = errno;
  1096. if (listener != -1)
  1097. tor_close_socket(listener);
  1098. if (connector != -1)
  1099. tor_close_socket(connector);
  1100. if (acceptor != -1)
  1101. tor_close_socket(acceptor);
  1102. errno = save_errno;
  1103. return -1;
  1104. }
  1105. #endif
  1106. }
  1107. /**
  1108. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  1109. * you need to ask the socket for its actual errno. Also, you need to
  1110. * get your errors from WSAGetLastError, not errno. (If you supply a
  1111. * socket of -1, we check WSAGetLastError, but don't correct
  1112. * WSAEWOULDBLOCKs.)
  1113. */
  1114. #ifdef MS_WINDOWS
  1115. int tor_socket_errno(int sock)
  1116. {
  1117. int optval, optvallen=sizeof(optval);
  1118. int err = WSAGetLastError();
  1119. if (err == WSAEWOULDBLOCK && sock >= 0) {
  1120. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  1121. return err;
  1122. if (optval)
  1123. return optval;
  1124. }
  1125. return err;
  1126. }
  1127. #endif
  1128. #ifdef MS_WINDOWS
  1129. #define E(code, s) { code, (s " [" #code " ]") }
  1130. struct { int code; const char *msg; } windows_socket_errors[] = {
  1131. E(WSAEINTR, "Interrupted function call"),
  1132. E(WSAEACCES, "Permission denied"),
  1133. E(WSAEFAULT, "Bad address"),
  1134. E(WSAEINVAL, "Invalid argument"),
  1135. E(WSAEMFILE, "Too many open files"),
  1136. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  1137. E(WSAEINPROGRESS, "Operation now in progress"),
  1138. E(WSAEALREADY, "Operation already in progress"),
  1139. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  1140. E(WSAEDESTADDRREQ, "Destination address required"),
  1141. E(WSAEMSGSIZE, "Message too long"),
  1142. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  1143. E(WSAENOPROTOOPT, "Bad protocol option"),
  1144. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  1145. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  1146. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  1147. E(WSAEOPNOTSUPP, "Operation not supported"),
  1148. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  1149. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  1150. E(WSAEADDRINUSE, "Address already in use"),
  1151. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  1152. E(WSAENETDOWN, "Network is down"),
  1153. E(WSAENETUNREACH, "Network is unreachable"),
  1154. E(WSAENETRESET, "Network dropped connection on reset"),
  1155. E(WSAECONNABORTED, "Software caused connection abort"),
  1156. E(WSAECONNRESET, "Connection reset by peer"),
  1157. E(WSAENOBUFS, "No buffer space avaialable"),
  1158. E(WSAEISCONN, "Socket is already connected"),
  1159. E(WSAENOTCONN, "Socket is not connected"),
  1160. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  1161. E(WSAETIMEDOUT, "Connection timed out"),
  1162. E(WSAECONNREFUSED, "Connection refused"),
  1163. E(WSAEHOSTDOWN, "Host is down"),
  1164. E(WSAEHOSTUNREACH, "No route to host"),
  1165. E(WSAEPROCLIM, "Too many processes"),
  1166. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  1167. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  1168. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  1169. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  1170. E(WSAEDISCON, "Graceful shutdown now in progress"),
  1171. #ifdef WSATYPE_NOT_FOUND
  1172. E(WSATYPE_NOT_FOUND, "Class type not found"),
  1173. #endif
  1174. E(WSAHOST_NOT_FOUND, "Host not found"),
  1175. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  1176. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  1177. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  1178. /* There are some more error codes whose numeric values are marked
  1179. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  1180. * reason that practitioners of some craft traditions deliberately
  1181. * introduce imperfections into their baskets and rugs "to allow the
  1182. * evil spirits to escape." If we catch them, then our binaries
  1183. * might not report consistent results across versions of Windows.
  1184. * Thus, I'm going to let them all fall through.
  1185. */
  1186. { -1, NULL },
  1187. };
  1188. /** There does not seem to be a strerror equivalent for winsock errors.
  1189. * Naturally, we have to roll our own.
  1190. */
  1191. const char *tor_socket_strerror(int e)
  1192. {
  1193. int i;
  1194. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  1195. if (e == windows_socket_errors[i].code)
  1196. return windows_socket_errors[i].msg;
  1197. }
  1198. return strerror(e);
  1199. }
  1200. #endif
  1201. /*
  1202. * Filesystem operations.
  1203. */
  1204. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1205. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1206. * directory. */
  1207. file_status_t file_status(const char *fname)
  1208. {
  1209. struct stat st;
  1210. if (stat(fname, &st)) {
  1211. if (errno == ENOENT) {
  1212. return FN_NOENT;
  1213. }
  1214. return FN_ERROR;
  1215. }
  1216. if (st.st_mode & S_IFDIR)
  1217. return FN_DIR;
  1218. else if (st.st_mode & S_IFREG)
  1219. return FN_FILE;
  1220. else
  1221. return FN_ERROR;
  1222. }
  1223. /** Check whether dirname exists and is private. If yes return 0. If
  1224. * it does not exist, and create is set, try to create it and return 0
  1225. * on success. Else return -1. */
  1226. int check_private_dir(const char *dirname, int create)
  1227. {
  1228. int r;
  1229. struct stat st;
  1230. tor_assert(dirname);
  1231. if (stat(dirname, &st)) {
  1232. if (errno != ENOENT) {
  1233. log(LOG_WARN, "Directory %s cannot be read: %s", dirname,
  1234. strerror(errno));
  1235. return -1;
  1236. }
  1237. if (!create) {
  1238. log(LOG_WARN, "Directory %s does not exist.", dirname);
  1239. return -1;
  1240. }
  1241. log(LOG_INFO, "Creating directory %s", dirname);
  1242. #ifdef MS_WINDOWS
  1243. r = mkdir(dirname);
  1244. #else
  1245. r = mkdir(dirname, 0700);
  1246. #endif
  1247. if (r) {
  1248. log(LOG_WARN, "Error creating directory %s: %s", dirname,
  1249. strerror(errno));
  1250. return -1;
  1251. } else {
  1252. return 0;
  1253. }
  1254. }
  1255. if (!(st.st_mode & S_IFDIR)) {
  1256. log(LOG_WARN, "%s is not a directory", dirname);
  1257. return -1;
  1258. }
  1259. #ifndef MS_WINDOWS
  1260. if (st.st_uid != getuid()) {
  1261. log(LOG_WARN, "%s is not owned by this UID (%d). You must fix this to proceed.", dirname, (int)getuid());
  1262. return -1;
  1263. }
  1264. if (st.st_mode & 0077) {
  1265. log(LOG_WARN, "Fixing permissions on directory %s", dirname);
  1266. if (chmod(dirname, 0700)) {
  1267. log(LOG_WARN, "Could not chmod directory %s: %s", dirname,
  1268. strerror(errno));
  1269. return -1;
  1270. } else {
  1271. return 0;
  1272. }
  1273. }
  1274. #endif
  1275. return 0;
  1276. }
  1277. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite the
  1278. * previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1279. *
  1280. * This function replaces the old file atomically, if possible.
  1281. */
  1282. int
  1283. write_str_to_file(const char *fname, const char *str)
  1284. {
  1285. char tempname[1024];
  1286. int fd;
  1287. FILE *file;
  1288. if ((strlcpy(tempname,fname,1024) >= 1024) ||
  1289. (strlcat(tempname,".tmp",1024) >= 1024)) {
  1290. log(LOG_WARN, "Filename %s.tmp too long (>1024 chars)", fname);
  1291. return -1;
  1292. }
  1293. if ((fd = open(tempname, O_WRONLY|O_CREAT|O_TRUNC, 0600)) < 0) {
  1294. log(LOG_WARN, "Couldn't open %s for writing: %s", tempname,
  1295. strerror(errno));
  1296. return -1;
  1297. }
  1298. if (!(file = fdopen(fd, "w"))) {
  1299. log(LOG_WARN, "Couldn't fdopen %s for writing: %s", tempname,
  1300. strerror(errno));
  1301. close(fd);
  1302. return -1;
  1303. }
  1304. if (fputs(str,file) == EOF) {
  1305. log(LOG_WARN, "Error writing to %s: %s", tempname, strerror(errno));
  1306. fclose(file);
  1307. return -1;
  1308. }
  1309. if (fclose(file) == EOF) {
  1310. log(LOG_WARN,"Error flushing to %s: %s", tempname, strerror(errno));
  1311. return -1;
  1312. }
  1313. #ifdef MS_WINDOWS
  1314. /* On Windows, rename doesn't replace. We could call ReplaceFile, but
  1315. * that's hard, and we can probably sneak by without atomicity. */
  1316. switch (file_status(fname)) {
  1317. case FN_ERROR:
  1318. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  1319. return -1;
  1320. case FN_DIR:
  1321. log(LOG_WARN, "Error replacing %s: is directory", fname);
  1322. return -1;
  1323. case FN_FILE:
  1324. if (unlink(fname)) {
  1325. log(LOG_WARN, "Error replacing %s while removing old copy: %s",
  1326. fname, strerror(errno));
  1327. return -1;
  1328. }
  1329. break;
  1330. case FN_NOENT:
  1331. ;
  1332. }
  1333. #endif
  1334. if (rename(tempname, fname)) {
  1335. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  1336. return -1;
  1337. }
  1338. return 0;
  1339. }
  1340. /** Read the contents of <b>filename</b> into a newly allocated string; return the
  1341. * string on success or NULL on failure.
  1342. */
  1343. char *read_file_to_str(const char *filename) {
  1344. int fd; /* router file */
  1345. struct stat statbuf;
  1346. char *string;
  1347. tor_assert(filename);
  1348. if(strcspn(filename,CONFIG_LEGAL_FILENAME_CHARACTERS) != 0) {
  1349. log_fn(LOG_WARN,"Filename %s contains illegal characters.",filename);
  1350. return NULL;
  1351. }
  1352. if(stat(filename, &statbuf) < 0) {
  1353. log_fn(LOG_INFO,"Could not stat %s.",filename);
  1354. return NULL;
  1355. }
  1356. fd = open(filename,O_RDONLY,0);
  1357. if (fd<0) {
  1358. log_fn(LOG_WARN,"Could not open %s.",filename);
  1359. return NULL;
  1360. }
  1361. string = tor_malloc(statbuf.st_size+1);
  1362. if(read_all(fd,string,statbuf.st_size,0) != statbuf.st_size) {
  1363. log_fn(LOG_WARN,"Couldn't read all %ld bytes of file '%s'.",
  1364. (long)statbuf.st_size,filename);
  1365. free(string);
  1366. close(fd);
  1367. return NULL;
  1368. }
  1369. close(fd);
  1370. string[statbuf.st_size] = 0; /* null terminate it */
  1371. return string;
  1372. }
  1373. /** read lines from f (no more than maxlen-1 bytes each) until we
  1374. * get a non-whitespace line. If it isn't of the form "key value"
  1375. * (value can have spaces), return -1.
  1376. * Point *key to the first word in line, point *value * to the second.
  1377. * Put a \0 at the end of key, remove everything at the end of value
  1378. * that is whitespace or comment.
  1379. * Return 1 if success, 0 if no more lines, -1 if error.
  1380. */
  1381. int parse_line_from_file(char *line, int maxlen, FILE *f, char **key_out, char **value_out) {
  1382. char *s, *key, *end, *value;
  1383. try_next_line:
  1384. if(!fgets(line, maxlen, f)) {
  1385. if(feof(f))
  1386. return 0;
  1387. return -1; /* real error */
  1388. }
  1389. if((s = strchr(line,'#'))) /* strip comments */
  1390. *s = 0; /* stop the line there */
  1391. /* remove end whitespace */
  1392. s = strchr(line, 0); /* now we're at the null */
  1393. do {
  1394. *s = 0;
  1395. s--;
  1396. } while (s >= line && isspace((int)*s));
  1397. key = line;
  1398. while(isspace((int)*key))
  1399. key++;
  1400. if(*key == 0)
  1401. goto try_next_line; /* this line has nothing on it */
  1402. end = key;
  1403. while(*end && !isspace((int)*end))
  1404. end++;
  1405. value = end;
  1406. while(*value && isspace((int)*value))
  1407. value++;
  1408. if(!*end || !*value) { /* only a key on this line. no value. */
  1409. *end = 0;
  1410. log_fn(LOG_WARN,"Line has keyword '%s' but no value. Failing.",key);
  1411. return -1;
  1412. }
  1413. *end = 0; /* null it out */
  1414. log_fn(LOG_DEBUG,"got keyword '%s', value '%s'", key, value);
  1415. *key_out = key, *value_out = value;
  1416. return 1;
  1417. }
  1418. /** Expand any homedir prefix on 'filename'; return a newly allocated
  1419. * string. */
  1420. char *expand_filename(const char *filename)
  1421. {
  1422. tor_assert(filename);
  1423. /* XXXX Should eventually check for ~username/ */
  1424. if (!strncmp(filename,"~/",2)) {
  1425. const char *home = getenv("HOME");
  1426. char *result;
  1427. if (!home) {
  1428. log_fn(LOG_ERR, "Couldn't find $HOME environment variable while expanding %s", filename);
  1429. return NULL;
  1430. }
  1431. /* minus two characters for ~/, plus one for /, plus one for NUL. */
  1432. result = tor_malloc(strlen(home)+strlen(filename)+16);
  1433. sprintf(result,"%s/%s",home,filename+2);
  1434. return result;
  1435. } else {
  1436. return tor_strdup(filename);
  1437. }
  1438. }
  1439. /**
  1440. * Rename the file 'from' to the file 'to'. On unix, this is the same as
  1441. * rename(2). On windows, this removes 'to' first if it already exists.
  1442. * Returns 0 on success. Returns -1 and sets errno on failure.
  1443. */
  1444. int replace_file(const char *from, const char *to)
  1445. {
  1446. #ifndef MS_WINDOWS
  1447. return rename(from,to);
  1448. #else
  1449. switch(file_status(to))
  1450. {
  1451. case FN_NOENT:
  1452. break;
  1453. case FN_FILE:
  1454. if (unlink(to)) return -1;
  1455. break;
  1456. case FN_ERROR:
  1457. return -1;
  1458. case FN_DIR:
  1459. errno = EISDIR;
  1460. return -1;
  1461. }
  1462. return rename(from,to);
  1463. #endif
  1464. }
  1465. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  1466. * or reserved for local networks by RFC 1918.
  1467. */
  1468. int is_internal_IP(uint32_t ip) {
  1469. if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
  1470. ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
  1471. ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
  1472. ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  1473. ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  1474. ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  1475. return 1;
  1476. return 0;
  1477. }
  1478. /** Return true iff <b>ip</b> (in host order) is judged to be on the
  1479. * same network as us. For now, check if it's an internal IP. For XXX008,
  1480. * also check if it's on the same class C network as our public IP.
  1481. */
  1482. int is_local_IP(uint32_t ip) {
  1483. return is_internal_IP(ip);
  1484. }
  1485. /* Hold the result of our call to <b>uname</b>. */
  1486. static char uname_result[256];
  1487. /* True iff uname_result is set. */
  1488. static int uname_result_is_set = 0;
  1489. /* Return a pointer to a description of our platform.
  1490. */
  1491. const char *
  1492. get_uname(void)
  1493. {
  1494. #ifdef HAVE_UNAME
  1495. struct utsname u;
  1496. #endif
  1497. if (!uname_result_is_set) {
  1498. #ifdef HAVE_UNAME
  1499. if (uname(&u) != -1) {
  1500. /* (linux says 0 is success, solaris says 1 is success) */
  1501. snprintf(uname_result, 255, "%s %s %s",
  1502. u.sysname, u.nodename, u.machine);
  1503. uname_result[255] = '\0';
  1504. } else
  1505. #endif
  1506. {
  1507. strcpy(uname_result, "Unknown platform");
  1508. }
  1509. uname_result_is_set = 1;
  1510. }
  1511. return uname_result;
  1512. }
  1513. #ifndef MS_WINDOWS
  1514. /* Based on code contributed by christian grothoff */
  1515. static int start_daemon_called = 0;
  1516. static int finish_daemon_called = 0;
  1517. static int daemon_filedes[2];
  1518. /** Start putting the process into daemon mode: fork and drop all resources
  1519. * except standard fds. The parent process never returns, but stays around
  1520. * until finish_daemon is called. (Note: it's safe to call this more
  1521. * than once: calls after the first are ignored.)
  1522. */
  1523. void start_daemon(const char *desired_cwd)
  1524. {
  1525. pid_t pid;
  1526. if (start_daemon_called)
  1527. return;
  1528. start_daemon_called = 1;
  1529. if(!desired_cwd)
  1530. desired_cwd = "/";
  1531. /* Don't hold the wrong FS mounted */
  1532. if (chdir(desired_cwd) < 0) {
  1533. log_fn(LOG_ERR,"chdir to %s failed. Exiting.",desired_cwd);
  1534. exit(1);
  1535. }
  1536. pipe(daemon_filedes);
  1537. pid = fork();
  1538. if (pid < 0) {
  1539. log_fn(LOG_ERR,"fork failed. Exiting.");
  1540. exit(1);
  1541. }
  1542. if (pid) { /* Parent */
  1543. int ok;
  1544. char c;
  1545. close(daemon_filedes[1]); /* we only read */
  1546. ok = -1;
  1547. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  1548. if (c == '.')
  1549. ok = 1;
  1550. }
  1551. fflush(stdout);
  1552. if (ok == 1)
  1553. exit(0);
  1554. else
  1555. exit(1); /* child reported error */
  1556. } else { /* Child */
  1557. close(daemon_filedes[0]); /* we only write */
  1558. pid = setsid(); /* Detach from controlling terminal */
  1559. /*
  1560. * Fork one more time, so the parent (the session group leader) can exit.
  1561. * This means that we, as a non-session group leader, can never regain a
  1562. * controlling terminal. This part is recommended by Stevens's
  1563. * _Advanced Programming in the Unix Environment_.
  1564. */
  1565. if (fork() != 0) {
  1566. exit(0);
  1567. }
  1568. return;
  1569. }
  1570. }
  1571. /** Finish putting the process into daemon mode: drop standard fds, and tell
  1572. * the parent process to exit. (Note: it's safe to call this more than once:
  1573. * calls after the first are ignored. Calls start_daemon first if it hasn't
  1574. * been called already.)
  1575. */
  1576. void finish_daemon(void)
  1577. {
  1578. int nullfd;
  1579. char c = '.';
  1580. if (finish_daemon_called)
  1581. return;
  1582. if (!start_daemon_called)
  1583. start_daemon(NULL);
  1584. finish_daemon_called = 1;
  1585. nullfd = open("/dev/null",
  1586. O_CREAT | O_RDWR | O_APPEND);
  1587. if (nullfd < 0) {
  1588. log_fn(LOG_ERR,"/dev/null can't be opened. Exiting.");
  1589. exit(1);
  1590. }
  1591. /* close fds linking to invoking terminal, but
  1592. * close usual incoming fds, but redirect them somewhere
  1593. * useful so the fds don't get reallocated elsewhere.
  1594. */
  1595. if (dup2(nullfd,0) < 0 ||
  1596. dup2(nullfd,1) < 0 ||
  1597. dup2(nullfd,2) < 0) {
  1598. log_fn(LOG_ERR,"dup2 failed. Exiting.");
  1599. exit(1);
  1600. }
  1601. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  1602. close(daemon_filedes[1]);
  1603. }
  1604. #else
  1605. /* defined(MS_WINDOWS) */
  1606. void start_daemon(const char *cp) {}
  1607. void finish_daemon(void) {}
  1608. #endif
  1609. /** Write the current process ID, followed by NL, into <b>filename</b>.
  1610. */
  1611. void write_pidfile(char *filename) {
  1612. #ifndef MS_WINDOWS
  1613. FILE *pidfile;
  1614. if ((pidfile = fopen(filename, "w")) == NULL) {
  1615. log_fn(LOG_WARN, "Unable to open %s for writing: %s", filename,
  1616. strerror(errno));
  1617. } else {
  1618. fprintf(pidfile, "%d\n", (int)getpid());
  1619. fclose(pidfile);
  1620. }
  1621. #endif
  1622. }
  1623. /** Call setuid and setgid to run as <b>user</b>:<b>group</b>. Return 0 on
  1624. * success. On failure, log and return -1.
  1625. */
  1626. int switch_id(char *user, char *group) {
  1627. #ifndef MS_WINDOWS
  1628. struct passwd *pw = NULL;
  1629. struct group *gr = NULL;
  1630. if (user) {
  1631. pw = getpwnam(user);
  1632. if (pw == NULL) {
  1633. log_fn(LOG_ERR,"User '%s' not found.", user);
  1634. return -1;
  1635. }
  1636. }
  1637. /* switch the group first, while we still have the privileges to do so */
  1638. if (group) {
  1639. gr = getgrnam(group);
  1640. if (gr == NULL) {
  1641. log_fn(LOG_ERR,"Group '%s' not found.", group);
  1642. return -1;
  1643. }
  1644. if (setgid(gr->gr_gid) != 0) {
  1645. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  1646. return -1;
  1647. }
  1648. } else if (user) {
  1649. if (setgid(pw->pw_gid) != 0) {
  1650. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  1651. return -1;
  1652. }
  1653. }
  1654. /* now that the group is switched, we can switch users and lose
  1655. privileges */
  1656. if (user) {
  1657. if (setuid(pw->pw_uid) != 0) {
  1658. log_fn(LOG_ERR,"Error setting UID: %s", strerror(errno));
  1659. return -1;
  1660. }
  1661. }
  1662. return 0;
  1663. #endif
  1664. log_fn(LOG_ERR,
  1665. "User or group specified, but switching users is not supported.");
  1666. return -1;
  1667. }
  1668. /** Set *addr to the IP address (in dotted-quad notation) stored in c.
  1669. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  1670. * but works on Windows and Solaris.)
  1671. */
  1672. int tor_inet_aton(const char *c, struct in_addr* addr)
  1673. {
  1674. #ifdef HAVE_INET_ATON
  1675. return inet_aton(c, addr);
  1676. #else
  1677. uint32_t r;
  1678. tor_assert(c && addr);
  1679. if (strcmp(c, "255.255.255.255") == 0) {
  1680. addr->s_addr = 0xFFFFFFFFu;
  1681. return 1;
  1682. }
  1683. r = inet_addr(c);
  1684. if (r == INADDR_NONE)
  1685. return 0;
  1686. addr->s_addr = r;
  1687. return 1;
  1688. #endif
  1689. }
  1690. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  1691. * *addr to the proper IP address, in network byte order. Returns 0
  1692. * on success, -1 on failure; 1 on transient failure.
  1693. *
  1694. * (This function exists because standard windows gethostbyname
  1695. * doesn't treat raw IP addresses properly.)
  1696. */
  1697. int tor_lookup_hostname(const char *name, uint32_t *addr)
  1698. {
  1699. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  1700. * something.
  1701. */
  1702. struct in_addr iaddr;
  1703. struct hostent *ent;
  1704. tor_assert(addr);
  1705. if (!*name) {
  1706. /* Empty address is an error. */
  1707. return -1;
  1708. } else if (tor_inet_aton(name, &iaddr)) {
  1709. /* It's an IP. */
  1710. memcpy(addr, &iaddr.s_addr, 4);
  1711. return 0;
  1712. } else {
  1713. ent = gethostbyname(name);
  1714. if (ent) {
  1715. /* break to remind us if we move away from IPv4 */
  1716. tor_assert(ent->h_length == 4);
  1717. memcpy(addr, ent->h_addr, 4);
  1718. return 0;
  1719. }
  1720. memset(addr, 0, 4);
  1721. #ifdef MS_WINDOWS
  1722. return (WSAGetLastError() == WSATRY_AGAIN) ? 1 : -1;
  1723. #else
  1724. return (h_errno == TRY_AGAIN) ? 1 : -1;
  1725. #endif
  1726. }
  1727. }
  1728. #ifndef MS_WINDOWS
  1729. struct tor_mutex_t {
  1730. };
  1731. tor_mutex_t *tor_mutex_new(void) { return NULL; }
  1732. void tor_mutex_acquire(tor_mutex_t *m) { }
  1733. void tor_mutex_release(tor_mutex_t *m) { }
  1734. void tor_mutex_free(tor_mutex_t *m) { }
  1735. #else
  1736. struct tor_mutex_t {
  1737. HANDLE handle;
  1738. };
  1739. tor_mutex_t *tor_mutex_new(void)
  1740. {
  1741. tor_mutex_t *m;
  1742. m = tor_malloc_zero(sizeof(tor_mutex_t));
  1743. m->handle = CreateMutex(NULL, FALSE, NULL);
  1744. tor_assert(m->handle != NULL);
  1745. return m;
  1746. }
  1747. void tor_mutex_free(tor_mutex_t *m)
  1748. {
  1749. CloseHandle(m->handle);
  1750. tor_free(m);
  1751. }
  1752. void tor_mutex_acquire(tor_mutex_t *m)
  1753. {
  1754. DWORD r;
  1755. r = WaitForSingleObject(m->handle, INFINITE);
  1756. switch (r) {
  1757. case WAIT_ABANDONED: /* holding thread exited. */
  1758. case WAIT_OBJECT_0: /* we got the mutex normally. */
  1759. break;
  1760. case WAIT_TIMEOUT: /* Should never happen. */
  1761. tor_assert(0);
  1762. break;
  1763. case WAIT_FAILED:
  1764. log_fn(LOG_WARN, "Failed to acquire mutex: %d", GetLastError());
  1765. }
  1766. }
  1767. void tor_mutex_release(tor_mutex_t *m)
  1768. {
  1769. BOOL r;
  1770. r = ReleaseMutex(m->handle);
  1771. if (!r) {
  1772. log_fn(LOG_WARN, "Failed to release mutex: %d", GetLastError());
  1773. }
  1774. }
  1775. #endif
  1776. /*
  1777. Local Variables:
  1778. mode:c
  1779. indent-tabs-mode:nil
  1780. c-basic-offset:2
  1781. End:
  1782. */