~ubuntu-branches/ubuntu/hardy/transmission/hardy-updates

« back to all changes in this revision

Viewing changes to third-party/libevent/evdns.c

  • Committer: Bazaar Package Importer
  • Author(s): Philipp Benner
  • Date: 2007-10-26 16:02:39 UTC
  • mto: This revision was merged to the branch mainline in revision 6.
  • Revision ID: james.westby@ubuntu.com-20071026160239-2c0agn7q1ken0xsp
Tags: upstream-0.90.dfsg
ImportĀ upstreamĀ versionĀ 0.90.dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* $Id: evdns.c 6979 2006-08-04 18:31:13Z nickm $ */
 
2
 
 
3
/* The original version of this module was written by Adam Langley; for
 
4
 * a history of modifications, check out the subversion logs.
 
5
 *
 
6
 * When editing this module, try to keep it re-mergeable by Adam.  Don't
 
7
 * reformat the whitespace, add Tor dependencies, or so on.
 
8
 *
 
9
 * TODO:
 
10
 *   - Support IPv6 and PTR records.
 
11
 *   - Replace all externally visible magic numbers with #defined constants.
 
12
 *   - Write doccumentation for APIs of all external functions.
 
13
 */
 
14
 
 
15
/* Async DNS Library
 
16
 * Adam Langley <agl@imperialviolet.org>
 
17
 * http://www.imperialviolet.org/eventdns.html
 
18
 * Public Domain code
 
19
 *
 
20
 * This software is Public Domain. To view a copy of the public domain dedication,
 
21
 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
 
22
 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
 
23
 *
 
24
 * I ask and expect, but do not require, that all derivative works contain an
 
25
 * attribution similar to:
 
26
 *      Parts developed by Adam Langley <agl@imperialviolet.org>
 
27
 *
 
28
 * You may wish to replace the word "Parts" with something else depending on
 
29
 * the amount of original code.
 
30
 *
 
31
 * (Derivative works does not include programs which link against, run or include
 
32
 * the source verbatim in their source distributions)
 
33
 *
 
34
 * Version: 0.1b
 
35
 */
 
36
 
 
37
#include <sys/types.h>
 
38
#ifdef HAVE_CONFIG_H
 
39
#include "config.h"
 
40
#endif
 
41
 
 
42
#ifdef WIN32
 
43
#include "misc.h"
 
44
#endif
 
45
 
 
46
/* #define NDEBUG */
 
47
 
 
48
#ifndef DNS_USE_CPU_CLOCK_FOR_ID
 
49
#ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
 
50
#ifndef DNS_USE_OPENSSL_FOR_ID
 
51
#error Must configure at least one id generation method.
 
52
#error Please see the documentation.
 
53
#endif
 
54
#endif
 
55
#endif
 
56
 
 
57
/* #define _POSIX_C_SOURCE 200507 */
 
58
#define _GNU_SOURCE
 
59
 
 
60
#ifdef DNS_USE_CPU_CLOCK_FOR_ID
 
61
#ifdef DNS_USE_OPENSSL_FOR_ID
 
62
#error Multiple id options selected
 
63
#endif
 
64
#ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
 
65
#error Multiple id options selected
 
66
#endif
 
67
#include <time.h>
 
68
#endif
 
69
 
 
70
#ifdef DNS_USE_OPENSSL_FOR_ID
 
71
#ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
 
72
#error Multiple id options selected
 
73
#endif
 
74
#include <openssl/rand.h>
 
75
#endif
 
76
 
 
77
#define _FORTIFY_SOURCE 3
 
78
 
 
79
#include <string.h>
 
80
#include <fcntl.h>
 
81
#include <sys/time.h>
 
82
#ifdef HAVE_STDINT_H
 
83
#include <stdint.h>
 
84
#endif
 
85
#include <stdlib.h>
 
86
#include <string.h>
 
87
#include <errno.h>
 
88
#include <assert.h>
 
89
#include <unistd.h>
 
90
#include <limits.h>
 
91
#include <sys/stat.h>
 
92
#include <ctype.h>
 
93
#include <stdio.h>
 
94
#include <stdarg.h>
 
95
 
 
96
#include "evdns.h"
 
97
#include "evutil.h"
 
98
#include "log.h"
 
99
#ifdef WIN32
 
100
#include <windows.h>
 
101
#include <winsock2.h>
 
102
#include <iphlpapi.h>
 
103
#else
 
104
#include <sys/socket.h>
 
105
#include <netinet/in.h>
 
106
#include <arpa/inet.h>
 
107
#endif
 
108
 
 
109
#ifdef HAVE_NETINET_IN6_H
 
110
#include <netinet/in6.h>
 
111
#endif
 
112
 
 
113
#define EVDNS_LOG_DEBUG 0
 
114
#define EVDNS_LOG_WARN 1
 
115
 
 
116
#ifndef HOST_NAME_MAX
 
117
#define HOST_NAME_MAX 255
 
118
#endif
 
119
 
 
120
#ifndef NDEBUG
 
121
#include <stdio.h>
 
122
#endif
 
123
 
 
124
#undef MIN
 
125
#define MIN(a,b) ((a)<(b)?(a):(b))
 
126
 
 
127
#ifdef __USE_ISOC99B
 
128
/* libevent doesn't work without this */
 
129
typedef uint8_t u_char;
 
130
typedef unsigned int uint;
 
131
#endif
 
132
#include <event.h>
 
133
 
 
134
#define u64 uint64_t
 
135
#define u32 uint32_t
 
136
#define u16 uint16_t
 
137
#define u8  uint8_t
 
138
 
 
139
#define MAX_ADDRS 4  /* maximum number of addresses from a single packet */
 
140
/* which we bother recording */
 
141
 
 
142
#define TYPE_A         EVDNS_TYPE_A
 
143
#define TYPE_CNAME     5
 
144
#define TYPE_PTR       EVDNS_TYPE_PTR
 
145
#define TYPE_AAAA      EVDNS_TYPE_AAAA
 
146
 
 
147
#define CLASS_INET     EVDNS_CLASS_INET
 
148
 
 
149
struct request {
 
150
        u8 *request;  /* the dns packet data */
 
151
        unsigned int request_len;
 
152
        int reissue_count;
 
153
        int tx_count;  /* the number of times that this packet has been sent */
 
154
        unsigned int request_type; /* TYPE_PTR or TYPE_A */
 
155
        void *user_pointer;  /* the pointer given to us for this request */
 
156
        evdns_callback_type user_callback;
 
157
        struct nameserver *ns;  /* the server which we last sent it */
 
158
 
 
159
        /* elements used by the searching code */
 
160
        int search_index;
 
161
        struct search_state *search_state;
 
162
        char *search_origname;  /* needs to be free()ed */
 
163
        int search_flags;
 
164
 
 
165
        /* these objects are kept in a circular list */
 
166
        struct request *next, *prev;
 
167
 
 
168
        struct event timeout_event;
 
169
 
 
170
        u16 trans_id;  /* the transaction id */
 
171
        char request_appended;  /* true if the request pointer is data which follows this struct */
 
172
        char transmit_me;  /* needs to be transmitted */
 
173
};
 
174
 
 
175
#ifndef HAVE_STRUCT_IN6_ADDR
 
176
struct in6_addr {
 
177
        u8 s6_addr[16];
 
178
};
 
179
#endif
 
180
 
 
181
struct reply {
 
182
        unsigned int type;
 
183
        unsigned int have_answer;
 
184
        union {
 
185
                struct {
 
186
                        u32 addrcount;
 
187
                        u32 addresses[MAX_ADDRS];
 
188
                } a;
 
189
                struct {
 
190
                        u32 addrcount;
 
191
                        struct in6_addr addresses[MAX_ADDRS];
 
192
                } aaaa;
 
193
                struct {
 
194
                        char name[HOST_NAME_MAX];
 
195
                } ptr;
 
196
        } data;
 
197
};
 
198
 
 
199
struct nameserver {
 
200
        int socket;  /* a connected UDP socket */
 
201
        u32 address;
 
202
        int failed_times;  /* number of times which we have given this server a chance */
 
203
        int timedout;  /* number of times in a row a request has timed out */
 
204
        struct event event;
 
205
        /* these objects are kept in a circular list */
 
206
        struct nameserver *next, *prev;
 
207
        struct event timeout_event;  /* used to keep the timeout for */
 
208
                                     /* when we next probe this server. */
 
209
                                     /* Valid if state == 0 */
 
210
        char state;  /* zero if we think that this server is down */
 
211
        char choked;  /* true if we have an EAGAIN from this server's socket */
 
212
        char write_waiting;  /* true if we are waiting for EV_WRITE events */
 
213
};
 
214
 
 
215
static struct request *req_head = NULL, *req_waiting_head = NULL;
 
216
static struct nameserver *server_head = NULL;
 
217
 
 
218
/* Represents a local port where we're listening for DNS requests. Right now, */
 
219
/* only UDP is supported. */
 
220
struct evdns_server_port {
 
221
        int socket; /* socket we use to read queries and write replies. */
 
222
        int refcnt; /* reference count. */
 
223
        char choked; /* Are we currently blocked from writing? */
 
224
        char closing; /* Are we trying to close this port, pending writes? */
 
225
        evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
 
226
        void *user_data; /* Opaque pointer passed to user_callback */
 
227
        struct event event; /* Read/write event */
 
228
        /* circular list of replies that we want to write. */
 
229
        struct server_request *pending_replies;
 
230
};
 
231
 
 
232
/* Represents part of a reply being built.      (That is, a single RR.) */
 
233
struct server_reply_item {
 
234
        struct server_reply_item *next; /* next item in sequence. */
 
235
        char *name; /* name part of the RR */
 
236
        u16 type : 16; /* The RR type */
 
237
        u16 class : 16; /* The RR class (usually CLASS_INET) */
 
238
        u32 ttl; /* The RR TTL */
 
239
        char is_name; /* True iff data is a label */
 
240
        u16 datalen; /* Length of data; -1 if data is a label */
 
241
        void *data; /* The contents of the RR */
 
242
};
 
243
 
 
244
/* Represents a request that we've received as a DNS server, and holds */
 
245
/* the components of the reply as we're constructing it. */
 
246
struct server_request {
 
247
        /* Pointers to the next and previous entries on the list of replies */
 
248
        /* that we're waiting to write.  Only set if we have tried to respond */
 
249
        /* and gotten EAGAIN. */
 
250
        struct server_request *next_pending;
 
251
        struct server_request *prev_pending;
 
252
 
 
253
        u16 trans_id; /* Transaction id. */
 
254
        struct evdns_server_port *port; /* Which port received this request on? */
 
255
        struct sockaddr_storage addr; /* Where to send the response */
 
256
        socklen_t addrlen; /* length of addr */
 
257
 
 
258
        int n_answer; /* how many answer RRs have been set? */
 
259
        int n_authority; /* how many authority RRs have been set? */
 
260
        int n_additional; /* how many additional RRs have been set? */
 
261
 
 
262
        struct server_reply_item *answer; /* linked list of answer RRs */
 
263
        struct server_reply_item *authority; /* linked list of authority RRs */
 
264
        struct server_reply_item *additional; /* linked list of additional RRs */
 
265
 
 
266
        /* Constructed response.  Only set once we're ready to send a reply. */
 
267
        /* Once this is set, the RR fields are cleared, and no more should be set. */
 
268
        char *response;
 
269
        size_t response_len;
 
270
 
 
271
        /* Caller-visible fields: flags, questions. */
 
272
        struct evdns_server_request base;
 
273
};
 
274
 
 
275
/* helper macro */
 
276
#define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
 
277
 
 
278
/* Given a pointer to an evdns_server_request, get the corresponding */
 
279
/* server_request. */
 
280
#define TO_SERVER_REQUEST(base_ptr)                                                                             \
 
281
        ((struct server_request*)                                                                                       \
 
282
         (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
 
283
 
 
284
/* The number of good nameservers that we have */
 
285
static int global_good_nameservers = 0;
 
286
 
 
287
/* inflight requests are contained in the req_head list */
 
288
/* and are actually going out across the network */
 
289
static int global_requests_inflight = 0;
 
290
/* requests which aren't inflight are in the waiting list */
 
291
/* and are counted here */
 
292
static int global_requests_waiting = 0;
 
293
 
 
294
static int global_max_requests_inflight = 64;
 
295
 
 
296
static struct timeval global_timeout = {5, 0};  /* 5 seconds */
 
297
static int global_max_reissues = 1;  /* a reissue occurs when we get some errors from the server */
 
298
static int global_max_retransmits = 3;  /* number of times we'll retransmit a request which timed out */
 
299
/* number of timeouts in a row before we consider this server to be down */
 
300
static int global_max_nameserver_timeout = 3;
 
301
 
 
302
/* These are the timeout values for nameservers. If we find a nameserver is down */
 
303
/* we try to probe it at intervals as given below. Values are in seconds. */
 
304
static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
 
305
static const int global_nameserver_timeouts_length = sizeof(global_nameserver_timeouts)/sizeof(struct timeval);
 
306
 
 
307
static struct nameserver *nameserver_pick(void);
 
308
static void evdns_request_insert(struct request *req, struct request **head);
 
309
static void nameserver_ready_callback(int fd, short events, void *arg);
 
310
static int evdns_transmit(void);
 
311
static int evdns_request_transmit(struct request *req);
 
312
static void nameserver_send_probe(struct nameserver *const ns);
 
313
static void search_request_finished(struct request *const);
 
314
static int search_try_next(struct request *const req);
 
315
static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
 
316
static void evdns_requests_pump_waiting_queue(void);
 
317
static u16 transaction_id_pick(void);
 
318
static struct request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
 
319
static void request_submit(struct request *req);
 
320
 
 
321
static int server_request_free(struct server_request *req);
 
322
static void server_request_free_answers(struct server_request *req);
 
323
static void server_port_free(struct evdns_server_port *port);
 
324
static void server_port_ready_callback(int fd, short events, void *arg);
 
325
 
 
326
static int strtoint(const char *const str);
 
327
 
 
328
#ifdef WIN32
 
329
static int
 
330
last_error(int sock)
 
331
{
 
332
        int optval, optvallen=sizeof(optval);
 
333
        int err = WSAGetLastError();
 
334
        if (err == WSAEWOULDBLOCK && sock >= 0) {
 
335
                if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
 
336
                               &optvallen))
 
337
                        return err;
 
338
                if (optval)
 
339
                        return optval;
 
340
        }
 
341
        return err;
 
342
 
 
343
}
 
344
static int
 
345
error_is_eagain(int err)
 
346
{
 
347
        return err == EAGAIN || err == WSAEWOULDBLOCK;
 
348
}
 
349
static int
 
350
inet_aton(const char *c, struct in_addr *addr)
 
351
{
 
352
        uint32_t r;
 
353
        if (strcmp(c, "255.255.255.255") == 0) {
 
354
                addr->s_addr = 0xffffffffu;
 
355
        } else {
 
356
                r = inet_addr(c);
 
357
                if (r == INADDR_NONE)
 
358
                        return 0;
 
359
                addr->s_addr = r;
 
360
        }
 
361
        return 1;
 
362
}
 
363
#else
 
364
#define last_error(sock) (errno)
 
