Coverage Report

Created: 2026-12-01 06:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/unbound/services/outside_network.c
Line
Count
Source
1
/*
2
 * services/outside_network.c - implement sending of queries and wait answer.
3
 *
4
 * Copyright (c) 2007, NLnet Labs. All rights reserved.
5
 *
6
 * This software is open source.
7
 * 
8
 * Redistribution and use in source and binary forms, with or without
9
 * modification, are permitted provided that the following conditions
10
 * are met:
11
 * 
12
 * Redistributions of source code must retain the above copyright notice,
13
 * this list of conditions and the following disclaimer.
14
 * 
15
 * Redistributions in binary form must reproduce the above copyright notice,
16
 * this list of conditions and the following disclaimer in the documentation
17
 * and/or other materials provided with the distribution.
18
 * 
19
 * Neither the name of the NLNET LABS nor the names of its contributors may
20
 * be used to endorse or promote products derived from this software without
21
 * specific prior written permission.
22
 * 
23
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
 */
35
36
/**
37
 * \file
38
 *
39
 * This file has functions to send queries to authoritative servers and
40
 * wait for the pending answer events.
41
 */
42
#include "config.h"
43
#include <ctype.h>
44
#ifdef HAVE_SYS_TYPES_H
45
#  include <sys/types.h>
46
#endif
47
#include <sys/time.h>
48
#include "services/outside_network.h"
49
#include "services/listen_dnsport.h"
50
#include "services/cache/infra.h"
51
#include "iterator/iterator.h"
52
#include "util/data/msgparse.h"
53
#include "util/data/msgreply.h"
54
#include "util/data/msgencode.h"
55
#include "util/data/dname.h"
56
#include "util/netevent.h"
57
#include "util/log.h"
58
#include "util/net_help.h"
59
#include "util/random.h"
60
#include "util/fptr_wlist.h"
61
#include "util/edns.h"
62
#include "sldns/sbuffer.h"
63
#include "dnstap/dnstap.h"
64
#ifdef HAVE_OPENSSL_SSL_H
65
#include <openssl/ssl.h>
66
#endif
67
#ifdef HAVE_X509_VERIFY_PARAM_SET1_HOST
68
#include <openssl/x509v3.h>
69
#endif
70
71
#ifdef HAVE_NETDB_H
72
#include <netdb.h>
73
#endif
74
#include <fcntl.h>
75
76
/** number of times to retry making a random ID that is unique. */
77
0
#define MAX_ID_RETRY 1000
78
/** number of times to retry finding interface, port that can be opened. */
79
0
#define MAX_PORT_RETRY 10000
80
/** number of retries on outgoing UDP queries */
81
0
#define OUTBOUND_UDP_RETRY 1
82
83
/** initiate TCP transaction for serviced query */
84
static void serviced_tcp_initiate(struct serviced_query* sq, sldns_buffer* buff);
85
/** with a fd available, randomize and send UDP */
86
static int randomize_and_send_udp(struct pending* pend, sldns_buffer* packet,
87
  int timeout);
88
89
/** select a DNS ID for a TCP stream */
90
static uint16_t tcp_select_id(struct outside_network* outnet,
91
  struct reuse_tcp* reuse);
92
93
/** Perform serviced query UDP sending operation */
94
static int serviced_udp_send(struct serviced_query* sq, sldns_buffer* buff);
95
96
/** Send serviced query over TCP return false on initial failure */
97
static int serviced_tcp_send(struct serviced_query* sq, sldns_buffer* buff);
98
99
/** call the callbacks for a serviced query */
100
static void serviced_callbacks(struct serviced_query* sq, int error,
101
  struct comm_point* c, struct comm_reply* rep);
102
103
int 
104
pending_cmp(const void* key1, const void* key2)
105
0
{
106
0
  struct pending *p1 = (struct pending*)key1;
107
0
  struct pending *p2 = (struct pending*)key2;
108
0
  if(p1->id < p2->id)
109
0
    return -1;
110
0
  if(p1->id > p2->id)
111
0
    return 1;
112
0
  log_assert(p1->id == p2->id);
113
0
  return sockaddr_cmp(&p1->addr, p1->addrlen, &p2->addr, p2->addrlen);
114
0
}
115
116
int 
117
serviced_cmp(const void* key1, const void* key2)
118
0
{
119
0
  struct serviced_query* q1 = (struct serviced_query*)key1;
120
0
  struct serviced_query* q2 = (struct serviced_query*)key2;
121
0
  int r;
122
0
  if(q1->qbuflen < q2->qbuflen)
123
0
    return -1;
124
0
  if(q1->qbuflen > q2->qbuflen)
125
0
    return 1;
126
0
  log_assert(q1->qbuflen == q2->qbuflen);
127
0
  log_assert(q1->qbuflen >= 15 /* 10 header, root, type, class */);
128
  /* alternate casing of qname is still the same query */
129
0
  if((r = memcmp(q1->qbuf, q2->qbuf, 10)) != 0)
130
0
    return r;
131
0
  if((r = memcmp(q1->qbuf+q1->qbuflen-4, q2->qbuf+q2->qbuflen-4, 4)) != 0)
132
0
    return r;
133
0
  if(q1->dnssec != q2->dnssec) {
134
0
    if(q1->dnssec < q2->dnssec)
135
0
      return -1;
136
0
    return 1;
137
0
  }
138
0
  if((r = query_dname_compare(q1->qbuf+10, q2->qbuf+10)) != 0)
139
0
    return r;
140
0
  if((r = edns_opt_list_compare(q1->opt_list, q2->opt_list)) != 0)
141
0
    return r;
142
0
  return sockaddr_cmp(&q1->addr, q1->addrlen, &q2->addr, q2->addrlen);
143
0
}
144
145
/** compare if the reuse element has the same address, port and same ssl-is
146
 * used-for-it characteristic */
147
static int
148
reuse_cmp_addrportssl(const void* key1, const void* key2)
149
0
{
150
0
  struct reuse_tcp* r1 = (struct reuse_tcp*)key1;
151
0
  struct reuse_tcp* r2 = (struct reuse_tcp*)key2;
152
0
  int r;
153
  /* compare address and port */
154
0
  r = sockaddr_cmp(&r1->addr, r1->addrlen, &r2->addr, r2->addrlen);
155
0
  if(r != 0)
156
0
    return r;
157
158
  /* compare if SSL-enabled */
159
0
  if(r1->is_ssl && !r2->is_ssl)
160
0
    return 1;
161
0
  if(!r1->is_ssl && r2->is_ssl)
162
0
    return -1;
163
164
  /* compare tls_auth_name if SSL-enabled */
165
0
  if(r1->is_ssl) {
166
0
    if(r1->tls_auth_name && !r2->tls_auth_name)
167
0
      return 1;
168
0
    if(!r1->tls_auth_name && r2->tls_auth_name)
169
0
      return -1;
170
0
    if(r1->tls_auth_name && r2->tls_auth_name) {
171
0
      r = strcmp(r1->tls_auth_name, r2->tls_auth_name);
172
0
      if(r != 0)
173
0
        return r;
174
0
    }
175
0
  }
176
0
  return 0;
177
0
}
178
179
int
180
reuse_cmp(const void* key1, const void* key2)
181
0
{
182
0
  int r;
183
0
  r = reuse_cmp_addrportssl(key1, key2);
184
0
  if(r != 0)
185
0
    return r;
186
187
  /* compare ptr value */
188
0
  if(key1 < key2) return -1;
189
0
  if(key1 > key2) return 1;
190
0
  return 0;
191
0
}
192
193
int reuse_id_cmp(const void* key1, const void* key2)
194
0
{
195
0
  struct waiting_tcp* w1 = (struct waiting_tcp*)key1;
196
0
  struct waiting_tcp* w2 = (struct waiting_tcp*)key2;
197
0
  if(w1->id < w2->id)
198
0
    return -1;
199
0
  if(w1->id > w2->id)
200
0
    return 1;
201
0
  return 0;
202
0
}
203
204
/** delete waiting_tcp entry. Does not unlink from waiting list. 
205
 * @param w: to delete.
206
 */
207
static void
208
waiting_tcp_delete(struct waiting_tcp* w)
209
0
{
210
0
  if(!w) return;
211
0
  free(w->tls_auth_name);
212
0
  if(w->timer)
213
0
    comm_timer_delete(w->timer);
214
0
  free(w);
215
0
}
216
217
/** 
218
 * Pick random outgoing-interface of that family, and bind it.
219
 * port set to 0 so OS picks a port number for us.
220
 * if it is the ANY address, do not bind.
221
 * @param pend: pending tcp structure, for storing the local address choice.
222
 * @param w: tcp structure with destination address.
223
 * @param s: socket fd.
224
 * @return false on error, socket closed.
225
 */
226
static int
227
pick_outgoing_tcp(struct pending_tcp* pend, struct waiting_tcp* w, int s)
228
0
{
229
0
  struct port_if* pi = NULL;
230
0
  int num;
231
0
  pend->pi = NULL;
232
0
#ifdef INET6
233
0
  if(addr_is_ip6(&w->addr, w->addrlen))
234
0
    num = w->outnet->num_ip6;
235
0
  else
236
0
#endif
237
0
    num = w->outnet->num_ip4;
238
0
  if(num == 0) {
239
0
    log_err("no TCP outgoing interfaces of family");
240
0
    log_addr(VERB_OPS, "for addr", &w->addr, w->addrlen);
241
0
    sock_close(s);
242
0
    return 0;
243
0
  }
244
0
#ifdef INET6
245
0
  if(addr_is_ip6(&w->addr, w->addrlen))
246
0
    pi = &w->outnet->ip6_ifs[ub_random_max(w->outnet->rnd, num)];
247
0
  else
248
0
#endif
249
0
    pi = &w->outnet->ip4_ifs[ub_random_max(w->outnet->rnd, num)];
250
0
  log_assert(pi);
251
0
  pend->pi = pi;
252
0
  if(addr_is_any(&pi->addr, pi->addrlen)) {
253
    /* binding to the ANY interface is for listening sockets */
254
0
    return 1;
255
0
  }
256
  /* set port to 0 */
257
0
  if(addr_is_ip6(&pi->addr, pi->addrlen))
258
0
    ((struct sockaddr_in6*)&pi->addr)->sin6_port = 0;
259
0
  else  ((struct sockaddr_in*)&pi->addr)->sin_port = 0;
260
0
  if(bind(s, (struct sockaddr*)&pi->addr, pi->addrlen) != 0) {
261
0
#ifndef USE_WINSOCK
262
0
#ifdef EADDRNOTAVAIL
263
0
    if(!(verbosity < 4 && errno == EADDRNOTAVAIL))
264
0
#endif
265
#else /* USE_WINSOCK */
266
    if(!(verbosity < 4 && WSAGetLastError() == WSAEADDRNOTAVAIL))
267
#endif
268
0
        log_err("outgoing tcp: bind: %s", sock_strerror(errno));
269
0
    sock_close(s);
270
0
    return 0;
271
0
  }
272
0
  log_addr(VERB_ALGO, "tcp bound to src", &pi->addr, pi->addrlen);
273
0
  return 1;
274
0
}
275
276
/** get TCP file descriptor for address, returns -1 on failure,
277
 * tcp_mss is 0 or maxseg size to set for TCP packets. */
278
int
279
outnet_get_tcp_fd(struct sockaddr_storage* addr, socklen_t addrlen,
280
  int tcp_mss, int dscp, int nodelay)
281
0
{
282
0
  int s;
283
0
  int af;
284
0
  char* err;
285
0
#if defined(SO_REUSEADDR) || defined(IP_BIND_ADDRESS_NO_PORT) \
286
0
  || defined(TCP_NODELAY)
287
0
  int on = 1;
288
0
#endif
289
0
#ifdef INET6
290
0
  if(addr_is_ip6(addr, addrlen)){
291
0
    s = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
292
0
    af = AF_INET6;
293
0
  } else {
294
#else
295
  {
296
#endif
297
0
    af = AF_INET;
298
0
    s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
299
0
  }
300
0
  if(s == -1) {
301
0
    log_err_addr("outgoing tcp: socket", sock_strerror(errno),
302
0
      addr, addrlen);
303
0
    return -1;
304
0
  }
305
306
0
#ifdef SO_REUSEADDR
307
0
  if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on,
308
0
    (socklen_t)sizeof(on)) < 0) {
309
0
    verbose(VERB_ALGO, "outgoing tcp:"
310
0
      " setsockopt(.. SO_REUSEADDR ..) failed");
311
0
  }
312
0
#endif
313
314
0
  err = set_ip_dscp(s, af, dscp);
315
0
  if(err != NULL) {
316
0
    verbose(VERB_ALGO, "outgoing tcp:"
317
0
      "error setting IP DiffServ codepoint on socket");
318
0
  }
319
320
0
  if(tcp_mss > 0) {
321
0
#if defined(IPPROTO_TCP) && defined(TCP_MAXSEG)
322
0
    if(setsockopt(s, IPPROTO_TCP, TCP_MAXSEG,
323
0
      (void*)&tcp_mss, (socklen_t)sizeof(tcp_mss)) < 0) {
324
0
      verbose(VERB_ALGO, "outgoing tcp:"
325
0
        " setsockopt(.. TCP_MAXSEG ..) failed");
326
0
    }
327
#else
328
    verbose(VERB_ALGO, "outgoing tcp:"
329
      " setsockopt(TCP_MAXSEG) unsupported");
330
#endif /* defined(IPPROTO_TCP) && defined(TCP_MAXSEG) */
331
0
  }
332
0
#ifdef IP_BIND_ADDRESS_NO_PORT
333
0
  if(setsockopt(s, IPPROTO_IP, IP_BIND_ADDRESS_NO_PORT, (void*)&on,
334
0
    (socklen_t)sizeof(on)) < 0) {
335
0
    verbose(VERB_ALGO, "outgoing tcp:"
336
0
      " setsockopt(.. IP_BIND_ADDRESS_NO_PORT ..) failed");
337
0
  }
338
0
#endif /* IP_BIND_ADDRESS_NO_PORT */
339
0
  if(nodelay) {
340
0
#if defined(IPPROTO_TCP) && defined(TCP_NODELAY)
341
0
    if(setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void*)&on,
342
0
      (socklen_t)sizeof(on)) < 0) {
343
0
      verbose(VERB_ALGO, "outgoing tcp:"
344
0
        " setsockopt(.. TCP_NODELAY ..) failed");
345
0
    }
346
#else
347
    verbose(VERB_ALGO, "outgoing tcp:"
348
      " setsockopt(.. TCP_NODELAY ..) unsupported");
349
#endif /* defined(IPPROTO_TCP) && defined(TCP_NODELAY) */
350
0
  }
351
0
  return s;
352
0
}
353
354
/** connect tcp connection to addr, 0 on failure */
355
int
356
outnet_tcp_connect(int s, struct sockaddr_storage* addr, socklen_t addrlen)
357
0
{
358
0
  if(connect(s, (struct sockaddr*)addr, addrlen) == -1) {
359
0
#ifndef USE_WINSOCK
360
0
#ifdef EINPROGRESS
361
0
    if(errno != EINPROGRESS) {
362
0
#endif
363
0
      if(tcp_connect_errno_needs_log(
364
0
        (struct sockaddr*)addr, addrlen))
365
0
        log_err_addr("outgoing tcp: connect",
366
0
          strerror(errno), addr, addrlen);
367
0
      close(s);
368
0
      return 0;
369
0
#ifdef EINPROGRESS
370
0
    }
371
0
#endif
372
#else /* USE_WINSOCK */
373
    if(WSAGetLastError() != WSAEINPROGRESS &&
374
      WSAGetLastError() != WSAEWOULDBLOCK) {
375
      closesocket(s);
376
      return 0;
377
    }
378
#endif
379
0
  }
380
0
  return 1;
381
0
}
382
383
/** log reuse item addr and ptr with message */
384
static void
385
log_reuse_tcp(enum verbosity_value v, const char* msg, struct reuse_tcp* reuse)
386
0
{
387
0
  uint16_t port;
388
0
  char addrbuf[128];
389
0
  if(verbosity < v) return;
390
0
  if(!reuse || !reuse->pending || !reuse->pending->c)
391
0
    return;
392
0
  addr_to_str(&reuse->addr, reuse->addrlen, addrbuf, sizeof(addrbuf));
393
0
  port = ntohs(((struct sockaddr_in*)&reuse->addr)->sin_port);
394
0
  verbose(v, "%s %s#%u fd %d", msg, addrbuf, (unsigned)port,
395
0
    reuse->pending->c->fd);
396
0
}
397
398
/** pop the first element from the writewait list */
399
struct waiting_tcp*
400
reuse_write_wait_pop(struct reuse_tcp* reuse)
401
0
{
402
0
  struct waiting_tcp* w = reuse->write_wait_first;
403
0
  if(!w)
404
0
    return NULL;
405
0
  log_assert(w->write_wait_queued);
406
0
  log_assert(!w->write_wait_prev);
407
0
  reuse->write_wait_first = w->write_wait_next;
408
0
  if(w->write_wait_next)
409
0
    w->write_wait_next->write_wait_prev = NULL;
410
0
  else  reuse->write_wait_last = NULL;
411
0
  w->write_wait_queued = 0;
412
0
  w->write_wait_next = NULL;
413
0
  w->write_wait_prev = NULL;
414
0
  return w;
415
0
}
416
417
/** remove the element from the writewait list */
418
void
419
reuse_write_wait_remove(struct reuse_tcp* reuse, struct waiting_tcp* w)
420
0
{
421
0
  log_assert(w);
422
0
  log_assert(w->write_wait_queued);
423
0
  if(!w)
424
0
    return;
425
0
  if(!w->write_wait_queued)
426
0
    return;
427
0
  if(w->write_wait_prev)
428
0
    w->write_wait_prev->write_wait_next = w->write_wait_next;
429
0
  else  reuse->write_wait_first = w->write_wait_next;
430
0
  log_assert(!w->write_wait_prev ||
431
0
    w->write_wait_prev->write_wait_next != w->write_wait_prev);
432
0
  if(w->write_wait_next)
433
0
    w->write_wait_next->write_wait_prev = w->write_wait_prev;
434
0
  else  reuse->write_wait_last = w->write_wait_prev;
435
0
  log_assert(!w->write_wait_next
436
0
    || w->write_wait_next->write_wait_prev != w->write_wait_next);
437
0
  w->write_wait_queued = 0;
438
0
  w->write_wait_next = NULL;
439
0
  w->write_wait_prev = NULL;
440
0
}
441
442
/** push the element after the last on the writewait list */
443
void
444
reuse_write_wait_push_back(struct reuse_tcp* reuse, struct waiting_tcp* w)
445
0
{
446
0
  if(!w) return;
447
0
  log_assert(!w->write_wait_queued);
448
0
  if(reuse->write_wait_last) {
449
0
    reuse->write_wait_last->write_wait_next = w;
450
0
    log_assert(reuse->write_wait_last->write_wait_next !=
451
0
      reuse->write_wait_last);
452
0
    w->write_wait_prev = reuse->write_wait_last;
453
0
  } else {
454
0
    reuse->write_wait_first = w;
455
0
    w->write_wait_prev = NULL;
456
0
  }
457
0
  w->write_wait_next = NULL;
458
0
  reuse->write_wait_last = w;
459
0
  w->write_wait_queued = 1;
460
0
}
461
462
/** insert element in tree by id */
463
void
464
reuse_tree_by_id_insert(struct reuse_tcp* reuse, struct waiting_tcp* w)
465
0
{
466
#ifdef UNBOUND_DEBUG
467
  rbnode_type* added;
468
#endif
469
0
  log_assert(w->id_node.key == NULL);
470
0
  w->id_node.key = w;
471
#ifdef UNBOUND_DEBUG
472
  added =
473
#else
474
0
  (void)
475
0
#endif
476
0
  rbtree_insert(&reuse->tree_by_id, &w->id_node);
477
0
  log_assert(added);  /* should have been added */
478
0
}
479
480
/** find element in tree by id */
481
struct waiting_tcp*
482
reuse_tcp_by_id_find(struct reuse_tcp* reuse, uint16_t id)
483
0
{
484
0
  struct waiting_tcp key_w;
485
0
  rbnode_type* n;
486
0
  memset(&key_w, 0, sizeof(key_w));
487
0
  key_w.id_node.key = &key_w;
488
0
  key_w.id = id;
489
0
  n = rbtree_search(&reuse->tree_by_id, &key_w);
490
0
  if(!n) return NULL;
491
0
  return (struct waiting_tcp*)n->key;
492
0
}
493
494
/** return ID value of rbnode in tree_by_id */
495
static uint16_t
496
tree_by_id_get_id(rbnode_type* node)
497
0
{
498
0
  struct waiting_tcp* w = (struct waiting_tcp*)node->key;
499
0
  return w->id;
500
0
}
501
502
/** insert into reuse tcp tree and LRU, false on failure (duplicate) */
503
int
504
reuse_tcp_insert(struct outside_network* outnet, struct pending_tcp* pend_tcp)
505
0
{
506
0
  log_reuse_tcp(VERB_CLIENT, "reuse_tcp_insert", &pend_tcp->reuse);
507
0
  if(pend_tcp->reuse.item_on_lru_list) {
508
0
    if(!pend_tcp->reuse.node.key)
509
0
      log_err("internal error: reuse_tcp_insert: "
510
0
        "in lru list without key");
511
0
    return 1;
512
0
  }
513
0
  pend_tcp->reuse.node.key = &pend_tcp->reuse;
514
0
  pend_tcp->reuse.pending = pend_tcp;
515
0
  if(!rbtree_insert(&outnet->tcp_reuse, &pend_tcp->reuse.node)) {
516
    /* We are not in the LRU list but we are already in the
517
     * tcp_reuse tree, strange.
518
     * Continue to add ourselves to the LRU list. */
519
0
    log_err("internal error: reuse_tcp_insert: in lru list but "
520
0
      "not in the tree");
521
0
  }
522
  /* insert into LRU, first is newest */
523
0
  pend_tcp->reuse.lru_prev = NULL;
524
0
  if(outnet->tcp_reuse_first) {
525
0
    pend_tcp->reuse.lru_next = outnet->tcp_reuse_first;
526
0
    log_assert(pend_tcp->reuse.lru_next != &pend_tcp->reuse);
527
0
    outnet->tcp_reuse_first->lru_prev = &pend_tcp->reuse;
528
0
    log_assert(outnet->tcp_reuse_first->lru_prev !=
529
0
      outnet->tcp_reuse_first);
530
0
  } else {
531
0
    pend_tcp->reuse.lru_next = NULL;
532
0
    outnet->tcp_reuse_last = &pend_tcp->reuse;
533
0
  }
534
0
  outnet->tcp_reuse_first = &pend_tcp->reuse;
535
0
  pend_tcp->reuse.item_on_lru_list = 1;
536
0
  log_assert((!outnet->tcp_reuse_first && !outnet->tcp_reuse_last) ||
537
0
    (outnet->tcp_reuse_first && outnet->tcp_reuse_last));
538
0
  log_assert(outnet->tcp_reuse_first != outnet->tcp_reuse_first->lru_next &&
539
0
    outnet->tcp_reuse_first != outnet->tcp_reuse_first->lru_prev);
540
0
  log_assert(outnet->tcp_reuse_last != outnet->tcp_reuse_last->lru_next &&
541
0
    outnet->tcp_reuse_last != outnet->tcp_reuse_last->lru_prev);
542
0
  return 1;
543
0
}
544
545
/** find reuse tcp stream to destination for query, or NULL if none */
546
static struct reuse_tcp*
547
reuse_tcp_find(struct outside_network* outnet, struct sockaddr_storage* addr,
548
  socklen_t addrlen, int use_ssl, char* tls_auth_name)
549
0
{
550
0
  struct waiting_tcp key_w;
551
0
  struct pending_tcp key_p;
552
0
  struct comm_point c;
553
0
  rbnode_type* result = NULL, *prev;
554
0
  verbose(VERB_CLIENT, "reuse_tcp_find");
555
0
  memset(&key_w, 0, sizeof(key_w));
556
0
  memset(&key_p, 0, sizeof(key_p));
557
0
  memset(&c, 0, sizeof(c));
558
0
  key_p.query = &key_w;
559
0
  key_p.c = &c;
560
0
  key_p.reuse.pending = &key_p;
561
0
  key_p.reuse.node.key = &key_p.reuse;
562
0
  if(use_ssl) {
563
0
    key_p.reuse.is_ssl = 1;
564
0
    key_p.reuse.tls_auth_name = tls_auth_name;
565
0
  }
566
0
  if(addrlen > (socklen_t)sizeof(key_p.reuse.addr))
567
0
    return NULL;
568
0
  memmove(&key_p.reuse.addr, addr, addrlen);
569
0
  key_p.reuse.addrlen = addrlen;
570
571
0
  verbose(VERB_CLIENT, "reuse_tcp_find: num reuse streams %u",
572
0
    (unsigned)outnet->tcp_reuse.count);
573
0
  if(outnet->tcp_reuse.root == NULL ||
574
0
    outnet->tcp_reuse.root == RBTREE_NULL)
575
0
    return NULL;
576
0
  if(rbtree_find_less_equal(&outnet->tcp_reuse, &key_p.reuse,
577
0
    &result)) {
578
    /* exact match */
579
    /* but the key is on stack, and ptr is compared, impossible */
580
0
    log_assert(&key_p.reuse != (struct reuse_tcp*)result);
581
0
    log_assert(&key_p != ((struct reuse_tcp*)result)->pending);
582
0
  }
583
584
  /* It is possible that we search for something before the first element
585
   * in the tree. Replace a null pointer with the first element.
586
   */
587
0
  if (!result) {
588
0
    verbose(VERB_CLIENT, "reuse_tcp_find: taking first");
589
0
    result = rbtree_first(&outnet->tcp_reuse);
590
0
  }
591
592
  /* not found, return null */
593
0
  if(!result || result == RBTREE_NULL)
594
0
    return NULL;
595
596
  /* It is possible that we got the previous address, but that the
597
   * address we are looking for is in the tree. If the address we got
598
   * is less than the address we are looking, then take the next entry.
599
   */
600
0
  if (reuse_cmp_addrportssl(result->key, &key_p.reuse) < 0) {
601
0
    verbose(VERB_CLIENT, "reuse_tcp_find: key too low");
602
0
    result = rbtree_next(result);
603
0
  }
604
605
0
  verbose(VERB_CLIENT, "reuse_tcp_find check inexact match");
606
  /* inexact match, find one of possibly several connections to the
607
   * same destination address, with the correct port, ssl, and
608
   * also less than max number of open queries, or else, fail to open
609
   * a new one */
610
  /* rewind to start of sequence of same address,port,ssl */
611
0
  prev = rbtree_previous(result);
612
0
  while(prev && prev != RBTREE_NULL &&
613
0
    reuse_cmp_addrportssl(prev->key, &key_p.reuse) == 0) {
614
0
    result = prev;
615
0
    prev = rbtree_previous(result);
616
0
  }
617
618
  /* loop to find first one that has correct characteristics */
619
0
  while(result && result != RBTREE_NULL &&
620
0
    reuse_cmp_addrportssl(result->key, &key_p.reuse) == 0) {
621
0
    if(((struct reuse_tcp*)result)->tree_by_id.count <
622
0
      outnet->max_reuse_tcp_queries) {
623
      /* same address, port, ssl-yes-or-no, and has
624
       * space for another query */
625
0
      return (struct reuse_tcp*)result;
626
0
    }
627
0
    result = rbtree_next(result);
628
0
  }
629
0
  return NULL;
630
0
}
631
632
/** use the buffer to setup writing the query */
633
static void
634
outnet_tcp_take_query_setup(int s, struct pending_tcp* pend,
635
  struct waiting_tcp* w)
