Merge branch 'maint-0.4.5' into release-0.4.5
[tor.git] / src / test / resolve_test_helpers.c
blobed5853c359af800aae4f7ca10f62705ddb423be8
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-2020, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * @file resolve_test_helpers.c
9 * @brief Helper functions for mocking libc's blocking hostname lookup
10 * facilities.
11 **/
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"
20 #include <stdio.h>
21 #include <string.h>
23 /**
24 * Mock replacement for our getaddrinfo/gethostbyname wrapper.
25 **/
26 static int
27 replacement_host_lookup(const char *name, uint16_t family, tor_addr_t *addr)
29 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 },
39 int r = -1;
41 for (unsigned i = 0; entries[i].name != NULL; ++i) {
42 if (!strcasecmp(name, entries[i].name)) {
43 if (family == AF_INET6) {
44 int s = tor_addr_parse(addr, entries[i].ipv6);
45 tt_int_op(s, OP_EQ, AF_INET6);
46 } else {
47 int s = tor_addr_parse(addr, entries[i].ipv4);
48 tt_int_op(s, OP_EQ, AF_INET);
50 r = 0;
51 break;
55 log_debug(LD_GENERAL, "resolve(%s,%d) => %s",
56 name, family, r == 0 ? fmt_addr(addr) : "-1");
58 return r;
59 done:
60 return -1;
63 /**
64 * Set up a mock replacement for our wrapper on libc's resolver code.
66 * According to our replacement, only "localhost" and "torproject.org"
67 * are real addresses; everything else doesn't exist.
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 mock_hostname_resolver(void)
75 MOCK(tor_addr_lookup_host_impl, replacement_host_lookup);
78 /**
79 * Unmock our wrappers for libc's blocking hostname resolver code.
80 **/
81 void
82 unmock_hostname_resolver(void)
84 UNMOCK(tor_addr_lookup_host_impl);