365
#define error_is_eagain(err) ((err) == EAGAIN)
 
366
#endif
 
367
#define CLOSE_SOCKET(s) EVUTIL_CLOSESOCKET(s)
 
368
 
 
369
#define ISSPACE(c) isspace((int)(unsigned char)(c))
 
370
#define ISDIGIT(c) isdigit((int)(unsigned char)(c))
 
371
 
 
372
#ifndef NDEBUG
 
373
static const char *
 
374
debug_ntoa(u32 address)
 
375
{
 
376
        static char buf[32];
 
377
        u32 a = ntohl(address);
 
378
        snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
 
379
                      (int)(u8)((a>>24)&0xff),
 
380
                      (int)(u8)((a>>16)&0xff),
 
381
                      (int)(u8)((a>>8 )&0xff),
 
382
                      (int)(u8)((a    )&0xff));
 
383
        return buf;
 
384
}
 
385
#endif
 
386
 
 
387
static evdns_debug_log_fn_type evdns_log_fn = NULL;
 
388
 
 
389
void
 
390
evdns_set_log_fn(evdns_debug_log_fn_type fn)
 
391
{
 
392
  evdns_log_fn = fn;
 
393
}
 
394
 
 
395
#ifdef __GNUC__
 
396
#define EVDNS_LOG_CHECK  __attribute__ ((format(printf, 2, 3)))
 
397
#else
 
398
#define EVDNS_LOG_CHECK
 
399
#endif
 
400
 
 
401
static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
 
402
static void
 
403
_evdns_log(int warn, const char *fmt, ...)
 
404
{
 
405
  va_list args;
 
406
  static char buf[512];
 
407
  if (!evdns_log_fn)
 
408
    return;
 
409
  va_start(args,fmt);
 
410
#ifdef WIN32
 
411
  _vsnprintf(buf, sizeof(buf), fmt, args);
 
412
#else
 
413
  vsnprintf(buf, sizeof(buf), fmt, args);
 
414
#endif
 
415
  buf[sizeof(buf)-1] = '\0';
 
416
  evdns_log_fn(warn, buf);
 
417
  va_end(args);
 
418
}
 
419
 
 
420
#define log _evdns_log
 
421
 
 
422
/* This walks the list of inflight requests to find the */
 
423
/* one with a matching transaction id. Returns NULL on */
 
424
/* failure */
 
425
static struct request *
 
426
request_find_from_trans_id(u16 trans_id) {
 
427
        struct request *req = req_head, *const started_at = req_head;
 
428
 
 
429
        if (req) {
 
430
                do {
 
431
                        if (req->trans_id == trans_id) return req;
 
432
                        req = req->next;
 
433
                } while (req != started_at);
 
434
        }
 
435
 
 
436
        return NULL;
 
437
}
 
438
 
 
439
/* a libevent callback function which is called when a nameserver */
 
440
/* has gone down and we want to test if it has came back to life yet */
 
441
static void
 
442
nameserver_prod_callback(int fd, short events, void *arg) {
 
443
        struct nameserver *const ns = (struct nameserver *) arg;
 
444
        (void)fd;
 
445
        (void)events;
 
446
 
 
447
        nameserver_send_probe(ns);
 
448
}
 
449
 
 
450
/* a libevent callback which is called when a nameserver probe (to see if */
 
451
/* it has come back to life) times out. We increment the count of failed_times */
 
452
/* and wait longer to send the next probe packet. */
 
453
static void
 
454
nameserver_probe_failed(struct nameserver *const ns) {
 
455
        const struct timeval * timeout;
 
456
        (void) evtimer_del(&ns->timeout_event);
 
457
        if (ns->state == 1) {
 
458
                /* This can happen if the nameserver acts in a way which makes us mark */
 
459
                /* it as bad and then starts sending good replies. */
 
460
                return;
 
461
        }
 
462
 
 
463
        timeout =
 
464
          &global_nameserver_timeouts[MIN(ns->failed_times,
 
465
                                          global_nameserver_timeouts_length - 1)];
 
466
        ns->failed_times++;
 
467
 
 
468
        evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
 
469
        if (evtimer_add(&ns->timeout_event, (struct timeval *) timeout) < 0) {
 
470
          log(EVDNS_LOG_WARN,
 
471
              "Error from libevent when adding timer event for %s",
 
472
              debug_ntoa(ns->address));
 
473
          /* ???? Do more? */
 
474
        }
 
475
}
 
476
 
 
477
/* called when a nameserver has been deemed to have failed. For example, too */
 
478
/* many packets have timed out etc */
 
479
static void
 
480
nameserver_failed(struct nameserver *const ns, const char *msg) {
 
481
        struct request *req, *started_at;
 
482
        /* if this nameserver has already been marked as failed */
 
483
        /* then don't do anything */
 
484
        if (!ns->state) return;
 
485
 
 
486
        log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
 
487
            debug_ntoa(ns->address), msg);
 
488
        global_good_nameservers--;
 
489
        assert(global_good_nameservers >= 0);
 
490
        if (global_good_nameservers == 0) {
 
491
                log(EVDNS_LOG_WARN, "All nameservers have failed");
 
492
        }
 
493
 
 
494
        ns->state = 0;
 
495
        ns->failed_times = 1;
 
496
 
 
497
        evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
 
498
        if (evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
 
499
                log(EVDNS_LOG_WARN,
 
500
                    "Error from libevent when adding timer event for %s",
 
501
                    debug_ntoa(ns->address));
 
502
                /* ???? Do more? */
 
503
        }
 
504
 
 
505
        /* walk the list of inflight requests to see if any can be reassigned to */
 
506
        /* a different server. Requests in the waiting queue don't have a */
 
507
        /* nameserver assigned yet */
 
508
 
 
509
        /* if we don't have *any* good nameservers then there's no point */
 
510
        /* trying to reassign requests to one */
 
511
        if (!global_good_nameservers) return;
 
512
 
 
513
        req = req_head;
 
514
        started_at = req_head;
 
515
        if (req) {
 
516
                do {
 
517
                        if (req->tx_count == 0 && req->ns == ns) {
 
518
                                /* still waiting to go out, can be moved */
 
519
                                /* to another server */
 
520
                                req->ns = nameserver_pick();
 
521
                        }
 
522
                        req = req->next;
 
523
                } while (req != started_at);
 
524
        }
 
525
}
 
526
 
 
527
static void
 
528
nameserver_up(struct nameserver *const ns) {
 
529
        if (ns->state) return;
 
530
        log(EVDNS_LOG_WARN, "Nameserver %s is back up",
 
531
            debug_ntoa(ns->address));
 
532
        evtimer_del(&ns->timeout_event);
 
533
        ns->state = 1;
 
534
        ns->failed_times = 0;
 
535
        ns->timedout = 0;
 
536
        global_good_nameservers++;
 
537
}
 
538
 
 
539
static void
 
540
request_trans_id_set(struct request *const req, const u16 trans_id) {
 
541
        req->trans_id = trans_id;
 
542
        *((u16 *) req->request) = htons(trans_id);
 
543
}
 
544
 
 
545
/* Called to remove a request from a list and dealloc it. */
 
546
/* head is a pointer to the head of the list it should be */
 
547
/* removed from or NULL if the request isn't in a list. */
 
548
static void
 
549
request_finished(struct request *const req, struct request **head) {
 
550
        if (head) {
 
551
                if (req->next == req) {
 
552
                        /* only item in the list */
 
553
                        *head = NULL;
 
554
                } else {
 
555
                        req->next->prev = req->prev;
 
556
                        req->prev->next = req->next;
 
557
                        if (*head == req) *head = req->next;
 
558
                }
 
559
        }
 
560
 
 
561
        log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
 
562
            (unsigned long) req);
 
563
        evtimer_del(&req->timeout_event);
 
564
 
 
565
        search_request_finished(req);
 
566
        global_requests_inflight--;
 
567
 
 
568
        if (!req->request_appended) {
 
569
                /* need to free the request data on it's own */
 
570
                free(req->request);
 
571
        } else {
 
572
                /* the request data is appended onto the header */
 
573
                /* so everything gets free()ed when we: */
 
574
        }
 
575
 
 
576
        free(req);
 
577
 
 
578
        evdns_requests_pump_waiting_queue();
 
579
}
 
580
 
 
581
/* This is called when a server returns a funny error code. */
 
582
/* We try the request again with another server. */
 
583
/* */
 
584
/* return: */
 
585
/*   0 ok */
 
586
/*   1 failed/reissue is pointless */
 
587
static int
 
588
request_reissue(struct request *req) {
 
589
        const struct nameserver *const last_ns = req->ns;
 
590
        /* the last nameserver should have been marked as failing */
 
591
        /* by the caller of this function, therefore pick will try */
 
592
        /* not to return it */
 
593
        req->ns = nameserver_pick();
 
594
        if (req->ns == last_ns) {
 
595
                /* ... but pick did return it */
 
596
                /* not a lot of point in trying again with the */
 
597
                /* same server */
 
598
                return 1;
 
599
        }
 
600
 
 
601
        req->reissue_count++;
 
602
        req->tx_count = 0;
 
603
        req->transmit_me = 1;
 
604
 
 
605
        return 0;
 
606
}
 
607
 
 
608
/* this function looks for space on the inflight queue and promotes */
 
609
/* requests from the waiting queue if it can. */
 
610
static void
 
611
evdns_requests_pump_waiting_queue(void) {
 
612
        while (global_requests_inflight < global_max_requests_inflight &&
 
613
            global_requests_waiting) {
 
614
                struct request *req;
 
615
                /* move a request from the waiting queue to the inflight queue */
 
616
                assert(req_waiting_head);
 
617
                if (req_waiting_head->next == req_waiting_head) {
 
618
                        /* only one item in the queue */
 
619
                        req = req_waiting_head;
 
620
                        req_waiting_head = NULL;
 
621
                } else {
 
622
                        req = req_waiting_head;
 
623
                        req->next->prev = req->prev;
 
624
                        req->prev->next = req->next;
 
625
                        req_waiting_head = req->next;
 
626
                }
 
627
 
 
628
                global_requests_waiting--;
 
629
                global_requests_inflight++;
 
630
 
 
631
                req->ns = nameserver_pick();
 
632
                request_trans_id_set(req, transaction_id_pick());
 
633
 
 
634
                evdns_request_insert(req, &req_head);
 
635
                evdns_request_transmit(req);
 
636
                evdns_transmit();
 
637
        }
 
638
}
 
639
 
 
640
static void
 
641
reply_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply) {
 
642
        switch (req->request_type) {
 
643
        case TYPE_A:
 
644
                if (reply)
 
645
                        req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
 
646
                                                           reply->data.a.addrcount, ttl,
 
647
                                                 reply->data.a.addresses,
 
648
                                                           req->user_pointer);
 
649
                else
 
650
                        req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
 
651
                return;
 
652
        case TYPE_PTR:
 
653
                if (reply) {
 
654
                        char *name = reply->data.ptr.name;
 
655
                        req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
 
656
                                                           &name, req->user_pointer);
 
657
                } else {
 
658
                        req->user_callback(err, 0, 0, 0, NULL,
 
659
                                                           req->user_pointer);
 
660
                }
 
661
                return;
 
662
        case TYPE_AAAA:
 
663
                if (reply)
 
664
                        req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
 
665
                                                           reply->data.aaaa.addrcount, ttl,
 
666
                                                           reply->data.aaaa.addresses,
 
667
                                                           req->user_pointer);
 
668
                else
 
669
                        req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
 
670
                return;
 
671
        }
 
672
        assert(0);
 
673
}
 
674
 
 
675
/* this processes a parsed reply packet */
 
676
static void
 
677
reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
 
678
        int error;
 
679
        static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
 
680
 
 
681
        if (flags & 0x020f || !reply || !reply->have_answer) {
 
682
                /* there was an error */
 
683
                if (flags & 0x0200) {
 
684
                        error = DNS_ERR_TRUNCATED;
 
685
                } else {
 
686
                        u16 error_code = (flags & 0x000f) - 1;
 
687
                        if (error_code > 4) {
 
688
                                error = DNS_ERR_UNKNOWN;
 
689
                        } else {
 
690
                                error = error_codes[error_code];
 
691
                        }
 
692
                }
 
693
 
 
694
                switch(error) {
 
695
                case DNS_ERR_NOTIMPL:
 
696
                case DNS_ERR_REFUSED:
 
697
                        /* we regard these errors as marking a bad nameserver */
 
698
                        if (req->reissue_count < global_max_reissues) {
 
699
                                char msg[64];
 
700
                                snprintf(msg, sizeof(msg), "Bad response %d (%s)",
 
701
                                         error, evdns_err_to_string(error));
 
702
                                nameserver_failed(req->ns, msg);
 
703
                                if (!request_reissue(req)) return;
 
704
                        }
 
705
                        break;
 
706
                case DNS_ERR_SERVERFAILED:
 
707
                        /* rcode 2 (servfailed) sometimes means "we are broken" and
 
708
                         * sometimes (with some binds) means "that request was very
 
709
                         * confusing."  Treat this as a timeout, not a failure. 
 
710
                         */
 
711
                        log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver %s; "
 
712
                                "will allow the request to time out.",
 
713
                                debug_ntoa(req->ns->address));
 
714
                        break;
 
715
                default:
 
716
                        /* we got a good reply from the nameserver */
 
717
                        nameserver_up(req->ns);
 
718
                }
 
719
 
 
720
                if (req->search_state && req->request_type != TYPE_PTR) {
 
721
                        /* if we have a list of domains to search in, try the next one */
 
722
                        if (!search_try_next(req)) {
 
723
                                /* a new request was issued so this request is finished and */
 
724
                                /* the user callback will be made when that request (or a */
 
725
                                /* child of it) finishes. */
 
726
                                request_finished(req, &req_head);
 
727
                                return;
 
728
                        }
 
729
                }
 
730
 
 
731
                /* all else failed. Pass the failure up */
 
732
                reply_callback(req, 0, error, NULL);
 
733
                request_finished(req, &req_head);
 
734
        } else {
 
735
                /* all ok, tell the user */
 
736
                reply_callback(req, ttl, 0, reply);
 
737
                nameserver_up(req->ns);
 
738
                request_finished(req, &req_head);
 
739
        }
 
740
}
 
741
 
 
742
static int
 
743
name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
 
744
        int name_end = -1;
 
745
        int j = *idx;
 
746
        int ptr_count = 0;
 
747
#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
 
748
#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
 
749
#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
 
750
 
 
751
        char *cp = name_out;
 
752
        const char *const end = name_out + name_out_len;
 
753
 
 
754
        /* Normally, names are a series of length prefixed strings terminated */
 
755
        /* with a length of 0 (the lengths are u8's < 63). */
 
756
        /* However, the length can start with a pair of 1 bits and that */
 
757
        /* means that the next 14 bits are a pointer within the current */
 
758
        /* packet. */
 