636
0
{
637
0
  struct timeval tv;
638
0
  verbose(VERB_CLIENT, "outnet_tcp_take_query_setup: setup packet to write "
639
0
    "len %d timeout %d msec",
640
0
    (int)w->pkt_len, w->timeout);
641
0
  pend->c->tcp_write_pkt = w->pkt;
642
0
  pend->c->tcp_write_pkt_len = w->pkt_len;
643
0
  pend->c->tcp_write_and_read = 1;
644
0
  pend->c->tcp_write_byte_count = 0;
645
0
  pend->c->tcp_is_reading = 0;
646
0
  comm_point_start_listening(pend->c, s, -1);
647
  /* set timer on the waiting_tcp entry, this is the write timeout
648
   * for the written packet.  The timer on pend->c is the timer
649
   * for when there is no written packet and we have readtimeouts */
650
0
#ifndef S_SPLINT_S
651
0
  tv.tv_sec = w->timeout/1000;
652
0
  tv.tv_usec = (w->timeout%1000)*1000;
653
0
#endif
654
  /* if the waiting_tcp was previously waiting for a buffer in the
655
   * outside_network.tcpwaitlist, then the timer is reset now that
656
   * we start writing it */
657
0
  comm_timer_set(w->timer, &tv);
658
0
}
659
660
/** use next free buffer to service a tcp query */
661
static int
662
outnet_tcp_take_into_use(struct waiting_tcp* w)
663
0
{
664
0
  struct pending_tcp* pend = w->outnet->tcp_free;
665
0
  char* tls_auth_name = NULL;
666
0
  int s;
667
0
  log_assert(pend);
668
0
  log_assert(w->pkt);
669
0
  log_assert(w->pkt_len > 0);
670
0
  log_assert(w->addrlen > 0);
671
0
  pend->c->tcp_do_toggle_rw = 0;
672
0
  pend->c->tcp_do_close = 0;
673
674
  /* Consistency check, if we have ssl_upstream but no sslctx, then
675
   * log an error and return failure.
676
   */
677
0
  if (w->ssl_upstream && !w->outnet->sslctx) {
678
0
    log_err("SSL upstream requested but no SSL context");
679
0
    return 0;
680
0
  }
681
682
  /* open socket */
683
0
  s = outnet_get_tcp_fd(&w->addr, w->addrlen, w->outnet->tcp_mss,
684
0
    w->outnet->ip_dscp, w->ssl_upstream);
685
686
0
  if(s == -1)
687
0
    return 0;
688
689
0
  if(!pick_outgoing_tcp(pend, w, s))
690
0
    return 0;
691
692
0
  fd_set_nonblock(s);
693
#ifdef USE_OSX_MSG_FASTOPEN
694
  /* API for fast open is different here. We use a connectx() function and 
695
     then writes can happen as normal even using SSL.*/
696
  /* connectx requires that the len be set in the sockaddr struct*/
697
  struct sockaddr_in *addr_in = (struct sockaddr_in *)&w->addr;
698
  addr_in->sin_len = w->addrlen;
699
  sa_endpoints_t endpoints;
700
  endpoints.sae_srcif = 0;
701
  endpoints.sae_srcaddr = NULL;
702
  endpoints.sae_srcaddrlen = 0;
703
  endpoints.sae_dstaddr = (struct sockaddr *)&w->addr;
704
  endpoints.sae_dstaddrlen = w->addrlen;
705
  if (connectx(s, &endpoints, SAE_ASSOCID_ANY,  
706
               CONNECT_DATA_IDEMPOTENT | CONNECT_RESUME_ON_READ_WRITE,
707
               NULL, 0, NULL, NULL) == -1) {
708
    /* if fails, failover to connect for OSX 10.10 */
709
#ifdef EINPROGRESS
710
    if(errno != EINPROGRESS) {
711
#else
712
    if(1) {
713
#endif
714
      if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) {
715
#else /* USE_OSX_MSG_FASTOPEN*/
716
#ifdef USE_MSG_FASTOPEN
717
  pend->c->tcp_do_fastopen = 1;
718
  /* Only do TFO for TCP in which case no connect() is required here.
719
     Don't combine client TFO with SSL, since OpenSSL can't 
720
     currently support doing a handshake on fd that already isn't connected*/
721
  if (w->outnet->sslctx && w->ssl_upstream) {
722
    if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) {
723
#else /* USE_MSG_FASTOPEN*/
724
0
  if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) {
725
0
#endif /* USE_MSG_FASTOPEN*/
726
0
#endif /* USE_OSX_MSG_FASTOPEN*/
727
0
#ifndef USE_WINSOCK
728
0
#ifdef EINPROGRESS
729
0
    if(errno != EINPROGRESS) {
730
#else
731
    if(1) {
732
#endif
733
0
      if(tcp_connect_errno_needs_log(
734
0
        (struct sockaddr*)&w->addr, w->addrlen))
735
0
        log_err_addr("outgoing tcp: connect",
736
0
          strerror(errno), &w->addr, w->addrlen);
737
0
      close(s);
738
#else /* USE_WINSOCK */
739
    if(WSAGetLastError() != WSAEINPROGRESS &&
740
      WSAGetLastError() != WSAEWOULDBLOCK) {
741
      closesocket(s);
742
#endif
743
0
      return 0;
744
0
    }
745
0
  }
746
#ifdef USE_MSG_FASTOPEN
747
  }
748
#endif /* USE_MSG_FASTOPEN */
749
#ifdef USE_OSX_MSG_FASTOPEN
750
    }
751
  }
752
#endif /* USE_OSX_MSG_FASTOPEN */
753
0
  if(w->outnet->sslctx && w->ssl_upstream) {
754
0
    pend->c->ssl = outgoing_ssl_fd(w->outnet->sslctx, s);
755
0
    if(!pend->c->ssl) {
756
0
      pend->c->fd = s;
757
0
      comm_point_close(pend->c);
758
0
      return 0;
759
0
    }
760
0
    verbose(VERB_ALGO, "the query is using TLS encryption, for %s",
761
0
      (w->tls_auth_name?w->tls_auth_name:"an unauthenticated connection"));
762
#ifdef USE_WINSOCK
763
    comm_point_tcp_win_bio_cb(pend->c, pend->c->ssl);
764
#endif
765
0
    pend->c->ssl_shake_state = comm_ssl_shake_write;
766
0
    if(w->tls_auth_name) {
767
      /* strdup the auth name, while not linked the list yet,
768
       * in case of failure, easy cleanup. */
769
0
      tls_auth_name = strdup(w->tls_auth_name);
770
0
      if(!tls_auth_name) {
771
0
        log_err("out of memory: alloc tls auth name");
772
0
        pend->c->fd = s;
773
0
#ifdef HAVE_SSL
774
0
        SSL_free(pend->c->ssl);
775
0
#endif
776
0
        pend->c->ssl = NULL;
777
0
        comm_point_close(pend->c);
778
0
        return 0;
779
0
      }
780
0
    }
781
0
    if(!set_auth_name_on_ssl(pend->c->ssl, tls_auth_name,
782
0
      w->outnet->tls_use_sni)) {
783
0
      pend->c->fd = s;
784
0
#ifdef HAVE_SSL
785
0
      SSL_free(pend->c->ssl);
786
0
#endif
787
0
      pend->c->ssl = NULL;
788
0
      comm_point_close(pend->c);
789
0
      free(tls_auth_name);
790
0
      return 0;
791
0
    }
792
0
  }
793
0
  w->next_waiting = (void*)pend;
794
0
  w->outnet->num_tcp_outgoing++;
795
0
  w->outnet->tcp_free = pend->next_free;
796
0
  pend->next_free = NULL;
797
0
  pend->query = w;
798
0
  pend->reuse.outnet = w->outnet;
799
0
  pend->c->repinfo.remote_addrlen = w->addrlen;
800
0
  pend->c->tcp_more_read_again = &pend->reuse.cp_more_read_again;
801
0
  pend->c->tcp_more_write_again = &pend->reuse.cp_more_write_again;
802
0
  pend->reuse.cp_more_read_again = 0;
803
0
  pend->reuse.cp_more_write_again = 0;
804
0
  memcpy(&pend->c->repinfo.remote_addr, &w->addr, w->addrlen);
805
0
  pend->reuse.pending = pend;
806
807
  /* Remove from tree in case the is_ssl will be different and causes the
808
   * identity of the reuse_tcp to change; could result in nodes not being
809
   * deleted from the tree (because the new identity does not match the
810
   * previous node) but their ->key would be changed to NULL. */
811
0
  if(pend->reuse.node.key)
812
0
    reuse_tcp_remove_tree_list(w->outnet, &pend->reuse);
813
814
0
  if(pend->c->ssl) {
815
0
    pend->reuse.is_ssl = 1;
816
0
    if(pend->reuse.tls_auth_name)
817
0
      free(pend->reuse.tls_auth_name);
818
0
    pend->reuse.tls_auth_name = tls_auth_name;
819
0
    tls_auth_name = NULL;
820
0
  } else {
821
0
    pend->reuse.is_ssl = 0;
822
0
    if(pend->reuse.tls_auth_name)
823
0
      free(pend->reuse.tls_auth_name);
824
0
    pend->reuse.tls_auth_name = NULL;
825
0
  }
826
  /* free tls auth name if nonNULL */
827
0
  free(tls_auth_name);
828
  /* insert in reuse by address tree if not already inserted there */
829
0
  (void)reuse_tcp_insert(w->outnet, pend);
830
0
  reuse_tree_by_id_insert(&pend->reuse, w);
831
0
  outnet_tcp_take_query_setup(s, pend, w);
832
0
  return 1;
833
0
}
834
835
/** Touch the lru of a reuse_tcp element, it is in use.
836
 * This moves it to the front of the list, where it is not likely to
837
 * be closed.  Items at the back of the list are closed to make space. */
838
void
839
reuse_tcp_lru_touch(struct outside_network* outnet, struct reuse_tcp* reuse)
840
0
{
841
0
  if(!reuse->item_on_lru_list) {
842
0
    log_err("internal error: we need to touch the lru_list but item not in list");
843
0
    return; /* not on the list, no lru to modify */
844
0
  }
845
0
  log_assert(reuse->lru_prev ||
846
0
    (!reuse->lru_prev && outnet->tcp_reuse_first == reuse));
847
0
  if(!reuse->lru_prev)
848
0
    return; /* already first in the list */
849
  /* remove at current position */
850
  /* since it is not first, there is a previous element */
851
0
  reuse->lru_prev->lru_next = reuse->lru_next;
852
0
  log_assert(reuse->lru_prev->lru_next != reuse->lru_prev);
853
0
  if(reuse->lru_next)
854
0
    reuse->lru_next->lru_prev = reuse->lru_prev;
855
0
  else  outnet->tcp_reuse_last = reuse->lru_prev;
856
0
  log_assert(!reuse->lru_next || reuse->lru_next->lru_prev != reuse->lru_next);
857
0
  log_assert(outnet->tcp_reuse_last != outnet->tcp_reuse_last->lru_next &&
858
0
    outnet->tcp_reuse_last != outnet->tcp_reuse_last->lru_prev);
859
  /* insert at the front */
860
0
  reuse->lru_prev = NULL;
861
0
  reuse->lru_next = outnet->tcp_reuse_first;
862
0
  if(outnet->tcp_reuse_first) {
863
0
    outnet->tcp_reuse_first->lru_prev = reuse;
864
0
  }
865
0
  log_assert(reuse->lru_next != reuse);
866
  /* since it is not first, it is not the only element and
867
   * lru_next is thus not NULL and thus reuse is now not the last in
868
   * the list, so outnet->tcp_reuse_last does not need to be modified */
869
0
  outnet->tcp_reuse_first = reuse;
870
0
  log_assert(outnet->tcp_reuse_first != outnet->tcp_reuse_first->lru_next &&
871
0
    outnet->tcp_reuse_first != outnet->tcp_reuse_first->lru_prev);
872
0
  log_assert((!outnet->tcp_reuse_first && !outnet->tcp_reuse_last) ||
873
0
    (outnet->tcp_reuse_first && outnet->tcp_reuse_last));
874
0
}
875
876
/** Snip the last reuse_tcp element off of the LRU list */
877
struct reuse_tcp*
878
reuse_tcp_lru_snip(struct outside_network* outnet)
879
0
{
880
0
  struct reuse_tcp* reuse = outnet->tcp_reuse_last;
881
0
  if(!reuse) return NULL;
882
  /* snip off of LRU */
883
0
  log_assert(reuse->lru_next == NULL);
884
0
  if(reuse->lru_prev) {
885
0
    outnet->tcp_reuse_last = reuse->lru_prev;
886
0
    reuse->lru_prev->lru_next = NULL;
887
0
  } else {
888
0
    outnet->tcp_reuse_last = NULL;
889
0
    outnet->tcp_reuse_first = NULL;
890
0
  }
891
0
  log_assert((!outnet->tcp_reuse_first && !outnet->tcp_reuse_last) ||
892
0
    (outnet->tcp_reuse_first && outnet->tcp_reuse_last));
893
0
  reuse->item_on_lru_list = 0;
894
0
  reuse->lru_next = NULL;
895
0
  reuse->lru_prev = NULL;
896
0
  return reuse;
897
0
}
898
899
/** remove waiting tcp from the outnet waiting list */
900
void
901
outnet_waiting_tcp_list_remove(struct outside_network* outnet, struct waiting_tcp* w)
902
0
{
903
0
  struct waiting_tcp* p = outnet->tcp_wait_first, *prev = NULL;
904
0
  w->on_tcp_waiting_list = 0;
905
0
  while(p) {
906
0
    if(p == w) {
907
      /* remove w */
908
0
      if(prev)
909
0
        prev->next_waiting = w->next_waiting;
910
0
      else  outnet->tcp_wait_first = w->next_waiting;
911
0
      if(outnet->tcp_wait_last == w)
912
0
        outnet->tcp_wait_last = prev;
913
0
      w->next_waiting = NULL;
914
0
      return;
915
0
    }
916
0
    prev = p;
917
0
    p = p->next_waiting;
918
0
  }
919
  /* outnet_waiting_tcp_list_remove is currently called only with items
920
   * that are already in the waiting list. */
921
0
  log_assert(0);
922
0
}
923
924
/** pop the first waiting tcp from the outnet waiting list */
925
struct waiting_tcp*
926
outnet_waiting_tcp_list_pop(struct outside_network* outnet)
927
0
{
928
0
  struct waiting_tcp* w = outnet->tcp_wait_first;
929
0
  if(!outnet->tcp_wait_first) return NULL;
930
0
  log_assert(w->on_tcp_waiting_list);
931
0
  outnet->tcp_wait_first = w->next_waiting;
932
0
  if(outnet->tcp_wait_last == w)
933
0
    outnet->tcp_wait_last = NULL;
934
0
  w->on_tcp_waiting_list = 0;
935
0
  w->next_waiting = NULL;
936
0
  return w;
937
0
}
938
939
/** add waiting_tcp element to the outnet tcp waiting list */
940
void
941
outnet_waiting_tcp_list_add(struct outside_network* outnet,
942
  struct waiting_tcp* w, int set_timer)
943
0
{
944
0
  struct timeval tv;
945
0
  log_assert(!w->on_tcp_waiting_list);
946
0
  if(w->on_tcp_waiting_list)
947
0
    return;
948
0
  w->next_waiting = NULL;
949
0
  if(outnet->tcp_wait_last)
950
0
    outnet->tcp_wait_last->next_waiting = w;
951
0
  else  outnet->tcp_wait_first = w;
952
0
  outnet->tcp_wait_last = w;
953
0
  w->on_tcp_waiting_list = 1;
954
0
  if(set_timer) {
955
0
#ifndef S_SPLINT_S
956
0
    tv.tv_sec = w->timeout/1000;
957
0
    tv.tv_usec = (w->timeout%1000)*1000;
958
0
#endif
959
0
    comm_timer_set(w->timer, &tv);
960
0
  }
961
0
}
962
963
/** add waiting_tcp element as first to the outnet tcp waiting list */
964
void
965
outnet_waiting_tcp_list_add_first(struct outside_network* outnet,
966
  struct waiting_tcp* w, int reset_timer)
967
0
{
968
0
  struct timeval tv;
969
0
  log_assert(!w->on_tcp_waiting_list);
970
0
  if(w->on_tcp_waiting_list)
971
0
    return;
972
0
  w->next_waiting = outnet->tcp_wait_first;
973
0
  log_assert(w->next_waiting != w);
974
0
  if(!outnet->tcp_wait_last)
975
0
    outnet->tcp_wait_last = w;
976
0
  outnet->tcp_wait_first = w;
977
0
  w->on_tcp_waiting_list = 1;
978
0
  if(reset_timer) {
979
0
#ifndef S_SPLINT_S
980
0
    tv.tv_sec = w->timeout/1000;
981
0
    tv.tv_usec = (w->timeout%1000)*1000;
982
0
#endif
983
0
    comm_timer_set(w->timer, &tv);
984
0
  }
985
0
  log_assert(
986
0
    (!outnet->tcp_reuse_first && !outnet->tcp_reuse_last) ||
987
0
    (outnet->tcp_reuse_first && outnet->tcp_reuse_last));
988
0
}
989
990
/** call callback on waiting_tcp, if not NULL */
991
static void
992
waiting_tcp_callback(struct waiting_tcp* w, struct comm_point* c, int error,
993
  struct comm_reply* reply_info)
994
0
{
995
0
  if(w && w->cb) {
996
0
    fptr_ok(fptr_whitelist_pending_tcp(w->cb));
997
0
    (void)(*w->cb)(c, w->cb_arg, error, reply_info);
998
0
  }
999
0
}
1000
1001
/** see if buffers can be used to service TCP queries */
1002
static void
1003
use_free_buffer(struct outside_network* outnet)
1004
0
{
1005
0
  struct waiting_tcp* w;
1006
0
  while(outnet->tcp_wait_first && !outnet->want_to_quit) {
1007
#ifdef USE_DNSTAP
1008
    struct pending_tcp* pend_tcp = NULL;
1009
#endif
1010
0
    struct reuse_tcp* reuse = NULL;
1011
0
    w = outnet_waiting_tcp_list_pop(outnet);
1012
0
    log_assert(
1013
0
      (!outnet->tcp_reuse_first && !outnet->tcp_reuse_last) ||
1014
0
      (outnet->tcp_reuse_first && outnet->tcp_reuse_last));
1015
0
    reuse = reuse_tcp_find(outnet, &w->addr, w->addrlen,
1016
0
      w->ssl_upstream, w->tls_auth_name);
1017
    /* re-select an ID when moving to a new TCP buffer */
1018
0
    w->id = tcp_select_id(outnet, reuse);
1019
0
    LDNS_ID_SET(w->pkt, w->id);
1020
0
    if(reuse) {
1021
0
      log_reuse_tcp(VERB_CLIENT, "use free buffer for waiting tcp: "
1022
0
        "found reuse", reuse);
1023
#ifdef USE_DNSTAP
1024
      pend_tcp = reuse->pending;
1025
#endif
1026
0
      reuse_tcp_lru_touch(outnet, reuse);
1027
0
      comm_timer_disable(w->timer);
1028
0
      w->next_waiting = (void*)reuse->pending;
1029
0
      reuse_tree_by_id_insert(reuse, w);
1030
0
      if(reuse->pending->query) {
1031
        /* on the write wait list */
1032
0
        reuse_write_wait_push_back(reuse, w);
1033
0
      } else {
1034
        /* write straight away */
1035
        /* stop the timer on read of the fd */
1036
0
        comm_point_stop_listening(reuse->pending->c);
1037
0
        reuse->pending->query = w;
1038
0
        outnet_tcp_take_query_setup(
1039
0
          reuse->pending->c->fd, reuse->pending,
1040
0
          w);
1041
0
      }
1042
0
    } else if(outnet->tcp_free) {
1043
0
      struct pending_tcp* pend = w->outnet->tcp_free;
1044
0
      rbtree_init(&pend->reuse.tree_by_id, reuse_id_cmp);
1045
0
      pend->reuse.pending = pend;
1046
0
      memcpy(&pend->reuse.addr, &w->addr, w->addrlen);
1047
0
      pend->reuse.addrlen = w->addrlen;
1048
0
      if(!outnet_tcp_take_into_use(w)) {
1049
0
        waiting_tcp_callback(w, NULL, NETEVENT_CLOSED,
1050
0
          NULL);
1051
0
        waiting_tcp_delete(w);
1052
#ifdef USE_DNSTAP
1053
        w = NULL;
1054
#endif
1055
0
      }
1056
#ifdef USE_DNSTAP
1057
      pend_tcp = pend;
1058
#endif
1059
0
    } else {
1060
      /* no reuse and no free buffer, put back at the start */
1061
0
      outnet_waiting_tcp_list_add_first(outnet, w, 0);
1062
0
      break;
1063
0
    }
1064
#ifdef USE_DNSTAP
1065
    if(outnet->dtenv && pend_tcp && w && w->sq &&
1066
      (outnet->dtenv->log_resolver_query_messages ||
1067
      outnet->dtenv->log_forwarder_query_messages)) {
1068
      sldns_buffer tmp;
1069
      sldns_buffer_init_frm_data(&tmp, w->pkt, w->pkt_len);
1070
      dt_msg_send_outside_query(outnet->dtenv, &w->sq->addr,
1071
        &pend_tcp->pi->addr, comm_tcp, NULL, w->sq->zone,
1072
        w->sq->zonelen, &tmp);
1073
    }
1074
#endif
1075
0
  }
1076
0
}
1077
1078
/** delete element from tree by id */
1079
static void
1080
reuse_tree_by_id_delete(struct reuse_tcp* reuse, struct waiting_tcp* w)
1081
0
{
1082
#ifdef UNBOUND_DEBUG
1083
  rbnode_type* rem;
1084
#endif
1085
0
  log_assert(w->id_node.key != NULL);
1086
#ifdef UNBOUND_DEBUG
1087
  rem =
1088
#else
1089
0
  (void)
1090
0
#endif
1091
0
  rbtree_delete(&reuse->tree_by_id, w);
1092
0
  log_assert(rem);  /* should have been there */
1093
0
  w->id_node.key = NULL;
1094
0
}
1095
1096
/** move writewait list to go for another connection. */
1097
static void
1098
reuse_move_writewait_away(struct outside_network* outnet,
1099
  struct pending_tcp* pend)
1100
0
{
1101
  /* the writewait list has not been written yet, so if the
1102
   * stream was closed, they have not actually been failed, only
1103
   * the queries written.  Other queries can get written to another
1104
   * stream.  For upstreams that do not support multiple queries
1105
   * and answers, the stream can get closed, and then the queries
1106
   * can get written on a new socket */
1107
0
  struct waiting_tcp* w;
1108
0
  if(pend->query && pend->query->error_count == 0 &&
1109
0
    pend->c->tcp_write_pkt == pend->query->pkt &&
1110
0
    pend->c->tcp_write_pkt_len == pend->query->pkt_len) {
1111
    /* since the current query is not written, it can also
1112
     * move to a free buffer */
1113
0
    if(verbosity >= VERB_CLIENT && pend->query->pkt_len > 12+2+2 &&
1114
0
      LDNS_QDCOUNT(pend->query->pkt) > 0 &&
1115
0
      dname_valid(pend->query->pkt+12, pend->query->pkt_len-12)) {
1116
0
      char buf[LDNS_MAX_DOMAINLEN];
1117
0
      dname_str(pend->query->pkt+12, buf);
1118
0
      verbose(VERB_CLIENT, "reuse_move_writewait_away current %s %d bytes were written",
1119
0
        buf, (int)pend->c->tcp_write_byte_count);
1120
0
    }
1121
0
    pend->c->tcp_write_pkt = NULL;
1122
0
    pend->c->tcp_write_pkt_len = 0;
1123
0
    pend->c->tcp_write_and_read = 0;
1124
0
    pend->reuse.cp_more_read_again = 0;
1125
0
    pend->reuse.cp_more_write_again = 0;
1126
0
    pend->c->tcp_is_reading = 1;
1127
0
    w = pend->query;
1128
0
    pend->query = NULL;
1129
    /* increase error count, so that if the next socket fails too
1130
     * the server selection is run again with this query failed
1131
     * and it can select a different server (if possible), or
1132
     * fail the query */
1133
0
    w->error_count ++;
1134
0
    reuse_tree_by_id_delete(&pend->reuse, w);
1135
0
    outnet_waiting_tcp_list_add(outnet, w, 1);
1136
0
  }
1137
0
  while((w = reuse_write_wait_pop(&pend->reuse)) != NULL) {
1138
0
    if(verbosity >= VERB_CLIENT && w->pkt_len > 12+2+2 &&
1139
0
      LDNS_QDCOUNT(w->pkt) > 0 &&
1140
0
      dname_valid(w->pkt+12, w->pkt_len-12)) {
1141
0
      char buf[LDNS_MAX_DOMAINLEN];
1142
0
      dname_str(w->pkt+12, buf);
1143
0
      verbose(VERB_CLIENT, "reuse_move_writewait_away item %s", buf);
1144
0
    }
1145
0
    reuse_tree_by_id_delete(&pend->reuse, w);
1146
0
    outnet_waiting_tcp_list_add(outnet, w, 1);
1147
0
  }
1148
0
}
1149
1150
/** remove reused element from tree and lru list */
1151
void
1152
reuse_tcp_remove_tree_list(struct outside_network* outnet,
1153
  struct reuse_tcp* reuse)
1154
0
{
1155
0
  verbose(VERB_CLIENT, "reuse_tcp_remove_tree_list");
1156
0
  if(reuse->node.key) {
1157
    /* delete it from reuse tree */
1158
0
    if(!rbtree_delete(&outnet->tcp_reuse, reuse)) {
1159
      /* should not be possible, it should be there */
1160
0
      char buf[256];
1161
0
      addr_to_str(&reuse->addr, reuse->addrlen, buf,
1162
0
        sizeof(buf));
1163
0
      log_err("reuse tcp delete: node not present, internal error, %s ssl %d lru %d", buf, reuse->is_ssl, reuse->item_on_lru_list);
1164
0
    }
1165
0
    reuse->node.key = NULL;
1166
    /* defend against loops on broken tree by zeroing the
1167
     * rbnode structure */
1168
0
    memset(&reuse->node, 0, sizeof(reuse->node));
1169
0
  }
1170
  /* delete from reuse list */
1171
0
  if(reuse->item_on_lru_list) {
1172
0
    if(reuse->lru_prev) {
1173
      /* assert that members of the lru list are waiting
1174
       * and thus have a pending pointer to the struct */
1175
0
      log_assert(reuse->lru_prev->pending);
1176
0
      reuse->lru_prev->lru_next = reuse->lru_next;
1177
0
      log_assert(reuse->lru_prev->lru_next != reuse->lru_prev);
1178
0
    } else {
1179
0
      log_assert(!reuse->lru_next || reuse->lru_next->pending);
1180
0
      outnet->tcp_reuse_first = reuse->lru_next;
1181
0
      log_assert(!outnet->tcp_reuse_first ||
1182
0
        (outnet->tcp_reuse_first !=
1183
0
         outnet->tcp_reuse_first->lru_next &&
1184
0
         outnet->tcp_reuse_first !=
1185
0
         outnet->tcp_reuse_first->lru_prev));
1186
0
    }
1187
0
    if(reuse->lru_next) {
1188
      /* assert that members of the lru list are waiting
1189
       * and thus have a pending pointer to the struct */
1190
0
      log_assert(reuse->lru_next->pending);
1191
0
      reuse->lru_next->lru_prev = reuse->lru_prev;
1192
0
      log_assert(reuse->lru_next->lru_prev != reuse->lru_next);
1193
0
    } else {
1194
0
      log_assert(!reuse->lru_prev || reuse->lru_prev->pending);
1195
0
      outnet->tcp_reuse_last = reuse->lru_prev;
1196
0
      log_assert(!outnet->tcp_reuse_last ||
1197
0
        (outnet->tcp_reuse_last !=
1198
0
         outnet->tcp_reuse_last->lru_next &&
1199
0
         outnet->tcp_reuse_last !=
1200
0
         outnet->tcp_reuse_last->lru_prev));
1201
0
    }
1202
0
    log_assert((!outnet->tcp_reuse_first && !outnet->tcp_reuse_last) ||
1203
0
      (outnet->tcp_reuse_first && outnet->tcp_reuse_last));
1204
0
    reuse->item_on_lru_list = 0;
1205
0
    reuse->lru_next = NULL;
1206
0
    reuse->lru_prev = NULL;
1207
0
  }
1208
0
  reuse->pending = NULL;
1209
0
}
1210
1211
/** helper function that deletes an element from the tree of readwait
1212
 * elements in tcp reuse structure */
1213
static void reuse_del_readwait_elem(rbnode_type* node, void* ATTR_UNUSED(arg))
1214
0
{
1215
0
  struct waiting_tcp* w = (struct waiting_tcp*)node->key;
1216
0
  waiting_tcp_delete(w);
1217
0
}
1218
1219
/** delete readwait waiting_tcp elements, deletes the elements in the list */
1220
void reuse_del_readwait(rbtree_type* tree_by_id)
1221
0
{
1222
0
  if(tree_by_id->root == NULL ||
1223
0
    tree_by_id->root == RBTREE_NULL)
1224
0
    return;
1225
0
  traverse_postorder(tree_by_id, &reuse_del_readwait_elem, NULL);
1226
0
  rbtree_init(tree_by_id, reuse_id_cmp);
1227
0
}
1228
1229
/** decommission a tcp buffer, closes commpoint and frees waiting_tcp entry */
1230
static void
1231
decommission_pending_tcp(struct outside_network* outnet, 
1232
  struct pending_tcp* pend)
1233
0
{
1234
0
  verbose(VERB_CLIENT, "decommission_pending_tcp");
1235
  /* A certain code path can lead here twice for the same pending_tcp
1236
   * creating a loop in the free pending_tcp list. */
1237
0
  if(outnet->tcp_free != pend) {
1238
0
    pend->next_free = outnet->tcp_free;
1239
0
    outnet->tcp_free = pend;
1240
0
  }
1241
0
  if(pend->reuse.node.key) {
1242
    /* needs unlink from the reuse tree to get deleted */
1243
0
    reuse_tcp_remove_tree_list(outnet, &pend->reuse);
1244
0
  }
1245
0
  if(pend->reuse.tls_auth_name) {
1246
0
    free(pend->reuse.tls_auth_name);
1247
0
    pend->reuse.tls_auth_name = NULL;
1248
0
  }
1249
  /* free SSL structure after remove from outnet tcp reuse tree,
1250
   * because the c->ssl null or not is used for sorting in the tree */
1251
0
  if(pend->c->ssl) {
1252
0
#ifdef HAVE_SSL
1253
0
    SSL_shutdown(pend->c->ssl);
1254
0
    SSL_free(pend->c->ssl);
1255
0
    pend->c->ssl = NULL;
1256
0
#endif
1257
0
  }
1258
0
  comm_point_close(pend->c);
1259
0
  pend->reuse.cp_more_read_again = 0;
1260
0
  pend->reuse.cp_more_write_again = 0;
1261
  /* unlink the query and writewait list, it is part of the tree
1262
   * nodes and is deleted */
1263
0
  pend->query = NULL;
1264
0
  pend->reuse.write_wait_first = NULL;
1265
0
  pend->reuse.write_wait_last = NULL;
1266
0
  reuse_del_readwait(&pend->reuse.tree_by_id);
1267
0
}
1268
1269
/** perform failure callbacks for waiting queries in reuse read rbtree */
1270
static void reuse_cb_readwait_for_failure(rbtree_type* tree_by_id, int err)
1271
0
{
1272
0
  rbnode_type* node;
1273
0
  if(tree_by_id->root == NULL ||
1274
0
    tree_by_id->root == RBTREE_NULL)
1275
0
    return;
1276
0
  node = rbtree_first(tree_by_id);
1277
0
  while(node && node != RBTREE_NULL) {
1278
0
    struct waiting_tcp* w = (struct waiting_tcp*)node->key;
1279
0
    waiting_tcp_callback(w, NULL, err, NULL);
1280
0
    node = rbtree_next(node);
1281
0
  }
1282
0
}
1283
1284
/** mark the entry for being in the cb_and_decommission stage */
1285
static void mark_for_cb_and_decommission(rbnode_type* node,
1286
  void* ATTR_UNUSED(arg))
1287
0
{
1288
0
  struct waiting_tcp* w = (struct waiting_tcp*)node->key;
1289
  /* Mark the waiting_tcp to signal later code (serviced_delete) that
1290
   * this item is part of the backed up tree_by_id and will be deleted
1291
   * later. */
1292
0
  w->in_cb_and_decommission = 1;
1293
  /* Mark the serviced_query for deletion so that later code through
1294
   * callbacks (iter_clear .. outnet_serviced_query_stop) won't
1295
   * prematurely delete it. */
1296
0
  if(w->cb)
1297
0
    ((struct serviced_query*)w->cb_arg)->to_be_deleted = 1;
1298
0
}
1299
1300
/** perform callbacks for failure and also decommission pending tcp.
1301
 * the callbacks remove references in sq->pending to the waiting_tcp
1302
 * members of the tree_by_id in the pending tcp.  The pending_tcp is
1303
 * removed before the callbacks, so that the callbacks do not modify
1304
 * the pending_tcp due to its reference in the outside_network reuse tree */
1305
static void reuse_cb_and_decommission(struct outside_network* outnet,
1306
  struct pending_tcp* pend, int error)
1307
0
{
1308
0
  rbtree_type store;
1309
0
  store = pend->reuse.tree_by_id;
1310
0
  pend->query = NULL;
1311
0
  rbtree_init(&pend->reuse.tree_by_id, reuse_id_cmp);
1312
0
  pend->reuse.write_wait_first = NULL;
1313
0
  pend->reuse.write_wait_last = NULL;
1314
0
  decommission_pending_tcp(outnet, pend);
1315
0
  if(store.root != NULL && store.root != RBTREE_NULL) {
1316
0
    traverse_postorder(&store, &mark_for_cb_and_decommission, NULL);
1317
0
  }
1318
0
  reuse_cb_readwait_for_failure(&store, error);
1319
0
  reuse_del_readwait(&store);
1320
0
}
1321
1322
/** set timeout on tcp fd and setup read event to catch incoming dns msgs */
1323
static void
1324
reuse_tcp_setup_timeout(struct pending_tcp* pend_tcp, int tcp_reuse_timeout)
1325
0
{
1326
0
  log_reuse_tcp(VERB_CLIENT, "reuse_tcp_setup_timeout", &pend_tcp->reuse);
1327
0
  comm_point_start_listening(pend_tcp->c, -1, tcp_reuse_timeout);
1328
0
}
1329
1330
/** set timeout on tcp fd and setup read event to catch incoming dns msgs */
1331
static void
1332
reuse_tcp_setup_read_and_timeout(struct pending_tcp* pend_tcp, int tcp_reuse_timeout)
1333
0
{
1334
0
  log_reuse_tcp(VERB_CLIENT, "reuse_tcp_setup_readtimeout", &pend_tcp->reuse);
1335
0
  sldns_buffer_clear(pend_tcp->c->buffer);
1336
0
  pend_tcp->c->tcp_is_reading = 1;
1337
0
  pend_tcp->c->tcp_byte_count = 0;
1338
0
  comm_point_stop_listening(pend_tcp->c);
1339
0
  comm_point_start_listening(pend_tcp->c, -1, tcp_reuse_timeout);
1340
0
}
1341
1342
int 
1343
outnet_tcp_cb(struct comm_point* c, void* arg, int error,
1344
  struct comm_reply *reply_info)
1345
0
{
1346
0
  struct pending_tcp* pend = (struct pending_tcp*)arg;
1347
0
  struct outside_network* outnet = pend->reuse.outnet;
1348
0
  struct waiting_tcp* w = NULL;
1349
0
  log_assert(pend->reuse.item_on_lru_list && pend->reuse.node.key);
1350
0
  verbose(VERB_ALGO, "outnettcp cb");
1351
0
  if(error == NETEVENT_TIMEOUT) {
1352
0
    if(pend->c->tcp_write_and_read) {
1353
0
      verbose(VERB_QUERY, "outnettcp got tcp timeout "
1354
0
        "for read, ignored because write underway");
1355
      /* if we are writing, ignore readtimer, wait for write timer
1356
       * or write is done */
1357
0
      return 0;
1358
0
    } else {
1359
0
      verbose(VERB_QUERY, "outnettcp got tcp timeout %s",
1360
0
        (pend->reuse.tree_by_id.count?"for reading pkt":
1361
0
        "for keepalive for reuse"));
1362
0
    }
1363
    /* must be timeout for reading or keepalive reuse,
1364
     * close it. */
1365
0
    reuse_tcp_remove_tree_list(outnet, &pend->reuse);
1366
0
  } else if(error == NETEVENT_PKT_WRITTEN) {
1367
    /* the packet we want to write has been written. */
1368
0
    verbose(VERB_ALGO, "outnet tcp pkt was written event");
1369
0
    log_assert(c == pend->c);
1370
0
    log_assert(pend->query->pkt == pend->c->tcp_write_pkt);
1371
0
    log_assert(pend->query->pkt_len == pend->c->tcp_write_pkt_len);
1372
0
    pend->c->tcp_write_pkt = NULL;
1373
0
    pend->c->tcp_write_pkt_len = 0;
1374
    /* the pend.query is already in tree_by_id */
1375
0
    log_assert(pend->query->id_node.key);
1376
0
    pend->query = NULL;
1377
    /* setup to write next packet or setup read timeout */
1378
0
    if(pend->reuse.write_wait_first) {
1379
0
      verbose(VERB_ALGO, "outnet tcp setup next pkt");
1380
      /* we can write it straight away perhaps, set flag
1381
       * because this callback called after a tcp write
1382
       * succeeded and likely more buffer space is available
1383
       * and we can write some more. */
1384
0
      pend->reuse.cp_more_write_again = 1;
1385
0
      pend->query = reuse_write_wait_pop(&pend->reuse);
1386
0
      comm_point_stop_listening(pend->c);
1387
0
      outnet_tcp_take_query_setup(pend->c->fd, pend,
1388
0
        pend->query);
1389
0
    } else {
1390
0
      verbose(VERB_ALGO, "outnet tcp writes done, wait");
1391
0
      pend->c->tcp_write_and_read = 0;
1392
0
      pend->reuse.cp_more_read_again = 0;
1393
0
      pend->reuse.cp_more_write_again = 0;
1394
0
      pend->c->tcp_is_reading = 1;
1395
0
      comm_point_stop_listening(pend->c);
1396
0
      reuse_tcp_setup_timeout(pend, outnet->tcp_reuse_timeout);
1397
0
    }
1398
0
    return 0;
1399
0
  } else if(error != NETEVENT_NOERROR) {
1400
0
    verbose(VERB_QUERY, "outnettcp got tcp error %d", error);
1401
0
    reuse_move_writewait_away(outnet, pend);
1402
    /* pass error below and exit */
1403
0
  } else {
1404
    /* check ID */
1405
0
    if(sldns_buffer_limit(c->buffer) < sizeof(uint16_t)) {
1406
0
      log_addr(VERB_QUERY, 
1407
0
        "outnettcp: bad ID in reply, too short, from:",
1408
0
        &pend->reuse.addr, pend->reuse.addrlen);
1409
0
      error = NETEVENT_CLOSED;
1410
0
    } else {
1411
0
      uint16_t id = LDNS_ID_WIRE(sldns_buffer_begin(
1412
0
        c->buffer));
1413
      /* find the query the reply is for */
1414
0
      w = reuse_tcp_by_id_find(&pend->reuse, id);
1415
      /* Make sure that the reply we got is at least for a
1416
       * sent query with the same ID; the waiting_tcp that
1417
       * gets a reply is assumed to not be waiting to be
1418
       * sent. */
1419
0
      if(w && (w->on_tcp_waiting_list || w->write_wait_queued))
1420
0
        w = NULL;
1421
0
    }
1422
0
  }
1423
0
  if(error == NETEVENT_NOERROR && !w) {
1424
    /* no struct waiting found in tree, no reply to call */
1425
0
    log_addr(VERB_QUERY, "outnettcp: bad ID in reply, from:",
1426
0
      &pend->reuse.addr, pend->reuse.addrlen);
1427
0
    error = NETEVENT_CLOSED;
1428
0
  }
1429
0
  if(error == NETEVENT_NOERROR) {
1430
    /* add to reuse tree so it can be reused, if not a failure.
1431
     * This is possible if the state machine wants to make a tcp
1432
     * query again to the same destination. */
1433
0
    if(outnet->tcp_reuse.count < outnet->tcp_reuse_max) {
1434
0
      (void)reuse_tcp_insert(outnet, pend);
1435
0
    }
1436
0
  }
1437
0
  if(w) {
1438
0
    log_assert(!w->on_tcp_waiting_list);
1439
0
    log_assert(!w->write_wait_queued);
1440
0
    reuse_tree_by_id_delete(&pend->reuse, w);
1441
0
    verbose(VERB_CLIENT, "outnet tcp callback query err %d buflen %d",
1442
0
      error, (int)sldns_buffer_limit(c->buffer));
1443
0
    waiting_tcp_callback(w, c, error, reply_info);
1444
0
    waiting_tcp_delete(w);
1445
0
  }
1446
0
  verbose(VERB_CLIENT, "outnet_tcp_cb reuse after cb");
1447
0
  if(error == NETEVENT_NOERROR && pend->reuse.node.key) {
1448
0
    verbose(VERB_CLIENT, "outnet_tcp_cb reuse after cb: keep it");
1449
    /* it is in the reuse_tcp tree, with other queries, or
1450
     * on the empty list. do not decommission it */
1451
    /* if there are more outstanding queries, we could try to
1452
     * read again, to see if it is on the input,
1453
     * because this callback called after a successful read
1454
     * and there could be more bytes to read on the input */
1455
0
    if(pend->reuse.tree_by_id.count != 0)
1456
0
      pend->reuse.cp_more_read_again = 1;
1457
0
    reuse_tcp_setup_read_and_timeout(pend, outnet->tcp_reuse_timeout);
1458
0
    return 0;
1459
0
  }
1460
0
  verbose(VERB_CLIENT, "outnet_tcp_cb reuse after cb: decommission it");
1461
  /* no queries on it, no space to keep it. or timeout or closed due
1462
   * to error.  Close it */
1463
0
  reuse_cb_and_decommission(outnet, pend, (error==NETEVENT_TIMEOUT?
1464
0
    NETEVENT_TIMEOUT:NETEVENT_CLOSED));
1465
0
  use_free_buffer(outnet);
1466
0
  return 0;
1467
0
}
1468
1469
/** lower use count on pc, see if it can be closed */
1470
static void
1471
portcomm_loweruse(struct outside_network* outnet, struct port_comm* pc)
1472
0
{
1473
0
  struct port_if* pif;
1474
0
  pc->num_outstanding--;
1475
0
  if(pc->num_outstanding > 0) {
1476
0
    return;
1477
0
  }
1478
  /* close it and replace in unused list */
1479
0
  verbose(VERB_ALGO, "close of port %d", pc->number);
1480
0
  comm_point_close(pc->cp);
1481
0
  pif = pc->pif;
1482
0
  log_assert(pif->inuse > 0);
1483
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
1484
0
  shared_ports_return_port(outnet->shared_ports, pif->shpif, pc->number);
1485
0
#endif
1486
0
  pif->inuse--;
1487
0
  pif->out[pc->index] = pif->out[pif->inuse];
1488
0
  pif->out[pc->index]->index = pc->index;
1489
0
  pc->next = outnet->unused_fds;
1490
0
  outnet->unused_fds = pc;
1491
0
}
1492
1493
/** try to send waiting UDP queries */
1494
static void
1495
outnet_send_wait_udp(struct outside_network* outnet)
1496
0
{
1497
0
  struct pending* pend;
1498
  /* process waiting queries */
1499
0
  while(outnet->udp_wait_first && outnet->unused_fds
1500
0
    && !outnet->want_to_quit) {
1501
0
    pend = outnet->udp_wait_first;
1502
0
    outnet->udp_wait_first = pend->next_waiting;
1503
0
    if(!pend->next_waiting) outnet->udp_wait_last = NULL;
1504
0
    sldns_buffer_clear(outnet->udp_buff);
1505
0
    sldns_buffer_write(outnet->udp_buff, pend->pkt, pend->pkt_len);
1506
0
    sldns_buffer_flip(outnet->udp_buff);
1507
0
    free(pend->pkt); /* freeing now makes get_mem correct */
1508
0
    pend->pkt = NULL;
1509
0
    pend->pkt_len = 0;
1510
0
    log_assert(!pend->sq->busy);
1511
0
    pend->sq->busy = 1;
1512
0
    if(!randomize_and_send_udp(pend, outnet->udp_buff,
1513
0
      pend->timeout)) {
1514
      /* callback error on pending */
1515
0
      if(pend->cb) {
1516
0
        fptr_ok(fptr_whitelist_pending_udp(pend->cb));
1517
0
        (void)(*pend->cb)(outnet->unused_fds->cp, pend->cb_arg, 
1518
0
          NETEVENT_CLOSED, NULL);
1519
0
      }
1520
0
      pending_delete(outnet, pend);
1521
0
    } else {
1522
0
      pend->sq->busy = 0;
1523
0
    }
1524
0
  }
1525
0
}
1526
1527
/** Clear out all pending requests that are on the port. */
1528
static void
1529
clear_pending_from_port(struct outside_network* outnet, struct comm_point* c)
1530
0
{
1531
  /* Otherwise, the clear the cache action of unwanted_threshold, can
1532
   * have revealed this communication port. */
1533
0
  struct pending* p, *np, *list = NULL, *last = NULL;
1534
  /* First, remove the entries from the tree. */
1535
  /* The rbtree rbnode.right is used to build the temporary list here.
1536
   * Otherwise the list could be malloced. */
1537
0
  p = (struct pending*)rbtree_first(outnet->pending);
1538
0
  while((rbnode_type*)p != RBTREE_NULL) {
1539
0
    np = (struct pending*)rbtree_next((rbnode_type*)p);
1540
0
    if(p->pc->cp == c) {
1541
0
      comm_timer_disable(p->timer);
1542
0
      (void)rbtree_delete(outnet->pending, p->node.key);
1543
0
      if(last)
1544
0
        last->node.right = (rbnode_type*)p;
1545
0
      else  list = p;
1546
0
      last = p;
1547
0
      p->node.right = NULL;
1548
0
    }
1549
0
    p = np;
1550
0
  }
1551
1552
  /* The entries are removed from the tree, call their callbacks. */
1553
0
  p = list;
1554
0
  while(p) {
1555
0
    np = (struct pending*)p->node.right;
1556
0
    p->node.right = RBTREE_NULL;
1557
    /* callback error on pending */
1558
0
    if(p->cb) {
1559
0
      fptr_ok(fptr_whitelist_pending_udp(p->cb));
1560
0
      (void)(*p->cb)(p->pc->cp, p->cb_arg,
1561
0
        NETEVENT_CLOSED, NULL);
1562
0
    }
1563
0
    portcomm_loweruse(outnet, p->pc);
1564
0
    pending_delete(NULL, p);
1565
0
    outnet_send_wait_udp(outnet);
1566
0
    p = np;
1567
0
  }
1568
0
}
1569
1570
int 
1571
outnet_udp_cb(struct comm_point* c, void* arg, int error,
1572
  struct comm_reply *reply_info)
1573
0
{
1574
0
  struct outside_network* outnet = (struct outside_network*)arg;
1575
0
  struct pending key;
1576
0
  struct pending* p;
1577
0
  verbose(VERB_ALGO, "answer cb");
1578
1579
0
  if(error != NETEVENT_NOERROR) {
1580
0
    verbose(VERB_QUERY, "outnetudp got udp error %d", error);
1581
0
    return 0;
1582
0
  }
1583
0
  if(sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
1584
0
    verbose(VERB_QUERY, "outnetudp udp too short");
1585
0
    return 0;
1586
0
  }
1587
0
  log_assert(reply_info);
1588
1589
  /* setup lookup key */
1590
0
  key.id = (unsigned)LDNS_ID_WIRE(sldns_buffer_begin(c->buffer));
1591
0
  memcpy(&key.addr, &reply_info->remote_addr, reply_info->remote_addrlen);
1592
0
  key.addrlen = reply_info->remote_addrlen;
1593
0
  verbose(VERB_ALGO, "Incoming reply id = %4.4x", key.id);
1594
0
  log_addr(VERB_ALGO, "Incoming reply addr =", 
1595
0
    &reply_info->remote_addr, reply_info->remote_addrlen);
1596
1597
  /* find it, see if this thing is a valid query response */
1598
0
  verbose(VERB_ALGO, "lookup size is %d entries", (int)outnet->pending->count);
1599
0
  p = (struct pending*)rbtree_search(outnet->pending, &key);
1600
0
  if(!p) {
1601
0
    verbose(VERB_QUERY, "received unwanted or unsolicited udp reply dropped.");
1602
0
    log_buf(VERB_ALGO, "dropped message", c->buffer);
1603
0
    outnet->unwanted_replies++;
1604
0
    if(outnet->unwanted_threshold && ++outnet->unwanted_total 
1605
0
      >= outnet->unwanted_threshold) {
1606
0
      log_warn("unwanted reply total reached threshold (%u)"
1607
0
        " you may be under attack."
1608
0
        " defensive action: clearing the cache",
1609
0
        (unsigned)outnet->unwanted_threshold);
1610
0
      fptr_ok(fptr_whitelist_alloc_cleanup(
1611
0
        outnet->unwanted_action));
1612
0
      (*outnet->unwanted_action)(outnet->unwanted_param);
1613
0
      outnet->unwanted_total = 0;
1614
0
      clear_pending_from_port(outnet, c);
1615
0
    }
1616
0
    return 0;
1617
0
  }
1618
1619
0
  verbose(VERB_ALGO, "received udp reply.");
1620
0
  log_buf(VERB_ALGO, "udp message", c->buffer);
1621
0
  if(p->pc->cp != c) {
1622
0
    verbose(VERB_QUERY, "received reply id,addr on wrong port. "
1623
0
      "dropped.");
1624
0
    outnet->unwanted_replies++;
1625
0
    if(outnet->unwanted_threshold && ++outnet->unwanted_total 
1626
0
      >= outnet->unwanted_threshold) {
1627
0
      log_warn("unwanted reply total reached threshold (%u)"
1628
0
        " you may be under attack."
1629
0
        " defensive action: clearing the cache",
1630
0
        (unsigned)outnet->unwanted_threshold);
1631
0
      fptr_ok(fptr_whitelist_alloc_cleanup(
1632
0
        outnet->unwanted_action));
1633
0
      (*outnet->unwanted_action)(outnet->unwanted_param);
1634
0
      outnet->unwanted_total = 0;
1635
0
      clear_pending_from_port(outnet, c);
1636
0
    }
1637
0
    return 0;
1638
0
  }
1639
0
  comm_timer_disable(p->timer);
1640
0
  verbose(VERB_ALGO, "outnet handle udp reply");
1641
  /* delete from tree first in case callback creates a retry */
1642
0
  (void)rbtree_delete(outnet->pending, p->node.key);
1643
0
  if(p->cb) {
1644
0
    fptr_ok(fptr_whitelist_pending_udp(p->cb));
1645
0
    (void)(*p->cb)(p->pc->cp, p->cb_arg, NETEVENT_NOERROR, reply_info);
1646
0
  }
1647
0
  portcomm_loweruse(outnet, p->pc);
1648
0
  pending_delete(NULL, p);
1649
0
  outnet_send_wait_udp(outnet);
1650
0
  return 0;
1651
0
}
1652
1653
/** calculate number of ip4 and ip6 interfaces*/
1654
static void 
1655
calc_num46(char** ifs, int num_ifs, int do_ip4, int do_ip6, 
1656
  int* num_ip4, int* num_ip6)
1657
0
{
1658
0
  int i;
1659
0
  *num_ip4 = 0;
1660
0
  *num_ip6 = 0;
1661
0
  if(num_ifs <= 0) {
1662
0
    if(do_ip4)
1663
0
      *num_ip4 = 1;
1664
0
    if(do_ip6)
1665
0
      *num_ip6 = 1;
1666
0
    return;
1667
0
  }
1668
0
  for(i=0; i<num_ifs; i++)
1669
0
  {
1670
0
    if(str_is_ip6(ifs[i])) {
1671
0
      if(do_ip6)
1672
0
        (*num_ip6)++;
1673
0
    } else {
1674
0
      if(do_ip4)
1675
0
        (*num_ip4)++;
1676
0
    }
1677
0
  }
1678
0
}
1679
1680
void
1681
pending_udp_timer_delay_cb(void* arg)
1682
0
{
1683
0
  struct pending* p = (struct pending*)arg;
1684
0
  struct outside_network* outnet = p->outnet;
1685
0
  verbose(VERB_ALGO, "timeout udp with delay");
1686
0
  portcomm_loweruse(outnet, p->pc);
1687
0
  pending_delete(outnet, p);
1688
0
  outnet_send_wait_udp(outnet);
1689
0
}
1690
1691
void 
1692
pending_udp_timer_cb(void *arg)
1693
0
{
1694
0
  struct pending* p = (struct pending*)arg;
1695
0
  struct outside_network* outnet = p->outnet;
1696
  /* it timed out */
1697
0
  verbose(VERB_ALGO, "timeout udp");
1698
0
  if(p->cb) {
1699
0
    fptr_ok(fptr_whitelist_pending_udp(p->cb));
1700
0
    (void)(*p->cb)(p->pc->cp, p->cb_arg, NETEVENT_TIMEOUT, NULL);
1701
0
  }
1702
  /* if delayclose, keep port open for a longer time.
1703
   * But if the udpwaitlist exists, then we are struggling to
1704
   * keep up with demand for sockets, so do not wait, but service
1705
   * the customer (customer service more important than portICMPs) */
1706
0
  if(outnet->delayclose && !outnet->udp_wait_first) {
1707
0
    p->cb = NULL;
1708
0
    p->timer->callback = &pending_udp_timer_delay_cb;
1709
0
    comm_timer_set(p->timer, &outnet->delay_tv);
1710
0
    return;
1711
0
  }
1712
0
  portcomm_loweruse(outnet, p->pc);
1713
0
  pending_delete(outnet, p);
1714
0
  outnet_send_wait_udp(outnet);
1715
0
}
1716
1717
/** create pending_tcp buffers */
1718
static int
1719
create_pending_tcp(struct outside_network* outnet, size_t bufsize)
1720
0
{
1721
0
  size_t i;
1722
0
  if(outnet->num_tcp == 0)
1723
0
    return 1; /* no tcp needed, nothing to do */
1724
0
  if(!(outnet->tcp_conns = (struct pending_tcp **)calloc(
1725
0
      outnet->num_tcp, sizeof(struct pending_tcp*))))
1726
0
    return 0;
1727
0
  for(i=0; i<outnet->num_tcp; i++) {
1728
0
    if(!(outnet->tcp_conns[i] = (struct pending_tcp*)calloc(1, 
1729
0
      sizeof(struct pending_tcp))))
1730
0
      return 0;
1731
0
    outnet->tcp_conns[i]->next_free = outnet->tcp_free;
1732
0
    outnet->tcp_free = outnet->tcp_conns[i];
1733
0
    outnet->tcp_conns[i]->c = comm_point_create_tcp_out(
1734
0
      outnet->base, bufsize, outnet_tcp_cb, 
1735
0
      outnet->tcp_conns[i]);
1736
0
    if(!outnet->tcp_conns[i]->c)
1737
0
      return 0;
1738
0
  }
1739
0
  return 1;
1740
0
}
1741
1742
/** setup an outgoing interface, ready address */
1743
static int setup_if(struct port_if* pif, const char* addrstr, size_t numfd,
1744
  struct shared_ports* shp)
1745
0
{
1746
0
  if(!ipstrtoaddr(addrstr, UNBOUND_DNS_PORT, &pif->addr, &pif->addrlen) &&
1747
0
     !netblockstrtoaddr(addrstr, UNBOUND_DNS_PORT,
1748
0
            &pif->addr, &pif->addrlen, &pif->pfxlen))
1749
0
    return 0;
1750
0
#ifdef INT_MAX
1751
0
  if(numfd > (size_t)INT_MAX) {
1752
0
    log_err("num_ports exceeds INT_MAX");
1753
0
    return 0;
1754
0
  }
1755
0
#endif
1756
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
1757
0
  pif->shpif = shared_ports_find_if(shp, &pif->addr, pif->addrlen,
1758
0
    pif->pfxlen);
1759
#else
1760
  (void)shp;
1761
#endif
1762
0
  pif->maxout = (int)numfd;
1763
0
  pif->inuse = 0;
1764
0
  pif->out = (struct port_comm**)calloc(numfd, 
1765
0
    sizeof(struct port_comm*));
1766
0
  if(!pif->out)
1767
0
    return 0;
1768
0
  return 1;
1769
0
}
1770
1771
struct outside_network* 
1772
outside_network_create(struct comm_base *base, size_t bufsize, 
1773
  size_t num_ports, char** ifs, int num_ifs, int do_ip4, 
1774
  int do_ip6, size_t num_tcp, int dscp, struct infra_cache* infra,
1775
  struct ub_randstate* rnd, int use_caps_for_id,
1776
  size_t unwanted_threshold, int tcp_mss,
1777
  void (*unwanted_action)(void*), void* unwanted_param, int do_udp,
1778
  void* sslctx, int delayclose, int tls_use_sni, struct dt_env* dtenv,
1779
  int udp_connect, int max_reuse_tcp_queries, int tcp_reuse_timeout,
1780
  int tcp_auth_query_timeout, struct shared_ports* shared_ports)
1781
0
{
1782
0
  struct outside_network* outnet = (struct outside_network*)
1783
0
    calloc(1, sizeof(struct outside_network));
1784
0
  size_t k;
1785
0
  if(!outnet) {
1786
0
    log_err("malloc failed");
1787
0
    return NULL;
1788
0
  }
1789
0
  comm_base_timept(base, &outnet->now_secs, &outnet->now_tv);
1790
0
  outnet->base = base;
1791
0
  outnet->num_tcp = num_tcp;
1792
0
  outnet->max_reuse_tcp_queries = max_reuse_tcp_queries;
1793
0
  outnet->tcp_reuse_timeout= tcp_reuse_timeout;
1794
0
  outnet->tcp_auth_query_timeout = tcp_auth_query_timeout;
1795
0
  outnet->num_tcp_outgoing = 0;
1796
0
  outnet->num_udp_outgoing = 0;
1797
0
  outnet->infra = infra;
1798
0
  outnet->rnd = rnd;
1799
0
  outnet->sslctx = sslctx;
1800
0
  outnet->tls_use_sni = tls_use_sni;
1801
#ifdef USE_DNSTAP
1802
  outnet->dtenv = dtenv;
1803
#else
1804
0
  (void)dtenv;
1805
0
#endif
1806
0
  outnet->svcd_overhead = 0;
1807
0
  outnet->want_to_quit = 0;
1808
0
  outnet->unwanted_threshold = unwanted_threshold;
1809
0
  outnet->unwanted_action = unwanted_action;
1810
0
  outnet->unwanted_param = unwanted_param;
1811
0
  outnet->use_caps_for_id = use_caps_for_id;
1812
0
  outnet->do_udp = do_udp;
1813
0
  outnet->tcp_mss = tcp_mss;
1814
0
  outnet->ip_dscp = dscp;
1815
0
  outnet->shared_ports = shared_ports;
1816
0
#ifndef S_SPLINT_S
1817
0
  if(delayclose) {
1818
0
    outnet->delayclose = 1;
1819
0
    outnet->delay_tv.tv_sec = delayclose/1000;
1820
0
    outnet->delay_tv.tv_usec = (delayclose%1000)*1000;
1821
0
  }
1822
0
#endif
1823
0
  if(udp_connect) {
1824
0
    outnet->udp_connect = 1;
1825
0
  }
1826
0
  if(num_ports == 0) {
1827
0
    log_err("no outgoing ports available");
1828
0
    outside_network_delete(outnet);
1829
0
    return NULL;
1830
0
  }
1831
0
#ifdef INT_MAX
1832
0
  if(num_ports > (size_t)INT_MAX) {
1833
0
    log_err("outgoing num_ports exceeds INT_MAX");
1834
0
    outside_network_delete(outnet);
1835
0
    return NULL;
1836
0
  }
1837
0
#endif
1838
#ifndef INET6
1839
  do_ip6 = 0;
1840
#endif
1841
0
  calc_num46(ifs, num_ifs, do_ip4, do_ip6, 
1842
0
    &outnet->num_ip4, &outnet->num_ip6);
1843
0
  if(outnet->num_ip4 != 0) {
1844
0
    if(!(outnet->ip4_ifs = (struct port_if*)calloc(
1845
0
      (size_t)outnet->num_ip4, sizeof(struct port_if)))) {
1846
0
      log_err("malloc failed");
1847
0
      outside_network_delete(outnet);
1848
0
      return NULL;
1849
0
    }
1850
0
  }
1851
0
  if(outnet->num_ip6 != 0) {
1852
0
    if(!(outnet->ip6_ifs = (struct port_if*)calloc(
1853
0
      (size_t)outnet->num_ip6, sizeof(struct port_if)))) {
1854
0
      log_err("malloc failed");
1855
0
      outside_network_delete(outnet);
1856
0
      return NULL;
1857
0
    }
1858
0
  }
1859
0
  if( !(outnet->udp_buff = sldns_buffer_new(bufsize)) ||
1860
0
    !(outnet->pending = rbtree_create(pending_cmp)) ||
1861
0
    !(outnet->serviced = rbtree_create(serviced_cmp)) ||
1862
0
    !create_pending_tcp(outnet, bufsize)) {
1863
0
    log_err("malloc failed");
1864
0
    outside_network_delete(outnet);
1865
0
    return NULL;
1866
0
  }
1867
0
  rbtree_init(&outnet->tcp_reuse, reuse_cmp);
1868
0
  outnet->tcp_reuse_max = num_tcp;
1869
1870
  /* allocate commpoints */
1871
0
  for(k=0; k<num_ports; k++) {
1872
0
    struct port_comm* pc;
1873
0
    pc = (struct port_comm*)calloc(1, sizeof(*pc));
1874
0
    if(!pc) {
1875
0
      log_err("malloc failed");
1876
0
      outside_network_delete(outnet);
1877
0
      return NULL;
1878
0
    }
1879
0
    pc->cp = comm_point_create_udp(outnet->base, -1, 
1880
0
      outnet->udp_buff, 0, outnet_udp_cb, outnet, NULL);
1881
0
    if(!pc->cp) {
1882
0
      log_err("malloc failed");
1883
0
      free(pc);
1884
0
      outside_network_delete(outnet);
1885
0
      return NULL;
1886
0
    }
1887
0
    pc->next = outnet->unused_fds;
1888
0
    outnet->unused_fds = pc;
1889
0
  }
1890
1891
  /* allocate interfaces */
1892
0
  if(num_ifs == 0) {
1893
0
    if(do_ip4 && !setup_if(&outnet->ip4_ifs[0], "0.0.0.0", 
1894
0
      num_ports, outnet->shared_ports)) {
1895
0
      log_err("malloc failed");
1896
0
      outside_network_delete(outnet);
1897
0
      return NULL;
1898
0
    }
1899
0
    if(do_ip6 && !setup_if(&outnet->ip6_ifs[0], "::", 
1900
0
      num_ports, outnet->shared_ports)) {
1901
0
      log_err("malloc failed");
1902
0
      outside_network_delete(outnet);
1903
0
      return NULL;
1904
0
    }
1905
0
  } else {
1906
0
    size_t done_4 = 0, done_6 = 0;
1907
0
    int i;
1908
0
    for(i=0; i<num_ifs; i++) {
1909
0
      if(str_is_ip6(ifs[i]) && do_ip6) {
1910
0
        if(!setup_if(&outnet->ip6_ifs[done_6], ifs[i],
1911
0
          num_ports, outnet->shared_ports)){
1912
0
          log_err("malloc failed");
1913
0
          outside_network_delete(outnet);
1914
0
          return NULL;
1915
0
        }
1916
0
        done_6++;
1917
0
      }
1918
0
      if(!str_is_ip6(ifs[i]) && do_ip4) {
1919
0
        if(!setup_if(&outnet->ip4_ifs[done_4], ifs[i],
1920
0
          num_ports, outnet->shared_ports)){
1921
0
          log_err("malloc failed");
1922
0
          outside_network_delete(outnet);
1923
0
          return NULL;
1924
0
        }
1925
0
        done_4++;
1926
0
      }
1927
0
    }
1928
0
  }
1929
0
  return outnet;
1930
0
}
1931
1932
/** helper pending delete */
1933
static void
1934
pending_node_del(rbnode_type* node, void* arg)
1935
0
{
1936
0
  struct pending* pend = (struct pending*)node;
1937
0
  struct outside_network* outnet = (struct outside_network*)arg;
1938
0
  pending_delete(outnet, pend);
1939
0
}
1940
1941
/** helper serviced delete */
1942
static void
1943
serviced_node_del(rbnode_type* node, void* ATTR_UNUSED(arg))
1944
0
{
1945
0
  struct serviced_query* sq = (struct serviced_query*)node;
1946
0
  alloc_reg_release(sq->alloc, sq->region);
1947
0
  if(sq->timer)
1948
0
    comm_timer_delete(sq->timer);
1949
0
  free(sq);
1950
0
}
1951
1952
void 
1953
outside_network_quit_prepare(struct outside_network* outnet)
1954
0
{
1955
0
  if(!outnet)
1956
0
    return;
1957
  /* prevent queued items from being sent */
1958
0
  outnet->want_to_quit = 1; 
1959
0
}
1960
1961
void 
1962
outside_network_delete(struct outside_network* outnet)
1963
0
{
1964
0
  if(!outnet)
1965
0
    return;
1966
0
  outnet->want_to_quit = 1;
1967
  /* check every element, since we can be called on malloc error */
1968
0
  if(outnet->pending) {
1969
    /* free pending elements, but do no unlink from tree. */
1970
0
    traverse_postorder(outnet->pending, pending_node_del, NULL);
1971
0
    free(outnet->pending);
1972
0
  }
1973
0
  if(outnet->serviced) {
1974
0
    traverse_postorder(outnet->serviced, serviced_node_del, NULL);
1975
0
    free(outnet->serviced);
1976
0
  }
1977
0
  if(outnet->udp_buff)
1978
0
    sldns_buffer_free(outnet->udp_buff);
1979
0
  if(outnet->unused_fds) {
1980
0
    struct port_comm* p = outnet->unused_fds, *np;
1981
0
    while(p) {
1982
0
      np = p->next;
1983
0
      comm_point_delete(p->cp);
1984
0
      free(p);
1985
0
      p = np;
1986
0
    }
1987
0
    outnet->unused_fds = NULL;
1988
0
  }
1989
0
  if(outnet->ip4_ifs) {
1990
0
    int i, k;
1991
0
    for(i=0; i<outnet->num_ip4; i++) {
1992
0
      for(k=0; k<outnet->ip4_ifs[i].inuse; k++) {
1993
0
        struct port_comm* pc = outnet->ip4_ifs[i].
1994
0
          out[k];
1995
0
        comm_point_delete(pc->cp);
1996
0
        free(pc);
1997
0
      }
1998
0
      free(outnet->ip4_ifs[i].out);
1999
0
    }
2000
0
    free(outnet->ip4_ifs);
2001
0
  }
2002
0
  if(outnet->ip6_ifs) {
2003
0
    int i, k;
2004
0
    for(i=0; i<outnet->num_ip6; i++) {
2005
0
      for(k=0; k<outnet->ip6_ifs[i].inuse; k++) {
2006
0
        struct port_comm* pc = outnet->ip6_ifs[i].
2007
0
          out[k];
2008
0
        comm_point_delete(pc->cp);
2009
0
        free(pc);
2010
0
      }
2011
0
      free(outnet->ip6_ifs[i].out);
2012
0
    }
2013
0
    free(outnet->ip6_ifs);
2014
0
  }
2015
0
  if(outnet->tcp_conns) {
2016
0
    size_t i;
2017
0
    for(i=0; i<outnet->num_tcp; i++)
2018
0
      if(outnet->tcp_conns[i]) {
2019
0
        struct pending_tcp* pend;
2020
0
        pend = outnet->tcp_conns[i];
2021
0
        if(pend->reuse.item_on_lru_list) {
2022
          /* delete waiting_tcp elements that
2023
           * the tcp conn is working on */
2024
0
          decommission_pending_tcp(outnet, pend);
2025
0
        }
2026
0
        if(pend->reuse.tls_auth_name) {
2027
0
          free(pend->reuse.tls_auth_name);
2028
0
          pend->reuse.tls_auth_name = NULL;
2029
0
        }
2030
0
        comm_point_delete(outnet->tcp_conns[i]->c);
2031
0
        free(outnet->tcp_conns[i]);
2032
0
        outnet->tcp_conns[i] = NULL;
2033
0
      }
2034
0
    free(outnet->tcp_conns);
2035
0
    outnet->tcp_conns = NULL;
2036
0
  }
2037
0
  if(outnet->tcp_wait_first) {
2038
0
    struct waiting_tcp* p = outnet->tcp_wait_first, *np;
2039
0
    while(p) {
2040
0
      np = p->next_waiting;
2041
0
      waiting_tcp_delete(p);
2042
0
      p = np;
2043
0
    }
2044
0
  }
2045
  /* was allocated in struct pending that was deleted above */
2046
0
  rbtree_init(&outnet->tcp_reuse, reuse_cmp);
2047
0
  outnet->tcp_reuse_first = NULL;
2048
0
  outnet->tcp_reuse_last = NULL;
2049
0
  if(outnet->udp_wait_first) {
2050
0
    struct pending* p = outnet->udp_wait_first, *np;
2051
0
    while(p) {
2052
0
      np = p->next_waiting;
2053
0
      pending_delete(NULL, p);
2054
0
      p = np;
2055
0
    }
2056
0
  }
2057
0
  free(outnet);
2058
0
}
2059
2060
void 
2061
pending_delete(struct outside_network* outnet, struct pending* p)
2062
0
{
2063
0
  if(!p)
2064
0
    return;
2065
0
  if(outnet && outnet->udp_wait_first &&
2066
0
    (p->next_waiting || p == outnet->udp_wait_last) ) {
2067
    /* delete from waiting list, if it is in the waiting list */
2068
0
    struct pending* prev = NULL, *x = outnet->udp_wait_first;
2069
0
    while(x && x != p) {
2070
0
      prev = x;
2071
0
      x = x->next_waiting;
2072
0
    }
2073
0
    if(x) {
2074
0
      log_assert(x == p);
2075
0
      if(prev)
2076
0
        prev->next_waiting = p->next_waiting;
2077
0
      else  outnet->udp_wait_first = p->next_waiting;
2078
0
      if(outnet->udp_wait_last == p)
2079
0
        outnet->udp_wait_last = prev;
2080
0
    }
2081
0
  }
2082
0
  if(outnet) {
2083
0
    (void)rbtree_delete(outnet->pending, p->node.key);
2084
0
  }
2085
0
  if(p->timer)
2086
0
    comm_timer_delete(p->timer);
2087
0
  free(p->pkt);
2088
0
  free(p);
2089
0
}
2090
2091
static void
2092
sai6_putrandom(struct sockaddr_in6 *sa, int pfxlen, struct ub_randstate *rnd)
2093
0
{
2094
0
  int i, last;
2095
0
  if(!(pfxlen > 0 && pfxlen < 128))
2096
0
    return;
2097
0
  for(i = 0; i < (128 - pfxlen) / 8; i++) {
2098
0
    sa->sin6_addr.s6_addr[15-i] = (uint8_t)ub_random_max(rnd, 256);
2099
0
  }
2100
0
  last = pfxlen & 7;
2101
0
  if(last != 0) {
2102
0
    sa->sin6_addr.s6_addr[15-i] |=
2103
0
      ((0xFF >> last) & ub_random_max(rnd, 256));
2104
0
  }
2105
0
}
2106
2107
/**
2108
 * Try to open a UDP socket for outgoing communication.
2109
 * Sets sockets options as needed.
2110
 * @param addr: socket address.
2111
 * @param addrlen: length of address.
2112
 * @param pfxlen: length of network prefix (for address randomisation).
2113
 * @param port: port override for addr.
2114
 * @param inuse: if -1 is returned, this bool means the port was in use.
2115
 * @param rnd: random state (for address randomisation).
2116
 * @param dscp: DSCP to use.
2117
 * @return fd or -1
2118
 */
2119
static int
2120
udp_sockport(struct sockaddr_storage* addr, socklen_t addrlen, int pfxlen,
2121
  int port, int* inuse, struct ub_randstate* rnd, int dscp)
2122
0
{
2123
0
  int fd, noproto;
2124
0
  if(addr_is_ip6(addr, addrlen)) {
2125
0
    int freebind = 0;
2126
0
    struct sockaddr_in6 sa = *(struct sockaddr_in6*)addr;
2127
0
    sa.sin6_port = (in_port_t)htons((uint16_t)port);
2128
0
    sa.sin6_flowinfo = 0;
2129
0
    sa.sin6_scope_id = 0;
2130
0
    if(pfxlen != 0) {
2131
0
      freebind = 1;
2132
0
      sai6_putrandom(&sa, pfxlen, rnd);
2133
0
    }
2134
0
    fd = create_udp_sock(AF_INET6, SOCK_DGRAM, 
2135
0
      (struct sockaddr*)&sa, addrlen, 1, inuse, &noproto,
2136
0
      0, 0, 0, NULL, 0, freebind, 0, dscp);
2137
0
  } else {
2138
0
    struct sockaddr_in* sa = (struct sockaddr_in*)addr;
2139
0
    sa->sin_port = (in_port_t)htons((uint16_t)port);
2140
0
    fd = create_udp_sock(AF_INET, SOCK_DGRAM, 
2141
0
      (struct sockaddr*)addr, addrlen, 1, inuse, &noproto,
2142
0
      0, 0, 0, NULL, 0, 0, 0, dscp);
2143
0
  }
2144
0
  return fd;
2145
0
}
2146
2147
/** Select random ID */
2148
static int
2149
select_id(struct outside_network* outnet, struct pending* pend,
2150
  sldns_buffer* packet)
2151
0
{
2152
0
  int id_tries = 0;
2153
0
  pend->id = GET_RANDOM_ID(outnet->rnd);
2154
0
  LDNS_ID_SET(sldns_buffer_begin(packet), pend->id);
2155
2156
  /* insert in tree */
2157
0
  pend->node.key = pend;
2158
0
  while(!rbtree_insert(outnet->pending, &pend->node)) {
2159
    /* change ID to avoid collision */
2160
0
    pend->id = GET_RANDOM_ID(outnet->rnd);
2161
0
    LDNS_ID_SET(sldns_buffer_begin(packet), pend->id);
2162
0
    id_tries++;
2163
0
    if(id_tries == MAX_ID_RETRY) {
2164
0
      pend->id=99999; /* non existent ID */
2165
0
      log_err("failed to generate unique ID, drop msg");
2166
0
      return 0;
2167
0
    }
2168
0
  }
2169
0
  verbose(VERB_ALGO, "inserted new pending reply id=%4.4x", pend->id);
2170
0
  return 1;
2171
0
}
2172
2173
/** return true is UDP connect error needs to be logged */
2174
static int udp_connect_needs_log(int err, struct sockaddr_storage* addr,
2175
  socklen_t addrlen)
2176
0
{
2177
0
  switch(err) {
2178
0
  case ECONNREFUSED:
2179
0
#  ifdef ENETUNREACH
2180
0
  case ENETUNREACH:
2181
0
#  endif
2182
0
#  ifdef EHOSTDOWN
2183
0
  case EHOSTDOWN:
2184
0
#  endif
2185
0
#  ifdef EHOSTUNREACH
2186
0
  case EHOSTUNREACH:
2187
0
#  endif
2188
0
#  ifdef ENETDOWN
2189
0
  case ENETDOWN:
2190
0
#  endif
2191
0
#  ifdef EADDRNOTAVAIL
2192
0
  case EADDRNOTAVAIL:
2193
0
#  endif
2194
0
  case EPERM:
2195
0
  case EACCES:
2196
0
    if(verbosity >= VERB_ALGO)
2197
0
      return 1;
2198
0
    return 0;
2199
0
  case EINVAL:
2200
    /* Stop 'Invalid argument for fe80::/10' addresses appearing
2201
     * in the logs, at low verbosity. They cannot be sent to. */
2202
0
    if(addr_is_ip6linklocal(addr, addrlen)) {
2203
0
      if(verbosity >= VERB_ALGO)
2204
0
        return 1;
2205
0
      return 0;
2206
0
    }
2207
0
    break;
2208
0
  default:
2209
0
    break;
2210
0
  }
2211
0
  return 1;
2212
0
}
2213
2214
2215
/** Select random interface and port */
2216
static int
2217
select_ifport(struct outside_network* outnet, struct pending* pend,
2218
  int num_if, struct port_if* ifs)
2219
0
{
2220
0
  int my_if, fd, portno, inuse, tries=0;
2221
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
2222
0
  int reused;
2223
0
#endif
2224
0
  struct port_if* pif;
2225
  /* randomly select interface and port */
2226
0
  if(num_if == 0) {
2227
0
    verbose(VERB_QUERY, "Need to send query but have no "
2228
0
      "outgoing interfaces of that family");
2229
0
    return 0;
2230
0
  }
2231
0
  log_assert(outnet->unused_fds);
2232
0
  tries = 0;
2233
0
  while(1) {
2234
0
    my_if = ub_random_max(outnet->rnd, num_if);
2235
0
    pif = &ifs[my_if];
2236
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
2237
0
    if(!shared_ports_fetch_random(outnet->shared_ports,
2238
0
      pif->shpif, outnet->rnd, outnet->udp_connect,
2239
0
      pif->inuse, &portno, &reused)) {
2240
0
      tries++;
2241
0
      if(tries < MAX_PORT_RETRY)
2242
0
        continue;
2243
0
      log_err("failed to find an open port, drop msg");
2244
0
      return 0;
2245
0
    }
2246
0
    if(reused) {
2247
      /* port already open */
2248
0
      log_assert(portno < pif->inuse);
2249
0
      pend->pc = pif->out[portno];
2250
0
      verbose(VERB_ALGO, "using UDP if=%d port=%d",
2251
0
        my_if, pend->pc->number);
2252
0
      break;
2253
0
    }
2254
#else
2255
    portno = 0;
2256
#endif
2257
    /* try to open new port, if fails, loop to try again */
2258
0
    fd = udp_sockport(&pif->addr, pif->addrlen, pif->pfxlen,
2259
0
      portno, &inuse, outnet->rnd, outnet->ip_dscp);
2260
0
    if(fd == -1 && !inuse) {
2261
      /* nonrecoverable error making socket */
2262
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
2263
0
      shared_ports_return_port(outnet->shared_ports,
2264
0
        pif->shpif, portno);
2265
0
#endif
2266
0
      return 0;
2267
0
    }
2268
0
    if(fd != -1) {
2269
0
      verbose(VERB_ALGO, "opened UDP if=%d port=%d", 
2270
0
        my_if, portno);
2271
0
      if(outnet->udp_connect) {
2272
        /* connect() to the destination */
2273
0
        if(connect(fd, (struct sockaddr*)&pend->addr,
2274
0
          pend->addrlen) < 0) {
2275
0
          if(udp_connect_needs_log(errno,
2276
0
            &pend->addr, pend->addrlen)) {
2277
0
            log_err_addr("udp connect failed",
2278
0
              strerror(errno), &pend->addr,
2279
0
              pend->addrlen);
2280
0
          }
2281
0
          sock_close(fd);
2282
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
2283
0
          shared_ports_return_port(
2284
0
            outnet->shared_ports,
2285
0
            pif->shpif, portno);
2286
0
#endif
2287
0
          return 0;
2288
0
        }
2289
0
      }
2290
      /* grab fd */
2291
0
      pend->pc = outnet->unused_fds;
2292
0
      outnet->unused_fds = pend->pc->next;
2293
2294
      /* setup portcomm */
2295
0
      pend->pc->next = NULL;
2296
0
      pend->pc->number = portno;
2297
0
      pend->pc->pif = pif;
2298
0
      pend->pc->index = pif->inuse;
2299
0
      pend->pc->num_outstanding = 0;
2300
0
      comm_point_start_listening(pend->pc->cp, fd, -1);
2301
2302
      /* grab port in interface */
2303
0
      pif->out[pif->inuse] = pend->pc;
2304
0
      pif->inuse++;
2305
0
      break;
2306
0
    }
2307
    /* failed, already in use */
2308
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
2309
0
    shared_ports_return_port(outnet->shared_ports, pif->shpif,
2310
0
      portno);
2311
0
#endif
2312
0
    verbose(VERB_QUERY, "port %d in use, trying another", portno);
2313
0
    tries++;
2314
0
    if(tries == MAX_PORT_RETRY) {
2315
0
      log_err("failed to find an open port, drop msg");
2316
0
      return 0;
2317
0
    }
2318
0
  }
2319
0
  log_assert(pend->pc);
2320
0
  pend->pc->num_outstanding++;
2321
2322
0
  return 1;
2323
0
}
2324
2325
static int
2326
randomize_and_send_udp(struct pending* pend, sldns_buffer* packet, int timeout)
2327
0
{
2328
0
  struct timeval tv;
2329
0
  struct outside_network* outnet = pend->sq->outnet;
2330
2331
  /* select id */
2332
0
  if(!select_id(outnet, pend, packet)) {
2333
0
    return 0;
2334
0
  }
2335
2336
  /* select src_if, port */
2337
0
  if(addr_is_ip6(&pend->addr, pend->addrlen)) {
2338
0
    if(!select_ifport(outnet, pend, 
2339
0
      outnet->num_ip6, outnet->ip6_ifs))
2340
0
      return 0;
2341
0
  } else {
2342
0
    if(!select_ifport(outnet, pend, 
2343
0
      outnet->num_ip4, outnet->ip4_ifs))
2344
0
      return 0;
2345
0
  }
2346
0
  log_assert(pend->pc && pend->pc->cp);
2347
2348
  /* send it over the commlink */
2349
0
  if(!comm_point_send_udp_msg(pend->pc->cp, packet,
2350
0
    (struct sockaddr*)&pend->addr, pend->addrlen, outnet->udp_connect)) {
2351
0
    portcomm_loweruse(outnet, pend->pc);
2352
0
    return 0;
2353
0
  }
2354
0
  outnet->num_udp_outgoing++;
2355
2356
  /* system calls to set timeout after sending UDP to make roundtrip
2357
     smaller. */
2358
0
#ifndef S_SPLINT_S
2359
0
  tv.tv_sec = timeout/1000;
2360
0
  tv.tv_usec = (timeout%1000)*1000;
2361
0
#endif
2362
0
  comm_timer_set(pend->timer, &tv);
2363
2364
#ifdef USE_DNSTAP
2365
  /*
2366
   * sending src (local service)/dst (upstream) addresses over DNSTAP
2367
   * There are no chances to get the src (local service) addr if unbound
2368
   * is not configured with specific outgoing IP-addresses. So we will
2369
   * pass 0.0.0.0 (::) to argument for
2370
   * dt_msg_send_outside_query()/dt_msg_send_outside_response() calls.
2371
   */
2372
  if(outnet->dtenv &&
2373
     (outnet->dtenv->log_resolver_query_messages ||
2374
    outnet->dtenv->log_forwarder_query_messages)) {
2375
      log_addr(VERB_ALGO, "from local addr", &pend->pc->pif->addr, pend->pc->pif->addrlen);
2376
      log_addr(VERB_ALGO, "request to upstream", &pend->addr, pend->addrlen);
2377
      dt_msg_send_outside_query(outnet->dtenv, &pend->addr, &pend->pc->pif->addr, comm_udp, NULL,
2378
        pend->sq->zone, pend->sq->zonelen, packet);
2379
  }
2380
#endif
2381
0
  return 1;
2382
0
}
2383
2384
struct pending* 
2385
pending_udp_query(struct serviced_query* sq, struct sldns_buffer* packet,
2386
  int timeout, comm_point_callback_type* cb, void* cb_arg)
2387
0
{
2388
0
  struct pending* pend = (struct pending*)calloc(1, sizeof(*pend));
2389
0
  if(!pend) return NULL;
2390
0
  pend->outnet = sq->outnet;
2391
0
  pend->sq = sq;
2392
0
  pend->addrlen = sq->addrlen;
2393
0
  memmove(&pend->addr, &sq->addr, sq->addrlen);
2394
0
  pend->cb = cb;
2395
0
  pend->cb_arg = cb_arg;
2396
0
  pend->node.key = pend;
2397
0
  pend->timer = comm_timer_create(sq->outnet->base, pending_udp_timer_cb,
2398
0
    pend);
2399
0
  if(!pend->timer) {
2400
0
    free(pend);
2401
0
    return NULL;
2402
0
  }
2403
2404
0
  if(sq->outnet->unused_fds == NULL) {
2405
    /* no unused fd, cannot create a new port (randomly) */
2406
0
    verbose(VERB_ALGO, "no fds available, udp query waiting");
2407
0
    pend->timeout = timeout;
2408
0
    pend->pkt_len = sldns_buffer_limit(packet);
2409
0
    pend->pkt = (uint8_t*)memdup(sldns_buffer_begin(packet),
2410
0
      pend->pkt_len);
2411
0
    if(!pend->pkt) {
2412
0
      comm_timer_delete(pend->timer);
2413
0
      free(pend);
2414
0
      return NULL;
2415
0
    }
2416
    /* put at end of waiting list */
2417
0
    if(sq->outnet->udp_wait_last)
2418
0
      sq->outnet->udp_wait_last->next_waiting = pend;
2419
0
    else 
2420
0
      sq->outnet->udp_wait_first = pend;
2421
0
    sq->outnet->udp_wait_last = pend;
2422
0
    return pend;
2423
0
  }
2424
0
  log_assert(!sq->busy);
2425
0
  sq->busy = 1;
2426
0
  if(!randomize_and_send_udp(pend, packet, timeout)) {
2427
0
    pending_delete(sq->outnet, pend);
2428
0
    return NULL;
2429
0
  }
2430
0
  sq->busy = 0;
2431
0
  return pend;
2432
0
}
2433
2434
void
2435
outnet_tcptimer(void* arg)
2436
0
{
2437
0
  struct waiting_tcp* w = (struct waiting_tcp*)arg;
2438
0
  struct outside_network* outnet = w->outnet;
2439
0
  verbose(VERB_CLIENT, "outnet_tcptimer");
2440
0
  if(w->on_tcp_waiting_list) {
2441
    /* it is on the waiting list */
2442
0
    outnet_waiting_tcp_list_remove(outnet, w);
2443
0
    waiting_tcp_callback(w, NULL, NETEVENT_TIMEOUT, NULL);
2444
0
    waiting_tcp_delete(w);
2445
0
  } else {
2446
    /* it was in use */
2447
0
    struct pending_tcp* pend=(struct pending_tcp*)w->next_waiting;
2448
0
    reuse_cb_and_decommission(outnet, pend, NETEVENT_TIMEOUT);
2449
0
  }
2450
0
  use_free_buffer(outnet);
2451
0
}
2452
2453
/** close the oldest reuse_tcp connection to make a fd and struct pend
2454
 * available for a new stream connection */
2455
static void
2456
reuse_tcp_close_oldest(struct outside_network* outnet)
2457
0
{
2458
0
  struct reuse_tcp* reuse;
2459
0
  verbose(VERB_CLIENT, "reuse_tcp_close_oldest");
2460
0
  reuse = reuse_tcp_lru_snip(outnet);
2461
0
  if(!reuse) return;
2462
  /* free up */
2463
0
  reuse_cb_and_decommission(outnet, reuse->pending, NETEVENT_CLOSED);
2464
0
}
2465
2466
static uint16_t
2467
tcp_select_id(struct outside_network* outnet, struct reuse_tcp* reuse)
2468
0
{
2469
0
  if(reuse)
2470
0
    return reuse_tcp_select_id(reuse, outnet);
2471
0
  return GET_RANDOM_ID(outnet->rnd);
2472
0
}
2473
2474
/** find spare ID value for reuse tcp stream.  That is random and also does
2475
 * not collide with an existing query ID that is in use or waiting */
2476
uint16_t
2477
reuse_tcp_select_id(struct reuse_tcp* reuse, struct outside_network* outnet)
2478
0
{
2479
0
  uint16_t id = 0, curid, nextid;
2480
0
  const int try_random = 2000;
2481
0
  int i;
2482
0
  unsigned select, count, space;
2483
0
  rbnode_type* node;
2484
2485
  /* make really sure the tree is not empty */
2486
0
  if(reuse->tree_by_id.count == 0) {
2487
0
    id = GET_RANDOM_ID(outnet->rnd);
2488
0
    return id;
2489
0
  }
2490
2491
  /* try to find random empty spots by picking them */
2492
0
  for(i = 0; i<try_random; i++) {
2493
0
    id = GET_RANDOM_ID(outnet->rnd);
2494
0
    if(!reuse_tcp_by_id_find(reuse, id)) {
2495
0
      return id;
2496
0
    }
2497
0
  }
2498
2499
  /* equally pick a random unused element from the tree that is
2500
   * not in use.  Pick a the n-th index of an unused number,
2501
   * then loop over the empty spaces in the tree and find it */
2502
0
  log_assert(reuse->tree_by_id.count < 0xffff);
2503
0
  select = ub_random_max(outnet->rnd, 0xffff - reuse->tree_by_id.count);
2504
  /* select value now in 0 .. num free - 1 */
2505
2506
0
  count = 0; /* number of free spaces passed by */
2507
0
  node = rbtree_first(&reuse->tree_by_id);
2508
0
  log_assert(node && node != RBTREE_NULL); /* tree not empty */
2509
  /* see if select is before first node */
2510
0
  if(select < (unsigned)tree_by_id_get_id(node))
2511
0
    return select;
2512
0
  count += tree_by_id_get_id(node);
2513
  /* perhaps select is between nodes */
2514
0
  while(node && node != RBTREE_NULL) {
2515
0
    rbnode_type* next = rbtree_next(node);
2516
0
    if(next && next != RBTREE_NULL) {
2517
0
      curid = tree_by_id_get_id(node);
2518
0
      nextid = tree_by_id_get_id(next);
2519
0
      log_assert(curid < nextid);
2520
0
      if(curid != 0xffff && curid + 1 < nextid) {
2521
        /* space between nodes */
2522
0
        space = nextid - curid - 1;
2523
0
        log_assert(select >= count);
2524
0
        if(select < count + space) {
2525
          /* here it is */
2526
0
          return curid + 1 + (select - count);
2527
0
        }
2528
0
        count += space;
2529
0
      }
2530
0
    }
2531
0
    node = next;
2532
0
  }
2533
2534
  /* select is after the last node */
2535
  /* count is the number of free positions before the nodes in the
2536
   * tree */
2537
0
  node = rbtree_last(&reuse->tree_by_id);
2538
0
  log_assert(node && node != RBTREE_NULL); /* tree not empty */
2539
0
  curid = tree_by_id_get_id(node);
2540
0
  log_assert(count + (0xffff-curid) + reuse->tree_by_id.count == 0xffff);
2541
0
  return curid + 1 + (select - count);
2542
0
}
2543
2544
struct waiting_tcp*
2545
pending_tcp_query(struct serviced_query* sq, sldns_buffer* packet,
2546
  int timeout, comm_point_callback_type* callback, void* callback_arg)
2547
0
{
2548
0
  struct pending_tcp* pend = sq->outnet->tcp_free;
2549
0
  struct reuse_tcp* reuse = NULL;
2550
0
  struct waiting_tcp* w;
2551
2552
0
  verbose(VERB_CLIENT, "pending_tcp_query");
2553
0
  if(sldns_buffer_limit(packet) < sizeof(uint16_t)) {
2554
0
    verbose(VERB_ALGO, "pending tcp query with too short buffer < 2");
2555
0
    return NULL;
2556
0
  }
2557
2558
  /* find out if a reused stream to the target exists */
2559
  /* if so, take it into use */
2560
0
  reuse = reuse_tcp_find(sq->outnet, &sq->addr, sq->addrlen,
2561
0
    sq->ssl_upstream, sq->tls_auth_name);
2562
0
  if(reuse) {
2563
0
    log_reuse_tcp(VERB_CLIENT, "pending_tcp_query: found reuse", reuse);
2564
0
    log_assert(reuse->pending);
2565
0
    pend = reuse->pending;
2566
0
    reuse_tcp_lru_touch(sq->outnet, reuse);
2567
0
  }
2568
2569
0
  log_assert(!reuse || (reuse && pend));
2570
  /* if !pend but we have reuse streams, close a reuse stream
2571
   * to be able to open a new one to this target, no use waiting
2572
   * to reuse a file descriptor while another query needs to use
2573
   * that buffer and file descriptor now. */
2574
0
  if(!pend) {
2575
0
    reuse_tcp_close_oldest(sq->outnet);
2576
0
    pend = sq->outnet->tcp_free;
2577
0
    log_assert(!reuse || (pend == reuse->pending));
2578
0
  }
2579
2580
  /* allocate space to store query */
2581
0
  w = (struct waiting_tcp*)malloc(sizeof(struct waiting_tcp) 
2582
0
    + sldns_buffer_limit(packet));
2583
0
  if(!w) {
2584
0
    return NULL;
2585
0
  }
2586
0
  if(!(w->timer = comm_timer_create(sq->outnet->base, outnet_tcptimer, w))) {
2587
0
    free(w);
2588
0
    return NULL;
2589
0
  }
2590
0
  w->pkt = (uint8_t*)w + sizeof(struct waiting_tcp);
2591
0
  w->pkt_len = sldns_buffer_limit(packet);
2592
0
  memmove(w->pkt, sldns_buffer_begin(packet), w->pkt_len);
2593
0
  w->id = tcp_select_id(sq->outnet, reuse);
2594
0
  LDNS_ID_SET(w->pkt, w->id);
2595
0
  memcpy(&w->addr, &sq->addr, sq->addrlen);
2596
0
  w->addrlen = sq->addrlen;
2597
0
  w->outnet = sq->outnet;
2598
0
  w->on_tcp_waiting_list = 0;
2599
0
  w->next_waiting = NULL;
2600
0
  w->cb = callback;
2601
0
  w->cb_arg = callback_arg;
2602
0
  w->ssl_upstream = sq->ssl_upstream;
2603
0
  if(sq->tls_auth_name) {
2604
0
    w->tls_auth_name = strdup(sq->tls_auth_name);
2605
0
    if(!w->tls_auth_name) {
2606
0
      comm_timer_delete(w->timer);
2607
0
      free(w);
2608
0
      return NULL;
2609
0
    }
2610
0
  } else {
2611
0
    w->tls_auth_name = NULL;
2612
0
  }
2613
0
  w->timeout = timeout;
2614
0
  w->id_node.key = NULL;
2615
0
  w->write_wait_prev = NULL;
2616
0
  w->write_wait_next = NULL;
2617
0
  w->write_wait_queued = 0;
2618
0
  w->error_count = 0;
2619
#ifdef USE_DNSTAP
2620
  w->sq = NULL;
2621
#endif
2622
0
  w->in_cb_and_decommission = 0;
2623
0
  if(pend) {
2624
    /* we have a buffer available right now */
2625
0
    if(reuse) {
2626
0
      log_assert(reuse == &pend->reuse);
2627
      /* reuse existing fd, write query and continue */
2628
      /* store query in tree by id */
2629
0
      verbose(VERB_CLIENT, "pending_tcp_query: reuse, store");
2630
0
      w->next_waiting = (void*)pend;
2631
0
      reuse_tree_by_id_insert(&pend->reuse, w);
2632
      /* can we write right now? */
2633
0
      if(pend->query == NULL) {
2634
        /* write straight away */
2635
        /* stop the timer on read of the fd */
2636
0
        comm_point_stop_listening(pend->c);
2637
0
        pend->query = w;
2638
0
        outnet_tcp_take_query_setup(pend->c->fd, pend,
2639
0
          w);
2640
0
      } else {
2641
        /* put it in the waiting list for
2642
         * this stream */
2643
0
        reuse_write_wait_push_back(&pend->reuse, w);
2644
0
      }
2645
0
    } else {
2646
      /* create new fd and connect to addr, setup to
2647
       * write query */
2648
0
      verbose(VERB_CLIENT, "pending_tcp_query: new fd, connect");
2649
0
      rbtree_init(&pend->reuse.tree_by_id, reuse_id_cmp);
2650
0
      pend->reuse.pending = pend;
2651
0
      memcpy(&pend->reuse.addr, &sq->addr, sq->addrlen);
2652
0
      pend->reuse.addrlen = sq->addrlen;
2653
0
      if(!outnet_tcp_take_into_use(w)) {
2654
0
        waiting_tcp_delete(w);
2655
0
        return NULL;
2656
0
      }
2657
0
    }
2658
#ifdef USE_DNSTAP
2659
    if(sq->outnet->dtenv &&
2660
       (sq->outnet->dtenv->log_resolver_query_messages ||
2661
        sq->outnet->dtenv->log_forwarder_query_messages)) {
2662
      /* use w->pkt, because it has the ID value */
2663
      sldns_buffer tmp;
2664
      sldns_buffer_init_frm_data(&tmp, w->pkt, w->pkt_len);
2665
      dt_msg_send_outside_query(sq->outnet->dtenv, &sq->addr,
2666
        &pend->pi->addr, comm_tcp, NULL, sq->zone,
2667
        sq->zonelen, &tmp);
2668
    }
2669
#endif
2670
0
  } else {
2671
    /* queue up */
2672
    /* waiting for a buffer on the outside network buffer wait
2673
     * list */
2674
0
    verbose(VERB_CLIENT, "pending_tcp_query: queue to wait");
2675
#ifdef USE_DNSTAP
2676
    w->sq = sq;
2677
#endif
2678
0
    outnet_waiting_tcp_list_add(sq->outnet, w, 1);
2679
0
  }
2680
0
  return w;
2681
0
}
2682
2683
/** create query for serviced queries */
2684
static void
2685
serviced_gen_query(sldns_buffer* buff, uint8_t* qname, size_t qnamelen, 
2686
  uint16_t qtype, uint16_t qclass, uint16_t flags)
2687
0
{
2688
0
  sldns_buffer_clear(buff);
2689
  /* skip id */
2690
0
  sldns_buffer_write_u16(buff, flags);
2691
0
  sldns_buffer_write_u16(buff, 1); /* qdcount */
2692
0
  sldns_buffer_write_u16(buff, 0); /* ancount */
2693
0
  sldns_buffer_write_u16(buff, 0); /* nscount */
2694
0
  sldns_buffer_write_u16(buff, 0); /* arcount */
2695
0
  sldns_buffer_write(buff, qname, qnamelen);
2696
0
  sldns_buffer_write_u16(buff, qtype);
2697
0
  sldns_buffer_write_u16(buff, qclass);
2698
0
  sldns_buffer_flip(buff);
2699
0
}
2700
2701
/** lookup serviced query in serviced query rbtree */
2702
static struct serviced_query*
2703
lookup_serviced(struct outside_network* outnet, sldns_buffer* buff, int dnssec,
2704
  struct sockaddr_storage* addr, socklen_t addrlen,
2705
  struct edns_option* opt_list)
2706
0
{
2707
0
  struct serviced_query key;
2708
0
  key.node.key = &key;
2709
0
  key.qbuf = sldns_buffer_begin(buff);
2710
0
  key.qbuflen = sldns_buffer_limit(buff);
2711
0
  key.dnssec = dnssec;
2712
0
  memcpy(&key.addr, addr, addrlen);
2713
0
  key.addrlen = addrlen;
2714
0
  key.outnet = outnet;
2715
0
  key.opt_list = opt_list;
2716
0
  return (struct serviced_query*)rbtree_search(outnet->serviced, &key);
2717
0
}
2718
2719
void
2720
serviced_timer_cb(void* arg)
2721
0
{
2722
0
  struct serviced_query* sq = (struct serviced_query*)arg;
2723
0
  struct outside_network* outnet = sq->outnet;
2724
0
  verbose(VERB_ALGO, "serviced send timer");
2725
  /* By the time this cb is called, if we don't have any registered
2726
   * callbacks for this serviced_query anymore; do not send. */
2727
0
  if(!sq->cblist)
2728
0
    goto delete;
2729
  /* perform first network action */
2730
0
  if(outnet->do_udp && !(sq->tcp_upstream || sq->ssl_upstream)) {
2731
0
    if(!serviced_udp_send(sq, outnet->udp_buff))
2732
0
      goto delete;
2733
0
  } else {
2734
0
    if(!serviced_tcp_send(sq, outnet->udp_buff))
2735
0
      goto delete;
2736
0
  }
2737
  /* Maybe by this time we don't have callbacks attached anymore. Don't
2738
   * proactively try to delete; let it run and maybe another callback
2739
   * will get attached by the time we get an answer. */
2740
0
  return;
2741
0
delete:
2742
0
  serviced_callbacks(sq, NETEVENT_CLOSED, NULL, NULL);
2743
0
}
2744
2745
/** Create new serviced entry */
2746
static struct serviced_query*
2747
serviced_create(struct outside_network* outnet, sldns_buffer* buff, int dnssec,
2748
  int want_dnssec, int nocaps, int tcp_upstream, int ssl_upstream,
2749
  char* tls_auth_name, struct sockaddr_storage* addr, socklen_t addrlen,
2750
  uint8_t* zone, size_t zonelen, int qtype, struct edns_option* opt_list,
2751
  size_t pad_queries_block_size, struct alloc_cache* alloc,
2752
  struct regional* region)
2753
0
{
2754
0
  struct serviced_query* sq = (struct serviced_query*)malloc(sizeof(*sq));
2755
0
  struct timeval t;
2756
#ifdef UNBOUND_DEBUG
2757
  rbnode_type* ins;
2758
#endif
2759
0
  if(!sq) {
2760
0
    alloc_reg_release(alloc, region);
2761
0
    return NULL;
2762
0
  }
2763
0
  sq->node.key = sq;
2764
0
  sq->alloc = alloc;
2765
0
  sq->region = region;
2766
0
  sq->qbuf = regional_alloc_init(region, sldns_buffer_begin(buff),
2767
0
    sldns_buffer_limit(buff));
2768
0
  if(!sq->qbuf) {
2769
0
    alloc_reg_release(alloc, region);
2770
0
    free(sq);
2771
0
    return NULL;
2772
0
  }
2773
0
  sq->qbuflen = sldns_buffer_limit(buff);
2774
0
  sq->zone = regional_alloc_init(region, zone, zonelen);
2775
0
  if(!sq->zone) {
2776
0
    alloc_reg_release(alloc, region);
2777
0
    free(sq);
2778
0
    return NULL;
2779
0
  }
2780
0
  sq->zonelen = zonelen;
2781
0
  sq->qtype = qtype;
2782
0
  sq->dnssec = dnssec;
2783
0
  sq->want_dnssec = want_dnssec;
2784
0
  sq->nocaps = nocaps;
2785
0
  sq->tcp_upstream = tcp_upstream;
2786
0
  sq->ssl_upstream = ssl_upstream;
2787
0
  if(tls_auth_name) {
2788
0
    sq->tls_auth_name = regional_strdup(region, tls_auth_name);
2789
0
    if(!sq->tls_auth_name) {
2790
0
      alloc_reg_release(alloc, region);
2791
0
      free(sq);
2792
0
      return NULL;
2793
0
    }
2794
0
  } else {
2795
0
    sq->tls_auth_name = NULL;
2796
0
  }
2797
0
  memcpy(&sq->addr, addr, addrlen);
2798
0
  sq->addrlen = addrlen;
2799
0
  sq->opt_list = opt_list;
2800
0
  sq->busy = 0;
2801
0
  sq->timer = comm_timer_create(outnet->base, serviced_timer_cb, sq);
2802
0
  if(!sq->timer) {
2803
0
    alloc_reg_release(alloc, region);
2804
0
    free(sq);
2805
0
    return NULL;
2806
0
  }
2807
0
  memset(&t, 0, sizeof(t));
2808
0
  comm_timer_set(sq->timer, &t);
2809
0
  sq->outnet = outnet;
2810
0
  sq->cblist = NULL;
2811
0
  sq->pending = NULL;
2812
0
  sq->status = serviced_initial;
2813
0
  sq->retry = 0;
2814
0
  sq->to_be_deleted = 0;
2815
0
  sq->padding_block_size = pad_queries_block_size;
2816
#ifdef UNBOUND_DEBUG
2817
  ins =
2818
#else
2819
0
  (void)
2820
0
#endif
2821
0
  rbtree_insert(outnet->serviced, &sq->node);
2822
0
  log_assert(ins != NULL); /* must not be already present */
2823
0
  return sq;
2824
0
}
2825
2826
/** reuse tcp stream, remove serviced query from stream,
2827
 * return true if the stream is kept, false if it is to be closed */
2828
static int
2829
reuse_tcp_remove_serviced_keep(struct waiting_tcp* w,
2830
  struct serviced_query* sq)
2831
0
{
2832
0
  struct pending_tcp* pend_tcp = (struct pending_tcp*)w->next_waiting;
2833
0
  verbose(VERB_CLIENT, "reuse_tcp_remove_serviced_keep");
2834
  /* remove the callback. let query continue to write to not cancel
2835
   * the stream itself.  also keep it as an entry in the tree_by_id,
2836
   * in case the answer returns (that we no longer want), but we cannot
2837
   * pick the same ID number meanwhile */
2838
0
  w->cb = NULL;
2839
  /* see if can be entered in reuse tree
2840
   * for that the FD has to be non-1 */
2841
0
  if(pend_tcp->c->fd == -1) {
2842
0
    verbose(VERB_CLIENT, "reuse_tcp_remove_serviced_keep: -1 fd");
2843
0
    return 0;
2844
0
  }
2845
  /* if in tree and used by other queries */
2846
0
  if(pend_tcp->reuse.node.key) {
2847
0
    verbose(VERB_CLIENT, "reuse_tcp_remove_serviced_keep: in use by other queries");
2848
    /* do not reset the keepalive timer, for that
2849
     * we'd need traffic, and this is where the serviced is
2850
     * removed due to state machine internal reasons,
2851
     * eg. iterator no longer interested in this query */
2852
0
    return 1;
2853
0
  }
2854
  /* if still open and want to keep it open */
2855
0
  if(pend_tcp->c->fd != -1 && sq->outnet->tcp_reuse.count <
2856
0
    sq->outnet->tcp_reuse_max) {
2857
0
    verbose(VERB_CLIENT, "reuse_tcp_remove_serviced_keep: keep open");
2858
    /* set a keepalive timer on it */
2859
0
    if(!reuse_tcp_insert(sq->outnet, pend_tcp)) {
2860
0
      return 0;
2861
0
    }
2862
0
    reuse_tcp_setup_timeout(pend_tcp, sq->outnet->tcp_reuse_timeout);
2863
0
    return 1;
2864
0
  }
2865
0
  return 0;
2866
0
}
2867
2868
/** cleanup serviced query entry */
2869
static void
2870
serviced_delete(struct serviced_query* sq)
2871
0
{
2872
0
  verbose(VERB_CLIENT, "serviced_delete");
2873
0
  if(sq->pending) {
2874
    /* clear up the pending query */
2875
0
    if(sq->status == serviced_query_UDP_EDNS ||
2876
0
      sq->status == serviced_query_UDP ||
2877
0
      sq->status == serviced_query_UDP_EDNS_FRAG ||
2878
0
      sq->status == serviced_query_UDP_EDNS_fallback) {
2879
0
      struct pending* p = (struct pending*)sq->pending;
2880
0
      verbose(VERB_CLIENT, "serviced_delete: UDP");
2881
0
      if(p->pc)
2882
0
        portcomm_loweruse(sq->outnet, p->pc);
2883
0
      pending_delete(sq->outnet, p);
2884
      /* this call can cause reentrant calls back into the
2885
       * mesh */
2886
0
      outnet_send_wait_udp(sq->outnet);
2887
0
    } else {
2888
0
      struct waiting_tcp* w = (struct waiting_tcp*)
2889
0
        sq->pending;
2890
0
      verbose(VERB_CLIENT, "serviced_delete: TCP");
2891
0
      log_assert(!(w->write_wait_queued && w->on_tcp_waiting_list));
2892
      /* if on stream-write-waiting list then
2893
       * remove from waiting list and waiting_tcp_delete */
2894
0
      if(w->write_wait_queued) {
2895
0
        struct pending_tcp* pend =
2896
0
          (struct pending_tcp*)w->next_waiting;
2897
0
        verbose(VERB_CLIENT, "serviced_delete: writewait");
2898
0
        if(!w->in_cb_and_decommission)
2899
0
          reuse_tree_by_id_delete(&pend->reuse, w);
2900
0
        reuse_write_wait_remove(&pend->reuse, w);
2901
0
        if(!w->in_cb_and_decommission)
2902
0
          waiting_tcp_delete(w);
2903
0
      } else if(!w->on_tcp_waiting_list) {
2904
0
        struct pending_tcp* pend =
2905
0
          (struct pending_tcp*)w->next_waiting;
2906
0
        verbose(VERB_CLIENT, "serviced_delete: tcpreusekeep");
2907
        /* w needs to stay on tree_by_id to not assign
2908
         * the same ID; remove the callback since its
2909
         * serviced_query will be gone. */
2910
0
        w->cb = NULL;
2911
0
        if(!reuse_tcp_remove_serviced_keep(w, sq)) {
2912
0
          if(!w->in_cb_and_decommission)
2913
0
            reuse_cb_and_decommission(sq->outnet,
2914
0
              pend, NETEVENT_CLOSED);
2915
0
          use_free_buffer(sq->outnet);
2916
0
        }
2917
0
        sq->pending = NULL;
2918
0
      } else {
2919
0
        verbose(VERB_CLIENT, "serviced_delete: tcpwait");
2920
0
        outnet_waiting_tcp_list_remove(sq->outnet, w);
2921
0
        if(!w->in_cb_and_decommission)
2922
0
          waiting_tcp_delete(w);
2923
0
      }
2924
0
    }
2925
0
  }
2926
  /* does not delete from tree, caller has to do that */
2927
0
  serviced_node_del(&sq->node, NULL);
2928
0
}
2929
2930
/** perturb a dname capitalization randomly */
2931
static void
2932
serviced_perturb_qname(struct ub_randstate* rnd, uint8_t* qbuf, size_t len)
2933
0
{
2934
0
  uint8_t lablen;
2935
0
  uint8_t* d = qbuf + 10;
2936
0
  long int random = 0;
2937
0
  int bits = 0;
2938
0
  log_assert(len >= 10 + 5 /* offset qname, root, qtype, qclass */);
2939
0
  (void)len;
2940
0
  lablen = *d++;
2941
0
  while(lablen) {
2942
0
    while(lablen--) {
2943
      /* only perturb A-Z, a-z */
2944
0
      if(isalpha((unsigned char)*d)) {
2945
        /* get a random bit */  
2946
0
        if(bits == 0) {
2947
0
          random = ub_random(rnd);
2948
0
          bits = 30;
2949
0
        }
2950
0
        if((random & 0x1)) {
2951
0
          *d = (uint8_t)toupper((unsigned char)*d);
2952
0
        } else {
2953
0
          *d = (uint8_t)tolower((unsigned char)*d);
2954
0
        }
2955
0
        random >>= 1;
2956
0
        bits--;
2957
0
      }
2958
0
      d++;
2959
0
    }
2960
0
    lablen = *d++;
2961
0
  }
2962
0
  if(verbosity >= VERB_ALGO) {
2963
0
    char buf[LDNS_MAX_DOMAINLEN];
2964
0
    dname_str(qbuf+10, buf);
2965
0
    verbose(VERB_ALGO, "qname perturbed to %s", buf);
2966
0
  }
2967
0
}
2968
2969
static uint16_t
2970
0
serviced_query_udp_size(struct serviced_query* sq, enum serviced_query_status status) {
2971
0
  uint16_t udp_size;
2972
0
  if(status == serviced_query_UDP_EDNS_FRAG) {
2973
0
    if(addr_is_ip6(&sq->addr, sq->addrlen)) {
2974
0
      if(EDNS_FRAG_SIZE_IP6 < EDNS_ADVERTISED_SIZE)
2975
0
        udp_size = EDNS_FRAG_SIZE_IP6;
2976
0
      else  udp_size = EDNS_ADVERTISED_SIZE;
2977
0
    } else {
2978
0
      if(EDNS_FRAG_SIZE_IP4 < EDNS_ADVERTISED_SIZE)
2979
0
        udp_size = EDNS_FRAG_SIZE_IP4;
2980
0
      else  udp_size = EDNS_ADVERTISED_SIZE;
2981
0
    }
2982
0
  } else {
2983
0
    udp_size = EDNS_ADVERTISED_SIZE;
2984
0
  }
2985
0
  return udp_size;
2986
0
}
2987
2988
/** put serviced query into a buffer */
2989
static void
2990
serviced_encode(struct serviced_query* sq, sldns_buffer* buff, int with_edns)
2991
0
{
2992
  /* if we are using 0x20 bits for ID randomness, perturb them */
2993
0
  if(sq->outnet->use_caps_for_id && !sq->nocaps) {
2994
0
    serviced_perturb_qname(sq->outnet->rnd, sq->qbuf, sq->qbuflen);
2995
0
  }
2996
  /* generate query */
2997
0
  sldns_buffer_clear(buff);
2998
0
  sldns_buffer_write_u16(buff, 0); /* id placeholder */
2999
0
  sldns_buffer_write(buff, sq->qbuf, sq->qbuflen);
3000
0
  sldns_buffer_flip(buff);
3001
0
  if(with_edns) {
3002
    /* add edns section */
3003
0
    struct edns_data edns;
3004
0
    struct edns_option padding_option;
3005
0
    edns.edns_present = 1;
3006
0
    edns.ext_rcode = 0;
3007
0
    edns.edns_version = EDNS_ADVERTISED_VERSION;
3008
0
    edns.opt_list_in = NULL;
3009
0
    edns.opt_list_out = sq->opt_list;
3010
0
    edns.opt_list_inplace_cb_out = NULL;
3011
0
    edns.udp_size = serviced_query_udp_size(sq, sq->status);
3012
0
    edns.bits = 0;
3013
0
    if((sq->dnssec & EDNS_DO))
3014
0
      edns.bits = EDNS_DO;
3015
0
    if((sq->dnssec & BIT_CD))
3016
0
      LDNS_CD_SET(sldns_buffer_begin(buff));
3017
0
    if (sq->ssl_upstream && sq->padding_block_size) {
3018
0
      padding_option.opt_code = LDNS_EDNS_PADDING;
3019
0
      padding_option.opt_len = 0;
3020
0
      padding_option.opt_data = NULL;
3021
0
      padding_option.next = edns.opt_list_out;
3022
0
      edns.opt_list_out = &padding_option;
3023
0
      edns.padding_block_size = sq->padding_block_size;
3024
0
    }
3025
0
    attach_edns_record(buff, &edns);
3026
0
  }
3027
0
}
3028
3029
/**
3030
 * Perform serviced query UDP sending operation.
3031
 * Sends UDP with EDNS, unless infra host marked non EDNS.
3032
 * @param sq: query to send.
3033
 * @param buff: buffer scratch space.
3034
 * @return 0 on error.
3035
 */
3036
static int
3037
serviced_udp_send(struct serviced_query* sq, sldns_buffer* buff)
3038
0
{
3039
0
  int rtt, vs;
3040
0
  uint8_t edns_lame_known;
3041
0
  time_t now = *sq->outnet->now_secs;
3042
3043
0
  if(!infra_host(sq->outnet->infra, &sq->addr, sq->addrlen, sq->zone,
3044
0
    sq->zonelen, now, &vs, &edns_lame_known, &rtt))
3045
0
    return 0;
3046
0
  sq->last_rtt = rtt;
3047
0
  verbose(VERB_ALGO, "EDNS lookup known=%d vs=%d", edns_lame_known, vs);
3048
0
  if(sq->status == serviced_initial) {
3049
0
    if(vs != -1) {
3050
0
      sq->status = serviced_query_UDP_EDNS;
3051
0
    } else {   
3052
0
      sq->status = serviced_query_UDP; 
3053
0
    }
3054
0
  }
3055
0
  serviced_encode(sq, buff, (sq->status == serviced_query_UDP_EDNS) ||
3056
0
    (sq->status == serviced_query_UDP_EDNS_FRAG));
3057
0
  sq->last_sent_time = *sq->outnet->now_tv;
3058
0
  sq->edns_lame_known = (int)edns_lame_known;
3059
0
  verbose(VERB_ALGO, "serviced query UDP timeout=%d msec", rtt);
3060
0
  sq->pending = pending_udp_query(sq, buff, rtt,
3061
0
    serviced_udp_callback, sq);
3062
0
  if(!sq->pending)
3063
0
    return 0;
3064
0
  return 1;
3065
0
}
3066
3067
/** check that perturbed qname is identical */
3068
static int
3069
serviced_check_qname(sldns_buffer* pkt, uint8_t* qbuf, size_t qbuflen)
3070
0
{
3071
0
  uint8_t* d1 = sldns_buffer_begin(pkt)+12;
3072
0
  uint8_t* d2 = qbuf+10;
3073
0
  uint8_t len1, len2;
3074
0
  int count = 0;
3075
0
  if(sldns_buffer_limit(pkt) < 12+1+4) /* packet too small for qname */
3076
0
    return 0;
3077
0
  log_assert(qbuflen >= 15 /* 10 header, root, type, class */);
3078
0
  len1 = *d1++;
3079
0
  len2 = *d2++;
3080
0
  while(len1 != 0 || len2 != 0) {
3081
0
    if(LABEL_IS_PTR(len1)) {
3082
      /* check if we can read *d1 with compression ptr rest */
3083
0
      if(d1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt)))
3084
0
        return 0;
3085
0
      d1 = sldns_buffer_begin(pkt)+PTR_OFFSET(len1, *d1);
3086
      /* check if we can read the destination *d1 */
3087
0
      if(d1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt)))
3088
0
        return 0;
3089
0
      len1 = *d1++;
3090
0
      if(count++ > MAX_COMPRESS_PTRS)
3091
0
        return 0;
3092
0
      continue;
3093
0
    }
