Use existing temporary variable conn.
[radsecproxy.git] / dtls.c
1 /*
2  * Copyright (C) 2008-2009 Stig Venaas <venaas@uninett.no>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  */
8
9 #include <signal.h>
10 #include <sys/socket.h>
11 #include <netinet/in.h>
12 #include <netdb.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <limits.h>
16 #ifdef SYS_SOLARIS9
17 #include <fcntl.h>
18 #endif
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <sys/select.h>
22 #include <ctype.h>
23 #include <sys/wait.h>
24 #include <arpa/inet.h>
25 #include <regex.h>
26 #include <pthread.h>
27 #include <openssl/ssl.h>
28 #include <openssl/err.h>
29 #include "list.h"
30 #include "hash.h"
31 #include "radsecproxy.h"
32
33 #ifdef RADPROT_DTLS
34 #include "debug.h"
35 #include "util.h"
36 #include "hostport.h"
37
38 static void setprotoopts(struct commonprotoopts *opts);
39 static char **getlistenerargs();
40 void *udpdtlsserverrd(void *arg);
41 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
42 void *dtlsclientrd(void *arg);
43 int clientradputdtls(struct server *server, unsigned char *rad);
44 void addserverextradtls(struct clsrvconf *conf);
45 void dtlssetsrcres();
46 void initextradtls();
47
48 static const struct protodefs protodefs = {
49     "dtls",
50     "mysecret", /* secretdefault */
51     SOCK_DGRAM, /* socktype */
52     "2083", /* portdefault */
53     REQUEST_RETRY_COUNT, /* retrycountdefault */
54     10, /* retrycountmax */
55     REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
56     60, /* retryintervalmax */
57     DUPLICATE_INTERVAL, /* duplicateintervaldefault */
58     setprotoopts, /* setprotoopts */
59     getlistenerargs, /* getlistenerargs */
60     udpdtlsserverrd, /* listener */
61     dtlsconnect, /* connecter */
62     dtlsclientrd, /* clientconnreader */
63     clientradputdtls, /* clientradput */
64     NULL, /* addclient */
65     addserverextradtls, /* addserverextra */
66     dtlssetsrcres, /* setsrcres */
67     initextradtls /* initextra */
68 };
69
70 static int client4_sock = -1;
71 static int client6_sock = -1;
72 static struct addrinfo *srcres = NULL;
73 static uint8_t handle;
74 static struct commonprotoopts *protoopts = NULL;
75
76 const struct protodefs *dtlsinit(uint8_t h) {
77     handle = h;
78     return &protodefs;
79 }
80
81 static void setprotoopts(struct commonprotoopts *opts) {
82     protoopts = opts;
83 }
84
85 static char **getlistenerargs() {
86     return protoopts ? protoopts->listenargs : NULL;
87 }
88
89 struct sessioncacheentry {
90     pthread_mutex_t mutex;
91     struct gqueue *rbios;
92     struct timeval expiry;
93 };
94
95 struct dtlsservernewparams {
96     struct sessioncacheentry *sesscache;
97     int sock;
98     struct sockaddr_storage addr;
99 };
100
101 void dtlssetsrcres() {
102     if (!srcres)
103         srcres = resolvepassiveaddrinfo(protoopts ? protoopts->sourcearg : NULL, NULL, protodefs.socktype);
104 }
105
106 int udp2bio(int s, struct gqueue *q, int cnt) {
107     unsigned char *buf;
108     BIO *rbio;
109
110     if (cnt < 1)
111         return 0;
112
113     buf = malloc(cnt);
114     if (!buf) {
115         unsigned char err;
116         debug(DBG_ERR, "udp2bio: malloc failed");
117         recv(s, &err, 1, 0);
118         return 0;
119     }
120
121     cnt = recv(s, buf, cnt, 0);
122     if (cnt < 1) {
123         debug(DBG_WARN, "udp2bio: recv failed");
124         free(buf);
125         return 0;
126     }
127
128     rbio = BIO_new_mem_buf(buf, cnt);
129     BIO_set_mem_eof_return(rbio, -1);
130
131     pthread_mutex_lock(&q->mutex);
132     if (!list_push(q->entries, rbio)) {
133         BIO_free(rbio);
134         pthread_mutex_unlock(&q->mutex);
135         return 0;
136     }
137     pthread_cond_signal(&q->cond);
138     pthread_mutex_unlock(&q->mutex);
139     return 1;
140 }
141
142 BIO *getrbio(SSL *ssl, struct gqueue *q, int timeout) {
143     BIO *rbio;
144     struct timeval now;
145     struct timespec to;
146
147     pthread_mutex_lock(&q->mutex);
148     if (!(rbio = (BIO *)list_shift(q->entries))) {
149         if (timeout) {
150             gettimeofday(&now, NULL);
151             memset(&to, 0, sizeof(struct timespec));
152             to.tv_sec = now.tv_sec + timeout;
153             pthread_cond_timedwait(&q->cond, &q->mutex, &to);
154         } else
155             pthread_cond_wait(&q->cond, &q->mutex);
156         rbio = (BIO *)list_shift(q->entries);
157     }
158     pthread_mutex_unlock(&q->mutex);
159     return rbio;
160 }
161
162 int dtlsread(SSL *ssl, struct gqueue *q, unsigned char *buf, int num, int timeout) {
163     int len, cnt;
164     BIO *rbio;
165
166     for (len = 0; len < num; len += cnt) {
167         cnt = SSL_read(ssl, buf + len, num - len);
168         if (cnt <= 0)
169             switch (cnt = SSL_get_error(ssl, cnt)) {
170             case SSL_ERROR_WANT_READ:
171                 rbio = getrbio(ssl, q, timeout);
172                 if (!rbio)
173                     return 0;
174                 BIO_free(ssl->rbio);
175                 ssl->rbio = rbio;
176                 cnt = 0;
177                 continue;
178             case SSL_ERROR_WANT_WRITE:
179                 cnt = 0;
180                 continue;
181             case SSL_ERROR_ZERO_RETURN:
182                 /* remote end sent close_notify, send one back */
183                 SSL_shutdown(ssl);
184                 return -1;
185             default:
186                 return -1;
187             }
188     }
189     return num;
190 }
191
192 /* accept if acc == 1, else connect */
193 SSL *dtlsacccon(uint8_t acc, SSL_CTX *ctx, int s, struct sockaddr *addr, struct gqueue *rbios) {
194     SSL *ssl;
195     int i, res;
196     unsigned long error;
197     BIO *mem0bio, *wbio;
198
199     ssl = SSL_new(ctx);
200     if (!ssl)
201         return NULL;
202
203     mem0bio = BIO_new(BIO_s_mem());
204     BIO_set_mem_eof_return(mem0bio, -1);
205     wbio = BIO_new_dgram(s, BIO_NOCLOSE);
206     i = BIO_dgram_set_peer(wbio, addr); /* i just to avoid warning */
207     SSL_set_bio(ssl, mem0bio, wbio);
208
209     for (i = 0; i < 5; i++) {
210         res = acc ? SSL_accept(ssl) : SSL_connect(ssl);
211         if (res > 0)
212             return ssl;
213         if (res == 0)
214             break;
215         if (SSL_get_error(ssl, res) == SSL_ERROR_WANT_READ) {
216             BIO_free(ssl->rbio);
217             ssl->rbio = getrbio(ssl, rbios, 5);
218             if (!ssl->rbio)
219                 break;
220         }
221         while ((error = ERR_get_error()))
222             debug(DBG_ERR, "dtls%st: DTLS: %s", acc ? "accep" : "connec", ERR_error_string(error, NULL));
223     }
224
225     SSL_free(ssl);
226     return NULL;
227 }
228
229 unsigned char *raddtlsget(SSL *ssl, struct gqueue *rbios, int timeout) {
230     int cnt, len;
231     unsigned char buf[4], *rad;
232
233     for (;;) {
234         cnt = dtlsread(ssl, rbios, buf, 4, timeout);
235         if (cnt < 1) {
236             debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
237             return NULL;
238         }
239
240         len = RADLEN(buf);
241         rad = malloc(len);
242         if (!rad) {
243             debug(DBG_ERR, "raddtlsget: malloc failed");
244             continue;
245         }
246         memcpy(rad, buf, 4);
247
248         cnt = dtlsread(ssl, rbios, rad + 4, len - 4, timeout);
249         if (cnt < 1) {
250             debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
251             free(rad);
252             return NULL;
253         }
254
255         if (len >= 20)
256             break;
257
258         free(rad);
259         debug(DBG_WARN, "raddtlsget: packet smaller than minimum radius size");
260     }
261
262     debug(DBG_DBG, "raddtlsget: got %d bytes", len);
263     return rad;
264 }
265
266 void *dtlsserverwr(void *arg) {
267     int cnt;
268     unsigned long error;
269     struct client *client = (struct client *)arg;
270     struct gqueue *replyq;
271     struct request *reply;
272
273     debug(DBG_DBG, "dtlsserverwr: starting for %s", addr2string(client->addr));
274     replyq = client->replyq;
275     for (;;) {
276         pthread_mutex_lock(&replyq->mutex);
277         while (!list_first(replyq->entries)) {
278             if (client->ssl) {
279                 debug(DBG_DBG, "dtlsserverwr: waiting for signal");
280                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
281                 debug(DBG_DBG, "dtlsserverwr: got signal");
282             }
283             if (!client->ssl) {
284                 /* ssl might have changed while waiting */
285                 pthread_mutex_unlock(&replyq->mutex);
286                 debug(DBG_DBG, "dtlsserverwr: exiting as requested");
287                 ERR_remove_state(0);
288                 pthread_exit(NULL);
289             }
290         }
291         reply = (struct request *)list_shift(replyq->entries);
292         pthread_mutex_unlock(&replyq->mutex);
293         cnt = SSL_write(client->ssl, reply->replybuf, RADLEN(reply->replybuf));
294         if (cnt > 0)
295             debug(DBG_DBG, "dtlsserverwr: sent %d bytes, Radius packet of length %d to %s",
296                   cnt, RADLEN(reply->replybuf), addr2string(client->addr));
297         else
298             while ((error = ERR_get_error()))
299                 debug(DBG_ERR, "dtlsserverwr: SSL: %s", ERR_error_string(error, NULL));
300         freerq(reply);
301     }
302 }
303
304 void dtlsserverrd(struct client *client) {
305     struct request *rq;
306     uint8_t *buf;
307     pthread_t dtlsserverwrth;
308
309     debug(DBG_DBG, "dtlsserverrd: starting for %s", addr2string(client->addr));
310
311     if (pthread_create(&dtlsserverwrth, NULL, dtlsserverwr, (void *)client)) {
312         debug(DBG_ERR, "dtlsserverrd: pthread_create failed");
313         return;
314     }
315
316     for (;;) {
317         buf = raddtlsget(client->ssl, client->rbios, IDLE_TIMEOUT);
318         if (!buf) {
319             debug(DBG_ERR, "dtlsserverrd: connection from %s lost", addr2string(client->addr));
320             break;
321         }
322         debug(DBG_DBG, "dtlsserverrd: got Radius message from %s", addr2string(client->addr));
323         rq = newrequest();
324         if (!rq) {
325             free(buf);
326             continue;
327         }
328         rq->buf = buf;
329         rq->from = client;
330         if (!radsrv(rq)) {
331             debug(DBG_ERR, "dtlsserverrd: message authentication/validation failed, closing connection from %s", addr2string(client->addr));
332             break;
333         }
334     }
335
336     /* stop writer by setting ssl to NULL and give signal in case waiting for data */
337     client->ssl = NULL;
338
339     pthread_mutex_lock(&client->replyq->mutex);
340     pthread_cond_signal(&client->replyq->cond);
341     pthread_mutex_unlock(&client->replyq->mutex);
342     debug(DBG_DBG, "dtlsserverrd: waiting for writer to end");
343     pthread_join(dtlsserverwrth, NULL);
344     debug(DBG_DBG, "dtlsserverrd: reader for %s exiting", addr2string(client->addr));
345 }
346
347 void *dtlsservernew(void *arg) {
348     struct dtlsservernewparams *params = (struct dtlsservernewparams *)arg;
349     struct client *client;
350     struct clsrvconf *conf;
351     struct list_node *cur = NULL;
352     SSL *ssl = NULL;
353     X509 *cert = NULL;
354     SSL_CTX *ctx = NULL;
355     uint8_t delay = 60;
356
357     debug(DBG_DBG, "dtlsservernew: starting");
358     conf = find_clconf(handle, (struct sockaddr *)&params->addr, NULL);
359     if (conf) {
360         ctx = tlsgetctx(handle, conf->tlsconf);
361         if (!ctx)
362             goto exit;
363         ssl = dtlsacccon(1, ctx, params->sock, (struct sockaddr *)&params->addr, params->sesscache->rbios);
364         if (!ssl)
365             goto exit;
366         cert = verifytlscert(ssl);
367         if (!cert)
368             goto exit;
369     }
370
371     while (conf) {
372         if (verifyconfcert(cert, conf)) {
373             X509_free(cert);
374             client = addclient(conf, 1);
375             if (client) {
376                 client->sock = params->sock;
377                 client->addr = addr_copy((struct sockaddr *)&params->addr);
378                 client->rbios = params->sesscache->rbios;
379                 client->ssl = ssl;
380                 dtlsserverrd(client);
381                 removeclient(client);
382                 delay = 0;
383             } else {
384                 debug(DBG_WARN, "dtlsservernew: failed to create new client instance");
385             }
386             goto exit;
387         }
388         conf = find_clconf(handle, (struct sockaddr *)&params->addr, &cur);
389     }
390     debug(DBG_WARN, "dtlsservernew: ignoring request, no matching TLS client");
391
392     if (cert)
393         X509_free(cert);
394
395 exit:
396     if (ssl) {
397         SSL_shutdown(ssl);
398         SSL_free(ssl);
399     }
400     pthread_mutex_lock(&params->sesscache->mutex);
401     freebios(params->sesscache->rbios);
402     params->sesscache->rbios = NULL;
403     gettimeofday(&params->sesscache->expiry, NULL);
404     params->sesscache->expiry.tv_sec += delay;
405     pthread_mutex_unlock(&params->sesscache->mutex);
406     free(params);
407     ERR_remove_state(0);
408     pthread_exit(NULL);
409     debug(DBG_DBG, "dtlsservernew: exiting");
410 }
411
412 void cacheexpire(struct hash *cache, struct timeval *last) {
413     struct timeval now;
414     struct hash_entry *he;
415     struct sessioncacheentry *e;
416
417     gettimeofday(&now, NULL);
418     if (now.tv_sec - last->tv_sec < 19)
419         return;
420
421     for (he = hash_first(cache); he; he = hash_next(he)) {
422         e = (struct sessioncacheentry *)he->data;
423         pthread_mutex_lock(&e->mutex);
424         if (!e->expiry.tv_sec || e->expiry.tv_sec > now.tv_sec) {
425             pthread_mutex_unlock(&e->mutex);
426             continue;
427         }
428         debug(DBG_DBG, "cacheexpire: freeing entry");
429         hash_extract(cache, he->key, he->keylen);
430         if (e->rbios) {
431             freebios(e->rbios);
432             e->rbios = NULL;
433         }
434         pthread_mutex_unlock(&e->mutex);
435         pthread_mutex_destroy(&e->mutex);
436     }
437     last->tv_sec = now.tv_sec;
438 }
439
440 void *udpdtlsserverrd(void *arg) {
441     int ndesc, cnt, s = *(int *)arg;
442     unsigned char buf[4];
443     struct sockaddr_storage from;
444     socklen_t fromlen = sizeof(from);
445     struct dtlsservernewparams *params;
446     fd_set readfds;
447     struct timeval timeout, lastexpiry;
448     pthread_t dtlsserverth;
449     struct hash *sessioncache;
450     struct sessioncacheentry *cacheentry;
451
452     sessioncache = hash_create();
453     if (!sessioncache)
454         debugx(1, DBG_ERR, "udpdtlsserverrd: malloc failed");
455     gettimeofday(&lastexpiry, NULL);
456
457     for (;;) {
458         FD_ZERO(&readfds);
459         FD_SET(s, &readfds);
460         memset(&timeout, 0, sizeof(struct timeval));
461         timeout.tv_sec = 60;
462         ndesc = select(s + 1, &readfds, NULL, NULL, &timeout);
463         if (ndesc < 1) {
464             cacheexpire(sessioncache, &lastexpiry);
465             continue;
466         }
467         cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
468         if (cnt == -1) {
469             debug(DBG_WARN, "udpdtlsserverrd: recv failed");
470             cacheexpire(sessioncache, &lastexpiry);
471             continue;
472         }
473         cacheentry = hash_read(sessioncache, &from, fromlen);
474         if (cacheentry) {
475             debug(DBG_DBG, "udpdtlsserverrd: cache hit");
476             pthread_mutex_lock(&cacheentry->mutex);
477             if (cacheentry->rbios) {
478                 if (udp2bio(s, cacheentry->rbios, cnt))
479                     debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
480             } else
481                 recv(s, buf, 1, 0);
482             pthread_mutex_unlock(&cacheentry->mutex);
483             cacheexpire(sessioncache, &lastexpiry);
484             continue;
485         }
486
487         /* from new source */
488         debug(DBG_DBG, "udpdtlsserverrd: cache miss");
489         params = malloc(sizeof(struct dtlsservernewparams));
490         if (!params) {
491             cacheexpire(sessioncache, &lastexpiry);
492             recv(s, buf, 1, 0);
493             continue;
494         }
495         memset(params, 0, sizeof(struct dtlsservernewparams));
496         params->sesscache = malloc(sizeof(struct sessioncacheentry));
497         if (!params->sesscache) {
498             free(params);
499             cacheexpire(sessioncache, &lastexpiry);
500             recv(s, buf, 1, 0);
501             continue;
502         }
503         memset(params->sesscache, 0, sizeof(struct sessioncacheentry));
504         pthread_mutex_init(&params->sesscache->mutex, NULL);
505         params->sesscache->rbios = newqueue();
506         if (hash_insert(sessioncache, &from, fromlen, params->sesscache)) {
507             params->sock = s;
508             memcpy(&params->addr, &from, fromlen);
509
510             if (udp2bio(s, params->sesscache->rbios, cnt)) {
511                 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
512                 if (!pthread_create(&dtlsserverth, NULL, dtlsservernew, (void *)params)) {
513                     pthread_detach(dtlsserverth);
514                     cacheexpire(sessioncache, &lastexpiry);
515                     continue;
516                 }
517                 debug(DBG_ERR, "udpdtlsserverrd: pthread_create failed");
518             }
519             hash_extract(sessioncache, &from, fromlen);
520         }
521         freebios(params->sesscache->rbios);
522         pthread_mutex_destroy(&params->sesscache->mutex);
523         free(params->sesscache);
524         free(params);
525         cacheexpire(sessioncache, &lastexpiry);
526     }
527 }
528
529 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
530     struct timeval now;
531     time_t elapsed;
532     X509 *cert;
533     SSL_CTX *ctx = NULL;
534     struct hostportres *hp;
535
536     debug(DBG_DBG, "dtlsconnect: called from %s", text);
537     pthread_mutex_lock(&server->lock);
538     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
539         /* already reconnected, nothing to do */
540         debug(DBG_DBG, "dtlsconnect(%s): seems already reconnected", text);
541         pthread_mutex_unlock(&server->lock);
542         return 1;
543     }
544
545     hp = (struct hostportres *)list_first(server->conf->hostports)->data;
546     for (;;) {
547         gettimeofday(&now, NULL);
548         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
549
550         if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
551             debug(DBG_DBG, "dtlsconnect: timeout");
552             SSL_free(server->ssl);
553             server->ssl = NULL;
554             pthread_mutex_unlock(&server->lock);
555             return 0;
556         }
557
558         if (server->connectionok) {
559             server->connectionok = 0;
560             sleep(2);
561         } else if (elapsed < 1)
562             sleep(2);
563         else if (elapsed < 60) {
564             debug(DBG_INFO, "dtlsconnect: sleeping %lds", elapsed);
565             sleep(elapsed);
566         } else if (elapsed < 100000) {
567             debug(DBG_INFO, "dtlsconnect: sleeping %ds", 60);
568             sleep(60);
569         } else
570             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
571         debug(DBG_WARN, "dtlsconnect: trying to open DTLS connection to %s port %s", hp->host, hp->port);
572
573         SSL_free(server->ssl);
574         server->ssl = NULL;
575         ctx = tlsgetctx(handle, server->conf->tlsconf);
576         if (!ctx)
577             continue;
578         server->ssl = dtlsacccon(0, ctx, server->sock, hp->addrinfo->ai_addr, server->rbios);
579         if (!server->ssl)
580             continue;
581         debug(DBG_DBG, "dtlsconnect: DTLS: ok");
582
583         cert = verifytlscert(server->ssl);
584         if (!cert)
585             continue;
586
587         if (verifyconfcert(cert, server->conf))
588             break;
589         X509_free(cert);
590     }
591     X509_free(cert);
592     debug(DBG_WARN, "dtlsconnect: DTLS connection to %s port %s up", hp->host, hp->port);
593     server->connectionok = 1;
594     gettimeofday(&server->lastconnecttry, NULL);
595     pthread_mutex_unlock(&server->lock);
596     return 1;
597 }
598
599 int clientradputdtls(struct server *server, unsigned char *rad) {
600     int cnt;
601     size_t len;
602     unsigned long error;
603     struct clsrvconf *conf = server->conf;
604
605     if (!server->connectionok)
606         return 0;
607     len = RADLEN(rad);
608     if ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
609         while ((error = ERR_get_error()))
610             debug(DBG_ERR, "clientradputdtls: DTLS: %s", ERR_error_string(error, NULL));
611         return 0;
612     }
613     debug(DBG_DBG, "clientradputdtls: Sent %d bytes, Radius packet of length %d to DTLS peer %s", cnt, len, conf->name);
614     return 1;
615 }
616
617 /* reads UDP containing DTLS and passes it on to dtlsclientrd */
618 void *udpdtlsclientrd(void *arg) {
619     int cnt, s = *(int *)arg;
620     unsigned char buf[4];
621     struct sockaddr_storage from;
622     socklen_t fromlen = sizeof(from);
623     struct clsrvconf *conf;
624     fd_set readfds;
625
626     for (;;) {
627         FD_ZERO(&readfds);
628         FD_SET(s, &readfds);
629         if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
630             continue;
631         cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
632         if (cnt == -1) {
633             debug(DBG_WARN, "udpdtlsclientrd: recv failed");
634             continue;
635         }
636
637         conf = find_srvconf(handle, (struct sockaddr *)&from, NULL);
638         if (!conf) {
639             debug(DBG_WARN, "udpdtlsclientrd: got packet from wrong or unknown DTLS peer %s, ignoring", addr2string((struct sockaddr *)&from));
640             recv(s, buf, 4, 0);
641             continue;
642         }
643         if (udp2bio(s, conf->servers->rbios, cnt))
644             debug(DBG_DBG, "radudpget: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
645     }
646 }
647
648 void *dtlsclientrd(void *arg) {
649     struct server *server = (struct server *)arg;
650     unsigned char *buf;
651     struct timeval lastconnecttry;
652     int secs;
653
654     for (;;) {
655         /* yes, lastconnecttry is really necessary */
656         lastconnecttry = server->lastconnecttry;
657         for (secs = 0; !(buf = raddtlsget(server->ssl, server->rbios, 10)) && !server->lostrqs && secs < IDLE_TIMEOUT; secs += 10);
658         if (!buf) {
659             dtlsconnect(server, &lastconnecttry, 0, "dtlsclientrd");
660             continue;
661         }
662         replyh(server, buf);
663     }
664     ERR_remove_state(0);
665     server->clientrdgone = 1;
666     return NULL;
667 }
668
669 void addserverextradtls(struct clsrvconf *conf) {
670     switch (((struct hostportres *)list_first(conf->hostports)->data)->addrinfo->ai_family) {
671     case AF_INET:
672         if (client4_sock < 0) {
673             client4_sock = bindtoaddr(srcres, AF_INET, 0, 1);
674             if (client4_sock < 0)
675                 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->name);
676         }
677         conf->servers->sock = client4_sock;
678         break;
679     case AF_INET6:
680         if (client6_sock < 0) {
681             client6_sock = bindtoaddr(srcres, AF_INET6, 0, 1);
682             if (client6_sock < 0)
683                 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->name);
684         }
685         conf->servers->sock = client6_sock;
686         break;
687     default:
688         debugx(1, DBG_ERR, "addserver: unsupported address family");
689     }
690 }
691
692 void initextradtls() {
693     pthread_t cl4th, cl6th;
694
695     if (srcres) {
696         freeaddrinfo(srcres);
697         srcres = NULL;
698     }
699
700     if (client4_sock >= 0)
701         if (pthread_create(&cl4th, NULL, udpdtlsclientrd, (void *)&client4_sock))
702             debugx(1, DBG_ERR, "pthread_create failed");
703     if (client6_sock >= 0)
704         if (pthread_create(&cl6th, NULL, udpdtlsclientrd, (void *)&client6_sock))
705             debugx(1, DBG_ERR, "pthread_create failed");
706 }
707 #else
708 const struct protodefs *dtlsinit(uint8_t h) {
709     return NULL;
710 }
711 #endif
712
713 /* Local Variables: */
714 /* c-file-style: "stroustrup" */
715 /* End: */