759
 
 
760
        for(;;) {
 
761
                u8 label_len;
 
762
                if (j >= length) return -1;
 
763
                GET8(label_len);
 
764
                if (!label_len) break;
 
765
                if (label_len & 0xc0) {
 
766
                        u8 ptr_low;
 
767
                        GET8(ptr_low);
 
768
                        if (name_end < 0) name_end = j;
 
769
                        j = (((int)label_len & 0x3f) << 8) + ptr_low;
 
770
                        /* Make sure that the target offset is in-bounds. */
 
771
                        if (j < 0 || j >= length) return -1;
 
772
                        /* If we've jumped more times than there are characters in the
 
773
                         * message, we must have a loop. */
 
774
                        if (++ptr_count > length) return -1;
 
775
                        continue;
 
776
                }
 
777
                if (label_len > 63) return -1;
 
778
                if (cp != name_out) {
 
779
                        if (cp + 1 >= end) return -1;
 
780
                        *cp++ = '.';
 
781
                }
 
782
                if (cp + label_len >= end) return -1;
 
783
                memcpy(cp, packet + j, label_len);
 
784
                cp += label_len;
 
785
                j += label_len;
 
786
        }
 
787
        if (cp >= end) return -1;
 
788
        *cp = '\0';
 
789
        if (name_end < 0)
 
790
                *idx = j;
 
791
        else
 
792
                *idx = name_end;
 
793
        return 0;
 
794
 err:
 
795
        return -1;
 
796
}
 
797
 
 
798
/* parses a raw request from a nameserver */
 
799
static int
 
800
reply_parse(u8 *packet, int length) {
 
801
        int j = 0;  /* index into packet */
 
802
        u16 _t;  /* used by the macros */
 
803
        u32 _t32;  /* used by the macros */
 
804
        char tmp_name[256]; /* used by the macros */
 
805
 
 
806
        u16 trans_id, questions, answers, authority, additional, datalength;
 
807
        u16 flags = 0;
 
808
        u32 ttl, ttl_r = 0xffffffff;
 
809
        struct reply reply;
 
810
        struct request *req = NULL;
 
811
        unsigned int i;
 
812
 
 
813
        GET16(trans_id);
 
814
        GET16(flags);
 
815
        GET16(questions);
 
816
        GET16(answers);
 
817
        GET16(authority);
 
818
        GET16(additional);
 
819
        (void) authority; /* suppress "unused variable" warnings. */
 
820
        (void) additional; /* suppress "unused variable" warnings. */
 
821
 
 
822
        req = request_find_from_trans_id(trans_id);
 
823
        if (!req) return -1;
 
824
 
 
825
        memset(&reply, 0, sizeof(reply));
 
826
 
 
827
        /* If it's not an answer, it doesn't correspond to any request. */
 
828
        if (!(flags & 0x8000)) return -1;  /* must be an answer */
 
829
        if (flags & 0x020f) {
 
830
                /* there was an error */
 
831
                goto err;
 
832
        }
 
833
        /* if (!answers) return; */  /* must have an answer of some form */
 
834
 
 
835
        /* This macro skips a name in the DNS reply. */
 
836
#define SKIP_NAME \
 
837
        do { tmp_name[0] = '\0';                                        \
 
838
                if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0) \
 
839
                        goto err;                                                                                                       \
 
840
        } while(0);
 
841
 
 
842
        reply.type = req->request_type;
 
843
 
 
844
        /* skip over each question in the reply */
 
845
        for (i = 0; i < questions; ++i) {
 
846
                /* the question looks like
 
847
                 *   <label:name><u16:type><u16:class>
 
848
                 */
 
849
                SKIP_NAME;
 
850
                j += 4;
 
851
                if (j >= length) goto err;
 
852
        }
 
853
 
 
854
        /* now we have the answer section which looks like
 
855
         * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
 
856
         */
 
857
 
 
858
        for (i = 0; i < answers; ++i) {
 
859
                u16 type, class;
 
860
 
 
861
                SKIP_NAME;
 
862
                GET16(type);
 
863
                GET16(class);
 
864
                GET32(ttl);
 
865
                GET16(datalength);
 
866
 
 
867
                if (type == TYPE_A && class == CLASS_INET) {
 
868
                        int addrcount, addrtocopy;
 
869
                        if (req->request_type != TYPE_A) {
 
870
                                j += datalength; continue;
 
871
                        }
 
872
                        if ((datalength & 3) != 0) /* not an even number of As. */
 
873
                            goto err;
 
874
                        addrcount = datalength >> 2;
 
875
                        addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
 
876
 
 
877
                        ttl_r = MIN(ttl_r, ttl);
 
878
                        /* we only bother with the first four addresses. */
 
879
                        if (j + 4*addrtocopy > length) goto err;
 
880
                        memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
 
881
                                   packet + j, 4*addrtocopy);
 
882
                        j += 4*addrtocopy;
 
883
                        reply.data.a.addrcount += addrtocopy;
 
884
                        reply.have_answer = 1;
 
885
                        if (reply.data.a.addrcount == MAX_ADDRS) break;
 
886
                } else if (type == TYPE_PTR && class == CLASS_INET) {
 
887
                        if (req->request_type != TYPE_PTR) {
 
888
                                j += datalength; continue;
 
889
                        }
 
890
                        if (name_parse(packet, length, &j, reply.data.ptr.name,
 
891
                                                   sizeof(reply.data.ptr.name))<0)
 
892
                                goto err;
 
893
                        ttl_r = MIN(ttl_r, ttl);
 
894
                        reply.have_answer = 1;
 
895
                        break;
 
896
                } else if (type == TYPE_AAAA && class == CLASS_INET) {
 
897
                        int addrcount, addrtocopy;
 
898
                        if (req->request_type != TYPE_AAAA) {
 
899
                                j += datalength; continue;
 
900
                        }
 
901
                        if ((datalength & 15) != 0) /* not an even number of AAAAs. */
 
902
                                goto err;
 
903
                        addrcount = datalength >> 4;  /* each address is 16 bytes long */
 
904
                        addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
 
905
                        ttl_r = MIN(ttl_r, ttl);
 
906
 
 
907
                        /* we only bother with the first four addresses. */
 
908
                        if (j + 16*addrtocopy > length) goto err;
 
909
                        memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
 
910
                                   packet + j, 16*addrtocopy);
 
911
                        reply.data.aaaa.addrcount += addrtocopy;
 
912
                        j += 16*addrtocopy;
 
913
                        reply.have_answer = 1;
 
914
                        if (reply.data.aaaa.addrcount == MAX_ADDRS) break;
 
915
                } else {
 
916
                        /* skip over any other type of resource */
 
917
                        j += datalength;
 
918
                }
 
919
        }
 
920
 
 
921
        reply_handle(req, flags, ttl_r, &reply);
 
922
        return 0;
 
923
 err:
 
924
        if (req)
 
925
                reply_handle(req, flags, 0, NULL);
 
926
        return -1;
 
927
}
 
928
 
 
929
/* Parse a raw request (packet,length) sent to a nameserver port (port) from */
 
930
/* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
 
931
/* callback. */
 
932
static int
 
933
request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, socklen_t addrlen)
 
934
{
 
935
        int j = 0;      /* index into packet */
 
936
        u16 _t;  /* used by the macros */
 
937
        char tmp_name[256]; /* used by the macros */
 
938
 
 
939
        int i;
 
940
        u16 trans_id, flags, questions, answers, authority, additional;
 
941
        struct server_request *server_req = NULL;
 
942
 
 
943
        /* Get the header fields */
 
944
        GET16(trans_id);
 
945
        GET16(flags);
 
946
        GET16(questions);
 
947
        GET16(answers);
 
948
        GET16(authority);
 
949
        GET16(additional);
 
950
 
 
951
        if (flags & 0x8000) return -1; /* Must not be an answer. */
 
952
        flags &= 0x0110; /* Only RD and CD get preserved. */
 
953
 
 
954
        server_req = malloc(sizeof(struct server_request));
 
955
        if (server_req == NULL) return -1;
 
956
        memset(server_req, 0, sizeof(struct server_request));
 
957
 
 
958
        server_req->trans_id = trans_id;
 
959
        memcpy(&server_req->addr, addr, addrlen);
 
960
        server_req->addrlen = addrlen;
 
961
 
 
962
        server_req->base.flags = flags;
 
963
        server_req->base.nquestions = 0;
 
964
        server_req->base.questions = malloc(sizeof(struct evdns_server_question *) * questions);
 
965
        if (server_req->base.questions == NULL)
 
966
                goto err;
 
967
 
 
968
        for (i = 0; i < questions; ++i) {
 
969
                u16 type, class;
 
970
                struct evdns_server_question *q;
 
971
                int namelen;
 
972
                if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
 
973
                        goto err;
 
974
                GET16(type);
 
975
                GET16(class);
 
976
                namelen = strlen(tmp_name);
 
977
                q = malloc(sizeof(struct evdns_server_question) + namelen);
 
978
                if (!q)
 
979
                        goto err;
 
980
                q->type = type;
 
981
                q->class = class;
 
982
                memcpy(q->name, tmp_name, namelen+1);
 
983
                server_req->base.questions[server_req->base.nquestions++] = q;
 
984
        }
 
985
 
 
986
        /* Ignore answers, authority, and additional. */
 
987
 
 
988
        server_req->port = port;
 
989
        port->refcnt++;
 
990
 
 
991
        /* Only standard queries are supported. */
 
992
        if (flags & 0x7800) {
 
993
                evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
 
994
                return -1;
 
995
        }
 
996
 
 
997
        port->user_callback(&(server_req->base), port->user_data);
 
998
 
 
999
        return 0;
 
1000
err:
 
1001
        if (server_req) {
 
1002
                if (server_req->base.questions) {
 
1003
                        for (i = 0; i < server_req->base.nquestions; ++i)
 
1004
                                free(server_req->base.questions[i]);
 
1005
                        free(server_req->base.questions);
 
1006
                }
 
1007
                free(server_req);
 
1008
        }
 
1009
        return -1;
 
1010
 
 
1011
#undef SKIP_NAME
 
1012
#undef GET32
 
1013
#undef GET16
 
1014
#undef GET8
 
1015
}
 
1016
 
 
1017
static u16
 
1018
default_transaction_id_fn(void)
 
1019
{
 
1020
        u16 trans_id;
 
1021
#ifdef DNS_USE_CPU_CLOCK_FOR_ID
 
1022
        struct timespec ts;
 
1023
#ifdef CLOCK_MONOTONIC
 
1024
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
 
1025
#else
 
1026
        if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
 
1027
#endif
 
1028
        event_err(1, "clock_gettime");
 
1029
        trans_id = ts.tv_nsec & 0xffff;
 
1030
#endif
 
1031
 
 
1032
#ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
 
1033
        struct timeval tv;
 
1034
        gettimeofday(&tv, NULL);
 
1035
        trans_id = tv.tv_usec & 0xffff;
 
1036
#endif
 
1037
 
 
1038
#ifdef DNS_USE_OPENSSL_FOR_ID
 
1039
        if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
 
1040
                /* in the case that the RAND call fails we back */
 
1041
                /* down to using gettimeofday. */
 
1042
                /*
 
1043
                  struct timeval tv;
 
1044
                  gettimeofday(&tv, NULL);
 
1045
                  trans_id = tv.tv_usec & 0xffff;
 
1046
                */
 
1047
                abort();
 
1048
        }
 
1049
#endif
 
1050
        return trans_id;
 
1051
}
 
1052
 
 
1053
static uint16_t (*trans_id_function)(void) = default_transaction_id_fn;
 
1054
 
 
1055
void
 
1056
evdns_set_transaction_id_fn(uint16_t (*fn)(void))
 
1057
{
 
1058
        if (fn)
 
1059
                trans_id_function = fn;
 
1060
        else
 
1061
                trans_id_function = default_transaction_id_fn;
 
1062
}
 
1063
 
 
1064
/* Try to choose a strong transaction id which isn't already in flight */
 
1065
static u16
 
1066
transaction_id_pick(void) {
 
1067
        for (;;) {
 
1068
                const struct request *req = req_head, *started_at;
 
1069
                u16 trans_id = trans_id_function();
 
1070
 
 
1071
                if (trans_id == 0xffff) continue;
 
1072
                /* now check to see if that id is already inflight */
 
1073
                req = started_at = req_head;
 
1074
                if (req) {
 
1075
                        do {
 
1076
                                if (req->trans_id == trans_id) break;
 
1077
                                req = req->next;
 
1078
                        } while (req != started_at);
 
1079
                }
 
1080
                /* we didn't find it, so this is a good id */
 
1081
                if (req == started_at) return trans_id;
 
1082
        }
 
1083
}
 
1084
 
 
1085
/* choose a namesever to use. This function will try to ignore */
 
1086
/* nameservers which we think are down and load balance across the rest */
 
1087
/* by updating the server_head global each time. */
 
1088
static struct nameserver *
 
1089
nameserver_pick(void) {
 
1090
        struct nameserver *started_at = server_head, *picked;
 
1091
        if (!server_head) return NULL;
 
1092
 
 
1093
        /* if we don't have any good nameservers then there's no */
 
1094
        /* point in trying to find one. */
 
1095
        if (!global_good_nameservers) {
 
1096
                server_head = server_head->next;
 
1097
                return server_head;
 
1098
        }
 
1099
 
 
1100
        /* remember that nameservers are in a circular list */
 
1101
        for (;;) {
 
1102
                if (server_head->state) {
 
1103
                        /* we think this server is currently good */
 
1104
                        picked = server_head;
 
1105
                        server_head = server_head->next;
 
1106
                        return picked;
 
1107
                }
 
1108
 
 
1109
                server_head = server_head->next;
 
1110
                if (server_head == started_at) {
 
1111
                        /* all the nameservers seem to be down */
 
1112
                        /* so we just return this one and hope for the */
 
1113
                        /* best */
 
1114
                        assert(global_good_nameservers == 0);
 
1115
                        picked = server_head;
 
1116
                        server_head = server_head->next;
 
1117
                        return picked;
 
1118
                }
 
1119
        }
 
1120
}
 
1121
 
 
1122
/* this is called when a namesever socket is ready for reading */
 
1123
static void
 
1124
nameserver_read(struct nameserver *ns) {
 
1125
        u8 packet[1500];
 
1126
 
 
1127
        for (;;) {
 
1128
                const int r = recv(ns->socket, packet, sizeof(packet), 0);
 
1129
                if (r < 0) {
 
1130
                        int err = last_error(ns->socket);
 
1131
                        if (error_is_eagain(err)) return;
 
1132
                        nameserver_failed(ns, strerror(err));
 
1133
                        return;
 
1134
                }
 
1135
                ns->timedout = 0;
 
1136
                reply_parse(packet, r);
 
1137
        }
 
1138
}
 
1139
 
 
1140
/* Read a packet from a DNS client on a server port s, parse it, and */
 
1141
/* act accordingly. */
 
1142
static void
 
1143
server_port_read(struct evdns_server_port *s) {
 
1144
        u8 packet[1500];
 
1145
        struct sockaddr_storage addr;
 
1146
        socklen_t addrlen;
 
1147
        int r;
 
1148
 
 
1149
        for (;;) {
 
1150
                addrlen = sizeof(struct sockaddr_storage);
 
1151
                r = recvfrom(s->socket, packet, sizeof(packet), 0,
 
1152
                                         (struct sockaddr*) &addr, &addrlen);
 
1153
                if (r < 0) {
 
1154
                        int err = last_error(s->socket);
 
1155
                        if (error_is_eagain(err)) return;
 
1156
                        log(EVDNS_LOG_WARN, "Error %s (%d) while reading request.",
 
1157
                                strerror(err), err);
 
1158
                        return;
 
1159
                }
 
1160
                request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
 
1161
        }
 
1162
}
 