3094
0
    if(d2 > qbuf+qbuflen)
3095
0
      return 0;
3096
0
    if(len1 != len2)
3097
0
      return 0;
3098
0
    if(len1 > LDNS_MAX_LABELLEN)
3099
0
      return 0;
3100
    /* check len1 + 1(next length) are okay to read */
3101
0
    if(d1+len1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt)))
3102
0
      return 0;
3103
0
    log_assert(len1 <= LDNS_MAX_LABELLEN);
3104
0
    log_assert(len2 <= LDNS_MAX_LABELLEN);
3105
0
    log_assert(len1 == len2 && len1 != 0);
3106
    /* compare the labels - bitwise identical */
3107
0
    if(memcmp(d1, d2, len1) != 0)
3108
0
      return 0;
3109
0
    d1 += len1;
3110
0
    d2 += len2;
3111
0
    len1 = *d1++;
3112
0
    len2 = *d2++;
3113
0
  }
3114
0
  return 1;
3115
0
}
3116
3117
/** call the callbacks for a serviced query */
3118
static void
3119
serviced_callbacks(struct serviced_query* sq, int error, struct comm_point* c,
3120
  struct comm_reply* rep)
3121
0
{
3122
0
  struct service_callback* p;
3123
0
  int dobackup = (sq->cblist && sq->cblist->next); /* >1 cb*/
3124
0
  uint8_t *backup_p = NULL;
3125
0
  size_t backlen = 0;
3126
#ifdef UNBOUND_DEBUG
3127
  rbnode_type* rem =
3128
#else
3129
0
  (void)
3130
0
#endif
3131
  /* remove from tree, and schedule for deletion, so that callbacks
3132
   * can safely deregister themselves and even create new serviced
3133
   * queries that are identical to this one. */
3134
0
  rbtree_delete(sq->outnet->serviced, sq);
3135
0
  log_assert(rem); /* should have been present */
3136
0
  sq->to_be_deleted = 1; 
3137
0
  verbose(VERB_ALGO, "svcd callbacks start");
3138
0
  if(sq->outnet->use_caps_for_id && error == NETEVENT_NOERROR && c &&
3139
0
    !sq->nocaps && sq->qtype != LDNS_RR_TYPE_PTR) {
3140
    /* for type PTR do not check perturbed name in answer,
3141
     * compatibility with cisco dns guard boxes that mess up
3142
     * reverse queries 0x20 contents */
3143
    /* noerror and nxdomain must have a qname in reply */
3144
0
    if(sldns_buffer_read_u16_at(c->buffer, 4) == 0 &&
3145
0
      (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer))
3146
0
        == LDNS_RCODE_NOERROR || 
3147
0
       LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer))
