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