1163
 
 
1164
/* Try to write all pending replies on a given DNS server port. */
 
1165
static void
 
1166
server_port_flush(struct evdns_server_port *port)
 
1167
{
 
1168
        while (port->pending_replies) {
 
1169
                struct server_request *req = port->pending_replies;
 
1170
                int r = sendto(port->socket, req->response, req->response_len, 0,
 
1171
                           (struct sockaddr*) &req->addr, req->addrlen);
 
1172
                if (r < 0) {
 
1173
                        int err = last_error(port->socket);
 
1174
                        if (error_is_eagain(err))
 
1175
                                return;
 
1176
                        log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", strerror(err), err);
 
1177
                }
 
1178
                if (server_request_free(req)) {
 
1179
                        /* we released the last reference to req->port. */
 
1180
                        return;
 
1181
                }
 
1182
        }
 
1183
 
 
1184
        /* We have no more pending requests; stop listening for 'writeable' events. */
 
1185
        (void) event_del(&port->event);
 
1186
        event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
 
1187
                          server_port_ready_callback, port);
 
1188
        if (event_add(&port->event, NULL) < 0) {
 
1189
                log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
 
1190
                /* ???? Do more? */
 
1191
        }
 
1192
}
 
1193
 
 
1194
/* set if we are waiting for the ability to write to this server. */
 
1195
/* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
 
1196
/* we stop these events. */
 
1197
static void
 
1198
nameserver_write_waiting(struct nameserver *ns, char waiting) {
 
1199
        if (ns->write_waiting == waiting) return;
 
1200
 
 
1201
        ns->write_waiting = waiting;
 
1202
        (void) event_del(&ns->event);
 
1203
        event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
 
1204
                        nameserver_ready_callback, ns);
 
1205
        if (event_add(&ns->event, NULL) < 0) {
 
1206
          log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
 
1207
              debug_ntoa(ns->address));
 
1208
          /* ???? Do more? */
 
1209
        }
 
1210
}
 
1211
 
 
1212
/* a callback function. Called by libevent when the kernel says that */
 
1213
/* a nameserver socket is ready for writing or reading */
 
1214
static void
 
1215
nameserver_ready_callback(int fd, short events, void *arg) {
 
1216
        struct nameserver *ns = (struct nameserver *) arg;
 
1217
        (void)fd;
 
1218
 
 
1219
        if (events & EV_WRITE) {
 
1220
                ns->choked = 0;
 
1221
                if (!evdns_transmit()) {
 
1222
                        nameserver_write_waiting(ns, 0);
 
1223
                }
 
1224
        }
 
1225
        if (events & EV_READ) {
 
1226
                nameserver_read(ns);
 
1227
        }
 
1228
}
 
1229
 
 
1230
/* a callback function. Called by libevent when the kernel says that */
 
1231
/* a server socket is ready for writing or reading. */
 
1232
static void
 
1233
server_port_ready_callback(int fd, short events, void *arg) {
 
1234
        struct evdns_server_port *port = (struct evdns_server_port *) arg;
 
1235
        (void) fd;
 
1236
 
 
1237
        if (events & EV_WRITE) {
 
1238
                port->choked = 0;
 
1239
                server_port_flush(port);
 
1240
        }
 
1241
        if (events & EV_READ) {
 
1242
                server_port_read(port);
 
1243
        }
 
1244
}
 
1245
 
 
1246
/* This is an inefficient representation; only use it via the dnslabel_table_*
 
1247
 * functions, so that is can be safely replaced with something smarter later. */
 
1248
#define MAX_LABELS 128
 
1249
/* Structures used to implement name compression */
 
1250
struct dnslabel_entry { char *v; off_t pos; };
 
1251
struct dnslabel_table {
 
1252
        int n_labels; /* number of current entries */
 
1253
        /* map from name to position in message */
 
1254
        struct dnslabel_entry labels[MAX_LABELS];
 
1255
};
 
1256
 
 
1257
/* Initialize dnslabel_table. */
 
1258
static void
 
1259
dnslabel_table_init(struct dnslabel_table *table)
 
1260
{
 
1261
        table->n_labels = 0;
 
1262
}
 
1263
 
 
1264
/* Free all storage held by table, but not the table itself. */
 
1265
static void
 
1266
dnslabel_clear(struct dnslabel_table *table)
 
1267
{
 
1268
        int i;
 
1269
        for (i = 0; i < table->n_labels; ++i)
 
1270
                free(table->labels[i].v);
 
1271
        table->n_labels = 0;
 
1272
}
 
1273
 
 
1274
/* return the position of the label in the current message, or -1 if the label */
 
1275
/* hasn't been used yet. */
 
1276
static int
 
1277
dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
 
1278
{
 
1279
        int i;
 
1280
        for (i = 0; i < table->n_labels; ++i) {
 
1281
                if (!strcmp(label, table->labels[i].v))
 
1282
                        return table->labels[i].pos;
 
1283
        }
 
1284
        return -1;
 
1285
}
 
1286
 
 
1287
/* remember that we've used the label at position pos */
 
1288
static int
 
1289
dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
 
1290
{
 
1291
        char *v;
 
1292
        int p;
 
1293
        if (table->n_labels == MAX_LABELS)
 
1294
                return (-1);
 
1295
        v = strdup(label);
 
1296
        if (v == NULL)
 
1297
                return (-1);
 
1298
        p = table->n_labels++;
 
1299
        table->labels[p].v = v;
 
1300
        table->labels[p].pos = pos;
 
1301
 
 
1302
        return (0);
 
1303
}
 
1304
 
 
1305
/* Converts a string to a length-prefixed set of DNS labels, starting */
 
1306
/* at buf[j]. name and buf must not overlap. name_len should be the length */
 
1307
/* of name.      table is optional, and is used for compression. */
 
1308
/* */
 
1309
/* Input: abc.def */
 
1310
/* Output: <3>abc<3>def<0> */
 
1311
/* */
 
1312
/* Returns the first index after the encoded name, or negative on error. */
 
1313
/*       -1      label was > 63 bytes */
 
1314
/*       -2      name too long to fit in buffer. */
 
1315
/* */
 
1316
static off_t
 
1317
dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
 
1318
                                  const char *name, const int name_len,
 
1319
                                  struct dnslabel_table *table) {
 
1320
        const char *end = name + name_len;
 
1321
        int ref = 0;
 
1322
        u16 _t;
 
1323
 
 
1324
#define APPEND16(x) do {                                                   \
 
1325
                if (j + 2 > (off_t)buf_len)                                \
 
1326
                        goto overflow;                                             \
 
1327
                _t = htons(x);                                                     \
 
1328
                memcpy(buf + j, &_t, 2);                                   \
 
1329
                j += 2;                                                                    \
 
1330
        } while (0)
 
1331
#define APPEND32(x) do {                                                   \
 
1332
                if (j + 4 > (off_t)buf_len)                                \
 
1333
                        goto overflow;                                             \
 
1334
                _t32 = htonl(x);                                                   \
 
1335
                memcpy(buf + j, &_t32, 4);                                 \
 
1336
                j += 4;                                                                    \
 
1337
        } while (0)
 
1338
 
 
1339
        if (name_len > 255) return -2;
 
1340
 
 
1341
        for (;;) {
 
1342
                const char *const start = name;
 
1343
                if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
 
1344
                        APPEND16(ref | 0xc000);
 
1345
                        return j;
 
1346
                }
 
1347
                name = strchr(name, '.');
 
1348
                if (!name) {
 
1349
                        const unsigned int label_len = end - start;
 
1350
                        if (label_len > 63) return -1;
 
1351
                        if ((size_t)(j+label_len+1) > buf_len) return -2;
 
1352
                        if (table) dnslabel_table_add(table, start, j);
 
1353
                        buf[j++] = label_len;
 
1354
 
 
1355
                        memcpy(buf + j, start, end - start);
 
1356
                        j += end - start;
 
1357
                        break;
 
1358
                } else {
 
1359
                        /* append length of the label. */
 
1360
                        const unsigned int label_len = name - start;
 
1361
                        if (label_len > 63) return -1;
 
1362
                        if ((size_t)(j+label_len+1) > buf_len) return -2;
 
1363
                        if (table) dnslabel_table_add(table, start, j);
 
1364
                        buf[j++] = label_len;
 
1365
 
 
1366
                        memcpy(buf + j, start, name - start);
 
1367
                        j += name - start;
 
1368
                        /* hop over the '.' */
 
1369
                        name++;
 
1370
                }
 
1371
        }
 
1372
 
 
1373
        /* the labels must be terminated by a 0. */
 
1374
        /* It's possible that the name ended in a . */
 
1375
        /* in which case the zero is already there */
 
1376
        if (!j || buf[j-1]) buf[j++] = 0;
 
1377
        return j;
 
1378
 overflow:
 
1379
        return (-2);
 
1380
}
 
1381
 
 
1382
/* Finds the length of a dns request for a DNS name of the given */
 
1383
/* length. The actual request may be smaller than the value returned */
 
1384
/* here */
 
1385
static int
 
1386
evdns_request_len(const int name_len) {
 
1387
        return 96 + /* length of the DNS standard header */
 
1388
                name_len + 2 +
 
1389
                4;  /* space for the resource type */
 
1390
}
 
1391
 
 
1392
/* build a dns request packet into buf. buf should be at least as long */
 
1393
/* as evdns_request_len told you it should be. */
 
1394
/* */
 
1395
/* Returns the amount of space used. Negative on error. */
 
1396
static int
 
1397
evdns_request_data_build(const char *const name, const int name_len,
 
1398
    const u16 trans_id, const u16 type, const u16 class,
 
1399
    u8 *const buf, size_t buf_len) {
 
1400
        off_t j = 0;  /* current offset into buf */
 
1401
        u16 _t;  /* used by the macros */
 
1402
 
 
1403
        APPEND16(trans_id);
 
1404
        APPEND16(0x0100);  /* standard query, recusion needed */
 
1405
        APPEND16(1);  /* one question */
 
1406
        APPEND16(0);  /* no answers */
 
1407
        APPEND16(0);  /* no authority */
 
1408
        APPEND16(0);  /* no additional */
 
1409
 
 
1410
        j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
 
1411
        if (j < 0) {
 
1412
                return (int)j;
 
1413
        }
 
1414
        
 
1415
        APPEND16(type);
 
1416
        APPEND16(class);
 
1417
 
 
1418
        return (int)j;
 
1419
 overflow:
 
1420
        return (-1);
 
1421
}
 
1422
 
 
1423
/* exported function */
 
1424
struct evdns_server_port *
 
1425
evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type cb, void *user_data)
 
1426
{
 
1427
        struct evdns_server_port *port;
 
1428
        if (!(port = malloc(sizeof(struct evdns_server_port))))
 
1429
                return NULL;
 
1430
        memset(port, 0, sizeof(struct evdns_server_port));
 
1431
 
 
1432
        assert(!is_tcp); /* TCP sockets not yet implemented */
 
1433
        port->socket = socket;
 
1434
        port->refcnt = 1;
 
1435
        port->choked = 0;
 
1436
        port->closing = 0;
 
1437
        port->user_callback = cb;
 
1438
        port->user_data = user_data;
 
1439
        port->pending_replies = NULL;
 
1440
 
 
1441
        event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
 
1442
                          server_port_ready_callback, port);
 
1443
        event_add(&port->event, NULL); /* check return. */
 
1444
        return port;
 
1445
}
 
1446
 
 
1447
/* exported function */
 
1448
void
 
1449
evdns_close_server_port(struct evdns_server_port *port)
 
1450
{
 
1451
        if (--port->refcnt == 0)
 
1452
                server_port_free(port);
 
1453
        port->closing = 1;
 
1454
}
 
1455
 
 
1456
/* exported function */
 
1457
int
 
1458
evdns_server_request_add_reply(struct evdns_server_request *_req, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data)
 
1459
{
 
1460
        struct server_request *req = TO_SERVER_REQUEST(_req);
 
1461
        struct server_reply_item **itemp, *item;
 
1462
        int *countp;
 
1463
 
 
1464
        if (req->response) /* have we already answered? */
 
1465
                return (-1);
 
1466
 
 
1467
        switch (section) {
 
1468
        case EVDNS_ANSWER_SECTION:
 
1469
                itemp = &req->answer;
 
1470
                countp = &req->n_answer;
 
1471
                break;
 
1472
        case EVDNS_AUTHORITY_SECTION:
 
1473
                itemp = &req->authority;
 
1474
                countp = &req->n_authority;
 
1475
                break;
 
1476
        case EVDNS_ADDITIONAL_SECTION:
 
1477
                itemp = &req->additional;
 
1478
                countp = &req->n_additional;
 
1479
                break;
 
1480
        default:
 
1481
                return (-1);
 
1482
        }
 
1483
        while (*itemp) {
 
1484
                itemp = &((*itemp)->next);
 
1485
        }
 
1486
        item = malloc(sizeof(struct server_reply_item));
 
1487
        if (!item)
 
1488
                return -1;
 
1489
        item->next = NULL;
 
1490
        if (!(item->name = strdup(name))) {
 
1491
                free(item);
 
1492
                return -1;
 
1493
        }
 
1494
        item->type = type;
 
1495
        item->class = class;
 
1496
        item->ttl = ttl;
 
1497
        item->is_name = is_name != 0;
 
1498
        item->datalen = 0;
 
1499
        item->data = NULL;
 
1500
        if (data) {
 
1501
                if (item->is_name) {
 
1502
                        if (!(item->data = strdup(data))) {
 
1503
                                free(item->name);
 
1504
                                free(item);
 
1505
                                return -1;
 
1506
                        }
 
1507
                        item->datalen = (u16)-1;
 
1508
                } else {
 
1509
                        if (!(item->data = malloc(datalen))) {
 
1510
                                free(item->name);
 
1511
                                free(item);
 
1512
                                return -1;
 
1513
                        }
 
1514
                        item->datalen = datalen;
 
1515
                        memcpy(item->data, data, datalen);
 
1516
                }
 
1517
        }
 
1518
 
 
1519
        *itemp = item;
 
1520
        ++(*countp);
 
1521
        return 0;
 
1522
}
 
1523
 
 
1524
/* exported function */
 
1525
int
 
1526
evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
 
1527
{
 
1528
        return evdns_server_request_add_reply(
 
1529
                  req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
 
1530
                  ttl, n*4, 0, addrs);
 
1531
}
 
1532
 
 
1533
/* exported function */
 
1534
int
 
1535
evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
 
1536
{
 
1537
        return evdns_server_request_add_reply(
 
1538
                  req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
 
1539
                  ttl, n*16, 0, addrs);
 
1540
}
 
1541
 
 
1542
/* exported function */
 
1543
int
 
1544
evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
 