3148
0
        == LDNS_RCODE_NXDOMAIN)) {
3149
0
      verbose(VERB_DETAIL, "no qname in reply to check 0x20ID");
3150
0
      log_addr(VERB_DETAIL, "from server", 
3151
0
        &sq->addr, sq->addrlen);
3152
0
      log_buf(VERB_DETAIL, "for packet", c->buffer);
3153
0
      error = NETEVENT_CLOSED;
3154
0
      c = NULL;
3155
0
    } else if(sldns_buffer_read_u16_at(c->buffer, 4) > 0 &&
3156
0
      !serviced_check_qname(c->buffer, sq->qbuf, 
3157
0
      sq->qbuflen)) {
3158
0
      verbose(VERB_DETAIL, "wrong 0x20-ID in reply qname");
3159
0
      log_addr(VERB_DETAIL, "from server", 
3160
0
        &sq->addr, sq->addrlen);
3161
0
      log_buf(VERB_DETAIL, "for packet", c->buffer);
3162
0
      error = NETEVENT_CAPSFAIL;
3163
      /* and cleanup too */
3164
0
      pkt_dname_tolower(c->buffer, 
3165
0
        sldns_buffer_at(c->buffer, 12));
3166
0
    } else {
3167
0
      verbose(VERB_ALGO, "good 0x20-ID in reply qname");
3168
      /* cleanup caps, prettier cache contents. */
3169
0
      pkt_dname_tolower(c->buffer, 
3170
0
        sldns_buffer_at(c->buffer, 12));
3171
0
    }
