Line data Source code
1 : /* Copyright (c) 2001 Matej Pfajfar. 2 : * Copyright (c) 2001-2004, Roger Dingledine. 3 : * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. 4 : * Copyright (c) 2007-2021, The Tor Project, Inc. */ 5 : /* See LICENSE for licensing information */ 6 : 7 : /** 8 : * @file resolve_test_helpers.c 9 : * @brief Helper functions for mocking libc's blocking hostname lookup 10 : * facilities. 11 : **/ 12 : 13 : #define RESOLVE_PRIVATE 14 : #include "orconfig.h" 15 : #include "test/resolve_test_helpers.h" 16 : #include "lib/net/address.h" 17 : #include "lib/net/resolve.h" 18 : #include "test/test.h" 19 : 20 : #include <stdio.h> 21 : #include <string.h> 22 : 23 : /** 24 : * Mock replacement for our getaddrinfo/gethostbyname wrapper. 25 : **/ 26 : static int 27 186 : replacement_host_lookup(const char *name, uint16_t family, tor_addr_t *addr) 28 : { 29 186 : static const struct lookup_table_ent { 30 : const char *name; 31 : const char *ipv4; 32 : const char *ipv6; 33 : } entries[] = { 34 : { "localhost", "127.0.0.1", "::1" }, 35 : { "torproject.org", "198.51.100.6", "2001:DB8::700" }, 36 : { NULL, NULL, NULL }, 37 : }; 38 : 39 186 : int r = -1; 40 : 41 538 : for (unsigned i = 0; entries[i].name != NULL; ++i) { 42 365 : if (!strcasecmp(name, entries[i].name)) { 43 13 : if (family == AF_INET6) { 44 2 : int s = tor_addr_parse(addr, entries[i].ipv6); 45 2 : tt_int_op(s, OP_EQ, AF_INET6); 46 : } else { 47 11 : int s = tor_addr_parse(addr, entries[i].ipv4); 48 11 : tt_int_op(s, OP_EQ, AF_INET); 49 : } 50 13 : r = 0; 51 13 : break; 52 : } 53 : } 54 : 55 13 : log_debug(LD_GENERAL, "resolve(%s,%d) => %s", 56 : name, family, r == 0 ? fmt_addr(addr) : "-1"); 57 : 58 186 : return r; 59 : done: 60 : return -1; 61 : } 62 : 63 : /** 64 : * Set up a mock replacement for our wrapper on libc's resolver code. 65 : * 66 : * According to our replacement, only "localhost" and "torproject.org" 67 : * are real addresses; everything else doesn't exist. 68 : * 69 : * Use this function to avoid using the DNS resolver during unit tests; 70 : * call unmock_hostname_resolver() when you're done. 71 : **/ 72 : void 73 4 : mock_hostname_resolver(void) 74 : { 75 4 : MOCK(tor_addr_lookup_host_impl, replacement_host_lookup); 76 4 : } 77 : 78 : /** 79 : * Unmock our wrappers for libc's blocking hostname resolver code. 80 : **/ 81 : void 82 4 : unmock_hostname_resolver(void) 83 : { 84 4 : UNMOCK(tor_addr_lookup_host_impl); 85 4 : }