1545
{
 
1546
        u32 a;
 
1547
        char buf[32];
 
1548
        assert(in || inaddr_name);
 
1549
        assert(!(in && inaddr_name));
 
1550
        if (in) {
 
1551
                a = ntohl(in->s_addr);
 
1552
                snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
 
1553
                                (int)(u8)((a    )&0xff),
 
1554
                                (int)(u8)((a>>8 )&0xff),
 
1555
                                (int)(u8)((a>>16)&0xff),
 
1556
                                (int)(u8)((a>>24)&0xff));
 
1557
                inaddr_name = buf;
 
1558
        }
 
1559
        return evdns_server_request_add_reply(
 
1560
                  req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
 
1561
                  ttl, -1, 1, hostname);
 
1562
}
 
1563
 
 
1564
/* exported function */
 
1565
int
 
1566
evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
 
1567
{
 
1568
        return evdns_server_request_add_reply(
 
1569
                  req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
 
1570
                  ttl, -1, 1, cname);
 
1571
}
 
1572
 
 
1573
 
 
1574
static int
 
1575
evdns_server_request_format_response(struct server_request *req, int err)
 
1576
{
 
1577
        unsigned char buf[1500];
 
1578
        size_t buf_len = sizeof(buf);
 
1579
        off_t j = 0, r;
 
1580
        u16 _t;
 
1581
        u32 _t32;
 
1582
        int i;
 
1583
        u16 flags;
 
1584
        struct dnslabel_table table;
 
1585
 
 
1586
        if (err < 0 || err > 15) return -1;
 
1587
 
 
1588
        /* Set response bit and error code; copy OPCODE and RD fields from
 
1589
         * question; copy RA and AA if set by caller. */
 
1590
        flags = req->base.flags;
 
1591
        flags |= (0x8000 | err);
 
1592
 
 
1593
        dnslabel_table_init(&table);
 
1594
        APPEND16(req->trans_id);
 
1595
        APPEND16(flags);
 
1596
        APPEND16(req->base.nquestions);
 
1597
        APPEND16(req->n_answer);
 
1598
        APPEND16(req->n_authority);
 
1599
        APPEND16(req->n_additional);
 
1600
 
 
1601
        /* Add questions. */
 
1602
        for (i=0; i < req->base.nquestions; ++i) {
 
1603
                const char *s = req->base.questions[i]->name;
 
1604
                j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
 
1605
                if (j < 0) {
 
1606
                        dnslabel_clear(&table);
 
1607
                        return (int) j;
 
1608
                }
 
1609
                APPEND16(req->base.questions[i]->type);
 
1610
                APPEND16(req->base.questions[i]->class);
 
1611
        }
 
1612
 
 
1613
        /* Add answer, authority, and additional sections. */
 
1614
        for (i=0; i<3; ++i) {
 
1615
                struct server_reply_item *item;
 
1616
                if (i==0)
 
1617
                        item = req->answer;
 
1618
                else if (i==1)
 
1619
                        item = req->authority;
 
1620
                else
 
1621
                        item = req->additional;
 
1622
                while (item) {
 
1623
                        r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
 
1624
                        if (r < 0)
 
1625
                                goto overflow;
 
1626
                        j = r;
 
1627
 
 
1628
                        APPEND16(item->type);
 
1629
                        APPEND16(item->class);
 
1630
                        APPEND32(item->ttl);
 
1631
                        if (item->is_name) {
 
1632
                                off_t len_idx = j, name_start;
 
1633
                                j += 2;
 
1634
                                name_start = j;
 
1635
                                r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
 
1636
                                if (r < 0)
 
1637
                                        goto overflow;
 
1638
                                j = r;
 
1639
                                _t = htons( (j-name_start) );
 
1640
                                memcpy(buf+len_idx, &_t, 2);
 
1641
                        } else {
 
1642
                                APPEND16(item->datalen);
 
1643
                                if (j+item->datalen > (off_t)buf_len)
 
1644
                                        goto overflow;
 
1645
                                memcpy(buf+j, item->data, item->datalen);
 
1646
                                j += item->datalen;
 
1647
                        }
 
1648
                        item = item->next;
 
1649
                }
 
1650
        }
 
1651
 
 
1652
        if (j > 512) {
 
1653
overflow:
 
1654
                j = 512;
 
1655
                buf[3] |= 0x02; /* set the truncated bit. */
 
1656
        }
 
1657
 
 
1658
        req->response_len = j;
 
1659
 
 
1660
        if (!(req->response = malloc(req->response_len))) {
 
1661
                server_request_free_answers(req);
 
1662
                dnslabel_clear(&table);
 
1663
                return (-1);
 
1664
        }
 
1665
        memcpy(req->response, buf, req->response_len);
 
1666
        server_request_free_answers(req);
 
1667
        dnslabel_clear(&table);
 
1668
        return (0);
 
1669
}
 
1670
 
 
1671
/* exported function */
 
1672
int
 
1673
evdns_server_request_respond(struct evdns_server_request *_req, int err)
 
1674
{
 
1675
        struct server_request *req = TO_SERVER_REQUEST(_req);
 
1676
        struct evdns_server_port *port = req->port;
 
1677
        int r;
 
1678
        if (!req->response) {
 
1679
                if ((r = evdns_server_request_format_response(req, err))<0)
 
1680
                        return r;
 
1681
        }
 
1682
 
 
1683
        r = sendto(port->socket, req->response, req->response_len, 0,
 
1684
                           (struct sockaddr*) &req->addr, req->addrlen);
 
1685
        if (r<0) {
 
1686
                int err = last_error(port->socket);
 
1687
                if (! error_is_eagain(err))
 
1688
                        return -1;
 
1689
 
 
1690
                if (port->pending_replies) {
 
1691
                        req->prev_pending = port->pending_replies->prev_pending;
 
1692
                        req->next_pending = port->pending_replies;
 
1693
                        req->prev_pending->next_pending =
 
1694
                                req->next_pending->prev_pending = req;
 
1695
                } else {
 
1696
                        req->prev_pending = req->next_pending = req;
 
1697
                        port->pending_replies = req;
 
1698
                        port->choked = 1;
 
1699
 
 
1700
                        (void) event_del(&port->event);
 
1701
                        event_set(&port->event, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
 
1702
 
 
1703
                        if (event_add(&port->event, NULL) < 0) {
 
1704
                                log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
 
1705
                        }
 
1706
 
 
1707
                }
 
1708
 
 
1709
                return 1;
 
1710
        }
 
1711
        if (server_request_free(req))
 
1712
                return 0;
 
1713
 
 
1714
        if (port->pending_replies)
 
1715
                server_port_flush(port);
 
1716
 
 
1717
        return 0;
 
1718
}
 
1719
 
 
1720
/* Free all storage held by RRs in req. */
 
1721
static void
 
1722
server_request_free_answers(struct server_request *req)
 
1723
{
 
1724
        struct server_reply_item *victim, *next, **list;
 
1725
        int i;
 
1726
        for (i = 0; i < 3; ++i) {
 
1727
                if (i==0)
 
1728
                        list = &req->answer;
 
1729
                else if (i==1)
 
1730
                        list = &req->authority;
 
1731
                else
 
1732
                        list = &req->additional;
 
1733
 
 
1734
                victim = *list;
 
1735
                while (victim) {
 
1736
                        next = victim->next;
 
1737
                        free(victim->name);
 
1738
                        if (victim->data)
 
1739
                                free(victim->data);
 
1740
                        free(victim);
 
1741
                        victim = next;
 
1742
                }
 
1743
                *list = NULL;
 
1744
        }
 
1745
}
 
1746
 
 
1747
/* Free all storage held by req, and remove links to it. */
 
1748
/* return true iff we just wound up freeing the server_port. */
 
1749
static int
 
1750
server_request_free(struct server_request *req)
 
1751
{
 
1752
        int i, rc=1;
 
1753
        if (req->base.questions) {
 
1754
                for (i = 0; i < req->base.nquestions; ++i)
 
1755
                        free(req->base.questions[i]);
 
1756
                free(req->base.questions);
 
1757
        }
 
1758
 
 
1759
        if (req->port) {
 
1760
                if (req->port->pending_replies == req) {
 
1761
                        if (req->next_pending)
 
1762
                                req->port->pending_replies = req->next_pending;
 
1763
                        else
 
1764
                                req->port->pending_replies = NULL;
 
1765
                }
 
1766
                rc = --req->port->refcnt;
 
1767
        }
 
1768
 
 
1769
        if (req->response) {
 
1770
                free(req->response);
 
1771
        }
 
1772
 
 
1773
        server_request_free_answers(req);
 
1774
 
 
1775
        if (req->next_pending && req->next_pending != req) {
 
1776
                req->next_pending->prev_pending = req->prev_pending;
 
1777
                req->prev_pending->next_pending = req->next_pending;
 
1778
        }
 
1779
 
 
1780
        if (rc == 0) {
 
1781
                server_port_free(req->port);
 
1782
                free(req);
 
1783
                return (1);
 
1784
        }
 
1785
        free(req);
 
1786
        return (0);
 
1787
}
 
1788
 
 
1789
/* Free all storage held by an evdns_server_port.  Only called when  */
 
1790
static void
 
1791
server_port_free(struct evdns_server_port *port)
 
1792
{
 
1793
        assert(port);
 
1794
        assert(!port->refcnt);
 
1795
        assert(!port->pending_replies);
 
1796
        if (port->socket > 0) {
 
1797
                CLOSE_SOCKET(port->socket);
 
1798
                port->socket = -1;
 
1799
        }
 
1800
        (void) event_del(&port->event);
 
1801
        /* XXXX actually free the port? -NM */
 
1802
}
 
1803
 
 
1804
/* exported function */
 
1805
int
 
1806
evdns_server_request_drop(struct evdns_server_request *_req)
 
1807
{
 
1808
        struct server_request *req = TO_SERVER_REQUEST(_req);
 
1809
        server_request_free(req);
 
1810
        return 0;
 
1811
}
 
1812
 
 
1813
/* exported function */
 
1814
int
 
1815
evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
 
1816
{
 
1817
        struct server_request *req = TO_SERVER_REQUEST(_req);
 
1818
        if (addr_len < (int)req->addrlen)
 
1819
                return -1;
 
1820
        memcpy(sa, &(req->addr), req->addrlen);
 
1821
        return req->addrlen;
 
1822
}
 
1823
 
 
1824
#undef APPEND16
 
1825
#undef APPEND32
 
1826
 
 
1827
/* this is a libevent callback function which is called when a request */
 
1828
/* has timed out. */
 
1829
static void
 
1830
evdns_request_timeout_callback(int fd, short events, void *arg) {
 
1831
        struct request *const req = (struct request *) arg;
 
1832
        (void) fd;
 
1833
        (void) events;
 
1834
 
 
1835
        log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
 
1836
 
 
1837
        req->ns->timedout++;
 
1838
        if (req->ns->timedout > global_max_nameserver_timeout) {
 
1839
                req->ns->timedout = 0;
 
1840
                nameserver_failed(req->ns, "request timed out.");
 
1841
        }
 
1842
 
 
1843
        (void) evtimer_del(&req->timeout_event);
 
1844
        if (req->tx_count >= global_max_retransmits) {
 
1845
                /* this request has failed */
 
1846
                reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
 
1847
                request_finished(req, &req_head);
 
1848
        } else {
 
1849
                /* retransmit it */
 
1850
                evdns_request_transmit(req);
 
1851
        }
 
1852
}
 
1853
 
 
1854
/* try to send a request to a given server. */
 
1855
/* */
 
1856
/* return: */
 
1857
/*   0 ok */
 
1858
/*   1 temporary failure */
 
1859
/*   2 other failure */
 
1860
static int
 
1861
evdns_request_transmit_to(struct request *req, struct nameserver *server) {
 
1862
        const int r = send(server->socket, req->request, req->request_len, 0);
 
1863
        if (r < 0) {
 
1864
                int err = last_error(server->socket);
 
1865
                if (error_is_eagain(err)) return 1;
 
1866
                nameserver_failed(req->ns, strerror(err));
 
1867
                return 2;
 
1868
        } else if (r != (int)req->request_len) {
 
1869
                return 1;  /* short write */
 
1870
        } else {
 
1871
                return 0;
 
1872
        }
 
1873
}
 
1874
 
 
1875
/* try to send a request, updating the fields of the request */
 
1876
/* as needed */
 
1877
/* */
 
1878
/* return: */
 
1879
/*   0 ok */
 
1880
/*   1 failed */
 
1881
static int
 
1882
evdns_request_transmit(struct request *req) {
 
1883
        int retcode = 0, r;
 
1884
 
 
1885
        /* if we fail to send this packet then this flag marks it */
 
1886
        /* for evdns_transmit */
 
1887
        req->transmit_me = 1;
 
1888
        if (req->trans_id == 0xffff) abort();
 
1889
 
 
1890
        if (req->ns->choked) {
 
1891
                /* don't bother trying to write to a socket */
 
1892
                /* which we have had EAGAIN from */
 
1893
                return 1;
 
1894
        }
 
1895
 
 
1896
        r = evdns_request_transmit_to(req, req->ns);
 
1897
        switch (r) {
 
1898
        case 1:
 
1899
                /* temp failure */
 
1900
                req->ns->choked = 1;
 
1901
                nameserver_write_waiting(req->ns, 1);
 
1902
                return 1;
 
1903
        case 2:
 
1904
                /* failed in some other way */
 
1905
                retcode = 1;
 
1906
                /* fall through */
 
1907
        default:
 
1908
                /* all ok */
 
1909
                log(EVDNS_LOG_DEBUG,
 
1910
                    "Setting timeout for request %lx", (unsigned long) req);
 
1911
                evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
 
1912
                if (evtimer_add(&req->timeout_event, &global_timeout) < 0) {
 
1913
                  log(EVDNS_LOG_WARN,
 
1914
                      "Error from libevent when adding timer for request %lx",
 
1915
                      (unsigned long) req);
 
1916
                  /* ???? Do more? */
 
1917
                }
 
1918
                req->tx_count++;
 
1919
                req->transmit_me = 0;
 
1920
                return retcode;
 
1921
        }
 
1922
}
 
1923
 
 
1924
static void
 
1925
nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
 
1926
        struct nameserver *const ns = (struct nameserver *) arg;
 
1927
        (void) type;
 
1928
        (void) count;
 
1929
        (void) ttl;
 
1930
        (void) addresses;
 
1931
 
 
1932
        if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
 
1933
                /* this is a good reply */
 
1934
                nameserver_up(ns);
 
1935
        } else nameserver_probe_failed(ns);
 
1936
}
 
1937
 
 
1938
static void
 
1939
nameserver_send_probe(struct nameserver *const ns) {
 
1940
        struct request *req;
 
1941
        /* here we need to send a probe to a given nameserver */
 
1942
        /* in the hope that it is up now. */
 
1943
 
 
1944
        log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntoa(ns->address));
 
1945
 
 
1946
        req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
 
1947
        if (!req) return;
 
1948
        /* we force this into the inflight queue no matter what */
 
1949
        request_trans_id_set(req, transaction_id_pick());
 
1950
        req->ns = ns;
 
1951
        request_submit(req);
 
1952
}
 
1953
 
 
1954
/* returns: */
 