3172
0
  }
3173
0
  if(dobackup && c) {
3174
    /* make a backup of the query, since the querystate processing
3175
     * may send outgoing queries that overwrite the buffer.
3176
     * use secondary buffer to store the query.
3177
     * This is a data copy, but faster than packet to server */
3178
0
    backlen = sldns_buffer_limit(c->buffer);
3179
0
    backup_p = regional_alloc_init(sq->region,
3180
0
      sldns_buffer_begin(c->buffer), backlen);
3181
0
    if(!backup_p) {
3182
0
      log_err("malloc failure in serviced query callbacks");
3183
0
      error = NETEVENT_CLOSED;
3184
0
      c = NULL;
3185
0
    }
3186
0
    sq->outnet->svcd_overhead = backlen;
3187
0
  }
3188
  /* test the actual sq->cblist, because the next elem could be deleted*/
3189
0
  while((p=sq->cblist) != NULL) {
3190
0
    sq->cblist = p->next; /* remove this element */
3191
0
    if(dobackup && c) {
3192
0
      sldns_buffer_clear(c->buffer);
3193
0
      sldns_buffer_write(c->buffer, backup_p, backlen);
3194
0
      sldns_buffer_flip(c->buffer);
3195
0
    }
3196
0
    fptr_ok(fptr_whitelist_serviced_query(p->cb));
3197
0
    (void)(*p->cb)(c, p->cb_arg, error, rep);
3198
0
  }
