1a797ed15f1497d662f2b6a1f91ea1883d35f0ce
[ashd.git] / src / ssl-gnutls.c
1 /*
2     ashd - A Sane HTTP Daemon
3     Copyright (C) 2008  Fredrik Tolf <fredrik@dolda2000.com>
4
5     This program is free software: you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation, either version 3 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <string.h>
22 #include <fcntl.h>
23 #include <dirent.h>
24 #include <sys/socket.h>
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
27 #include <errno.h>
28
29 #ifdef HAVE_CONFIG_H
30 #include <config.h>
31 #endif
32 #include <utils.h>
33 #include <mt.h>
34 #include <mtio.h>
35 #include <req.h>
36 #include <log.h>
37 #include <bufio.h>
38
39 #include "htparser.h"
40
41 #ifdef HAVE_GNUTLS
42
43 #include <gnutls/gnutls.h>
44 #include <gnutls/x509.h>
45
46 struct namedcreds {
47     char **names;
48     gnutls_certificate_credentials_t creds;
49 };
50
51 struct ncredbuf {
52     struct namedcreds **b;
53     size_t s, d;
54 };
55
56 struct sslport {
57     int fd, sport, clreq;
58     gnutls_certificate_credentials_t creds;
59     gnutls_priority_t ciphers;
60     struct namedcreds **ncreds;
61 };
62
63 struct sslconn {
64     int fd;
65     struct sslport *port;
66     struct sockaddr_storage name;
67     gnutls_session_t sess;
68     struct charbuf in;
69 };
70
71 struct savedsess {
72     struct savedsess *next, *prev;
73     gnutls_datum_t key, value;
74 };
75
76 struct certbuffer {
77     gnutls_x509_crt_t *b;
78     size_t s, d;
79 };
80
81 static int numconn = 0, numsess = 0;
82 static struct btree *sessidx = NULL;
83 static struct savedsess *sesslistf = NULL, *sesslistl = NULL;
84
85 static int sesscmp(void *ap, void *bp)
86 {
87     struct savedsess *a = ap, *b = bp;
88     
89     if(a->key.size != b->key.size)
90         return(a->key.size - b->key.size);
91     return(memcmp(a->key.data, b->key.data, a->key.size));
92 }
93
94 static gnutls_datum_t sessdbfetch(void *uudata, gnutls_datum_t key)
95 {
96     struct savedsess *sess, lkey;
97     gnutls_datum_t ret;
98     
99     memset(&ret, 0, sizeof(ret));
100     lkey.key = key;
101     if((sess = btreeget(sessidx, &lkey, sesscmp)) == NULL)
102         return(ret);
103     ret.data = memcpy(gnutls_malloc(ret.size = sess->value.size), sess->value.data, sess->value.size);
104     return(ret);
105 }
106
107 static void freesess(struct savedsess *sess)
108 {
109     bbtreedel(&sessidx, sess, sesscmp);
110     if(sess->next)
111         sess->next->prev = sess->prev;
112     if(sess->prev)
113         sess->prev->next = sess->next;
114     if(sess == sesslistf)
115         sesslistf = sess->next;
116     if(sess == sesslistl)
117         sesslistl = sess->prev;
118     free(sess->key.data);
119     free(sess->value.data);
120     free(sess);
121     numsess--;
122 }
123
124 static int sessdbdel(void *uudata, gnutls_datum_t key)
125 {
126     struct savedsess *sess, lkey;
127     
128     lkey.key = key;
129     if((sess = btreeget(sessidx, &lkey, sesscmp)) == NULL)
130         return(-1);
131     freesess(sess);
132     return(0);
133 }
134
135 static void cleansess(void)
136 {
137     while(numsess > (max(numconn, 1) * 100))
138         freesess(sesslistl);
139 }
140
141 static int sessdbstore(void *uudata, gnutls_datum_t key, gnutls_datum_t value)
142 {
143     static int cc = 0;
144     struct savedsess *sess, lkey;
145     
146     if((value.data == NULL) || (value.size == 0)) {
147         sessdbdel(NULL, key);
148         return(0);
149     }
150     lkey.key = key;
151     if((sess = btreeget(sessidx, &lkey, sesscmp)) == NULL) {
152         omalloc(sess);
153         sess->key.data = memcpy(smalloc(sess->key.size = key.size), key.data, key.size);
154         sess->value.data = memcpy(smalloc(sess->value.size = value.size), value.data, value.size);
155         bbtreeput(&sessidx, sess, sesscmp);
156         sess->prev = NULL;
157         sess->next = sesslistf;
158         if(sesslistf)
159             sesslistf->prev = sess;
160         sesslistf = sess;
161         if(sesslistl == NULL)
162             sesslistl = sess;
163         numsess++;
164     } else {
165         free(sess->value.data);
166         sess->value.data = memcpy(smalloc(sess->value.size = value.size), value.data, value.size);
167         if(sess != sesslistf) {
168             if(sess->next)
169                 sess->next->prev = sess->prev;
170             if(sess->prev)
171                 sess->prev->next = sess->next;
172             if(sess == sesslistl)
173                 sesslistl = sess->prev;
174             sess->prev = NULL;
175             sess->next = sesslistf;
176             if(sesslistf)
177                 sesslistf->prev = sess;
178             sesslistf = sess;
179         }
180     }
181     if(cc++ > 100) {
182         cleansess();
183         cc = 0;
184     }
185     return(0);
186 }
187
188 static int tlsblock(int fd, gnutls_session_t sess, time_t to)
189 {
190     if(gnutls_record_get_direction(sess))
191         return(block(fd, EV_WRITE, to));
192     else
193         return(block(fd, EV_READ, to));
194 }
195
196 static ssize_t sslread(void *cookie, void *buf, size_t len)
197 {
198     struct sslconn *ssl = cookie;
199     ssize_t xf;
200     int ret;
201
202     while(ssl->in.d == 0) {
203         sizebuf(ssl->in, ssl->in.d + 1024);
204         ret = gnutls_record_recv(ssl->sess, ssl->in.b + ssl->in.d, ssl->in.s - ssl->in.d);
205         if((ret == GNUTLS_E_INTERRUPTED) || (ret == GNUTLS_E_AGAIN)) {
206             if(tlsblock(ssl->fd, ssl->sess, 60) == 0) {
207                 errno = ETIMEDOUT;
208                 return(-1);
209             }
210         } else if(ret < 0) {
211             errno = EIO;
212             return(-1);
213         } else if(ret == 0) {
214             return(0);
215         } else {
216             ssl->in.d += ret;
217         }
218     }
219     xf = min(ssl->in.d, len);
220     memcpy(buf, ssl->in.b, xf);
221     memmove(ssl->in.b, ssl->in.b + xf, ssl->in.d -= xf);
222     return(xf);
223 }
224
225 static ssize_t sslwrite(void *cookie, const void *buf, size_t len)
226 {
227     struct sslconn *ssl = cookie;
228     int ret;
229     size_t off;
230     
231     off = 0;
232     while(off < len) {
233         ret = gnutls_record_send(ssl->sess, buf + off, len - off);
234         if((ret == GNUTLS_E_INTERRUPTED) || (ret == GNUTLS_E_AGAIN)) {
235             if(tlsblock(ssl->fd, ssl->sess, 60) == 0) {
236                 if(off == 0) {
237                     errno = ETIMEDOUT;
238                     return(-1);
239                 }
240                 return(off);
241             }
242         } else if(ret < 0) {
243             if(off == 0) {
244                 errno = EIO;
245                 return(-1);
246             }
247             return(off);
248         } else {
249             off += ret;
250         }
251     }
252     return(off);
253 }
254
255 static int sslclose(void *cookie)
256 {
257     struct sslconn *ssl = cookie;
258     
259     buffree(ssl->in);
260     return(0);
261 }
262
263 static struct bufioops iofuns = {
264     .read = sslread,
265     .write = sslwrite,
266     .close = sslclose,
267 };
268
269 static int initreq(struct conn *conn, struct hthead *req)
270 {
271     struct sslconn *ssl = conn->pdata;
272     struct sockaddr_storage sa;
273     socklen_t salen;
274     
275     headappheader(req, "X-Ash-Address", formathaddress((struct sockaddr *)&ssl->name, sizeof(sa)));
276     if(ssl->name.ss_family == AF_INET)
277         headappheader(req, "X-Ash-Port", sprintf3("%i", ntohs(((struct sockaddr_in *)&ssl->name)->sin_port)));
278     else if(ssl->name.ss_family == AF_INET6)
279         headappheader(req, "X-Ash-Port", sprintf3("%i", ntohs(((struct sockaddr_in6 *)&ssl->name)->sin6_port)));
280     salen = sizeof(sa);
281     if(!getsockname(ssl->fd, (struct sockaddr *)&sa, &salen))
282         headappheader(req, "X-Ash-Server-Address", formathaddress((struct sockaddr *)&sa, sizeof(sa)));
283     headappheader(req, "X-Ash-Server-Port", sprintf3("%i", ssl->port->sport));
284     headappheader(req, "X-Ash-Protocol", "https");
285     return(0);
286 }
287
288 static int setcreds(gnutls_session_t sess)
289 {
290     int i, o, u;
291     struct sslport *pd;
292     unsigned int ntype;
293     char nambuf[256];
294     size_t namlen;
295     
296     pd = gnutls_session_get_ptr(sess);
297     for(i = 0; 1; i++) {
298         namlen = sizeof(nambuf);
299         if(gnutls_server_name_get(sess, nambuf, &namlen, &ntype, i) != 0)
300             break;
301         if(ntype != GNUTLS_NAME_DNS)
302             continue;
303         for(o = 0; pd->ncreds[o] != NULL; o++) {
304             for(u = 0; pd->ncreds[o]->names[u] != NULL; u++) {
305                 if(!strcmp(pd->ncreds[o]->names[u], nambuf)) {
306                     gnutls_credentials_set(sess, GNUTLS_CRD_CERTIFICATE, pd->ncreds[o]->creds);
307                     if(pd->clreq)
308                         gnutls_certificate_server_set_request(sess, GNUTLS_CERT_REQUEST);
309                     return(0);
310                 }
311             }
312         }
313     }
314     gnutls_credentials_set(sess, GNUTLS_CRD_CERTIFICATE, pd->creds);
315     if(pd->clreq)
316         gnutls_certificate_server_set_request(sess, GNUTLS_CERT_REQUEST);
317     return(0);
318 }
319
320 static void servessl(struct muth *muth, va_list args)
321 {
322     vavar(int, fd);
323     vavar(struct sockaddr_storage, name);
324     vavar(struct sslport *, pd);
325     struct conn conn;
326     struct sslconn ssl;
327     gnutls_session_t sess;
328     int ret;
329
330     numconn++;
331     fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
332     gnutls_init(&sess, GNUTLS_SERVER);
333     gnutls_priority_set(sess, pd->ciphers);
334     gnutls_db_set_retrieve_function(sess, sessdbfetch);
335     gnutls_db_set_store_function(sess, sessdbstore);
336     gnutls_db_set_remove_function(sess, sessdbdel);
337     gnutls_db_set_ptr(sess, NULL);
338     gnutls_session_set_ptr(sess, pd);
339     gnutls_handshake_set_post_client_hello_function(sess, setcreds);
340     gnutls_transport_set_ptr(sess, (gnutls_transport_ptr_t)(intptr_t)fd);
341     while((ret = gnutls_handshake(sess)) != 0) {
342         if((ret != GNUTLS_E_INTERRUPTED) && (ret != GNUTLS_E_AGAIN))
343             goto out;
344         if(tlsblock(fd, sess, 60) <= 0)
345             goto out;
346     }
347     memset(&conn, 0, sizeof(conn));
348     memset(&ssl, 0, sizeof(ssl));
349     conn.pdata = &ssl;
350     conn.initreq = initreq;
351     ssl.fd = fd;
352     ssl.port = pd;
353     ssl.name = name;
354     ssl.sess = sess;
355     bufinit(ssl.in);
356     serve(bioopen(&ssl, &iofuns), fd, &conn);
357     
358 out:
359     gnutls_deinit(sess);
360     close(fd);
361     numconn--;
362 }
363
364 static void listenloop(struct muth *muth, va_list args)
365 {
366     vavar(struct sslport *, pd);
367     int i, ns, n;
368     struct sockaddr_storage name;
369     socklen_t namelen;
370     
371     fcntl(pd->fd, F_SETFL, fcntl(pd->fd, F_GETFL) | O_NONBLOCK);
372     while(1) {
373         namelen = sizeof(name);
374         if(block(pd->fd, EV_READ, 0) == 0)
375             goto out;
376         n = 0;
377         while(1) {
378             ns = accept(pd->fd, (struct sockaddr *)&name, &namelen);
379             if(ns < 0) {
380                 if(errno == EAGAIN)
381                     break;
382                 if(errno == ECONNABORTED)
383                     continue;
384                 flog(LOG_ERR, "accept: %s", strerror(errno));
385                 goto out;
386             }
387             mustart(servessl, ns, name, pd);
388             if(++n >= 100)
389                 break;
390         }
391     }
392     
393 out:
394     close(pd->fd);
395     free(pd);
396     for(i = 0; i < listeners.d; i++) {
397         if(listeners.b[i] == muth)
398             bufdel(listeners, i);
399     }
400 }
401
402 static gnutls_dh_params_t dhparams(void)
403 {
404     static int inited = 0;
405     static gnutls_dh_params_t pars;
406     int ret;
407     
408     if(!inited) {
409         if(((ret = gnutls_dh_params_init(&pars)) != 0) ||
410            ((ret = gnutls_dh_params_generate2(pars, 2048)) != 0)) {
411             flog(LOG_ERR, "GnuTLS could not generate Diffie-Hellman parameters: %s", gnutls_strerror(ret));
412             exit(1);
413         }
414         inited = 1;
415     }
416     return(pars);
417 }
418
419 static void init(void)
420 {
421     static int inited = 0;
422     int ret;
423     
424     if(inited)
425         return;
426     inited = 1;
427     if((ret = gnutls_global_init()) != 0) {
428         flog(LOG_ERR, "could not initialize GnuTLS: %s", gnutls_strerror(ret));
429         exit(1);
430     }
431 }
432
433 /* This implementation seems somewhat ugly, but it's the way the
434  * GnuTLS implements the same thing internally, so it should probably
435  * be interoperable, at least. */
436 static int readcrtchain(struct certbuffer *ret, struct charbuf *pem)
437 {
438     static char *headers[] = {"-----BEGIN CERTIFICATE", "-----BEGIN X509 CERTIFICATE"};
439     int i, rv;
440     char *p, *p2, *f;
441     gnutls_x509_crt_t crt;
442     
443     for(i = 0, p = NULL; i < sizeof(headers) / sizeof(*headers); i++) {
444         f = memmem(pem->b, pem->d, headers[i], strlen(headers[i]));
445         if((f != NULL) && ((p == NULL) || (f < p)))
446             p = f;
447     }
448     if(p == NULL)
449         return(-GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
450     do {
451         if((rv = gnutls_x509_crt_init(&crt)) < 0)
452             goto error;
453         if((rv = gnutls_x509_crt_import(crt, &(gnutls_datum_t){.data = (unsigned char *)p, .size = pem->d - (p - pem->b)}, GNUTLS_X509_FMT_PEM)) < 0) {
454             gnutls_x509_crt_deinit(crt);
455             goto error;
456         }
457         bufadd(*ret, crt);
458         for(i = 0, p2 = NULL; i < sizeof(headers) / sizeof(*headers); i++) {
459             f = memmem(p + 1, pem->d - (p + 1 - pem->b), headers[i], strlen(headers[i]));
460             if((f != NULL) && ((p2 == NULL) || (f < p2)))
461                 p2 = f;
462         }
463     } while((p = p2) != NULL);
464     return(0);
465 error:
466     for(i = 0; i < ret->d; i++)
467         gnutls_x509_crt_deinit(ret->b[i]);
468     ret->d = 0;
469     return(rv);
470 }
471
472 static struct namedcreds *readncreds(char *file, gnutls_x509_privkey_t defkey)
473 {
474     int i, fd, ret;
475     struct namedcreds *nc;
476     struct certbuffer crts;
477     gnutls_x509_privkey_t key;
478     char cn[1024];
479     size_t cnl;
480     struct charbuf keybuf;
481     struct charvbuf names;
482     unsigned int type;
483     
484     bufinit(keybuf);
485     bufinit(crts);
486     bufinit(names);
487     if((fd = open(file, O_RDONLY)) < 0) {
488         flog(LOG_ERR, "ssl: %s: %s", file, strerror(errno));
489         exit(1);
490     }
491     while(1) {
492         sizebuf(keybuf, keybuf.d + 1024);
493         ret = read(fd, keybuf.b + keybuf.d, keybuf.s - keybuf.d);
494         if(ret < 0) {
495             flog(LOG_ERR, "ssl: reading from %s: %s", file, strerror(errno));
496             exit(1);
497         } else if(ret == 0) {
498             break;
499         }
500         keybuf.d += ret;
501     }
502     close(fd);
503     if((ret = readcrtchain(&crts, &keybuf)) != 0) {
504         flog(LOG_ERR, "ssl: could not load certificate chain from %s: %s", file, gnutls_strerror(ret));
505         exit(1);
506     }
507     cnl = sizeof(cn) - 1;
508     if((ret = gnutls_x509_crt_get_dn_by_oid(crts.b[0], GNUTLS_OID_X520_COMMON_NAME, 0, 0, cn, &cnl)) != 0) {
509         flog(LOG_ERR, "ssl: could not read common name from %s: %s", file, gnutls_strerror(ret));
510         exit(1);
511     }
512     cn[cnl] = 0;
513     bufadd(names, sstrdup(cn));
514     for(i = 0; 1; i++) {
515         cnl = sizeof(cn) - 1;
516         if(gnutls_x509_crt_get_subject_alt_name2(crts.b[0], i, cn, &cnl, &type, NULL) < 0)
517             break;
518         cn[cnl] = 0;
519         if(type == GNUTLS_SAN_DNSNAME)
520             bufadd(names, sstrdup(cn));
521     }
522     gnutls_x509_privkey_init(&key);
523     if((ret = gnutls_x509_privkey_import(key, &(gnutls_datum_t){.data = (unsigned char *)keybuf.b, .size = keybuf.d}, GNUTLS_X509_FMT_PEM)) != 0) {
524         if(ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
525             gnutls_x509_privkey_deinit(key);
526             key = defkey;
527         } else {
528             flog(LOG_ERR, "ssl: could not load key from %s: %s", file, gnutls_strerror(ret));
529             exit(1);
530         }
531     }
532     buffree(keybuf);
533     bufadd(names, NULL);
534     omalloc(nc);
535     nc->names = names.b;
536     gnutls_certificate_allocate_credentials(&nc->creds);
537     if((ret = gnutls_certificate_set_x509_key(nc->creds, crts.b, crts.d, key)) != 0) {
538         flog(LOG_ERR, "ssl: could not use certificate from %s: %s", file, gnutls_strerror(ret));
539         exit(1);
540     }
541     gnutls_certificate_set_dh_params(nc->creds, dhparams());
542     return(nc);
543 }
544
545 static void readncdir(struct ncredbuf *buf, char *dir, gnutls_x509_privkey_t defkey)
546 {
547     DIR *d;
548     struct dirent *e;
549     size_t es;
550     
551     if((d = opendir(dir)) == NULL) {
552         flog(LOG_ERR, "ssl: could not read certificate directory %s: %s", dir, strerror(errno));
553         exit(1);
554     }
555     while((e = readdir(d)) != NULL) {
556         if(e->d_name[0] == '.')
557             continue;
558         if((es = strlen(e->d_name)) <= 4)
559             continue;
560         if(strcmp(e->d_name + es - 4, ".crt"))
561             continue;
562         bufadd(*buf, readncreds(sprintf3("%s/%s", dir, e->d_name), defkey));
563     }
564     closedir(d);
565 }
566
567 void handlegnussl(int argc, char **argp, char **argv)
568 {
569     int i, ret, port, fd, clreq;
570     gnutls_certificate_credentials_t creds;
571     gnutls_priority_t ciphers;
572     gnutls_x509_privkey_t defkey;
573     struct ncredbuf ncreds;
574     struct charvbuf ncertf, ncertd;
575     struct sslport *pd;
576     char *crtfile, *keyfile, *perr;
577     
578     init();
579     port = 443;
580     clreq = 0;
581     bufinit(ncreds);
582     bufinit(ncertf);
583     bufinit(ncertd);
584     gnutls_certificate_allocate_credentials(&creds);
585     keyfile = crtfile = NULL;
586     ciphers = NULL;
587     for(i = 0; i < argc; i++) {
588         if(!strcmp(argp[i], "help")) {
589             printf("ssl handler parameters:\n");
590             printf("\tcert=CERT-FILE  [mandatory]\n");
591             printf("\t\tThe name of the file to read the certificate from.\n");
592             printf("\tkey=KEY-FILE    [same as CERT-FILE]\n");
593             printf("\t\tThe name of the file to read the private key from.\n");
594             printf("\tprio=PRIORITIES [NORMAL]\n");
595             printf("\t\tCiphersuite priorities, as a GnuTLS priority string.\n");
596             printf("\ttrust=CA-FILE   [no default]\n");
597             printf("\t\tThe name of a file to read trusted certificates from.\n");
598             printf("\t\tMay be given multiple times.\n");
599             printf("\tcrl=CRL-FILE    [no default]\n");
600             printf("\t\tThe name of a file to read revocation lists from.\n");
601             printf("\t\tMay be given multiple times.\n");
602             printf("\tncert=CERT-FILE [no default]\n");
603             printf("\t\tThe name of a file to read a named certificate from,\n");
604             printf("\t\tfor use with SNI-enabled clients.\n");
605             printf("\t\tMay be given multiple times.\n");
606             printf("\tncertdir=DIR    [no default]\n");
607             printf("\t\tRead all *.crt files in the given directory as if they\n");
608             printf("\t\twere given with `ncert' options.\n");
609             printf("\t\tMay be given multiple times.\n");
610             printf("\tport=PORT       [443]\n");
611             printf("\t\tThe TCP port to listen on.\n");
612             printf("\n");
613             printf("\tAll X.509 data files must be PEM-encoded.\n");
614             printf("\tIf any certificates were given with `ncert' options, they will be\n");
615             printf("\tused if a client explicitly names one of them with a\n");
616             printf("\tserver-name indication. If a client indicates no server name,\n");
617             printf("\tor if a server-name indication does not match any given\n");
618             printf("\tcertificate, the certificate given with the `cert' option will\n");
619             printf("\tbe used instead.\n");
620             exit(0);
621         } else if(!strcmp(argp[i], "cert")) {
622             crtfile = argv[i];
623         } else if(!strcmp(argp[i], "key")) {
624             keyfile = argv[i];
625         } else if(!strcmp(argp[i], "prio")) {
626             if(ciphers != NULL)
627                 gnutls_priority_deinit(ciphers);
628             ret = gnutls_priority_init(&ciphers, argv[i], (const char **)&perr);
629             if(ret == GNUTLS_E_INVALID_REQUEST) {
630                 flog(LOG_ERR, "ssl: invalid cipher priority string, at `%s'", perr);
631                 exit(1);
632             } else if(ret != 0) {
633                 flog(LOG_ERR, "ssl: could not initialize cipher priorities: %s", gnutls_strerror(ret));
634                 exit(1);
635             }
636         } else if(!strcmp(argp[i], "trust")) {
637             if((ret = gnutls_certificate_set_x509_trust_file(creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
638                 flog(LOG_ERR, "ssl: could not load trust file `%s': %s", argv[i], gnutls_strerror(ret));
639                 exit(1);
640             }
641             for(i = 0; i < ncreds.d; i++) {
642                 if((ret = gnutls_certificate_set_x509_trust_file(ncreds.b[i]->creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
643                     flog(LOG_ERR, "ssl: could not load trust file `%s': %s", argv[i], gnutls_strerror(ret));
644                     exit(1);
645                 }
646             }
647             clreq = 1;
648         } else if(!strcmp(argp[i], "crl")) {
649             if((ret = gnutls_certificate_set_x509_crl_file(creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
650                 flog(LOG_ERR, "ssl: could not load CRL file `%s': %s", argv[i], gnutls_strerror(ret));
651                 exit(1);
652             }
653             for(i = 0; i < ncreds.d; i++) {
654                 if((ret = gnutls_certificate_set_x509_crl_file(ncreds.b[i]->creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
655                     flog(LOG_ERR, "ssl: could not load CRL file `%s': %s", argv[i], gnutls_strerror(ret));
656                     exit(1);
657                 }
658             }
659             clreq = 1;
660         } else if(!strcmp(argp[i], "port")) {
661             port = atoi(argv[i]);
662         } else if(!strcmp(argp[i], "ncert")) {
663             bufadd(ncertf, argv[i]);
664         } else if(!strcmp(argp[i], "ncertdir")) {
665             bufadd(ncertd, argv[i]);
666         } else {
667             flog(LOG_ERR, "unknown parameter `%s' to ssl handler", argp[i]);
668             exit(1);
669         }
670     }
671     if(crtfile == NULL) {
672         flog(LOG_ERR, "ssl: needs certificate file at the very least");
673         exit(1);
674     }
675     if((fd = listensock6(port)) < 0) {
676         flog(LOG_ERR, "could not listen on IPv6 port (port %i): %s", port, strerror(errno));
677         exit(1);
678     }
679     if(keyfile == NULL)
680         keyfile = crtfile;
681     if((ret = gnutls_certificate_set_x509_key_file(creds, crtfile, keyfile, GNUTLS_X509_FMT_PEM)) != 0) {
682         flog(LOG_ERR, "ssl: could not load certificate or key: %s", gnutls_strerror(ret));
683         exit(1);
684     }
685     if((ciphers == NULL) && ((ret = gnutls_priority_init(&ciphers, "NORMAL", NULL)) != 0)) {
686         flog(LOG_ERR, "ssl: could not initialize cipher priorities: %s", gnutls_strerror(ret));
687         exit(1);
688     }
689     if((ret = gnutls_certificate_get_x509_key(creds, 0, &defkey)) != 0) {
690         flog(LOG_ERR, "ssl: could not get default key: %s", gnutls_strerror(ret));
691         exit(1);
692     }
693     for(i = 0; i < ncertf.d; i++)
694         bufadd(ncreds, readncreds(ncertf.b[i], defkey));
695     for(i = 0; i < ncertd.d; i++)
696         readncdir(&ncreds, ncertd.b[i], defkey);
697     buffree(ncertf);
698     buffree(ncertd);
699     gnutls_certificate_set_dh_params(creds, dhparams());
700     bufadd(ncreds, NULL);
701     omalloc(pd);
702     pd->fd = fd;
703     pd->sport = port;
704     pd->clreq = clreq;
705     pd->creds = creds;
706     pd->ncreds = ncreds.b;
707     pd->ciphers = ciphers;
708     bufadd(listeners, mustart(listenloop, pd));
709     if((fd = listensock4(port)) < 0) {
710         if(errno != EADDRINUSE) {
711             flog(LOG_ERR, "could not listen on IPv4 port (port %i): %s", port, strerror(errno));
712             exit(1);
713         }
714     } else {
715         omalloc(pd);
716         pd->fd = fd;
717         pd->sport = port;
718         pd->creds = creds;
719         pd->ncreds = ncreds.b;
720         pd->ciphers = ciphers;
721         bufadd(listeners, mustart(listenloop, pd));
722     }
723 }
724
725 #endif