1955
/*   0 didn't try to transmit anything */
 
1956
/*   1 tried to transmit something */
 
1957
static int
 
1958
evdns_transmit(void) {
 
1959
        char did_try_to_transmit = 0;
 
1960
 
 
1961
        if (req_head) {
 
1962
                struct request *const started_at = req_head, *req = req_head;
 
1963
                /* first transmit all the requests which are currently waiting */
 
1964
                do {
 
1965
                        if (req->transmit_me) {
 
1966
                                did_try_to_transmit = 1;
 
1967
                                evdns_request_transmit(req);
 
1968
                        }
 
1969
 
 
1970
                        req = req->next;
 
1971
                } while (req != started_at);
 
1972
        }
 
1973
 
 
1974
        return did_try_to_transmit;
 
1975
}
 
1976
 
 
1977
/* exported function */
 
1978
int
 
1979
evdns_count_nameservers(void)
 
1980
{
 
1981
        const struct nameserver *server = server_head;
 
1982
        int n = 0;
 
1983
        if (!server)
 
1984
                return 0;
 
1985
        do {
 
1986
                ++n;
 
1987
                server = server->next;
 
1988
        } while (server != server_head);
 
1989
        return n;
 
1990
}
 
1991
 
 
1992
/* exported function */
 
1993
int
 
1994
evdns_clear_nameservers_and_suspend(void)
 
1995
{
 
1996
        struct nameserver *server = server_head, *started_at = server_head;
 
1997
        struct request *req = req_head, *req_started_at = req_head;
 
1998
 
 
1999
        if (!server)
 
2000
                return 0;
 
2001
        while (1) {
 
2002
                struct nameserver *next = server->next;
 
2003
                (void) event_del(&server->event);
 
2004
                (void) evtimer_del(&server->timeout_event);
 
2005
                if (server->socket >= 0)
 
2006
                        CLOSE_SOCKET(server->socket);
 
2007
                free(server);
 
2008
                if (next == started_at)
 
2009
                        break;
 
2010
                server = next;
 
2011
        }
 
2012
        server_head = NULL;
 
2013
        global_good_nameservers = 0;
 
2014
 
 
2015
        while (req) {
 
2016
                struct request *next = req->next;
 
2017
                req->tx_count = req->reissue_count = 0;
 
2018
                req->ns = NULL;
 
2019
                /* ???? What to do about searches? */
 
2020
                (void) evtimer_del(&req->timeout_event);
 
2021
                req->trans_id = 0;
 
2022
                req->transmit_me = 0;
 
2023
 
 
2024
                global_requests_waiting++;
 
2025
                evdns_request_insert(req, &req_waiting_head);
 
2026
                /* We want to insert these suspended elements at the front of
 
2027
                 * the waiting queue, since they were pending before any of
 
2028
                 * the waiting entries were added.  This is a circular list,
 
2029
                 * so we can just shift the start back by one.*/
 
2030
                req_waiting_head = req_waiting_head->prev;
 
2031
 
 
2032
                if (next == req_started_at)
 
2033
                        break;
 
2034
                req = next;
 
2035
        }
 
2036
        req_head = NULL;
 
2037
        global_requests_inflight = 0;
 
2038
 
 
2039
        return 0;
 
2040
}
 
2041
 
 
2042
 
 
2043
/* exported function */
 
2044
int
 
2045
evdns_resume(void)
 
2046
{
 
2047
        evdns_requests_pump_waiting_queue();
 
2048
        return 0;
 
2049
}
 
2050
 
 
2051
static int
 
2052
_evdns_nameserver_add_impl(unsigned long int address, int port) {
 
2053
        /* first check to see if we already have this nameserver */
 
2054
 
 
2055
        const struct nameserver *server = server_head, *const started_at = server_head;
 
2056
        struct nameserver *ns;
 
2057
        struct sockaddr_in sin;
 
2058
        int err = 0;
 
2059
        if (server) {
 
2060
                do {
 
2061
                        if (server->address == address) return 3;
 
2062
                        server = server->next;
 
2063
                } while (server != started_at);
 
2064
        }
 
2065
 
 
2066
        ns = (struct nameserver *) malloc(sizeof(struct nameserver));
 
2067
        if (!ns) return -1;
 
2068
 
 
2069
        memset(ns, 0, sizeof(struct nameserver));
 
2070
 
 
2071
        ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
 
2072
        if (ns->socket < 0) { err = 1; goto out1; }
 
2073
        evutil_make_socket_nonblocking(ns->socket);
 
2074
        sin.sin_addr.s_addr = address;
 
2075
        sin.sin_port = htons(port);
 
2076
        sin.sin_family = AF_INET;
 
2077
        if (connect(ns->socket, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
 
2078
                err = 2;
 
2079
                goto out2;
 
2080
        }
 
2081
 
 
2082
        ns->address = address;
 
2083
        ns->state = 1;
 
2084
        event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
 
2085
        if (event_add(&ns->event, NULL) < 0) {
 
2086
          err = 2;
 
2087
          goto out2;
 
2088
        }
 
2089
 
 
2090
        log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntoa(address));
 
2091
 
 
2092
        /* insert this nameserver into the list of them */
 
2093
        if (!server_head) {
 
2094
                ns->next = ns->prev = ns;
 
2095
                server_head = ns;
 
2096
        } else {
 
2097
                ns->next = server_head->next;
 
2098
                ns->prev = server_head;
 
2099
                server_head->next = ns;
 
2100
                if (server_head->prev == server_head) {
 
2101
                        server_head->prev = ns;
 
2102
                }
 
2103
        }
 
2104
 
 
2105
        global_good_nameservers++;
 
2106
 
 
2107
        return 0;
 
2108
 
 
2109
out2:
 
2110
        CLOSE_SOCKET(ns->socket);
 
2111
out1:
 
2112
        free(ns);
 
2113
        log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntoa(address), err);
 
2114
        return err;
 
2115
}
 
2116
 
 
2117
/* exported function */
 
2118
int
 
2119
evdns_nameserver_add(unsigned long int address) {
 
2120
        return _evdns_nameserver_add_impl(address, 53);
 
2121
}
 
2122
 
 
2123
/* exported function */
 
2124
int
 
2125
evdns_nameserver_ip_add(const char *ip_as_string) {
 
2126
        struct in_addr ina;
 
2127
        int port;
 
2128
        char buf[20];
 
2129
        const char *cp;
 
2130
        cp = strchr(ip_as_string, ':');
 
2131
        if (! cp) {
 
2132
                cp = ip_as_string;
 
2133
                port = 53;
 
2134
        } else {
 
2135
                port = strtoint(cp+1);
 
2136
                if (port < 0 || port > 65535) {
 
2137
                        return 4;
 
2138
                }
 
2139
                if ((cp-ip_as_string) >= (int)sizeof(buf)) {
 
2140
                        return 4;
 
2141
                }
 
2142
                memcpy(buf, ip_as_string, cp-ip_as_string);
 
2143
                buf[cp-ip_as_string] = '\0';
 
2144
                cp = buf;
 
2145
        }
 
2146
        if (!inet_aton(cp, &ina)) {
 
2147
                return 4;
 
2148
        }
 
2149
        return _evdns_nameserver_add_impl(ina.s_addr, port);
 
2150
}
 
2151
 
 
2152
/* insert into the tail of the queue */
 
2153
static void
 
2154
evdns_request_insert(struct request *req, struct request **head) {
 
2155
        if (!*head) {
 
2156
                *head = req;
 
2157
                req->next = req->prev = req;
 
2158
                return;
 
2159
        }
 
2160
 
 
2161
        req->prev = (*head)->prev;
 
2162
        req->prev->next = req;
 
2163
        req->next = *head;
 
2164
        (*head)->prev = req;
 
2165
}
 
2166
 
 
2167
static int
 
2168
string_num_dots(const char *s) {
 
2169
        int count = 0;
 
2170
        while ((s = strchr(s, '.'))) {
 
2171
                s++;
 
2172
                count++;
 
2173
        }
 
2174
        return count;
 
2175
}
 
2176
 
 
2177
static struct request *
 
2178
request_new(int type, const char *name, int flags,
 
2179
    evdns_callback_type callback, void *user_ptr) {
 
2180
        const char issuing_now =
 
2181
            (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
 
2182
 
 
2183
        const int name_len = strlen(name);
 
2184
        const int request_max_len = evdns_request_len(name_len);
 
2185
        const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
 
2186
        /* the request data is alloced in a single block with the header */
 
2187
        struct request *const req =
 
2188
            (struct request *) malloc(sizeof(struct request) + request_max_len);
 
2189
        int rlen;
 
2190
        (void) flags;
 
2191
 
 
2192
        if (!req) return NULL;
 
2193
        memset(req, 0, sizeof(struct request));
 
2194
 
 
2195
        /* request data lives just after the header */
 
2196
        req->request = ((u8 *) req) + sizeof(struct request);
 
2197
        /* denotes that the request data shouldn't be free()ed */
 
2198
        req->request_appended = 1;
 
2199
        rlen = evdns_request_data_build(name, name_len, trans_id,
 
2200
            type, CLASS_INET, req->request, request_max_len);
 
2201
        if (rlen < 0)
 
2202
                goto err1;
 
2203
        req->request_len = rlen;
 
2204
        req->trans_id = trans_id;
 
2205
        req->tx_count = 0;
 
2206
        req->request_type = type;
 
2207
        req->user_pointer = user_ptr;
 
2208
        req->user_callback = callback;
 
2209
        req->ns = issuing_now ? nameserver_pick() : NULL;
 
2210
        req->next = req->prev = NULL;
 
2211
 
 
2212
        return req;
 
2213
err1:
 
2214
        free(req);
 
2215
        return NULL;
 
2216
}
 
2217
 
 
2218
static void
 
2219
request_submit(struct request *const req) {
 
2220
        if (req->ns) {
 
2221
                /* if it has a nameserver assigned then this is going */
 
2222
                /* straight into the inflight queue */
 
2223
                evdns_request_insert(req, &req_head);
 
2224
                global_requests_inflight++;
 
2225
                evdns_request_transmit(req);
 
2226
        } else {
 
2227
                evdns_request_insert(req, &req_waiting_head);
 
2228
                global_requests_waiting++;
 
2229
        }
 
2230
}
 
2231
 
 
2232
/* exported function */
 
2233
int evdns_resolve_ipv4(const char *name, int flags,
 
2234
    evdns_callback_type callback, void *ptr) {
 
2235
        log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
 
2236
        if (flags & DNS_QUERY_NO_SEARCH) {
 
2237
                struct request *const req =
 
2238
                        request_new(TYPE_A, name, flags, callback, ptr);
 
2239
                if (req == NULL)
 
2240
                        return (1);
 
2241
                request_submit(req);
 
2242
                return (0);
 
2243
        } else {
 
2244
                return (search_request_new(TYPE_A, name, flags, callback, ptr));
 
2245
        }
 
2246
}
 
2247
 
 
2248
/* exported function */
 
2249
int evdns_resolve_ipv6(const char *name, int flags,
 
2250
                                           evdns_callback_type callback, void *ptr) {
 
2251
        log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
 
2252
        if (flags & DNS_QUERY_NO_SEARCH) {
 
2253
                struct request *const req =
 
2254
                        request_new(TYPE_AAAA, name, flags, callback, ptr);
 
2255
                if (req == NULL)
 
2256
                        return (1);
 
2257
                request_submit(req);
 
2258
                return (0);
 
2259
        } else {
 
2260
                return (search_request_new(TYPE_AAAA, name, flags, callback, ptr));
 
2261
        }
 
2262
}
 
2263
 
 
2264
int evdns_resolve_reverse(struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
 
2265
        char buf[32];
 
2266
        struct request *req;
 
2267
        u32 a;
 
2268
        assert(in);
 
2269
        a = ntohl(in->s_addr);
 
2270
        snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
 
2271
                        (int)(u8)((a    )&0xff),
 
2272
                        (int)(u8)((a>>8 )&0xff),
 
2273
                        (int)(u8)((a>>16)&0xff),
 
2274
                        (int)(u8)((a>>24)&0xff));
 
2275
        log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
 
2276
        req = request_new(TYPE_PTR, buf, flags, callback, ptr);
 
2277
        if (!req) return 1;
 
2278
        request_submit(req);
 
2279
        return 0;
 
2280
}
 
2281
 
 
2282
int evdns_resolve_reverse_ipv6(struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
 
2283
        /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
 
2284
        char buf[73];
 
2285
        char *cp;
 
2286
        struct request *req;
 
2287
        int i;
 
2288
        assert(in);
 
2289
        cp = buf;
 
2290
        for (i=15; i >= 0; --i) {
 
2291
                u8 byte = in->s6_addr[i];
 
2292
                *cp++ = "0123456789abcdef"[byte & 0x0f];
 
2293
                *cp++ = '.';
 
2294
                *cp++ = "0123456789abcdef"[byte >> 4];
 
2295
                *cp++ = '.';
 
2296
        }
 
2297
        assert(cp + strlen("ip6.arpa") < buf+sizeof(buf));
 
2298
        memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
 
2299
        log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
 
2300
        req = request_new(TYPE_PTR, buf, flags, callback, ptr);
 
2301
        if (!req) return 1;
 
2302
        request_submit(req);
 
2303
        return 0;
 
2304
}
 
2305
 
 
2306
/*/////////////////////////////////////////////////////////////////// */
 
2307
/* Search support */
 
2308
/* */
 
2309
/* the libc resolver has support for searching a number of domains */
 
2310
/* to find a name. If nothing else then it takes the single domain */
 
2311
/* from the gethostname() call. */
 
2312
/* */
 
2313
/* It can also be configured via the domain and search options in a */
 
2314
/* resolv.conf. */
 
2315
/* */
 
2316
/* The ndots option controls how many dots it takes for the resolver */
 
2317
/* to decide that a name is non-local and so try a raw lookup first. */
 
2318
 
 
2319
struct search_domain {
 
2320
        int len;
 
2321
        struct search_domain *next;
 
2322
        /* the text string is appended to this structure */
 
2323
};
 
2324
 
 
2325
struct search_state {
 
2326
        int refcount;
 
2327
        int ndots;
 
2328
        int num_domains;
 
2329
        struct search_domain *head;
 
2330
};
 
2331
 
 
2332
static struct search_state *global_search_state = NULL;
 
2333
 
 
2334
static void
 
2335
search_state_decref(struct search_state *const state) {
 
2336
        if (!state) return;
 
2337
        state->refcount--;
 
2338
        if (!state->refcount) {
 
2339
                struct search_domain *next, *dom;
 
2340
                for (dom = state->head; dom; dom = next) {
 
2341
                        next = dom->next;
 
2342
                        free(dom);
 
2343
                }
 
2344
                free(state);
 
2345
        }
 
2346
}
 
2347
 
 
2348
static struct search_state *
 
2349
search_state_new(void) {
 
2350
        struct search_state *state = (struct search_state *) malloc(sizeof(struct search_state));
 
2351
        if (!state) return NULL;
 
2352
        memset(state, 0, sizeof(struct search_state));
 
2353
        state->refcount = 1;
 
2354
        state->ndots = 1;
 
2355
 
 
2356
        return state;
 
2357
}
 