3199
0
  if(backup_p) {
3200
0
    sq->outnet->svcd_overhead = 0;
3201
0
  }
3202
0
  verbose(VERB_ALGO, "svcd callbacks end");
3203
0
  log_assert(sq->cblist == NULL);
3204
0
  serviced_delete(sq);
3205
0
}
3206
3207
int 
3208
serviced_tcp_callback(struct comm_point* c, void* arg, int error,
3209
        struct comm_reply* rep)
3210
0
{
3211
0
  struct serviced_query* sq = (struct serviced_query*)arg;
3212
0
  struct comm_reply r2;
3213
#ifdef USE_DNSTAP
3214
  struct waiting_tcp* w = (struct waiting_tcp*)sq->pending;
3215
  struct pending_tcp* pend_tcp = NULL;
3216
  struct port_if* pi = NULL;
3217
  if(w && !w->on_tcp_waiting_list && w->next_waiting) {
3218
    pend_tcp = (struct pending_tcp*)w->next_waiting;
3219
    pi = pend_tcp->pi;
3220
  }
3221
#endif
3222
0
  sq->pending = NULL; /* removed after this callback */
3223
0
  if(error != NETEVENT_NOERROR)
3224
0
    log_addr(VERB_QUERY, "tcp error for address", 
3225
0
      &sq->addr, sq->addrlen);
3226
0
  if(error==NETEVENT_NOERROR)
3227
0
    infra_update_tcp_works(sq->outnet->infra, &sq->addr,
3228
0
      sq->addrlen, sq->zone, sq->zonelen);
3229
#ifdef USE_DNSTAP
3230
  /*
3231
   * sending src (local service)/dst (upstream) addresses over DNSTAP
3232
   */
3233
  if(error==NETEVENT_NOERROR && pi && sq->outnet->dtenv &&
3234
     (sq->outnet->dtenv->log_resolver_response_messages ||
3235
      sq->outnet->dtenv->log_forwarder_response_messages)) {
3236
    log_addr(VERB_ALGO, "response from upstream", &sq->addr, sq->addrlen);
3237
    log_addr(VERB_ALGO, "to local addr", &pi->addr, pi->addrlen);
3238
    dt_msg_send_outside_response(sq->outnet->dtenv, &sq->addr,
3239
      &pi->addr, c->type, c->ssl, sq->zone, sq->zonelen, sq->qbuf,
3240
      sq->qbuflen, &sq->last_sent_time, sq->outnet->now_tv,
3241
      c->buffer);
3242
  }
3243
#endif
3244
0
  if(error==NETEVENT_NOERROR && sq->status == serviced_query_TCP_EDNS &&
3245
0
    (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) == 
3246
0
    LDNS_RCODE_FORMERR || LDNS_RCODE_WIRE(sldns_buffer_begin(
3247
0
    c->buffer)) == LDNS_RCODE_NOTIMPL) ) {
3248
    /* attempt to fallback to nonEDNS */
3249
0
    sq->status = serviced_query_TCP_EDNS_fallback;
3250
0
    serviced_tcp_initiate(sq, c->buffer);
3251
0
    return 0;
3252
0
  } else if(error==NETEVENT_NOERROR && 
3253
0
    sq->status == serviced_query_TCP_EDNS_fallback &&
3254
0
      (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) == 
3255
0
      LDNS_RCODE_NOERROR || LDNS_RCODE_WIRE(
3256
0
      sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NXDOMAIN 
3257
0
      || LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) 
3258
0
      == LDNS_RCODE_YXDOMAIN)) {
3259
    /* the fallback produced a result that looks promising, note
3260
     * that this server should be approached without EDNS */
3261
    /* only store noEDNS in cache if domain is noDNSSEC */
3262
0
    if(!sq->want_dnssec)
3263
0
      if(!infra_edns_update(sq->outnet->infra, &sq->addr, 
3264
0
      sq->addrlen, sq->zone, sq->zonelen, -1,
3265
0
      *sq->outnet->now_secs))
3266
0
      log_err("Out of memory caching no edns for host");
3267
0
    sq->status = serviced_query_TCP;
3268
0
  }
3269
0
  if(sq->tcp_upstream || sq->ssl_upstream) {
3270
0
      struct timeval now = *sq->outnet->now_tv;
3271
0
      if(error!=NETEVENT_NOERROR) {
3272
0
          if(!infra_rtt_update(sq->outnet->infra, &sq->addr,
3273
0
        sq->addrlen, sq->zone, sq->zonelen, sq->qtype,
3274
0
        -1, sq->last_rtt, (time_t)now.tv_sec))
3275
0
        log_err("out of memory in TCP exponential backoff.");
3276
0
      } else if(now.tv_sec > sq->last_sent_time.tv_sec ||
3277
0
    (now.tv_sec == sq->last_sent_time.tv_sec &&
3278
0
    now.tv_usec > sq->last_sent_time.tv_usec)) {
3279
    /* convert from microseconds to milliseconds */
3280
0
    int roundtime = ((int)(now.tv_sec - sq->last_sent_time.tv_sec))*1000
3281
0
      + ((int)now.tv_usec - (int)sq->last_sent_time.tv_usec)/1000;
3282
0
    verbose(VERB_ALGO, "measured TCP-time at %d msec", roundtime);
3283
0
    log_assert(roundtime >= 0);
3284
    /* only store if less then AUTH_TIMEOUT seconds, it could be
3285
     * huge due to system-hibernated and we woke up */
3286
0
    if(roundtime < 60000) {
3287
0
        if(!infra_rtt_update(sq->outnet->infra, &sq->addr,
3288
0
      sq->addrlen, sq->zone, sq->zonelen, sq->qtype,
3289
0
      roundtime, sq->last_rtt, (time_t)now.tv_sec))
3290
0
      log_err("out of memory noting rtt.");
3291
0
    }
3292
0
      }
3293
0
  }
