util.c 34 KB

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