2358
 
 
2359
static void
 
2360
search_postfix_clear(void) {
 
2361
        search_state_decref(global_search_state);
 
2362
 
 
2363
        global_search_state = search_state_new();
 
2364
}
 
2365
 
 
2366
/* exported function */
 
2367
void
 
2368
evdns_search_clear(void) {
 
2369
        search_postfix_clear();
 
2370
}
 
2371
 
 
2372
static void
 
2373
search_postfix_add(const char *domain) {
 
2374
        int domain_len;
 
2375
        struct search_domain *sdomain;
 
2376
        while (domain[0] == '.') domain++;
 
2377
        domain_len = strlen(domain);
 
2378
 
 
2379
        if (!global_search_state) global_search_state = search_state_new();
 
2380
        if (!global_search_state) return;
 
2381
        global_search_state->num_domains++;
 
2382
 
 
2383
        sdomain = (struct search_domain *) malloc(sizeof(struct search_domain) + domain_len);
 
2384
        if (!sdomain) return;
 
2385
        memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
 
2386
        sdomain->next = global_search_state->head;
 
2387
        sdomain->len = domain_len;
 
2388
 
 
2389
        global_search_state->head = sdomain;
 
2390
}
 
2391
 
 
2392
/* reverse the order of members in the postfix list. This is needed because, */
 
2393
/* when parsing resolv.conf we push elements in the wrong order */
 
2394
static void
 
2395
search_reverse(void) {
 
2396
        struct search_domain *cur, *prev = NULL, *next;
 
2397
        cur = global_search_state->head;
 
2398
        while (cur) {
 
2399
                next = cur->next;
 
2400
                cur->next = prev;
 
2401
                prev = cur;
 
2402
                cur = next;
 
2403
        }
 
2404
 
 
2405
        global_search_state->head = prev;
 
2406
}
 
2407
 
 
2408
/* exported function */
 
2409
void
 
2410
evdns_search_add(const char *domain) {
 
2411
        search_postfix_add(domain);
 
2412
}
 
2413
 
 
2414
/* exported function */
 
2415
void
 
2416
evdns_search_ndots_set(const int ndots) {
 
2417
        if (!global_search_state) global_search_state = search_state_new();
 
2418
        if (!global_search_state) return;
 
2419
        global_search_state->ndots = ndots;
 
2420
}
 
2421
 
 
2422
static void
 
2423
search_set_from_hostname(void) {
 
2424
        char hostname[HOST_NAME_MAX + 1], *domainname;
 
2425
 
 
2426
        search_postfix_clear();
 
2427
        if (gethostname(hostname, sizeof(hostname))) return;
 
2428
        domainname = strchr(hostname, '.');
 
2429
        if (!domainname) return;
 
2430
        search_postfix_add(domainname);
 
2431
}
 
2432
 
 
2433
/* warning: returns malloced string */
 
2434
static char *
 
2435
search_make_new(const struct search_state *const state, int n, const char *const base_name) {
 
2436
        const int base_len = strlen(base_name);
 
2437
        const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
 
2438
        struct search_domain *dom;
 
2439
 
 
2440
        for (dom = state->head; dom; dom = dom->next) {
 
2441
                if (!n--) {
 
2442
                        /* this is the postfix we want */
 
2443
                        /* the actual postfix string is kept at the end of the structure */
 
2444
                        const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
 
2445
                        const int postfix_len = dom->len;
 
2446
                        char *const newname = (char *) malloc(base_len + need_to_append_dot + postfix_len + 1);
 
2447
                        if (!newname) return NULL;
 
2448
                        memcpy(newname, base_name, base_len);
 
2449
                        if (need_to_append_dot) newname[base_len] = '.';
 
2450
                        memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
 
2451
                        newname[base_len + need_to_append_dot + postfix_len] = 0;
 
2452
                        return newname;
 
2453
                }
 
2454
        }
 
2455
 
 
2456
        /* we ran off the end of the list and still didn't find the requested string */
 
2457
        abort();
 
2458
        return NULL; /* unreachable; stops warnings in some compilers. */
 
2459
}
 
2460
 
 
2461
static int
 
2462
search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
 
2463
        assert(type == TYPE_A || type == TYPE_AAAA);
 
2464
        if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
 
2465
             global_search_state &&
 
2466
                 global_search_state->num_domains) {
 
2467
                /* we have some domains to search */
 
2468
                struct request *req;
 
2469
                if (string_num_dots(name) >= global_search_state->ndots) {
 
2470
                        req = request_new(type, name, flags, user_callback, user_arg);
 
2471
                        if (!req) return 1;
 
2472
                        req->search_index = -1;
 
2473
                } else {
 
2474
                        char *const new_name = search_make_new(global_search_state, 0, name);
 
2475
                        if (!new_name) return 1;
 
2476
                        req = request_new(type, new_name, flags, user_callback, user_arg);
 
2477
                        free(new_name);
 
2478
                        if (!req) return 1;
 
2479
                        req->search_index = 0;
 
2480
                }
 
2481
                req->search_origname = strdup(name);
 
2482
                req->search_state = global_search_state;
 
2483
                req->search_flags = flags;
 
2484
                global_search_state->refcount++;
 
2485
                request_submit(req);
 
2486
                return 0;
 
2487
        } else {
 
2488
                struct request *const req = request_new(type, name, flags, user_callback, user_arg);
 
2489
                if (!req) return 1;
 
2490
                request_submit(req);
 
2491
                return 0;
 
2492
        }
 
2493
}
 
2494
 
 
2495
/* this is called when a request has failed to find a name. We need to check */
 
2496
/* if it is part of a search and, if so, try the next name in the list */
 
2497
/* returns: */
 
2498
/*   0 another request has been submitted */
 
2499
/*   1 no more requests needed */
 
2500
static int
 
2501
search_try_next(struct request *const req) {
 
2502
        if (req->search_state) {
 
2503
                /* it is part of a search */
 
2504
                char *new_name;
 
2505
                struct request *newreq;
 
2506
                req->search_index++;
 
2507
                if (req->search_index >= req->search_state->num_domains) {
 
2508
                        /* no more postfixes to try, however we may need to try */
 
2509
                        /* this name without a postfix */
 
2510
                        if (string_num_dots(req->search_origname) < req->search_state->ndots) {
 
2511
                                /* yep, we need to try it raw */
 
2512
                                struct request *const newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
 
2513
                                log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
 
2514
                                if (newreq) {
 
2515
                                        request_submit(newreq);
 
2516
                                        return 0;
 
2517
                                }
 
2518
                        }
 
2519
                        return 1;
 
2520
                }
 
2521
 
 
2522
                new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
 
2523
                if (!new_name) return 1;
 
2524
                log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
 
2525
                newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
 
2526
                free(new_name);
 
2527
                if (!newreq) return 1;
 
2528
                newreq->search_origname = req->search_origname;
 
2529
                req->search_origname = NULL;
 
2530
                newreq->search_state = req->search_state;
 
2531
                newreq->search_flags = req->search_flags;
 
2532
                newreq->search_index = req->search_index;
 
2533
                newreq->search_state->refcount++;
 
2534
                request_submit(newreq);
 
2535
                return 0;
 
2536
        }
 
2537
        return 1;
 
2538
}
 
2539
 
 
2540
static void
 
2541
search_request_finished(struct request *const req) {
 
2542
        if (req->search_state) {
 
2543
                search_state_decref(req->search_state);
 
2544
                req->search_state = NULL;
 
2545
        }
 
2546
        if (req->search_origname) {
 
2547
                free(req->search_origname);
 
2548
                req->search_origname = NULL;
 
2549
        }
 
2550
}
 
2551
 
 
2552
/*/////////////////////////////////////////////////////////////////// */
 
2553
/* Parsing resolv.conf files */
 
2554
 
 
2555
static void
 
2556
evdns_resolv_set_defaults(int flags) {
 
2557
        /* if the file isn't found then we assume a local resolver */
 
2558
        if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
 
2559
        if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1");
 
2560
}
 
2561
 
 
2562
#ifndef HAVE_STRTOK_R
 
2563
static char *
 
2564
strtok_r(char *s, const char *delim, char **state) {
 
2565
        return strtok(s, delim);
 
2566
}
 
2567
#endif
 
2568
 
 
2569
/* helper version of atoi which returns -1 on error */
 
2570
static int
 
2571
strtoint(const char *const str) {
 
2572
        char *endptr;
 
2573
        const int r = strtol(str, &endptr, 10);
 
2574
        if (*endptr) return -1;
 
2575
        return r;
 
2576
}
 
2577
 
 
2578
/* helper version of atoi that returns -1 on error and clips to bounds. */
 
2579
static int
 
2580
strtoint_clipped(const char *const str, int min, int max)
 
2581
{
 
2582
        int r = strtoint(str);
 
2583
        if (r == -1)
 
2584
                return r;
 
2585
        else if (r<min)
 
2586
                return min;
 
2587
        else if (r>max)
 
2588
                return max;
 
2589
        else
 
2590
                return r;
 
2591
}
 
2592
 
 
2593
/* exported function */
 
2594
int
 
2595
evdns_set_option(const char *option, const char *val, int flags)
 
2596
{
 
2597
        if (!strncmp(option, "ndots:", 6)) {
 
2598
                const int ndots = strtoint(val);
 
2599
                if (ndots == -1) return -1;
 
2600
                if (!(flags & DNS_OPTION_SEARCH)) return 0;
 
2601
                log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
 
2602
                if (!global_search_state) global_search_state = search_state_new();
 
2603
                if (!global_search_state) return -1;
 
2604
                global_search_state->ndots = ndots;
 
2605
        } else if (!strncmp(option, "timeout:", 8)) {
 
2606
                const int timeout = strtoint(val);
 
2607
                if (timeout == -1) return -1;
 
2608
                if (!(flags & DNS_OPTION_MISC)) return 0;
 
2609
                log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
 
2610
                global_timeout.tv_sec = timeout;
 
2611
        } else if (!strncmp(option, "max-timeouts:", 12)) {
 
2612
                const int maxtimeout = strtoint_clipped(val, 1, 255);
 
2613
                if (maxtimeout == -1) return -1;
 
2614
                if (!(flags & DNS_OPTION_MISC)) return 0;
 
2615
                log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
 
2616
                        maxtimeout);
 
2617
                global_max_nameserver_timeout = maxtimeout;
 
2618
        } else if (!strncmp(option, "max-inflight:", 13)) {
 
2619
                const int maxinflight = strtoint_clipped(val, 1, 65000);
 
2620
                if (maxinflight == -1) return -1;
 
2621
                if (!(flags & DNS_OPTION_MISC)) return 0;
 
2622
                log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
 
2623
                        maxinflight);
 
2624
                global_max_requests_inflight = maxinflight;
 
2625
        } else if (!strncmp(option, "attempts:", 9)) {
 
2626
                int retries = strtoint(val);
 
2627
                if (retries == -1) return -1;
 
2628
                if (retries > 255) retries = 255;
 
2629
                if (!(flags & DNS_OPTION_MISC)) return 0;
 
2630
                log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
 
2631
                global_max_retransmits = retries;
 
2632
        }
 
2633
        return 0;
 
2634
}
 
2635
 
 
2636
static void
 
2637
resolv_conf_parse_line(char *const start, int flags) {
 
2638
        char *strtok_state;
 
2639
        static const char *const delims = " \t";
 
2640
#define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
 
2641
 
 
2642
        char *const first_token = strtok_r(start, delims, &strtok_state);
 
2643
        if (!first_token) return;
 
2644
 
 
2645
        if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
 
2646
                const char *const nameserver = NEXT_TOKEN;
 
2647
                struct in_addr ina;
 
2648
 
 
2649
                if (inet_aton(nameserver, &ina)) {
 
2650
                        /* address is valid */
 
2651
                        evdns_nameserver_add(ina.s_addr);
 
2652
                }
 
2653
        } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
 
2654
                const char *const domain = NEXT_TOKEN;
 
2655
                if (domain) {
 
2656
                        search_postfix_clear();
 
2657
                        search_postfix_add(domain);
 
2658
                }
 
2659
        } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
 
2660
                const char *domain;
 
2661
                search_postfix_clear();
 
2662
 
 
2663
                while ((domain = NEXT_TOKEN)) {
 
2664
                        search_postfix_add(domain);
 
2665
                }
 
2666
                search_reverse();
 
2667
        } else if (!strcmp(first_token, "options")) {
 
2668
                const char *option;
 
2669
                while ((option = NEXT_TOKEN)) {
 
2670
                        const char *val = strchr(option, ':');
 
2671
                        evdns_set_option(option, val ? val+1 : "", flags);
 
2672
                }
 
2673
        }
 
2674
#undef NEXT_TOKEN
 
2675
}
 
2676
 
 
2677
/* exported function */
 
2678
/* returns: */
 
2679
/*   0 no errors */
 
2680
/*   1 failed to open file */
 
2681
/*   2 failed to stat file */
 
2682
/*   3 file too large */
 
2683
/*   4 out of memory */
 
2684
/*   5 short read from file */
 
2685
int
 
2686
evdns_resolv_conf_parse(int flags, const char *const filename) {
 
2687
        struct stat st;
 
2688
        int fd, n, r;
 
2689
        u8 *resolv;
 
2690
        char *start;
 
2691
        int err = 0;
 
2692
 
 
2693
        log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
 
2694
 
 
2695
        fd = open(filename, O_RDONLY);
 
2696
        if (fd < 0) {
 
2697
                evdns_resolv_set_defaults(flags);
 
2698
                return 1;
 
2699
        }
 
2700
 
 
2701
        if (fstat(fd, &st)) { err = 2; goto out1; }
 
2702
        if (!st.st_size) {
 
2703
                evdns_resolv_set_defaults(flags);
 
2704
                err = (flags & DNS_OPTION_NAMESERVERS) ? 6 : 0;
 
2705
                goto out1;
 
2706
        }
 
2707
        if (st.st_size > 65535) { err = 3; goto out1; }  /* no resolv.conf should be any bigger */
 
2708
 
 
2709
        resolv = (u8 *) malloc((size_t)st.st_size + 1);
 
2710
        if (!resolv) { err = 4; goto out1; }
 
2711
 
 
2712
        n = 0;
 
2713
        while ((r = read(fd, resolv+n, (size_t)st.st_size-n)) > 0) {
 
2714
                n += r;
 
2715
                if (n == st.st_size)
 
2716
                        break;
 
2717
                assert(n < st.st_size);
 
2718
        }
 
2719
        if (r < 0) { err = 5; goto out2; }
 
2720
        resolv[n] = 0;   /* we malloced an extra byte; this should be fine. */
 
2721
 
 
2722
        start = (char *) resolv;
 
2723
        for (;;) {
 
2724
                char *const newline = strchr(start, '\n');
 
2725
                if (!newline) {
 
2726
                        resolv_conf_parse_line(start, flags);
 
2727
                        break;
 
2728
                } else {
 
2729
                        *newline = 0;
 
2730
                        resolv_conf_parse_line(start, flags);
 
2731
                        start = newline + 1;
 
2732
                }
 
2733
        }
 
2734
 
 
2735
        if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
 
2736
                /* no nameservers were configured. */
 
2737
                evdns_nameserver_ip_add("127.0.0.1");
 
2738
                err = 6;
 
2739
        }
 