3294
  /* insert address into reply info */
3295
0
  if(!rep) {
3296
    /* create one if there isn't (on errors) */
3297
0
    rep = &r2;
3298
0
    r2.c = c;
3299
0
  }
3300
0
  memcpy(&rep->remote_addr, &sq->addr, sq->addrlen);
3301
0
  rep->remote_addrlen = sq->addrlen;
3302
0
  serviced_callbacks(sq, error, c, rep);
3303
0
  return 0;
3304
0
}
3305
3306
static void
3307
serviced_tcp_initiate(struct serviced_query* sq, sldns_buffer* buff)
3308
0
{
3309
0
  verbose(VERB_ALGO, "initiate TCP query %s", 
3310
0
    sq->status==serviced_query_TCP_EDNS?"EDNS":"");
3311
0
  serviced_encode(sq, buff, sq->status == serviced_query_TCP_EDNS);
3312
0
  sq->last_sent_time = *sq->outnet->now_tv;
3313
0
  log_assert(!sq->busy);
3314
0
  sq->busy = 1;
3315
0
  sq->pending = pending_tcp_query(sq, buff, sq->outnet->tcp_auth_query_timeout,
3316
0
    serviced_tcp_callback, sq);
3317
0
  sq->busy = 0;
3318
0
  if(!sq->pending) {
3319
    /* delete from tree so that a retry by above layer does not
3320
     * clash with this entry */
3321
0
    verbose(VERB_ALGO, "serviced_tcp_initiate: failed to send tcp query");
3322
0
    serviced_callbacks(sq, NETEVENT_CLOSED, NULL, NULL);
3323
0
  }
3324
0
}
3325
3326
/** Send serviced query over TCP return false on initial failure */
3327
static int
3328
serviced_tcp_send(struct serviced_query* sq, sldns_buffer* buff)
3329
0
{
3330
0
  int vs, rtt, timeout;
3331
0
  uint8_t edns_lame_known;
3332
0
  if(!infra_host(sq->outnet->infra, &sq->addr, sq->addrlen, sq->zone,
3333
0
    sq->zonelen, *sq->outnet->now_secs, &vs, &edns_lame_known,
3334
0
    &rtt))
3335
0
    return 0;
3336
0
  sq->last_rtt = rtt;
3337
0
  if(vs != -1)
3338
0
    sq->status = serviced_query_TCP_EDNS;
3339
0
  else  sq->status = serviced_query_TCP;
3340
0
  serviced_encode(sq, buff, sq->status == serviced_query_TCP_EDNS);
3341
0
  sq->last_sent_time = *sq->outnet->now_tv;
3342
0
  if(sq->tcp_upstream || sq->ssl_upstream) {
3343
0
    timeout = rtt;
3344
0
    if(rtt >= UNKNOWN_SERVER_NICENESS && rtt < sq->outnet->tcp_auth_query_timeout)
3345
0
      timeout = sq->outnet->tcp_auth_query_timeout;
3346
0
  } else {
3347
0
    timeout = sq->outnet->tcp_auth_query_timeout;
3348
0
  }
3349
0
  log_assert(!sq->busy);
3350
0
  sq->busy = 1;
3351
0
  sq->pending = pending_tcp_query(sq, buff, timeout,
3352
0
    serviced_tcp_callback, sq);
3353
0
  sq->busy = 0;
3354
0
  return sq->pending != NULL;
3355
0
}
3356
3357
/* see if packet is edns malformed; got zeroes at start.
3358
 * This is from servers that return malformed packets to EDNS0 queries,
3359
 * but they return good packets for nonEDNS0 queries.
3360
 * We try to detect their output; without resorting to a full parse or
3361
 * check for too many bytes after the end of the packet. */
3362
static int
3363
packet_edns_malformed(struct sldns_buffer* buf, int qtype)
3364
0
{
3365
0
  size_t len;
3366
0
  if(sldns_buffer_limit(buf) < LDNS_HEADER_SIZE)
3367
0
    return 1; /* malformed */
3368
  /* they have NOERROR rcode, 1 answer. */
3369
0
  if(LDNS_RCODE_WIRE(sldns_buffer_begin(buf)) != LDNS_RCODE_NOERROR)
3370
0
    return 0;
3371
  /* one query (to skip) and answer records */
3372
0
  if(LDNS_QDCOUNT(sldns_buffer_begin(buf)) != 1 ||
3373
0
    LDNS_ANCOUNT(sldns_buffer_begin(buf)) == 0)
3374
0
    return 0;
3375
  /* skip qname */
3376
0
  len = dname_valid(sldns_buffer_at(buf, LDNS_HEADER_SIZE),
3377
0
    sldns_buffer_limit(buf)-LDNS_HEADER_SIZE);
3378
0
  if(len == 0)
3379
0
    return 0;
3380
0
  if(len == 1 && qtype == 0)
3381
0
    return 0; /* we asked for '.' and type 0 */
3382
  /* and then 4 bytes (type and class of query) */
3383
0
  if(sldns_buffer_limit(buf) < LDNS_HEADER_SIZE + len + 4 + 3)
3384
0
    return 0;
3385
3386
  /* and start with 11 zeroes as the answer RR */
3387
  /* so check the qtype of the answer record, qname=0, type=0 */
3388
0
  if(sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[0] == 0 &&
3389
0
     sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[1] == 0 &&
3390
0
     sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[2] == 0)
3391
0
    return 1;
3392
0
  return 0;
3393
0
}
3394
3395
int 
3396
serviced_udp_callback(struct comm_point* c, void* arg, int error,
3397
        struct comm_reply* rep)
3398
0
{
3399
0
  struct serviced_query* sq = (struct serviced_query*)arg;
3400
0
  struct outside_network* outnet = sq->outnet;
3401
0
  struct timeval now = *sq->outnet->now_tv;
3402
#ifdef USE_DNSTAP
3403
  struct pending* p = (struct pending*)sq->pending;
3404
#endif
3405
3406
0
  sq->pending = NULL; /* removed after callback */
3407
0
  if(error == NETEVENT_TIMEOUT) {
3408
0
    if(sq->status == serviced_query_UDP_EDNS && sq->last_rtt < 5000 &&
3409
0
       (serviced_query_udp_size(sq, serviced_query_UDP_EDNS_FRAG) < serviced_query_udp_size(sq, serviced_query_UDP_EDNS))) {
3410
      /* fallback to 1472/1232 */
3411
0
      sq->status = serviced_query_UDP_EDNS_FRAG;
3412
0
      log_name_addr(VERB_ALGO, "try edns1xx2", sq->qbuf+10,
3413
0
        &sq->addr, sq->addrlen);
3414
0
      if(!serviced_udp_send(sq, c->buffer)) {
3415
0
        serviced_callbacks(sq, NETEVENT_CLOSED, c, rep);
3416
0
      }
3417
0
      return 0;
3418
0
    }
3419
0
    if(sq->status == serviced_query_UDP_EDNS_FRAG) {
3420
      /* fragmentation size did not fix it */
3421
0
      sq->status = serviced_query_UDP_EDNS;
3422
0
    }
3423
0
    sq->retry++;
3424
0
    if(!infra_rtt_update(outnet->infra, &sq->addr, sq->addrlen,
3425
0
      sq->zone, sq->zonelen, sq->qtype, -1, sq->last_rtt,
3426
0
      (time_t)now.tv_sec))
3427
0
      log_err("out of memory in UDP exponential backoff");
3428
0
    if(sq->retry < OUTBOUND_UDP_RETRY) {
3429
0
      log_name_addr(VERB_ALGO, "retry query", sq->qbuf+10,
3430
0
        &sq->addr, sq->addrlen);
3431
0
      if(!serviced_udp_send(sq, c->buffer)) {
3432
0
        serviced_callbacks(sq, NETEVENT_CLOSED, c, rep);
3433
0
      }
3434
0
      return 0;
3435
0
    }
3436
0
  }
3437
0
  if(error != NETEVENT_NOERROR) {
3438
    /* udp returns error (due to no ID or interface available) */
3439
0
    serviced_callbacks(sq, error, c, rep);
3440
0
    return 0;
3441
0
  }
3442
#ifdef USE_DNSTAP
3443
  /*
3444
   * sending src (local service)/dst (upstream) addresses over DNSTAP
3445
   */
3446
  if(error == NETEVENT_NOERROR && outnet->dtenv && p->pc &&
3447
    (outnet->dtenv->log_resolver_response_messages ||
3448
    outnet->dtenv->log_forwarder_response_messages)) {
3449
    log_addr(VERB_ALGO, "response from upstream", &sq->addr, sq->addrlen);
3450
    log_addr(VERB_ALGO, "to local addr", &p->pc->pif->addr,
3451
      p->pc->pif->addrlen);
3452
    dt_msg_send_outside_response(outnet->dtenv, &sq->addr,
3453
      &p->pc->pif->addr, c->type, c->ssl, sq->zone, sq->zonelen,
3454
      sq->qbuf, sq->qbuflen, &sq->last_sent_time,
3455
      sq->outnet->now_tv, c->buffer);
3456
  }
3457
#endif
3458
0
  if( (sq->status == serviced_query_UDP_EDNS 
3459
0
    ||sq->status == serviced_query_UDP_EDNS_FRAG)
3460
0
    && (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) 
3461
0
      == LDNS_RCODE_FORMERR || LDNS_RCODE_WIRE(
3462
0
      sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NOTIMPL
3463
0
        || packet_edns_malformed(c->buffer, sq->qtype)
3464
0
      )) {
3465
    /* try to get an answer by falling back without EDNS */
3466
0
    verbose(VERB_ALGO, "serviced query: attempt without EDNS");
3467
0
    sq->status = serviced_query_UDP_EDNS_fallback;
3468
0
    sq->retry = 0;
3469
0
    if(!serviced_udp_send(sq, c->buffer)) {
3470
0
      serviced_callbacks(sq, NETEVENT_CLOSED, c, rep);
3471
0
    }
3472
0
    return 0;
3473
0
  } else if(sq->status == serviced_query_UDP_EDNS && 
3474
0
    !sq->edns_lame_known) {
3475
    /* now we know that edns queries received answers store that */
3476
0
    log_addr(VERB_ALGO, "serviced query: EDNS works for",
3477
0
      &sq->addr, sq->addrlen);
3478
0
    if(!infra_edns_update(outnet->infra, &sq->addr, sq->addrlen, 
3479
0
      sq->zone, sq->zonelen, 0, (time_t)now.tv_sec)) {
3480
0
      log_err("Out of memory caching edns works");
3481
0
    }
3482
0
    sq->edns_lame_known = 1;
3483
0
  } else if(sq->status == serviced_query_UDP_EDNS_fallback &&
3484
0
    !sq->edns_lame_known && (LDNS_RCODE_WIRE(
3485
0
    sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NOERROR || 
3486
0
    LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) == 
3487
0
    LDNS_RCODE_NXDOMAIN || LDNS_RCODE_WIRE(sldns_buffer_begin(
3488
0
    c->buffer)) == LDNS_RCODE_YXDOMAIN)) {
3489
    /* the fallback produced a result that looks promising, note
3490
     * that this server should be approached without EDNS */
3491
    /* only store noEDNS in cache if domain is noDNSSEC */
3492
0
    if(!sq->want_dnssec) {
3493
0
      log_addr(VERB_ALGO, "serviced query: EDNS fails for",
3494
0
      &sq->addr, sq->addrlen);
3495
0
      if(!infra_edns_update(outnet->infra, &sq->addr, sq->addrlen,
3496
0
      sq->zone, sq->zonelen, -1, (time_t)now.tv_sec)) {
3497
0
      log_err("Out of memory caching no edns for host");
3498
0
      }
3499
0
    } else {
3500
0
      log_addr(VERB_ALGO, "serviced query: EDNS fails, but "
3501
0
      "not stored because need DNSSEC for", &sq->addr,
3502
0
      sq->addrlen);
3503
0
    }
3504
0
    sq->status = serviced_query_UDP;
3505
0
  }
3506
0
  if(now.tv_sec > sq->last_sent_time.tv_sec ||
3507
0
    (now.tv_sec == sq->last_sent_time.tv_sec &&
3508
0
    now.tv_usec > sq->last_sent_time.tv_usec)) {
3509
    /* convert from microseconds to milliseconds */
3510
0
    int roundtime = ((int)(now.tv_sec - sq->last_sent_time.tv_sec))*1000
3511
0
      + ((int)now.tv_usec - (int)sq->last_sent_time.tv_usec)/1000;
3512
0
    verbose(VERB_ALGO, "measured roundtrip at %d msec", roundtime);
3513
0
    log_assert(roundtime >= 0);
3514
    /* in case the system hibernated, do not enter a huge value,
3515
     * above this value gives trouble with server selection */
3516
0
    if(roundtime < 60000) {
3517
0
        if(!infra_rtt_update(outnet->infra, &sq->addr, sq->addrlen, 
3518
0
      sq->zone, sq->zonelen, sq->qtype, roundtime,
3519
0
      sq->last_rtt, (time_t)now.tv_sec))
3520
0
      log_err("out of memory noting rtt.");
3521
0
    }
3522
0
  }
3523
  /* perform TC flag check and TCP fallback after updating our
3524
   * cache entries for EDNS status and RTT times */
3525
0
  if(LDNS_TC_WIRE(sldns_buffer_begin(c->buffer))) {
3526
    /* fallback to TCP */
3527
    /* this discards partial UDP contents */
3528
0
    if(sq->status == serviced_query_UDP_EDNS ||
3529
0
      sq->status == serviced_query_UDP_EDNS_FRAG ||
3530
0
      sq->status == serviced_query_UDP_EDNS_fallback)
3531
      /* if we have unfinished EDNS_fallback, start again */
3532
0
      sq->status = serviced_query_TCP_EDNS;
3533
0
    else  sq->status = serviced_query_TCP;
3534
0
    serviced_tcp_initiate(sq, c->buffer);
3535
0
    return 0;
3536
0
  }
3537
  /* yay! an answer */
3538
0
  serviced_callbacks(sq, error, c, rep);
3539
0
  return 0;
3540
0
}
3541
3542
struct serviced_query* 
3543
outnet_serviced_query(struct outside_network* outnet,
3544
  struct query_info* qinfo, uint16_t flags, int dnssec, int want_dnssec,
3545
  int nocaps, int check_ratelimit, int tcp_upstream, int ssl_upstream,
3546
  char* tls_auth_name, struct sockaddr_storage* addr, socklen_t addrlen,
3547
  uint8_t* zone, size_t zonelen, struct module_qstate* qstate,
3548
  comm_point_callback_type* callback, void* callback_arg,
3549
  sldns_buffer* buff, struct module_env* env, int* was_ratelimited,
3550
  int* ratelimit_incremented)
3551
0
{
3552
0
  struct serviced_query* sq;
3553
0
  struct service_callback* cb;
3554
0
  struct edns_string_addr* client_string_addr;
3555
0
  struct regional* region;
3556
0
  struct edns_option* backed_up_opt_list = qstate->edns_opts_back_out;
3557
0
  struct edns_option* per_upstream_opt_list = NULL;
3558
0
  time_t timenow = 0;
3559
3560
  /* If we have an already populated EDNS option list make a copy since
3561
   * we may now add upstream specific EDNS options. */
3562
  /* Use a region that could be attached to a serviced_query, if it needs
3563
   * to be created. If an existing one is found then this region will be
3564
   * destroyed here. */
3565
0
  region = alloc_reg_obtain(env->alloc);
3566
0
  if(!region) return NULL;
3567
0
  if(qstate->edns_opts_back_out) {
3568
0
    per_upstream_opt_list = edns_opt_copy_region(
3569
0
      qstate->edns_opts_back_out, region);
3570
0
    if(!per_upstream_opt_list) {
3571
0
      alloc_reg_release(env->alloc, region);
3572
0
      return NULL;
3573
0
    }
3574
0
    qstate->edns_opts_back_out = per_upstream_opt_list;
3575
0
  }
3576
3577
0
  if(!inplace_cb_query_call(env, qinfo, flags, addr, addrlen, zone,
3578
0
    zonelen, qstate, region)) {
3579
0
    alloc_reg_release(env->alloc, region);
3580
0
    return NULL;
3581
0
  }
3582
  /* Restore the option list; we can explicitly use the copied one from
3583
   * now on. */
3584
0
  per_upstream_opt_list = qstate->edns_opts_back_out;
3585
0
  qstate->edns_opts_back_out = backed_up_opt_list;
3586
3587
0
  if((client_string_addr = edns_string_addr_lookup(
3588
0
    &env->edns_strings->client_strings, addr, addrlen))) {
3589
0
    edns_opt_list_append(&per_upstream_opt_list,
3590
0
      env->edns_strings->client_string_opcode,
3591
0
      client_string_addr->string_len,
3592
0
      client_string_addr->string, region);
3593
0
  }
3594
3595
0
  serviced_gen_query(buff, qinfo->qname, qinfo->qname_len, qinfo->qtype,
3596
0
    qinfo->qclass, flags);
3597
0
  sq = lookup_serviced(outnet, buff, dnssec, addr, addrlen,
3598
0
    per_upstream_opt_list);
3599
0
  if(!sq) {
3600
    /* Check ratelimit only for new serviced_query */
3601
0
    if(check_ratelimit) {
3602
0
      timenow = *env->now;
3603
0
      if(!infra_ratelimit_inc(env->infra_cache, zone,
3604
0
        zonelen, timenow, env->cfg->ratelimit_backoff,
3605
0
        &qstate->qinfo,
3606
0
        qstate->mesh_info->reply_list
3607
0
          ?&qstate->mesh_info->reply_list->query_reply
3608
0
          :NULL)) {
3609
        /* Can we pass through with slip factor? */
3610
0
        if(env->cfg->ratelimit_factor == 0 ||
3611
0
          ub_random_max(env->rnd,
3612
0
          env->cfg->ratelimit_factor) != 1) {
3613
0
          *was_ratelimited = 1;
3614
0
          alloc_reg_release(env->alloc, region);
3615
0
          return NULL;
3616
0
        }
3617
0
        log_nametypeclass(VERB_ALGO,
3618
0
          "ratelimit allowed through for "
3619
0
          "delegation point", zone,
3620
0
          LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN);
3621
0
      }
3622
0
      *ratelimit_incremented = 1;
3623
0
    }
3624
    /* make new serviced query entry */
3625
0
    sq = serviced_create(outnet, buff, dnssec, want_dnssec, nocaps,
3626
0
      tcp_upstream, ssl_upstream, tls_auth_name, addr,
3627
0
      addrlen, zone, zonelen, (int)qinfo->qtype,
3628
0
      per_upstream_opt_list,
3629
0
      ( ssl_upstream && env->cfg->pad_queries
3630
0
      ? env->cfg->pad_queries_block_size : 0 ),
3631
0
      env->alloc, region);
3632
0
    if(!sq) {
3633
0
      if(check_ratelimit) {
3634
0
        infra_ratelimit_dec(env->infra_cache,
3635
0
          zone, zonelen, timenow);
3636
0
      }
3637
0
      return NULL;
3638
0
    }
3639
0
    if(!(cb = (struct service_callback*)regional_alloc(
3640
0
      sq->region, sizeof(*cb)))) {
3641
0
      if(check_ratelimit) {
3642
0
        infra_ratelimit_dec(env->infra_cache,
3643
0
          zone, zonelen, timenow);
3644
0
      }
3645
0
      (void)rbtree_delete(outnet->serviced, sq);
3646
0
      serviced_node_del(&sq->node, NULL);
3647
0
      return NULL;
3648
0
    }
3649
    /* No network action at this point; it will be invoked with the
3650
     * serviced_query timer instead to run outside of the mesh. */
3651
0
  } else {
3652
    /* We don't need this region anymore. */
3653
0
    alloc_reg_release(env->alloc, region);
3654
    /* duplicate entries are included in the callback list, because
3655
     * there is a counterpart registration by our caller that needs
3656
     * to be doubly-removed (with callbacks perhaps). */
3657
0
    if(!(cb = (struct service_callback*)regional_alloc(
3658
0
      sq->region, sizeof(*cb)))) {
3659
0
      return NULL;
3660
0
    }
3661
0
  }
3662
  /* add callback to list of callbacks */
3663
0
  cb->cb = callback;
3664
0
  cb->cb_arg = callback_arg;
3665
0
  cb->next = sq->cblist;
3666
0
  sq->cblist = cb;
3667
0
  return sq;
3668
0
}
3669
3670
/** remove callback from list */
3671
static void
3672
callback_list_remove(struct serviced_query* sq, void* cb_arg)
3673
0
{
3674
0
  struct service_callback** pp = &sq->cblist;
3675
0
  while(*pp) {
3676
0
    if((*pp)->cb_arg == cb_arg) {
3677
0
      struct service_callback* del = *pp;
3678
0
      *pp = del->next;
3679
0
      return;
3680
0
    }
3681
0
    pp = &(*pp)->next;
3682
0
  }
3683
0
}
3684
3685
void outnet_serviced_query_stop(struct serviced_query* sq, void* cb_arg)
3686
0
{
3687
0
  if(!sq)
3688
0
    return;
3689
0
  callback_list_remove(sq, cb_arg);
3690
  /* if callbacks() routine scheduled deletion, let it do that */
3691
0
  if(!sq->cblist && !sq->busy && !sq->to_be_deleted) {
3692
0
    (void)rbtree_delete(sq->outnet->serviced, sq);
3693
0
    serviced_delete(sq);
3694
0
  }
3695
0
}
3696
3697
/** create fd to send to this destination */
3698
static int
3699
fd_for_dest(struct outside_network* outnet, struct sockaddr_storage* to_addr,
3700
  socklen_t to_addrlen)
3701
0
{
3702
0
  struct sockaddr_storage* addr;
3703
0
  socklen_t addrlen;
3704
0
  int i, try, dscp;
3705
0
  struct port_if* pif;
3706
3707
  /* create fd */
3708
0
  dscp = outnet->ip_dscp;
3709
0
  for(try = 0; try<1000; try++) {
3710
0
    int port = 0;
3711
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
3712
0
    int reused = 0;
3713
0
#endif
3714
0
    int freebind = 0;
3715
0
    int noproto = 0;
3716
0
    int inuse = 0;
3717
0
    int fd = -1;
3718
3719
    /* select interface */
3720
0
    if(addr_is_ip6(to_addr, to_addrlen)) {
3721
0
      if(outnet->num_ip6 == 0) {
3722
0
        char to[64];
3723
0
        addr_to_str(to_addr, to_addrlen, to, sizeof(to));
3724
0
        verbose(VERB_QUERY, "need ipv6 to send, but no ipv6 outgoing interfaces, for %s", to);
3725
0
        return -1;
3726
0
      }
3727
0
      i = ub_random_max(outnet->rnd, outnet->num_ip6);
3728
0
      pif = &outnet->ip6_ifs[i];
3729
0
    } else {
3730
0
      if(outnet->num_ip4 == 0) {
3731
0
        char to[64];
3732
0
        addr_to_str(to_addr, to_addrlen, to, sizeof(to));
3733
0
        verbose(VERB_QUERY, "need ipv4 to send, but no ipv4 outgoing interfaces, for %s", to);
3734
0
        return -1;
3735
0
      }
3736
0
      i = ub_random_max(outnet->rnd, outnet->num_ip4);
3737
0
      pif = &outnet->ip4_ifs[i];
3738
0
    }
3739
0
    addr = &pif->addr;
3740
0
    addrlen = pif->addrlen;
3741
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
3742
0
    if(!shared_ports_fetch_random(outnet->shared_ports,
3743
0
      pif->shpif, outnet->rnd, 0, pif->inuse,
3744
0
      &port, &reused)) {
3745
      /* try again, perhaps another interface. */
3746
0
      continue;
3747
0
    }
3748
0
    if(reused) {
3749
0
      log_assert(port < pif->inuse);
3750
0
      port = pif->out[port]->number;
3751
0
    }
3752
#else
3753
    port = 0;
3754
#endif
3755
0
    if(addr_is_ip6(to_addr, to_addrlen)) {
3756
0
      struct sockaddr_in6 sa = *(struct sockaddr_in6*)addr;
3757
0
      sa.sin6_port = (in_port_t)htons((uint16_t)port);
3758
0
      fd = create_udp_sock(AF_INET6, SOCK_DGRAM,
3759
0
        (struct sockaddr*)&sa, addrlen, 1, &inuse, &noproto,
3760
0
        0, 0, 0, NULL, 0, freebind, 0, dscp);
3761
0
    } else {
3762
0
      struct sockaddr_in* sa = (struct sockaddr_in*)addr;
3763
0
      sa->sin_port = (in_port_t)htons((uint16_t)port);
3764
0
      fd = create_udp_sock(AF_INET, SOCK_DGRAM, 
3765
0
        (struct sockaddr*)addr, addrlen, 1, &inuse, &noproto,
3766
0
        0, 0, 0, NULL, 0, freebind, 0, dscp);
3767
0
    }
3768
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
3769
0
    if(!reused) {
3770
      /* Return the port to the pool, since the caller does
3771
       * not keep track of it, also have done fd, and bind. */
3772
0
      shared_ports_return_port(outnet->shared_ports,
3773
0
        pif->shpif, port);
3774
0
    }
3775
0
#endif
3776
0
    if(fd != -1) {
3777
0
      return fd;
3778
0
    }
3779
0
    if(!inuse) {
3780
0
      return -1;
3781
0
    }
3782
0
  }
3783
  /* too many tries */
3784
0
  log_err("cannot send probe, ports are in use");
3785
0
  return -1;
3786
0
}
3787
3788
struct comm_point*
3789
outnet_comm_point_for_udp(struct outside_network* outnet,
3790
  comm_point_callback_type* cb, void* cb_arg,
3791
  struct sockaddr_storage* to_addr, socklen_t to_addrlen)
