1
#include <event2/dns.h>
2
#include <event2/event.h>
5
#include "DNSModules.h"
8
struct DNSNetworkModule_context {
9
struct event_base* base;
10
evutil_socket_t socket;
11
struct evdns_server_port* server;
12
struct DNSModuleRegistry* registry;
15
static int handleOutgoing(struct DNSMessage* message,
16
struct DNSModule* module,
17
const struct DNSModuleRegistry* registry);
18
static void handleNetworkEvent(struct evdns_server_request* request, void* module);
19
static void shutdownModule(struct DNSModule* module);
22
* Create a new DNS network module.
24
* @param base a LibEvent context.
25
* @param socket the socket to bind to.
26
* @param allocator the memory allocator to use for getting memory.
28
struct DNSModule* DNSNetworkModule_new(struct event_base* base,
29
evutil_socket_t socket,
30
struct MemAllocator* allocator)
32
struct DNSNetworkModule_context* context =
33
allocator->malloc(sizeof(struct DNSNetworkModule_context), allocator);
35
struct DNSModule* module = allocator->malloc(sizeof(struct DNSModule), allocator);
37
if (context == NULL || module == NULL) {
42
context->socket = socket;
44
struct DNSModule localModule = {
45
.name = "DNSNetworkModule",
47
.free = shutdownModule,
50
.handleIncoming = NULL,
51
.handleOutgoing = handleOutgoing
53
memcpy(module, &localModule, sizeof(struct DNSModule));
59
* Register the module.
61
* @param module the module to register.
62
* @param registry the DNSModuleRegistry to call the on an incoming message.
63
* @return whatever is returned by DNSModules_Register().
65
int DNSNetworkModule_register(struct DNSModule* module,
66
struct DNSModuleRegistry* registry)
68
struct DNSNetworkModule_context* context =
69
(struct DNSNetworkModule_context*) module->context;
71
context->registry = registry;
73
context->server = evdns_add_server_port_with_base(context->base, context->socket,
74
0, handleNetworkEvent, context);
76
return DNSModules_register(module, registry);
79
/*--------------------Internal--------------------*/
81
static void shutdownModule(struct DNSModule* module)
83
struct DNSNetworkModule_context* context =
84
(struct DNSNetworkModule_context*) module->context;
86
evdns_close_server_port(context->server);
89
static void handleNetworkEvent(struct evdns_server_request* request,
92
struct DNSNetworkModule_context* context =
93
(struct DNSNetworkModule_context*) vcontext;
95
struct DNSMessage message = {
97
.returnCode = DNS_ERR_NONE
99
DNSModules_handleIncoming(&message, context->registry);
102
static int handleOutgoing(struct DNSMessage* message,
103
struct DNSModule* module,
104
const struct DNSModuleRegistry* registry)
108
evdns_server_request_respond(message->request, message->returnCode);