2740
        if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
 
2741
                search_set_from_hostname();
 
2742
        }
 
2743
 
 
2744
out2:
 
2745
        free(resolv);
 
2746
out1:
 
2747
        close(fd);
 
2748
        return err;
 
2749
}
 
2750
 
 
2751
#ifdef WIN32
 
2752
/* Add multiple nameservers from a space-or-comma-separated list. */
 
2753
static int
 
2754
evdns_nameserver_ip_add_line(const char *ips) {
 
2755
        const char *addr;
 
2756
        char *buf;
 
2757
        int r;
 
2758
        while (*ips) {
 
2759
                while (ISSPACE(*ips) || *ips == ',' || *ips == '\t')
 
2760
                        ++ips;
 
2761
                addr = ips;
 
2762
                while (ISDIGIT(*ips) || *ips == '.' || *ips == ':')
 
2763
                        ++ips;
 
2764
                buf = malloc(ips-addr+1);
 
2765
                if (!buf) return 4;
 
2766
                memcpy(buf, addr, ips-addr);
 
2767
                buf[ips-addr] = '\0';
 
2768
                r = evdns_nameserver_ip_add(buf);
 
2769
                free(buf);
 
2770
                if (r) return r;
 
2771
        }
 
2772
        return 0;
 
2773
}
 
2774
 
 
2775
typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
 
2776
 
 
2777
/* Use the windows GetNetworkParams interface in iphlpapi.dll to */
 
2778
/* figure out what our nameservers are. */
 
2779
static int
 
2780
load_nameservers_with_getnetworkparams(void)
 
2781
{
 
2782
        /* Based on MSDN examples and inspection of  c-ares code. */
 
2783
        FIXED_INFO *fixed;
 
2784
        HMODULE handle = 0;
 
2785
        ULONG size = sizeof(FIXED_INFO);
 
2786
        void *buf = NULL;
 
2787
        int status = 0, r, added_any;
 
2788
        IP_ADDR_STRING *ns;
 
2789
        GetNetworkParams_fn_t fn;
 
2790
 
 
2791
        if (!(handle = LoadLibrary("iphlpapi.dll"))) {
 
2792
                log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
 
2793
                status = -1;
 
2794
                goto done;
 
2795
        }
 
2796
        if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
 
2797
                log(EVDNS_LOG_WARN, "Could not get address of function.");
 
2798
                status = -1;
 
2799
                goto done;
 
2800
        }
 
2801
 
 
2802
        buf = malloc(size);
 
2803
        if (!buf) { status = 4; goto done; }
 
2804
        fixed = buf;
 
2805
        r = fn(fixed, &size);
 
2806
        if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
 
2807
                status = -1;
 
2808
                goto done;
 
2809
        }
 
2810
        if (r != ERROR_SUCCESS) {
 
2811
                free(buf);
 
2812
                buf = malloc(size);
 
2813
                if (!buf) { status = 4; goto done; }
 
2814
                fixed = buf;
 
2815
                r = fn(fixed, &size);
 
2816
                if (r != ERROR_SUCCESS) {
 
2817
                        log(EVDNS_LOG_DEBUG, "fn() failed.");
 
2818
                        status = -1;
 
2819
                        goto done;
 
2820
                }
 
2821
        }
 
2822
 
 
2823
        assert(fixed);
 
2824
        added_any = 0;
 
2825
        ns = &(fixed->DnsServerList);
 
2826
        while (ns) {
 
2827
                r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
 
2828
                if (r) {
 
2829
                        log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
 
2830
                                (ns->IpAddress.String),(int)GetLastError());
 
2831
                        status = r;
 
2832
                        goto done;
 
2833
                } else {
 
2834
                        log(EVDNS_LOG_DEBUG,"Succesfully added %s as nameserver",ns->IpAddress.String);
 
2835
                }
 
2836
 
 
2837
                added_any++;
 
2838
                ns = ns->Next;
 
2839
        }
 
2840
 
 
2841
        if (!added_any) {
 
2842
                log(EVDNS_LOG_DEBUG, "No nameservers added.");
 
2843
                status = -1;
 
2844
        }
 
2845
 
 
2846
 done:
 
2847
        if (buf)
 
2848
                free(buf);
 
2849
        if (handle)
 
2850
                FreeLibrary(handle);
 
2851
        return status;
 
2852
}
 
2853
 
 
2854
static int
 
2855
config_nameserver_from_reg_key(HKEY key, const char *subkey)
 
2856
{
 
2857
        char *buf;
 
2858
        DWORD bufsz = 0, type = 0;
 
2859
        int status = 0;
 
2860
 
 
2861
        if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
 
2862
            != ERROR_MORE_DATA)
 
2863
                return -1;
 
2864
        if (!(buf = malloc(bufsz)))
 
2865
                return -1;
 
2866
 
 
2867
        if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
 
2868
            == ERROR_SUCCESS && bufsz > 1) {
 
2869
                status = evdns_nameserver_ip_add_line(buf);
 
2870
        }
 
2871
 
 
2872
        free(buf);
 
2873
        return status;
 
2874
}
 
2875
 
 
2876
#define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
 
2877
#define WIN_NS_9X_KEY  SERVICES_KEY "VxD\\MSTCP"
 
2878
#define WIN_NS_NT_KEY  SERVICES_KEY "Tcpip\\Parameters"
 
2879
 
 
2880
static int
 
2881
load_nameservers_from_registry(void)
 
2882
{
 
2883
        int found = 0;
 
2884
        int r;
 
2885
#define TRY(k, name) \
 
2886
        if (!found && config_nameserver_from_reg_key(k,name) == 0) {    \
 
2887
                log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
 
2888
                found = 1;                                              \
 
2889
        } else if (!found) {                                            \
 
2890
                log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
 
2891
                    #k,#name);                                          \
 
2892
        }
 
2893
 
 
2894
        if (((int)GetVersion()) > 0) { /* NT */
 
2895
                HKEY nt_key = 0, interfaces_key = 0;
 
2896
 
 
2897
                if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
 
2898
                                 KEY_READ, &nt_key) != ERROR_SUCCESS) {
 
2899
                        log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
 
2900
                        return -1;
 
2901
                }
 
2902
                r = RegOpenKeyEx(nt_key, "Interfaces", 0,
 
2903
                             KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
 
2904
                             &interfaces_key);
 
2905
                if (r != ERROR_SUCCESS) {
 
2906
                        log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
 
2907
                        return -1;
 
2908
                }
 
2909
                TRY(nt_key, "NameServer");
 
2910
                TRY(nt_key, "DhcpNameServer");
 
2911
                TRY(interfaces_key, "NameServer");
 
2912
                TRY(interfaces_key, "DhcpNameServer");
 
2913
                RegCloseKey(interfaces_key);
 
2914
                RegCloseKey(nt_key);
 
2915
        } else {
 
2916
                HKEY win_key = 0;
 
2917
                if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
 
2918
                                 KEY_READ, &win_key) != ERROR_SUCCESS) {
 
2919
                        log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
 
2920
                        return -1;
 
2921
                }
 
2922
                TRY(win_key, "NameServer");
 
2923
                RegCloseKey(win_key);
 
2924
        }
 
2925
 
 
2926
        if (found == 0) {
 
2927
                log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
 
2928
        }
 
2929
 
 
2930
        return found ? 0 : -1;
 
2931
#undef TRY
 
2932
}
 
2933
 
 
2934
int
 
2935
evdns_config_windows_nameservers(void)
 
2936
{
 
2937
        if (load_nameservers_with_getnetworkparams() == 0)
 
2938
                return 0;
 
2939
        return load_nameservers_from_registry();
 
2940
}
 
2941
#endif
 
2942
 
 
2943
int
 
2944
evdns_init(void)
 
2945
{
 
2946
        int res = 0;
 
2947
#ifdef WIN32
 
2948
        evdns_config_windows_nameservers();
 
2949
#else
 
2950
        res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
 
2951
#endif
 
2952
 
 
2953
        return (res);
 
2954
}
 
2955
 
 
2956
const char *
 
2957
evdns_err_to_string(int err)
 
2958
{
 
2959
    switch (err) {
 
2960
        case DNS_ERR_NONE: return "no error";
 
2961
        case DNS_ERR_FORMAT: return "misformatted query";
 
2962
        case DNS_ERR_SERVERFAILED: return "server failed";
 
2963
        case DNS_ERR_NOTEXIST: return "name does not exist";
 
2964
        case DNS_ERR_NOTIMPL: return "query not implemented";
 
2965
        case DNS_ERR_REFUSED: return "refused";
 
2966
 
 
2967
        case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
 
2968
        case DNS_ERR_UNKNOWN: return "unknown";
 
2969
        case DNS_ERR_TIMEOUT: return "request timed out";
 
2970
        case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
 
2971
        default: return "[Unknown error code]";
 
2972
    }
 
2973
}
 
2974
 
 
2975
void
 
2976
evdns_shutdown(int fail_requests)
 
2977
{
 
2978
        struct nameserver *server, *server_next;
 
2979
        struct search_domain *dom, *dom_next;
 
2980
 
 
2981
        while (req_head) {
 
2982
                if (fail_requests)
 
2983
                        reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
 
2984
                request_finished(req_head, &req_head);
 
2985
        }
 
2986
        while (req_waiting_head) {
 
2987
                if (fail_requests)
 
2988
                        reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
 
2989
                request_finished(req_waiting_head, &req_waiting_head);
 
2990
        }
 
2991
        global_requests_inflight = global_requests_waiting = 0;
 
2992
 
 
2993
        for (server = server_head; server; server = server_next) {
 
2994
                server_next = server->next;
 
2995
                if (server->socket >= 0)
 
2996
                        CLOSE_SOCKET(server->socket);
 
2997
                (void) event_del(&server->event);
 
2998
                if (server->state == 0)
 
2999
                        (void) event_del(&server->timeout_event);
 
3000
                free(server);
 
3001
                if (server_next == server_head)
 
3002
                        break;
 
3003
        }
 
3004
        server_head = NULL;
 
3005
        global_good_nameservers = 0;
 
3006
 
 
3007
        if (global_search_state) {
 
3008
                for (dom = global_search_state->head; dom; dom = dom_next) {
 
3009
                        dom_next = dom->next;
 
3010
                        free(dom);
 
3011
                }
 
3012
                free(global_search_state);
 
3013
                global_search_state = NULL;
 
3014
        }
 
3015
        evdns_log_fn = NULL;
 
3016
}
 
3017
 
 
3018
#ifdef EVDNS_MAIN
 
3019
void
 
3020
main_callback(int result, char type, int count, int ttl,
 
3021
                          void *addrs, void *orig) {
 
3022
        char *n = (char*)orig;
 
3023
        int i;
 
3024
        for (i = 0; i < count; ++i) {
 
3025
                if (type == DNS_IPv4_A) {
 
3026
                        printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
 
3027
                } else if (type == DNS_PTR) {
 
3028
                        printf("%s: %s\n", n, ((char**)addrs)[i]);
 
3029
                }
 
3030
        }
 
3031
        if (!count) {
 
3032
                printf("%s: No answer (%d)\n", n, result);
 
3033
        }
 
3034
        fflush(stdout);
 
3035
}
 
3036
void
 
3037
evdns_server_callback(struct evdns_server_request *req, void *data)
 
3038
{
 
3039
        int i, r;
 
3040
        (void)data;
 
3041
        /* dummy; give 192.168.11.11 as an answer for all A questions,
 
3042
         *      give foo.bar.example.com as an answer for all PTR questions. */
 
3043
        for (i = 0; i < req->nquestions; ++i) {
 
3044
                u32 ans = htonl(0xc0a80b0bUL);
 
3045
                if (req->questions[i]->type == EVDNS_TYPE_A &&
 
3046
                        req->questions[i]->class == EVDNS_CLASS_INET) {
 
3047
                        printf(" -- replying for %s (A)\n", req->questions[i]->name);
 
3048
                        r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
 
3049
                                                                                  1, &ans, 10);
 
3050
                        if (r<0)
 
3051
                                printf("eeep, didn't work.\n");
 
3052
                } else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
 
3053
                                   req->questions[i]->class == EVDNS_CLASS_INET) {
 
3054
                        printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
 
3055
                        r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
 
3056
                                                                                        "foo.bar.example.com", 10);
 
3057
                } else {
 
3058
                        printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
 
3059
                                   req->questions[i]->type, req->questions[i]->class);
 
3060
                }
 
3061
        }
 
3062
 
 
3063
        r = evdns_request_respond(req, 0);
 
3064
        if (r<0)
 
3065
                printf("eeek, couldn't send reply.\n");
 
3066
}
 
3067
 
 
3068
void
 
3069
logfn(int is_warn, const char *msg) {
 
3070
  (void) is_warn;
 
3071
  fprintf(stderr, "%s\n", msg);
 
3072
}
 
3073
int
 
3074
main(int c, char **v) {
 
3075
        int idx;
 
3076
        int reverse = 0, verbose = 1, servertest = 0;
 
3077
        if (c<2) {
 
3078
                fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
 
3079
                fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
 
3080
                return 1;
 
3081
        }
 
3082
        idx = 1;
 
3083
        while (idx < c && v[idx][0] == '-') {
 
3084
                if (!strcmp(v[idx], "-x"))
 
3085
                        reverse = 1;
 
3086
                else if (!strcmp(v[idx], "-v"))
 
3087
                        verbose = 1;
 
3088
                else if (!strcmp(v[idx], "-servertest"))
 
3089
                        servertest = 1;
 
3090
                else
 
3091
                        fprintf(stderr, "Unknown option %s\n", v[idx]);
 
3092
                ++idx;
 
3093
        }
 
3094
        event_init();
 
3095
        if (verbose)
 
3096
                evdns_set_log_fn(logfn);
 
3097
        evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
 
3098
        if (servertest) {
 
3099
                int sock;
 
3100
                struct sockaddr_in my_addr;
 
3101
                sock = socket(PF_INET, SOCK_DGRAM, 0);
 
3102
                evutil_make_socket_nonblocking(sock);
 
3103
                my_addr.sin_family = AF_INET;
 
3104
                my_addr.sin_port = htons(10053);
 
3105
                my_addr.sin_addr.s_addr = INADDR_ANY;
 
3106
                if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
 
3107
                        perror("bind");
 
3108
                        exit(1);
 
3109
                }
 
3110
                evdns_add_server_port(sock, 0, evdns_server_callback, NULL);
 
3111
        }
 
3112
        for (; idx < c; ++idx) {
 
3113
                if (reverse) {
 
3114
                        struct in_addr addr;
 
3115
                        if (!inet_aton(v[idx], &addr)) {
 
3116
                                fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
 
3117
                                continue;
 
3118
                        }
 
3119
                        fprintf(stderr, "resolving %s...\n",v[idx]);
 
3120
                        evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
 
3121
                } else {
 
3122
                        fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
 
3123
                        evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);
 
3124
                }
 
3125
        }
 
3126
        fflush(stdout);
 
3127
        event_dispatch();
 
3128
        return 0;
 
3129
}
 
3130
#endif