3792
0
{
3793
0
  struct comm_point* cp;
3794
0
  int fd = fd_for_dest(outnet, to_addr, to_addrlen);
3795
0
  if(fd == -1) {
3796
0
    return NULL;
3797
0
  }
3798
0
  cp = comm_point_create_udp(outnet->base, fd, outnet->udp_buff, 0,
3799
0
    cb, cb_arg, NULL);
3800
0
  if(!cp) {
3801
0
    log_err("malloc failure");
3802
0
    close(fd);
3803
0
    return NULL;
3804
0
  }
3805
0
  return cp;
3806
0
}
3807
3808
/** setup SSL for comm point */
3809
static int
3810
setup_comm_ssl(struct comm_point* cp, struct outside_network* outnet,
3811
  int fd, char* host)
3812
0
{
3813
0
  cp->ssl = outgoing_ssl_fd(outnet->sslctx, fd);
3814
0
  if(!cp->ssl) {
3815
0
    log_err("cannot create SSL object");
3816
0
    return 0;
3817
0
  }
3818
#ifdef USE_WINSOCK
3819
  comm_point_tcp_win_bio_cb(cp, cp->ssl);
3820
#endif
3821
0
  cp->ssl_shake_state = comm_ssl_shake_write;
3822
  /* https verification */
3823
0
#ifdef HAVE_SSL
3824
0
  if(outnet->tls_use_sni) {
3825
0
    (void)SSL_set_tlsext_host_name(cp->ssl, host);
3826
0
  }
3827
0
#endif
3828
#ifdef HAVE_SSL_SET1_DNSNAME
3829
  if((SSL_CTX_get_verify_mode(outnet->sslctx)&SSL_VERIFY_PEER)) {
3830
    /* because we set SSL_VERIFY_PEER, in netevent in
3831
     * ssl_handshake, it'll check if the certificate
3832
     * verification has succeeded */
3833
    /* SSL_VERIFY_PEER is set on the sslctx */
3834
    /* and the certificates to verify with are loaded into
3835
     * it with SSL_load_verify_locations or
3836
     * SSL_CTX_set_default_verify_paths */
3837
    /* setting the hostname makes openssl verify the
3838
     * host name in the x509 certificate in the
3839
     * SSL connection*/
3840
    struct sockaddr_storage tmpaddr;
3841
    socklen_t tmpaddrlen = (socklen_t)sizeof(tmpaddr);
3842
    if(ipstrtoaddr(host, UNBOUND_DNS_PORT, &tmpaddr, &tmpaddrlen)) {
3843
      if(!SSL_set1_ipaddr(cp->ssl, host)) {
3844
        log_err("SSL_set1_ipaddr failed");
3845
        return 0;
3846
      }
3847
    } else {
3848
      if(!SSL_set1_dnsname(cp->ssl, host)) {
3849
        log_err("SSL_set1_dnsname failed");
3850
        return 0;
3851
      }
3852
    }
3853
  }
3854
#elif defined(HAVE_SSL_SET1_HOST)
3855
0
  if((SSL_CTX_get_verify_mode(outnet->sslctx)&SSL_VERIFY_PEER)) {
3856
    /* because we set SSL_VERIFY_PEER, in netevent in
3857
     * ssl_handshake, it'll check if the certificate
3858
     * verification has succeeded */
3859
    /* SSL_VERIFY_PEER is set on the sslctx */
3860
    /* and the certificates to verify with are loaded into
3861
     * it with SSL_load_verify_locations or
3862
     * SSL_CTX_set_default_verify_paths */
3863
    /* setting the hostname makes openssl verify the
3864
     * host name in the x509 certificate in the
3865
     * SSL connection*/
3866
0
    if(!SSL_set1_host(cp->ssl, host)) {
3867
0
      log_err("SSL_set1_host failed");
3868
0
      return 0;
3869
0
    }
3870
0
  }
3871
#elif defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
3872
  /* openssl 1.0.2 has this function that can be used for
3873
   * set1_host like verification */
3874
  if((SSL_CTX_get_verify_mode(outnet->sslctx)&SSL_VERIFY_PEER)) {
3875
    X509_VERIFY_PARAM* param = SSL_get0_param(cp->ssl);
3876
#  ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
3877
    X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
3878
#  endif
3879
    if(!X509_VERIFY_PARAM_set1_host(param, host, strlen(host))) {
3880
      log_err("X509_VERIFY_PARAM_set1_host failed");
3881
      return 0;
3882
    }
3883
  }
3884
#else
3885
  (void)host;
3886
#endif /* HAVE_SSL_SET1_HOST */
3887
0
  return 1;
3888
0
}
3889
3890
struct comm_point*
3891
outnet_comm_point_for_tcp(struct outside_network* outnet,
3892
  comm_point_callback_type* cb, void* cb_arg,
3893
  struct sockaddr_storage* to_addr, socklen_t to_addrlen,
3894
  sldns_buffer* query, int timeout, int ssl, char* host)
3895
0
{
3896
0
  struct comm_point* cp;
3897
0
  int fd = outnet_get_tcp_fd(to_addr, to_addrlen, outnet->tcp_mss,
3898
0
    outnet->ip_dscp, ssl);
3899
0
  if(fd == -1) {
3900
0
    return 0;
3901
0
  }
3902
0
  fd_set_nonblock(fd);
3903
0
  if(!outnet_tcp_connect(fd, to_addr, to_addrlen)) {
3904
    /* outnet_tcp_connect has closed fd on error for us */
3905
0
    return 0;
3906
0
  }
3907
0
  cp = comm_point_create_tcp_out(outnet->base, 65552, cb, cb_arg);
3908
0
  if(!cp) {
3909
0
    log_err("malloc failure");
3910
0
    close(fd);
3911
0
    return 0;
3912
0
  }
3913
0
  cp->repinfo.remote_addrlen = to_addrlen;
3914
0
  memcpy(&cp->repinfo.remote_addr, to_addr, to_addrlen);
3915
3916
  /* setup for SSL (if needed) */
3917
0
  if(ssl) {
3918
0
    if(!setup_comm_ssl(cp, outnet, fd, host)) {
3919
0
      log_err("cannot setup XoT");
3920
0
      comm_point_delete(cp);
3921
0
      return NULL;
3922
0
    }
3923
0
  }
3924
3925
  /* set timeout on TCP connection */
3926
0
  comm_point_start_listening(cp, fd, timeout);
3927
  /* copy scratch buffer to cp->buffer */
3928
0
  sldns_buffer_copy(cp->buffer, query);
3929
0
  return cp;
3930
0
}
3931
3932
/** setup the User-Agent HTTP header based on http-user-agent configuration */
3933
static void
3934
setup_http_user_agent(sldns_buffer* buf, struct config_file* cfg)
3935
0
{
3936
0
  if(cfg->hide_http_user_agent) return;
3937
0
  if(cfg->http_user_agent==NULL || cfg->http_user_agent[0] == 0) {
3938
0
    sldns_buffer_printf(buf, "User-Agent: %s/%s\r\n", PACKAGE_NAME,
3939
0
      PACKAGE_VERSION);
3940
0
  } else {
3941
0
    sldns_buffer_printf(buf, "User-Agent: %s\r\n", cfg->http_user_agent);
3942
0
  }
3943
0
}
3944
3945
/** setup http request headers in buffer for sending query to destination */
3946
static int
3947
setup_http_request(sldns_buffer* buf, char* host, char* path,
3948
  struct config_file* cfg, const char* etag)
3949
0
{
3950
0
  sldns_buffer_clear(buf);
3951
0
  sldns_buffer_printf(buf, "GET /%s HTTP/1.1\r\n", path);
3952
0
  sldns_buffer_printf(buf, "Host: %s\r\n", host);
3953
0
  if (etag) {
3954
0
    verbose(VERB_ALGO, "sending along ETag %s in http request", etag);
3955
0
    sldns_buffer_printf(buf, "If-None-Match: %s\r\n", etag);
3956
0
  }
3957
0
  setup_http_user_agent(buf, cfg);
3958
  /* We do not really do multiple queries per connection,
3959
   * but this header setting is also not needed.
3960
   * sldns_buffer_printf(buf, "Connection: close\r\n") */
3961
0
  sldns_buffer_printf(buf, "\r\n");
3962
0
  if(sldns_buffer_position(buf)+10 > sldns_buffer_capacity(buf))
3963
0
    return 0; /* somehow buffer too short, but it is about 60K
3964
    and the request is only a couple bytes long. */
3965
0
  sldns_buffer_flip(buf);
3966
0
  return 1;
3967
0
}
3968
3969
struct comm_point*
3970
outnet_comm_point_for_http(struct outside_network* outnet,
3971
  comm_point_callback_type* cb, void* cb_arg,
3972
  struct sockaddr_storage* to_addr, socklen_t to_addrlen, int timeout,
3973
  int ssl, char* host, char* path, struct config_file* cfg, char* etag)
3974
0
{
3975
  /* cp calls cb with err=NETEVENT_DONE when transfer is done */
3976
0
  struct comm_point* cp;
3977
0
  int fd = outnet_get_tcp_fd(to_addr, to_addrlen, outnet->tcp_mss,
3978
0
    outnet->ip_dscp, ssl);
3979
0
  if(fd == -1) {
3980
0
    return 0;
3981
0
  }
3982
0
  fd_set_nonblock(fd);
3983
0
  if(!outnet_tcp_connect(fd, to_addr, to_addrlen)) {
3984
    /* outnet_tcp_connect has closed fd on error for us */
3985
0
    return 0;
3986
0
  }
3987
0
  cp = comm_point_create_http_out(outnet->base,
3988
0
    sldns_buffer_capacity(outnet->udp_buff), cb, cb_arg,
3989
0
    outnet->udp_buff);
3990
0
  if(!cp) {
3991
0
    log_err("malloc failure");
3992
0
    close(fd);
3993
0
    return 0;
3994
0
  }
3995
0
  cp->repinfo.remote_addrlen = to_addrlen;
3996
0
  memcpy(&cp->repinfo.remote_addr, to_addr, to_addrlen);
3997
3998
  /* setup for SSL (if needed) */
3999
0
  if(ssl) {
4000
0
    if(!setup_comm_ssl(cp, outnet, fd, host)) {
4001
0
      log_err("cannot setup https");
4002
0
      comm_point_delete(cp);
4003
0
      return NULL;
4004
0
    }
4005
0
  }
4006
4007
  /* set timeout on TCP connection */
4008
0
  comm_point_start_listening(cp, fd, timeout);
4009
4010
  /* setup http request in cp->buffer */
4011
0
  if(!setup_http_request(cp->buffer, host, path, cfg, etag)) {
4012
0
    log_err("error setting up http request");
4013
0
    comm_point_delete(cp);
4014
0
    return NULL;
4015
0
  }
4016
0
  return cp;
4017
0
}
4018
4019
/** get memory used by waiting tcp entry (in use or not) */
4020
static size_t
4021
waiting_tcp_get_mem(struct waiting_tcp* w)
4022
0
{
4023
0
  size_t s;
4024
0
  if(!w) return 0;
4025
0
  s = sizeof(*w) + w->pkt_len;
4026
0
  if(w->timer)
4027
0
    s += comm_timer_get_mem(w->timer);
4028
0
  return s;
4029
0
}
4030
4031
/** get memory used by port if */
4032
static size_t
4033
if_get_mem(struct port_if* pif)
4034
0
{
4035
0
  size_t s;
4036
0
  int i;
4037
0
  s = sizeof(*pif) + sizeof(struct port_comm*)*pif->maxout;
4038
0
  for(i=0; i<pif->inuse; i++)
4039
0
    s += sizeof(*pif->out[i]) + 
4040
0
      comm_point_get_mem(pif->out[i]->cp);
4041
0
  return s;
4042
0
}
4043
4044
/** get memory used by waiting udp */
4045
static size_t
4046
waiting_udp_get_mem(struct pending* w)
4047
0
{
4048
0
  size_t s;
4049
0
  s = sizeof(*w) + comm_timer_get_mem(w->timer) + w->pkt_len;
4050
0
  return s;
4051
0
}
4052
4053
size_t outnet_get_mem(struct outside_network* outnet)
4054
0
{
4055
0
  size_t i;
4056
0
  int k;
4057
0
  struct waiting_tcp* w;
4058
0
  struct pending* u;
4059
0
  struct serviced_query* sq;
4060
0
  struct service_callback* sb;
4061
0
  struct port_comm* pc;
4062
0
  size_t s = sizeof(*outnet) + sizeof(*outnet->base) + 
4063
0
    sizeof(*outnet->udp_buff) + 
4064
0
    sldns_buffer_capacity(outnet->udp_buff);
4065
  /* second buffer is not ours */
4066
0
  for(pc = outnet->unused_fds; pc; pc = pc->next) {
4067
0
    s += sizeof(*pc) + comm_point_get_mem(pc->cp);
4068
0
  }
4069
0
  for(k=0; k<outnet->num_ip4; k++)
4070
0
    s += if_get_mem(&outnet->ip4_ifs[k]);
4071
0
  for(k=0; k<outnet->num_ip6; k++)
4072
0
    s += if_get_mem(&outnet->ip6_ifs[k]);
4073
0
  for(u=outnet->udp_wait_first; u; u=u->next_waiting)
4074
0
    s += waiting_udp_get_mem(u);
4075
  
4076
0
  s += sizeof(struct pending_tcp*)*outnet->num_tcp;
4077
0
  for(i=0; i<outnet->num_tcp; i++) {
4078
0
    s += sizeof(struct pending_tcp);
4079
0
    s += comm_point_get_mem(outnet->tcp_conns[i]->c);
4080
0
    if(outnet->tcp_conns[i]->query)
4081
0
      s += waiting_tcp_get_mem(outnet->tcp_conns[i]->query);
4082
0
  }
4083
0
  for(w=outnet->tcp_wait_first; w; w = w->next_waiting)
4084
0
    s += waiting_tcp_get_mem(w);
4085
0
  s += sizeof(*outnet->pending);
4086
0
  s += (sizeof(struct pending) + comm_timer_get_mem(NULL)) * 
4087
0
    outnet->pending->count;
4088
0
  s += sizeof(*outnet->serviced);
4089
0
  s += outnet->svcd_overhead;
4090
0
  RBTREE_FOR(sq, struct serviced_query*, outnet->serviced) {
4091
0
    s += sizeof(*sq) + sq->qbuflen;
4092
0
    for(sb = sq->cblist; sb; sb = sb->next)
4093
0
      s += sizeof(*sb);
4094
0
  }
4095
0
  return s;
4096
0
}
4097
4098
size_t 
4099
serviced_get_mem(struct serviced_query* sq)
4100
0
{
4101
0
  struct service_callback* sb;
4102
0
  size_t s;
4103
0
  s = sizeof(*sq) + sq->qbuflen;
4104
0
  for(sb = sq->cblist; sb; sb = sb->next)
4105
0
    s += sizeof(*sb);
4106
0
  if(sq->status == serviced_query_UDP_EDNS ||
4107
0
    sq->status == serviced_query_UDP ||
4108
0
    sq->status == serviced_query_UDP_EDNS_FRAG ||
4109
0
    sq->status == serviced_query_UDP_EDNS_fallback) {
4110
0
    s += sizeof(struct pending);
4111
0
    s += comm_timer_get_mem(NULL);
4112
0
  } else {
4113
    /* does not have size of the pkt pointer */
4114
    /* always has a timer except on malloc failures */
4115
4116
    /* these sizes are part of the main outside network mem */
4117
    /*
4118
    s += sizeof(struct waiting_tcp);
4119
    s += comm_timer_get_mem(NULL);
4120
    */
4121
0
  }
4122
0
  return s;
4123
0
}
4124
4125
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
4126
/** Setup shared port interface */
4127
static int shared_ports_setup_if(struct shared_ports_if* shpif, char* str,
4128
  int* availports, int numavailports)
4129
0
{
4130
0
  shpif->avail_ports = (int*)memdup(availports,
4131
0
    (size_t)numavailports*sizeof(int));
4132
0
  if(!shpif->avail_ports)
4133
0
    return 0;
4134
0
  shpif->avail_total = numavailports;
4135
0
  shpif->inuse = 0;
4136
0
  shpif->pfxlen = 0;
4137
0
  if(!ipstrtoaddr(str, UNBOUND_DNS_PORT, &shpif->addr, &shpif->addrlen) &&
4138
0
     !netblockstrtoaddr(str, UNBOUND_DNS_PORT, &shpif->addr,
4139
0
     &shpif->addrlen, &shpif->pfxlen))
4140
0
    return 0;
4141
0
  return 1;
4142
0
}
4143
#endif
4144
4145
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
4146
/** Allocate shared ports interfaces */
4147
static int shared_ports_alloc_ifs(struct shared_ports* shp, char** ifs,
4148
  int num_ifs, int do_ip4, int do_ip6, int* availports,
4149
  int numavailports)
4150
0
{
4151
#ifndef INET6
4152
  do_ip6 = 0;
4153
#endif
4154
0
  calc_num46(ifs, num_ifs, do_ip4, do_ip6,
4155
0
    &shp->num_ip4, &shp->num_ip6);
4156
0
  if(shp->num_ip4 != 0) {
4157
0
    if(!(shp->ip4_ifs = (struct shared_ports_if*)calloc(
4158
0
      (size_t)shp->num_ip4,
4159
0
      sizeof(struct shared_ports_if))))
4160
0
      return 0;
4161
0
  }
4162
0
  if(shp->num_ip6 != 0) {
4163
0
    if(!(shp->ip6_ifs = (struct shared_ports_if*)calloc(
4164
0
      (size_t)shp->num_ip6,
4165
0
      sizeof(struct shared_ports_if))))
4166
0
      return 0;
4167
0
  }
4168
0
  if(num_ifs == 0) {
4169
0
    if(do_ip4 && !shared_ports_setup_if(&shp->ip4_ifs[0],
4170
0
      "0.0.0.0", availports, numavailports))
4171
0
      return 0;
4172
0
    if(do_ip6 && !shared_ports_setup_if(&shp->ip6_ifs[0],
4173
0
      "::", availports, numavailports))
4174
0
      return 0;
4175
0
  } else {
4176
0
    size_t done_4 = 0, done_6 = 0;
4177
0
    int i;
4178
0
    for(i=0; i<num_ifs; i++) {
4179
0
      if(str_is_ip6(ifs[i]) && do_ip6 &&
4180
0
        (int)done_6 < shp->num_ip6) {
4181
0
        if(!shared_ports_setup_if(&shp->ip6_ifs[done_6],
4182
0
          ifs[i], availports, numavailports))
4183
0
          return 0;
4184
0
        done_6++;
4185
0
      }
4186
0
      if(!str_is_ip6(ifs[i]) && do_ip4 &&
4187
0
        (int)done_4 < shp->num_ip4) {
4188
0
        if(!shared_ports_setup_if(&shp->ip4_ifs[done_4],
4189
0
          ifs[i], availports, numavailports))
4190
0
          return 0;
4191
0
        done_4++;
4192
0
      }
4193
0
    }
4194
0
  }
4195
0
  return 1;
4196
0
}
4197
#endif
4198
4199
struct shared_ports* shared_ports_create(char** ifs, int num_ifs, int do_ip4,
4200
  int do_ip6, int* availports, int numavailports)
4201
0
{
4202
0
  struct shared_ports* shp = calloc(1, sizeof(*shp));
4203
0
  if(!shp) {
4204
0
    log_err("malloc failed");
4205
0
    return NULL;
4206
0
  }
4207
0
  lock_basic_init(&shp->lock);
4208
0
  lock_protect(&shp->lock, &shp->ip4_ifs, sizeof(shp->ip4_ifs));
4209
0
  lock_protect(&shp->lock, &shp->num_ip4, sizeof(shp->num_ip4));
4210
0
  lock_protect(&shp->lock, &shp->ip6_ifs, sizeof(shp->ip6_ifs));
4211
0
  lock_protect(&shp->lock, &shp->num_ip6, sizeof(shp->num_ip6));
4212
4213
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
4214
  /* Allocate interfaces */
4215
0
  lock_basic_lock(&shp->lock);
4216
0
  if(!shared_ports_alloc_ifs(shp, ifs, num_ifs, do_ip4, do_ip6,
4217
0
    availports, numavailports)) {
4218
0
    log_err("malloc failed");
4219
0
    shared_ports_delete(shp);
4220
0
    return NULL;
4221
0
  }
4222
0
  lock_basic_unlock(&shp->lock);
4223
#else
4224
  (void)ifs; (void)num_ifs; (void)do_ip4; (void)do_ip6;
4225
  (void)availports; (void)numavailports;
4226
#endif
4227
0
  return shp;
4228
0
}
4229
4230
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
4231
/** Delete shared ports interface structure */
4232
static void shared_ports_if_delete(struct shared_ports_if* shpif)
4233
0
{
4234
0
  if(!shpif)
4235
0
    return;
4236
0
  free(shpif->avail_ports);
4237
0
}
4238
#endif
4239
4240
void shared_ports_delete(struct shared_ports* shp)
4241
0
{
4242
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
4243
0
  int i;
4244
0
#endif
4245
0
  if(!shp)
4246
0
    return;
4247
0
  lock_basic_destroy(&shp->lock);
4248
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
4249
0
  for(i=0; i<shp->num_ip4; i++) {
4250
0
    shared_ports_if_delete(&shp->ip4_ifs[i]);
4251
0
  }
4252
0
  free(shp->ip4_ifs);
4253
0
  for(i=0; i<shp->num_ip6; i++) {
4254
0
    shared_ports_if_delete(&shp->ip6_ifs[i]);
4255
0
  }
4256
0
  free(shp->ip6_ifs);
4257
0
#endif
4258
0
  free(shp);
4259
0
}
4260
4261
struct shared_ports_if* shared_ports_find_if(struct shared_ports* shp,
4262
  struct sockaddr_storage* addr, socklen_t addrlen, int pfxlen)
4263
0
{
4264
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
4265
0
  struct shared_ports_if* ret, *ifs = NULL;
4266
0
  int i, num_ifs = 0;
4267
0
  lock_basic_lock(&shp->lock);
4268
0
  if(addr_is_ip6(addr, addrlen)) {
4269
0
    ifs = shp->ip6_ifs;
4270
0
    num_ifs = shp->num_ip6;
4271
0
  } else {
4272
0
    ifs = shp->ip4_ifs;
4273
0
    num_ifs = shp->num_ip4;
4274
0
  }
4275
0
  for(i=0; i<num_ifs; i++) {
4276
0
    if(sockaddr_cmp(addr, addrlen, &ifs[i].addr,
4277
0
      ifs[i].addrlen) == 0
4278
0
      && pfxlen == ifs[i].pfxlen) {
4279
0
      ret = &ifs[i];
4280
0
      lock_basic_unlock(&shp->lock);
4281
0
      return ret;
4282
0
    }
4283
0
  }
4284
0
  lock_basic_unlock(&shp->lock);
4285
0
  return NULL;
4286
#else
4287
  (void)shp; (void)addr; (void)addrlen; (void)pfxlen;
4288
  return NULL;
4289
#endif
4290
0
}
4291
4292
int shared_ports_fetch_random(struct shared_ports* shp,
4293
  struct shared_ports_if* shpif, struct ub_randstate* rnd,
4294
  int udp_connect, int reusenum, int* port, int* reused)
4295
0
{
4296
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
4297
0
  int portno = 0, my_port = 0;
4298
0
  if(!shpif)
4299
0
    return 0;
4300
#  ifdef THREADS_DISABLED
4301
  (void)shp;
4302
#  endif
4303
0
  lock_basic_lock(&shp->lock);
4304
0
  if(udp_connect) {
4305
    /* if we connect() we cannot reuse fds for a port. */
4306
0
    if(shpif->inuse >= shpif->avail_total) {
4307
0
      lock_basic_unlock(&shp->lock);
4308
0
      return 0;
4309
0
    }
4310
0
    my_port = ub_random_max(rnd,
4311
0
      shpif->avail_total - shpif->inuse);
4312
0
  } else {
4313
    /* select from free ports and open ports on this thread. */
4314
0
    if(shpif->inuse >= shpif->avail_total) {
4315
0
      lock_basic_unlock(&shp->lock);
4316
0
      if(reusenum == 0) {
4317
0
        return 0;
4318
0
      }
4319
0
      my_port = ub_random_max(rnd, reusenum);
4320
0
      *port = my_port;
4321
0
      *reused = 1;
4322
0
      return 1;
4323
0
    }
4324
0
    my_port = ub_random_max(rnd, shpif->avail_total - shpif->inuse
4325
0
      + reusenum);
4326
0
    if(my_port < reusenum) {
4327
      /* port already open */
4328
0
      lock_basic_unlock(&shp->lock);
4329
0
      *port = my_port;
4330
0
      *reused = 1;
4331
0
      return 1;
4332
0
    }
4333
0
    my_port -= reusenum;
4334
0
  }
4335
0
  log_assert(shpif->inuse < shpif->avail_total);
4336
0
  log_assert(my_port >= 0 && my_port < shpif->avail_total);
4337
0
  portno = shpif->avail_ports[my_port];
4338
0
  shpif->avail_ports[my_port] =
4339
0
    shpif->avail_ports[shpif->avail_total-shpif->inuse-1];
4340
0
  shpif->inuse++;
4341
0
  lock_basic_unlock(&shp->lock);
4342
0
  *port = portno;
4343
0
  *reused = 0;
4344
0
  return 1;
4345
#else
4346
  (void)shp; (void)shpif; (void)rnd; (void)udp_connect;
4347
  (void)reusenum;
4348
  *port = 0;
4349
  *reused = 0;
4350
  return 1;
4351
#endif
4352
0
}
4353
4354
void shared_ports_return_port(struct shared_ports* shp,
4355
  struct shared_ports_if* shpif, int port)
4356
0
{
4357
0
#ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
4358
0
  if(!shpif)
4359
0
    return;
4360
#  ifdef THREADS_DISABLED
4361
  (void)shp;
4362
#  endif
4363
0
  lock_basic_lock(&shp->lock);
4364
0
  log_assert(shpif->inuse > 0);
4365
0
  shpif->avail_ports[shpif->avail_total - shpif->inuse] = port;
4366
0
  shpif->inuse--;
4367
0
  lock_basic_unlock(&shp->lock);
4368
#else
4369
  (void)shp; (void)shpif; (void)port;
4370
#endif
4371
0
}