Revert "Imported Upstream version 3.4.11"
[platform/upstream/gnutls.git] / src / serv.c
1 /*
2  * Copyright (C) 2004-2012 Free Software Foundation, Inc.
3  * Copyright (C) 2001,2002 Paul Sheer
4  * Portions Copyright (C) 2002,2003 Nikos Mavrogiannopoulos
5  *
6  * This file is part of GnuTLS.
7  *
8  * GnuTLS is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuTLS is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 /* This server is heavily modified for GnuTLS by Nikos Mavrogiannopoulos
23  * (which means it is quite unreadable)
24  */
25
26 #include <config.h>
27
28 #include "common.h"
29 #include "serv-args.h"
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <errno.h>
33 #include <sys/types.h>
34 #include <string.h>
35 #include <gnutls/gnutls.h>
36 #include <gnutls/dtls.h>
37 #include <gnutls/openpgp.h>
38 #include <sys/time.h>
39 #include <sys/select.h>
40 #include <fcntl.h>
41 #include <list.h>
42 #include <netdb.h>
43 #include <unistd.h>
44 #include <socket.h>
45
46 /* Gnulib portability files. */
47 #include "read-file.h"
48 #include "minmax.h"
49 #include "sockets.h"
50 #include "udp-serv.h"
51
52 /* konqueror cannot handle sending the page in multiple
53  * pieces.
54  */
55 /* global stuff */
56 static int generate = 0;
57 static int http = 0;
58 static int x509ctype;
59 static int debug = 0;
60
61 unsigned int verbose = 1;
62 static int nodb;
63 static int noticket;
64 int require_cert;
65 int disable_client_cert;
66
67 const char *psk_passwd = NULL;
68 const char *srp_passwd = NULL;
69 const char *srp_passwd_conf = NULL;
70 const char *pgp_keyring = NULL;
71 const char *pgp_keyfile = NULL;
72 const char *pgp_certfile = NULL;
73 const char *x509_keyfile = NULL;
74 const char *x509_certfile = NULL;
75 const char *x509_dsakeyfile = NULL;
76 const char *x509_dsacertfile = NULL;
77 const char *x509_ecckeyfile = NULL;
78 const char *x509_ecccertfile = NULL;
79 const char *x509_cafile = NULL;
80 const char *dh_params_file = NULL;
81 const char *x509_crlfile = NULL;
82 const char *priorities = NULL;
83 const char *status_response_ocsp = NULL;
84
85 gnutls_datum_t session_ticket_key;
86 static void tcp_server(const char *name, int port);
87
88 /* end of globals */
89
90 /* This is a sample TCP echo server.
91  * This will behave as an http server if any argument in the
92  * command line is present
93  */
94
95 #define SMALL_READ_TEST (2147483647)
96
97 #define GERR(ret) fprintf(stdout, "Error: %s\n", safe_strerror(ret))
98
99 #define HTTP_END  "</BODY></HTML>\n\n"
100
101 #define HTTP_UNIMPLEMENTED "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n<HTML><HEAD>\r\n<TITLE>501 Method Not Implemented</TITLE>\r\n</HEAD><BODY>\r\n<H1>Method Not Implemented</H1>\r\n<HR>\r\n</BODY></HTML>\r\n"
102 #define HTTP_OK "HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n"
103
104 #define HTTP_BEGIN HTTP_OK \
105                 "\n" \
106                 "<HTML><BODY>\n" \
107                 "<CENTER><H1>This is <a href=\"http://www.gnu.org/software/gnutls\">" \
108                 "GnuTLS</a></H1></CENTER>\n\n"
109
110 /* These are global */
111 gnutls_srp_server_credentials_t srp_cred = NULL;
112 gnutls_psk_server_credentials_t psk_cred = NULL;
113 gnutls_anon_server_credentials_t dh_cred = NULL;
114 gnutls_certificate_credentials_t cert_cred = NULL;
115
116 const int ssl_session_cache = 128;
117
118 static void wrap_db_init(void);
119 static void wrap_db_deinit(void);
120 static int wrap_db_store(void *dbf, gnutls_datum_t key,
121                          gnutls_datum_t data);
122 static gnutls_datum_t wrap_db_fetch(void *dbf, gnutls_datum_t key);
123 static int wrap_db_delete(void *dbf, gnutls_datum_t key);
124
125 static void cmd_parser(int argc, char **argv);
126
127
128 #define HTTP_STATE_REQUEST      1
129 #define HTTP_STATE_RESPONSE     2
130 #define HTTP_STATE_CLOSING      3
131
132 LIST_TYPE_DECLARE(listener_item, char *http_request; char *http_response;
133                   int request_length; int response_length;
134                   int response_written; int http_state;
135                   int listen_socket; int fd;
136                   gnutls_session_t tls_session;
137                   int handshake_ok;
138                   time_t start;
139     );
140
141 static const char *safe_strerror(int value)
142 {
143         const char *ret = gnutls_strerror(value);
144         if (ret == NULL)
145                 ret = str_unknown;
146         return ret;
147 }
148
149 static void listener_free(listener_item * j)
150 {
151
152         free(j->http_request);
153         free(j->http_response);
154         if (j->fd >= 0) {
155                 gnutls_bye(j->tls_session, GNUTLS_SHUT_WR);
156                 shutdown(j->fd, 2);
157                 close(j->fd);
158                 gnutls_deinit(j->tls_session);
159         }
160 }
161
162
163 /* we use primes up to 1024 in this server.
164  * otherwise we should add them here.
165  */
166
167 gnutls_dh_params_t dh_params = NULL;
168 gnutls_rsa_params_t rsa_params = NULL;
169
170 static int generate_dh_primes(void)
171 {
172         int prime_bits =
173             gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH,
174                                         GNUTLS_SEC_PARAM_MEDIUM);
175
176         if (gnutls_dh_params_init(&dh_params) < 0) {
177                 fprintf(stderr, "Error in dh parameter initialization\n");
178                 exit(1);
179         }
180
181         /* Generate Diffie-Hellman parameters - for use with DHE
182          * kx algorithms. These should be discarded and regenerated
183          * once a week or once a month. Depends on the
184          * security requirements.
185          */
186         printf
187             ("Generating Diffie-Hellman parameters [%d]. Please wait...\n",
188              prime_bits);
189         fflush(stdout);
190
191         if (gnutls_dh_params_generate2(dh_params, prime_bits) < 0) {
192                 fprintf(stderr, "Error in prime generation\n");
193                 exit(1);
194         }
195
196         return 0;
197 }
198
199 static void read_dh_params(void)
200 {
201         char tmpdata[2048];
202         int size;
203         gnutls_datum_t params;
204         FILE *fd;
205
206         if (gnutls_dh_params_init(&dh_params) < 0) {
207                 fprintf(stderr, "Error in dh parameter initialization\n");
208                 exit(1);
209         }
210
211         /* read the params file
212          */
213         fd = fopen(dh_params_file, "r");
214         if (fd == NULL) {
215                 fprintf(stderr, "Could not open %s\n", dh_params_file);
216                 exit(1);
217         }
218
219         size = fread(tmpdata, 1, sizeof(tmpdata) - 1, fd);
220         tmpdata[size] = 0;
221         fclose(fd);
222
223         params.data = (unsigned char *) tmpdata;
224         params.size = size;
225
226         size =
227             gnutls_dh_params_import_pkcs3(dh_params, &params,
228                                           GNUTLS_X509_FMT_PEM);
229
230         if (size < 0) {
231                 fprintf(stderr, "Error parsing dh params: %s\n",
232                         safe_strerror(size));
233                 exit(1);
234         }
235
236         printf("Read Diffie-Hellman parameters.\n");
237         fflush(stdout);
238
239 }
240
241 static char pkcs3[] =
242     "-----BEGIN DH PARAMETERS-----\n"
243     "MIGGAoGAtkxw2jlsVCsrfLqxrN+IrF/3W8vVFvDzYbLmxi2GQv9s/PQGWP1d9i22\n"
244     "P2DprfcJknWt7KhCI1SaYseOQIIIAYP78CfyIpGScW/vS8khrw0rlQiyeCvQgF3O\n"
245     "GeGOEywcw+oQT4SmFOD7H0smJe2CNyjYpexBXQ/A0mbTF9QKm1cCAQU=\n"
246     "-----END DH PARAMETERS-----\n";
247
248 static int static_dh_params(void)
249 {
250         gnutls_datum_t params = { (void *) pkcs3, sizeof(pkcs3) };
251         int ret;
252
253         if (gnutls_dh_params_init(&dh_params) < 0) {
254                 fprintf(stderr, "Error in dh parameter initialization\n");
255                 exit(1);
256         }
257
258         ret = gnutls_dh_params_import_pkcs3(dh_params, &params,
259                                             GNUTLS_X509_FMT_PEM);
260
261         if (ret < 0) {
262                 fprintf(stderr, "Error parsing dh params: %s\n",
263                         safe_strerror(ret));
264                 exit(1);
265         }
266
267         printf
268             ("Set static Diffie-Hellman parameters, consider --dhparams.\n");
269
270         return 0;
271 }
272
273 static int
274 get_params(gnutls_session_t session, gnutls_params_type_t type,
275            gnutls_params_st * st)
276 {
277
278         if (type == GNUTLS_PARAMS_DH) {
279                 if (dh_params == NULL)
280                         return -1;
281                 st->params.dh = dh_params;
282         } else
283                 return -1;
284
285         st->type = type;
286         st->deinit = 0;
287
288         return 0;
289 }
290
291 LIST_DECLARE_INIT(listener_list, listener_item, listener_free);
292
293 static int cert_verify_callback(gnutls_session_t session)
294 {
295 listener_item * j = gnutls_session_get_ptr(session);
296 unsigned int size;
297 int ret;
298
299         if (gnutls_auth_get_type(session) == GNUTLS_CRD_CERTIFICATE) {
300                 if (!require_cert && gnutls_certificate_get_peers(session, &size) == NULL)
301                         return 0;
302
303                 if ((require_cert || ENABLED_OPT(VERIFY_CLIENT_CERT)) && cert_verify(session, NULL, NULL) == 0) {
304                         do {
305                                 ret = gnutls_alert_send(session, GNUTLS_AL_FATAL, GNUTLS_A_ACCESS_DENIED);
306                         } while(ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN);
307
308                         j->http_state = HTTP_STATE_CLOSING;
309                         return -1;
310                 }
311         }
312         return 0;
313 }
314
315 gnutls_session_t initialize_session(int dtls)
316 {
317         gnutls_session_t session;
318         int ret;
319         const char *err;
320
321         if (priorities == NULL)
322                 priorities = "NORMAL";
323
324         if (dtls)
325                 gnutls_init(&session, GNUTLS_SERVER | GNUTLS_DATAGRAM);
326         else
327                 gnutls_init(&session, GNUTLS_SERVER);
328
329         /* allow the use of private ciphersuites.
330          */
331         gnutls_handshake_set_private_extensions(session, 1);
332
333         if (nodb == 0) {
334                 gnutls_db_set_retrieve_function(session, wrap_db_fetch);
335                 gnutls_db_set_remove_function(session, wrap_db_delete);
336                 gnutls_db_set_store_function(session, wrap_db_store);
337                 gnutls_db_set_ptr(session, NULL);
338         }
339
340 #ifdef ENABLE_SESSION_TICKETS
341         if (noticket == 0)
342                 gnutls_session_ticket_enable_server(session,
343                                                     &session_ticket_key);
344 #endif
345
346         if (gnutls_priority_set_direct(session, priorities, &err) < 0) {
347                 fprintf(stderr, "Syntax error at: %s\n", err);
348                 exit(1);
349         }
350
351         gnutls_credentials_set(session, GNUTLS_CRD_ANON, dh_cred);
352
353         if (srp_cred != NULL)
354                 gnutls_credentials_set(session, GNUTLS_CRD_SRP, srp_cred);
355
356         if (psk_cred != NULL)
357                 gnutls_credentials_set(session, GNUTLS_CRD_PSK, psk_cred);
358
359         if (cert_cred != NULL) {
360                 gnutls_certificate_set_verify_function(cert_cred,
361                                                cert_verify_callback);
362
363                 gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
364                                        cert_cred);
365         }
366
367         if (disable_client_cert)
368                 gnutls_certificate_server_set_request(session,
369                                                       GNUTLS_CERT_IGNORE);
370         else {
371                 if (require_cert)
372                         gnutls_certificate_server_set_request(session,
373                                                               GNUTLS_CERT_REQUIRE);
374                 else
375                         gnutls_certificate_server_set_request(session,
376                                                               GNUTLS_CERT_REQUEST);
377         }
378
379         if (HAVE_OPT(HEARTBEAT))
380                 gnutls_heartbeat_enable(session,
381                                         GNUTLS_HB_PEER_ALLOWED_TO_SEND);
382
383 #ifdef ENABLE_DTLS_SRTP
384         if (HAVE_OPT(SRTP_PROFILES)) {
385                 ret =
386                     gnutls_srtp_set_profile_direct(session,
387                                                    OPT_ARG(SRTP_PROFILES),
388                                                    &err);
389                 if (ret == GNUTLS_E_INVALID_REQUEST)
390                         fprintf(stderr, "Syntax error at: %s\n", err);
391                 else
392                         fprintf(stderr, "Error in profiles: %s\n",
393                                 gnutls_strerror(ret));
394                 exit(1);
395         }
396 #endif
397
398         return session;
399 }
400
401 #include <gnutls/x509.h>
402
403 static const char DEFAULT_DATA[] =
404     "This is the default message reported by the GnuTLS implementation. "
405     "For more information please visit "
406     "<a href=\"http://www.gnutls.org/\">http://www.gnutls.org/</a>.";
407
408 /* Creates html with the current session information.
409  */
410 #define tmp_buffer &http_buffer[strlen(http_buffer)]
411 #define tmp_buffer_size len-strlen(http_buffer)
412 static char *peer_print_info(gnutls_session_t session, int *ret_length,
413                              const char *header)
414 {
415         const char *tmp;
416         unsigned char sesid[32];
417         size_t i, sesid_size;
418         char *http_buffer;
419         gnutls_kx_algorithm_t kx_alg;
420         size_t len = 20 * 1024 + strlen(header);
421         char *crtinfo = NULL, *crtinfo_old = NULL;
422         size_t ncrtinfo = 0;
423
424         if (verbose == 0) {
425                 http_buffer = malloc(len);
426                 if (http_buffer == NULL)
427                         return NULL;
428
429                 strcpy(http_buffer, HTTP_BEGIN);
430                 strcpy(&http_buffer[sizeof(HTTP_BEGIN) - 1], DEFAULT_DATA);
431                 strcpy(&http_buffer
432                        [sizeof(HTTP_BEGIN) + sizeof(DEFAULT_DATA) - 2],
433                        HTTP_END);
434                 *ret_length =
435                     sizeof(DEFAULT_DATA) + sizeof(HTTP_BEGIN) +
436                     sizeof(HTTP_END) - 3;
437                 return http_buffer;
438         }
439
440         if (gnutls_certificate_type_get(session) == GNUTLS_CRT_X509) {
441                 const gnutls_datum_t *cert_list;
442                 unsigned int cert_list_size = 0;
443
444                 cert_list =
445                     gnutls_certificate_get_peers(session, &cert_list_size);
446
447                 for (i = 0; i < cert_list_size; i++) {
448                         gnutls_x509_crt_t cert;
449                         gnutls_datum_t info;
450
451                         if (gnutls_x509_crt_init(&cert) == 0 &&
452                             gnutls_x509_crt_import(cert, &cert_list[i],
453                                                    GNUTLS_X509_FMT_DER) ==
454                             0
455                             && gnutls_x509_crt_print(cert,
456                                                      GNUTLS_CRT_PRINT_FULL,
457                                                      &info) == 0) {
458                                 const char *post = "</PRE><P><PRE>";
459                                 
460                                 crtinfo_old = crtinfo;
461                                 crtinfo =
462                                     realloc(crtinfo,
463                                             ncrtinfo + info.size +
464                                             strlen(post) + 1);
465                                 if (crtinfo == NULL) {
466                                         free(crtinfo_old);
467                                         return NULL;
468                                 }
469                                 memcpy(crtinfo + ncrtinfo, info.data,
470                                        info.size);
471                                 ncrtinfo += info.size;
472                                 memcpy(crtinfo + ncrtinfo, post,
473                                        strlen(post));
474                                 ncrtinfo += strlen(post);
475                                 crtinfo[ncrtinfo] = '\0';
476                                 gnutls_free(info.data);
477                         }
478                 }
479         }
480
481         http_buffer = malloc(len);
482         if (http_buffer == NULL) {
483                 free(crtinfo);
484                 return NULL;
485         }
486
487         strcpy(http_buffer, HTTP_BEGIN);
488
489         /* print session_id */
490         sesid_size = sizeof(sesid);
491         gnutls_session_get_id(session, sesid, &sesid_size);
492         snprintf(tmp_buffer, tmp_buffer_size, "\n<p>Session ID: <i>");
493         for (i = 0; i < sesid_size; i++)
494                 snprintf(tmp_buffer, tmp_buffer_size, "%.2X", sesid[i]);
495         snprintf(tmp_buffer, tmp_buffer_size, "</i></p>\n");
496         snprintf(tmp_buffer, tmp_buffer_size,
497                  "<h5>If your browser supports session resuming, then you should see the "
498                  "same session ID, when you press the <b>reload</b> button.</h5>\n");
499
500         /* Here unlike print_info() we use the kx algorithm to distinguish
501          * the functions to call.
502          */
503         {
504                 char dns[256];
505                 size_t dns_size = sizeof(dns);
506                 unsigned int type;
507
508                 if (gnutls_server_name_get
509                     (session, dns, &dns_size, &type, 0) == 0) {
510                         snprintf(tmp_buffer, tmp_buffer_size,
511                                  "\n<p>Server Name: %s</p>\n", dns);
512                 }
513
514         }
515
516         kx_alg = gnutls_kx_get(session);
517
518         /* print srp specific data */
519 #ifdef ENABLE_SRP
520         if (kx_alg == GNUTLS_KX_SRP) {
521                 snprintf(tmp_buffer, tmp_buffer_size,
522                          "<p>Connected as user '%s'.</p>\n",
523                          gnutls_srp_server_get_username(session));
524         }
525 #endif
526
527 #ifdef ENABLE_PSK
528         if (kx_alg == GNUTLS_KX_PSK) {
529                 snprintf(tmp_buffer, tmp_buffer_size,
530                          "<p>Connected as user '%s'.</p>\n",
531                          gnutls_psk_server_get_username(session));
532         }
533 #endif
534
535 #ifdef ENABLE_ANON
536         if (kx_alg == GNUTLS_KX_ANON_DH) {
537                 snprintf(tmp_buffer, tmp_buffer_size,
538                          "<p> Connect using anonymous DH (prime of %d bits)</p>\n",
539                          gnutls_dh_get_prime_bits(session));
540         }
541 #endif
542
543         if (kx_alg == GNUTLS_KX_DHE_RSA || kx_alg == GNUTLS_KX_DHE_DSS) {
544                 snprintf(tmp_buffer, tmp_buffer_size,
545                          "Ephemeral DH using prime of <b>%d</b> bits.<br>\n",
546                          gnutls_dh_get_prime_bits(session));
547         }
548
549         /* print session information */
550         strcat(http_buffer, "<P>\n");
551
552         tmp =
553             gnutls_protocol_get_name(gnutls_protocol_get_version(session));
554         if (tmp == NULL)
555                 tmp = str_unknown;
556         snprintf(tmp_buffer, tmp_buffer_size,
557                  "<TABLE border=1><TR><TD>Protocol version:</TD><TD>%s</TD></TR>\n",
558                  tmp);
559
560         if (gnutls_auth_get_type(session) == GNUTLS_CRD_CERTIFICATE) {
561                 tmp =
562                     gnutls_certificate_type_get_name
563                     (gnutls_certificate_type_get(session));
564                 if (tmp == NULL)
565                         tmp = str_unknown;
566                 snprintf(tmp_buffer, tmp_buffer_size,
567                          "<TR><TD>Certificate Type:</TD><TD>%s</TD></TR>\n",
568                          tmp);
569         }
570
571         tmp = gnutls_kx_get_name(kx_alg);
572         if (tmp == NULL)
573                 tmp = str_unknown;
574         snprintf(tmp_buffer, tmp_buffer_size,
575                  "<TR><TD>Key Exchange:</TD><TD>%s</TD></TR>\n", tmp);
576
577         tmp = gnutls_compression_get_name(gnutls_compression_get(session));
578         if (tmp == NULL)
579                 tmp = str_unknown;
580         snprintf(tmp_buffer, tmp_buffer_size,
581                  "<TR><TD>Compression</TD><TD>%s</TD></TR>\n", tmp);
582
583         tmp = gnutls_cipher_get_name(gnutls_cipher_get(session));
584         if (tmp == NULL)
585                 tmp = str_unknown;
586         snprintf(tmp_buffer, tmp_buffer_size,
587                  "<TR><TD>Cipher</TD><TD>%s</TD></TR>\n", tmp);
588
589         tmp = gnutls_mac_get_name(gnutls_mac_get(session));
590         if (tmp == NULL)
591                 tmp = str_unknown;
592         snprintf(tmp_buffer, tmp_buffer_size,
593                  "<TR><TD>MAC</TD><TD>%s</TD></TR>\n", tmp);
594
595         tmp = gnutls_cipher_suite_get_name(kx_alg,
596                                            gnutls_cipher_get(session),
597                                            gnutls_mac_get(session));
598         if (tmp == NULL)
599                 tmp = str_unknown;
600         snprintf(tmp_buffer, tmp_buffer_size,
601                  "<TR><TD>Ciphersuite</TD><TD>%s</TD></TR></p></TABLE>\n",
602                  tmp);
603
604         if (crtinfo) {
605                 snprintf(tmp_buffer, tmp_buffer_size,
606                          "<hr><PRE>%s\n</PRE>\n", crtinfo);
607                 free(crtinfo);
608         }
609
610         snprintf(tmp_buffer, tmp_buffer_size,
611                  "<hr><P>Your HTTP header was:<PRE>%s</PRE></P>\n"
612                  HTTP_END, header);
613
614         *ret_length = strlen(http_buffer);
615
616         return http_buffer;
617 }
618
619 const char *human_addr(const struct sockaddr *sa, socklen_t salen,
620                        char *buf, size_t buflen)
621 {
622         const char *save_buf = buf;
623         size_t l;
624
625         if (!buf || !buflen)
626                 return NULL;
627
628         *buf = 0;
629
630         switch (sa->sa_family) {
631 #if HAVE_IPV6
632         case AF_INET6:
633                 snprintf(buf, buflen, "IPv6 ");
634                 break;
635 #endif
636
637         case AF_INET:
638                 snprintf(buf, buflen, "IPv4 ");
639                 break;
640         }
641
642         l = 5;
643         buf += l;
644         buflen -= l;
645
646         if (getnameinfo(sa, salen, buf, buflen, NULL, 0, NI_NUMERICHOST) !=
647             0) {        
648                    return NULL;
649         }
650
651         l = strlen(buf);
652         buf += l;
653         buflen -= l;
654
655         if (buflen < 8)
656                 return save_buf;
657
658         strcat(buf, " port ");
659         buf += 6;
660         buflen -= 6;
661
662         if (getnameinfo(sa, salen, NULL, 0, buf, buflen, NI_NUMERICSERV) !=
663             0) {
664                 snprintf(buf, buflen, "%s", " unknown");
665         }
666
667         return save_buf;
668 }
669
670 int wait_for_connection(void)
671 {
672         listener_item *j;
673         fd_set rd, wr;
674         int n, sock = -1;
675
676         FD_ZERO(&rd);
677         FD_ZERO(&wr);
678         n = 0;
679
680         lloopstart(listener_list, j) {
681                 if (j->listen_socket) {
682                         FD_SET(j->fd, &rd);
683                         n = MAX(n, j->fd);
684                 }
685         }
686         lloopend(listener_list, j);
687
688         /* waiting part */
689         n = select(n + 1, &rd, &wr, NULL, NULL);
690         if (n == -1 && errno == EINTR)
691                 return -1;
692         if (n < 0) {
693                 perror("select()");
694                 exit(1);
695         }
696
697         /* find which one is ready */
698         lloopstart(listener_list, j) {
699                 /* a new connection has arrived */
700                 if (FD_ISSET(j->fd, &rd) && j->listen_socket) {
701                         sock = j->fd;
702                         break;
703                 }
704         }
705         lloopend(listener_list, j);
706         return sock;
707 }
708
709 int listen_socket(const char *name, int listen_port, int socktype)
710 {
711         struct addrinfo hints, *res, *ptr;
712         char portname[6];
713         int s = -1;
714         int yes;
715         listener_item *j = NULL;
716
717         snprintf(portname, sizeof(portname), "%d", listen_port);
718         memset(&hints, 0, sizeof(hints));
719         hints.ai_socktype = socktype;
720         hints.ai_flags = AI_PASSIVE
721 #ifdef AI_ADDRCONFIG
722             | AI_ADDRCONFIG
723 #endif
724             ;
725
726         if ((s = getaddrinfo(NULL, portname, &hints, &res)) != 0) {
727                 fprintf(stderr, "getaddrinfo() failed: %s\n",
728                         gai_strerror(s));
729                 return -1;
730         }
731
732         for (ptr = res; ptr != NULL; ptr = ptr->ai_next) {
733                 int news;
734 #ifndef HAVE_IPV6
735                 if (ptr->ai_family != AF_INET)
736                         continue;
737 #endif
738
739                 /* Print what we are doing. */
740                 {
741                         char topbuf[512];
742
743                         fprintf(stderr, "%s listening on %s...",
744                                 name, human_addr(ptr->ai_addr,
745                                                  ptr->ai_addrlen, topbuf,
746                                                  sizeof(topbuf)));
747                 }
748
749                 if ((news = socket(ptr->ai_family, ptr->ai_socktype,
750                                 ptr->ai_protocol)) < 0) {
751                         perror("socket() failed");
752                         continue;
753                 }
754                 s = news; /* to not overwrite existing s from previous loops */
755 #if defined(HAVE_IPV6) && !defined(_WIN32)
756                 if (ptr->ai_family == AF_INET6) {
757                         yes = 1;
758                         /* avoid listen on ipv6 addresses failing
759                          * because already listening on ipv4 addresses: */
760                         setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
761                                    (const void *) &yes, sizeof(yes));
762                 }
763 #endif
764
765                 if (socktype == SOCK_STREAM) {
766                         yes = 1;
767                         if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
768                                        (const void *) &yes,
769                                        sizeof(yes)) < 0) {
770                                 perror("setsockopt() failed");
771                                 close(s);
772                                 continue;
773                         }
774                 } else {
775 #if defined(IP_DONTFRAG)
776                         yes = 1;
777                         if (setsockopt(s, IPPROTO_IP, IP_DONTFRAG,
778                                        (const void *) &yes,
779                                        sizeof(yes)) < 0)
780                                 perror("setsockopt(IP_DF) failed");
781 #elif defined(IP_MTU_DISCOVER)
782                         yes = IP_PMTUDISC_DO;
783                         if (setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER,
784                                        (const void *) &yes,
785                                        sizeof(yes)) < 0)
786                                 perror("setsockopt(IP_DF) failed");
787 #endif
788                 }
789
790                 if (bind(s, ptr->ai_addr, ptr->ai_addrlen) < 0) {
791                         perror("bind() failed");
792                         close(s);
793                         continue;
794                 }
795
796                 if (socktype == SOCK_STREAM) {
797                         if (listen(s, 10) < 0) {
798                                 perror("listen() failed");
799                                 exit(1);
800                         }
801                 }
802
803                 /* new list entry for the connection */
804                 lappend(listener_list);
805                 j = listener_list.tail;
806                 j->listen_socket = 1;
807                 j->fd = s;
808
809                 /* Complete earlier message. */
810                 fprintf(stderr, "done\n");
811         }
812
813         fflush(stderr);
814
815         freeaddrinfo(res);
816
817         return s;
818 }
819
820 /* strips \r\n from the end of the string 
821  */
822 static void strip(char *data)
823 {
824         int i;
825         int len = strlen(data);
826
827         for (i = 0; i < len; i++) {
828                 if (data[i] == '\r' && data[i + 1] == '\n'
829                     && data[i + 1] == 0) {
830                         data[i] = '\n';
831                         data[i + 1] = 0;
832                         break;
833                 }
834         }
835 }
836
837 static void
838 get_response(gnutls_session_t session, char *request,
839              char **response, int *response_length)
840 {
841         char *p, *h;
842
843         if (http != 0) {
844                 if (strncmp(request, "GET ", 4))
845                         goto unimplemented;
846
847                 if (!(h = strchr(request, '\n')))
848                         goto unimplemented;
849
850                 *h++ = '\0';
851                 while (*h == '\r' || *h == '\n')
852                         h++;
853
854                 if (!(p = strchr(request + 4, ' ')))
855                         goto unimplemented;
856                 *p = '\0';
857         }
858 /*    *response = peer_print_info(session, request+4, h, response_length); */
859         if (http != 0) {
860                 *response = peer_print_info(session, response_length, h);
861         } else {
862                 strip(request);
863                 fprintf(stderr, "received: %s\n", request);
864                 if (check_command(session, request)) {
865                         *response = NULL;
866                         *response_length = 0;
867                         return;
868                 }
869                 *response = strdup(request);
870                 *response_length = ((*response) ? strlen(*response) : 0);
871         }
872
873         return;
874
875       unimplemented:
876         *response = strdup(HTTP_UNIMPLEMENTED);
877         *response_length = ((*response) ? strlen(*response) : 0);
878 }
879
880 static void terminate(int sig) __attribute__ ((noreturn));
881
882 static void terminate(int sig)
883 {
884         fprintf(stderr, "Exiting via signal %d\n", sig);
885         exit(1);
886 }
887
888
889 static void check_alert(gnutls_session_t session, int ret)
890 {
891         if (ret == GNUTLS_E_WARNING_ALERT_RECEIVED
892             || ret == GNUTLS_E_FATAL_ALERT_RECEIVED) {
893                 int last_alert = gnutls_alert_get(session);
894                 if (last_alert == GNUTLS_A_NO_RENEGOTIATION &&
895                     ret == GNUTLS_E_WARNING_ALERT_RECEIVED)
896                         printf
897                             ("* Received NO_RENEGOTIATION alert. Client does not support renegotiation.\n");
898                 else
899                         printf("* Received alert '%d': %s.\n", last_alert,
900                                gnutls_alert_get_name(last_alert));
901         }
902 }
903
904 static void tls_log_func(int level, const char *str)
905 {
906         fprintf(stderr, "|<%d>| %s", level, str);
907 }
908
909 static void tls_audit_log_func(gnutls_session_t session, const char *str)
910 {
911         fprintf(stderr, "|<%p>| %s", session, str);
912 }
913
914 int main(int argc, char **argv)
915 {
916         int ret, mtu, port;
917         char name[256];
918         int cert_set = 0;
919
920         cmd_parser(argc, argv);
921
922 #ifndef _WIN32
923         signal(SIGHUP, SIG_IGN);
924         signal(SIGTERM, terminate);
925         if (signal(SIGINT, terminate) == SIG_IGN)
926                 signal(SIGINT, SIG_IGN);        /* e.g. background process */
927 #endif
928
929         sockets_init();
930
931         if (nodb == 0)
932                 wrap_db_init();
933
934         if (HAVE_OPT(UDP))
935                 strcpy(name, "UDP ");
936         else
937                 name[0] = 0;
938
939         if (http == 1) {
940                 strcat(name, "HTTP Server");
941         } else {
942                 strcat(name, "Echo Server");
943         }
944
945         gnutls_global_set_log_function(tls_log_func);
946         gnutls_global_set_audit_log_function(tls_audit_log_func);
947         gnutls_global_set_log_level(debug);
948
949         if ((ret = gnutls_global_init()) < 0) {
950                 fprintf(stderr, "global_init: %s\n", gnutls_strerror(ret));
951                 exit(1);
952         }
953 #ifdef ENABLE_PKCS11
954         pkcs11_common();
955 #endif
956
957         /* Note that servers must generate parameters for
958          * Diffie-Hellman. See gnutls_dh_params_generate(), and
959          * gnutls_dh_params_set().
960          */
961         if (generate != 0) {
962                 generate_dh_primes();
963         } else if (dh_params_file) {
964                 read_dh_params();
965         } else {
966                 static_dh_params();
967         }
968
969         if (gnutls_certificate_allocate_credentials(&cert_cred) < 0) {
970                 fprintf(stderr, "memory error\n");
971                 exit(1);
972         }
973
974         if (x509_cafile != NULL) {
975                 if ((ret = gnutls_certificate_set_x509_trust_file
976                      (cert_cred, x509_cafile, x509ctype)) < 0) {
977                         fprintf(stderr, "Error reading '%s'\n",
978                                 x509_cafile);
979                         GERR(ret);
980                         exit(1);
981                 } else {
982                         printf("Processed %d CA certificate(s).\n", ret);
983                 }
984         }
985         if (x509_crlfile != NULL) {
986                 if ((ret = gnutls_certificate_set_x509_crl_file
987                      (cert_cred, x509_crlfile, x509ctype)) < 0) {
988                         fprintf(stderr, "Error reading '%s'\n",
989                                 x509_crlfile);
990                         GERR(ret);
991                         exit(1);
992                 } else {
993                         printf("Processed %d CRL(s).\n", ret);
994                 }
995         }
996 #ifdef ENABLE_OPENPGP
997         if (pgp_keyring != NULL) {
998                 ret =
999                     gnutls_certificate_set_openpgp_keyring_file(cert_cred,
1000                                                                 pgp_keyring,
1001                                                                 GNUTLS_OPENPGP_FMT_BASE64);
1002                 if (ret < 0) {
1003                         fprintf(stderr,
1004                                 "Error setting the OpenPGP keyring file\n");
1005                         GERR(ret);
1006                 }
1007         }
1008
1009         if (pgp_certfile != NULL && pgp_keyfile != NULL) {
1010                 if (HAVE_OPT(PGPSUBKEY))
1011                         ret = gnutls_certificate_set_openpgp_key_file2
1012                             (cert_cred, pgp_certfile, pgp_keyfile,
1013                              OPT_ARG(PGPSUBKEY),
1014                              GNUTLS_OPENPGP_FMT_BASE64);
1015                 else
1016                         ret = gnutls_certificate_set_openpgp_key_file
1017                             (cert_cred, pgp_certfile, pgp_keyfile,
1018                              GNUTLS_OPENPGP_FMT_BASE64);
1019
1020                 if (ret < 0) {
1021                         fprintf(stderr,
1022                                 "Error[%d] while reading the OpenPGP key pair ('%s', '%s')\n",
1023                                 ret, pgp_certfile, pgp_keyfile);
1024                         GERR(ret);
1025                 } else
1026                         cert_set = 1;
1027         }
1028 #endif
1029
1030         if (x509_certfile != NULL && x509_keyfile != NULL) {
1031                 ret = gnutls_certificate_set_x509_key_file
1032                     (cert_cred, x509_certfile, x509_keyfile, x509ctype);
1033                 if (ret < 0) {
1034                         fprintf(stderr,
1035                                 "Error reading '%s' or '%s'\n",
1036                                 x509_certfile, x509_keyfile);
1037                         GERR(ret);
1038                         exit(1);
1039                 } else
1040                         cert_set = 1;
1041         }
1042
1043         if (x509_dsacertfile != NULL && x509_dsakeyfile != NULL) {
1044                 ret = gnutls_certificate_set_x509_key_file
1045                     (cert_cred, x509_dsacertfile, x509_dsakeyfile,
1046                      x509ctype);
1047                 if (ret < 0) {
1048                         fprintf(stderr,
1049                                 "Error reading '%s' or '%s'\n",
1050                                 x509_dsacertfile, x509_dsakeyfile);
1051                         GERR(ret);
1052                         exit(1);
1053                 } else
1054                         cert_set = 1;
1055         }
1056
1057         if (x509_ecccertfile != NULL && x509_ecckeyfile != NULL) {
1058                 ret = gnutls_certificate_set_x509_key_file
1059                     (cert_cred, x509_ecccertfile, x509_ecckeyfile,
1060                      x509ctype);
1061                 if (ret < 0) {
1062                         fprintf(stderr,
1063                                 "Error reading '%s' or '%s'\n",
1064                                 x509_ecccertfile, x509_ecckeyfile);
1065                         GERR(ret);
1066                         exit(1);
1067                 } else
1068                         cert_set = 1;
1069         }
1070
1071         if (cert_set == 0) {
1072                 fprintf(stderr,
1073                         "Warning: no private key and certificate pairs were set.\n");
1074         }
1075
1076         /* OCSP status-request TLS extension */
1077         if (status_response_ocsp) {
1078                 if (gnutls_certificate_set_ocsp_status_request_file
1079                     (cert_cred, status_response_ocsp, 0) < 0) {
1080                         fprintf(stderr,
1081                                 "Cannot set OCSP status request file: %s\n",
1082                                 gnutls_strerror(ret));
1083                         exit(1);
1084                 }
1085         }
1086
1087         gnutls_certificate_set_params_function(cert_cred, get_params);
1088 /*     gnutls_certificate_set_dh_params(cert_cred, dh_params);
1089  *     gnutls_certificate_set_rsa_export_params(cert_cred, rsa_params);
1090  */
1091
1092         /* this is a password file (created with the included srpcrypt utility) 
1093          * Read README.crypt prior to using SRP.
1094          */
1095 #ifdef ENABLE_SRP
1096         if (srp_passwd != NULL) {
1097                 gnutls_srp_allocate_server_credentials(&srp_cred);
1098
1099                 if ((ret =
1100                      gnutls_srp_set_server_credentials_file(srp_cred,
1101                                                             srp_passwd,
1102                                                             srp_passwd_conf))
1103                     < 0) {
1104                         /* only exit is this function is not disabled 
1105                          */
1106                         fprintf(stderr,
1107                                 "Error while setting SRP parameters\n");
1108                         GERR(ret);
1109                 }
1110         }
1111 #endif
1112
1113         /* this is a password file 
1114          */
1115 #ifdef ENABLE_PSK
1116         if (psk_passwd != NULL) {
1117                 gnutls_psk_allocate_server_credentials(&psk_cred);
1118
1119                 if ((ret =
1120                      gnutls_psk_set_server_credentials_file(psk_cred,
1121                                                             psk_passwd)) <
1122                     0) {
1123                         /* only exit is this function is not disabled 
1124                          */
1125                         fprintf(stderr,
1126                                 "Error while setting PSK parameters\n");
1127                         GERR(ret);
1128                 }
1129
1130                 if (HAVE_OPT(PSKHINT)) {
1131                         ret =
1132                             gnutls_psk_set_server_credentials_hint
1133                             (psk_cred, OPT_ARG(PSKHINT));
1134                         if (ret) {
1135                                 fprintf(stderr,
1136                                         "Error setting PSK identity hint.\n");
1137                                 GERR(ret);
1138                         }
1139                 }
1140
1141                 gnutls_psk_set_server_params_function(psk_cred,
1142                                                       get_params);
1143         }
1144 #endif
1145
1146 #ifdef ENABLE_ANON
1147         gnutls_anon_allocate_server_credentials(&dh_cred);
1148         gnutls_anon_set_server_params_function(dh_cred, get_params);
1149
1150 /*      gnutls_anon_set_server_dh_params(dh_cred, dh_params); */
1151 #endif
1152
1153 #ifdef ENABLE_SESSION_TICKETS
1154         if (noticket == 0)
1155                 gnutls_session_ticket_key_generate(&session_ticket_key);
1156 #endif
1157
1158         if (HAVE_OPT(MTU))
1159                 mtu = OPT_VALUE_MTU;
1160         else
1161                 mtu = 1300;
1162
1163         if (HAVE_OPT(PORT))
1164                 port = OPT_VALUE_PORT;
1165         else
1166                 port = 5556;
1167
1168         if (HAVE_OPT(UDP))
1169                 udp_server(name, port, mtu);
1170         else
1171                 tcp_server(name, port);
1172
1173         return 0;
1174 }
1175
1176 static void retry_handshake(listener_item *j)
1177 {
1178         int r, ret;
1179
1180         r = gnutls_handshake(j->tls_session);
1181         if (r < 0 && gnutls_error_is_fatal(r) == 0) {
1182                 check_alert(j->tls_session, r);
1183                 /* nothing */
1184         } else if (r < 0) {
1185                 j->http_state = HTTP_STATE_CLOSING;
1186                 check_alert(j->tls_session, r);
1187                 fprintf(stderr, "Error in handshake\n");
1188                 GERR(r);
1189
1190                 do {
1191                         ret = gnutls_alert_send_appropriate(j->tls_session, r);
1192                 } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);
1193         } else if (r == 0) {
1194                 if (gnutls_session_is_resumed(j->tls_session) != 0 && verbose != 0)
1195                         printf("*** This is a resumed session\n");
1196
1197                 if (verbose != 0) {
1198 #if 0
1199                         printf("- connection from %s\n",
1200                              human_addr((struct sockaddr *)
1201                                 &client_address,
1202                                 calen,
1203                                 topbuf,
1204                                 sizeof(topbuf)));
1205 #endif
1206
1207                         print_info(j->tls_session, verbose, verbose);
1208                 }
1209
1210                 j->handshake_ok = 1;
1211         }
1212 }
1213
1214 static void try_rehandshake(listener_item *j)
1215 {
1216 int r, ret;
1217         fprintf(stderr, "*** Received hello message\n");
1218         do {
1219                 r = gnutls_handshake(j->tls_session);
1220         } while (r == GNUTLS_E_INTERRUPTED || r == GNUTLS_E_AGAIN);
1221
1222         if (r < 0) {
1223                 do {
1224                         ret = gnutls_alert_send_appropriate(j->tls_session, r);
1225                 } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);
1226                 GERR(r);
1227                 j->http_state = HTTP_STATE_CLOSING;
1228         } else {
1229                 j->http_state = HTTP_STATE_REQUEST;
1230         }
1231 }
1232
1233 static void tcp_server(const char *name, int port)
1234 {
1235         int n, s;
1236         char topbuf[512];
1237         int accept_fd;
1238         struct sockaddr_storage client_address;
1239         socklen_t calen;
1240         struct timeval tv;
1241
1242         s = listen_socket(name, port, SOCK_STREAM);
1243         if (s < 0)
1244                 exit(1);
1245
1246         for (;;) {
1247                 listener_item *j;
1248                 fd_set rd, wr;
1249                 time_t now = time(0);
1250 #ifndef _WIN32
1251                 int val;
1252 #endif
1253
1254                 FD_ZERO(&rd);
1255                 FD_ZERO(&wr);
1256                 n = 0;
1257
1258 /* flag which connections we are reading or writing to within the fd sets */
1259                 lloopstart(listener_list, j) {
1260
1261 #ifndef _WIN32
1262                         val = fcntl(j->fd, F_GETFL, 0);
1263                         if ((val == -1)
1264                             || (fcntl(j->fd, F_SETFL, val | O_NONBLOCK) <
1265                                 0)) {
1266                                 perror("fcntl()");
1267                                 exit(1);
1268                         }
1269 #endif
1270                         if (j->start != 0 && now - j->start > 30) {
1271                                 if (verbose != 0) {
1272                                         fprintf(stderr, "Scheduling inactive connection for close\n");
1273                                 }
1274                                 j->http_state = HTTP_STATE_CLOSING;
1275                         }
1276
1277                         if (j->listen_socket) {
1278                                 FD_SET(j->fd, &rd);
1279                                 n = MAX(n, j->fd);
1280                         }
1281                         if (j->http_state == HTTP_STATE_REQUEST) {
1282                                 FD_SET(j->fd, &rd);
1283                                 n = MAX(n, j->fd);
1284                         }
1285                         if (j->http_state == HTTP_STATE_RESPONSE) {
1286                                 FD_SET(j->fd, &wr);
1287                                 n = MAX(n, j->fd);
1288                         }
1289                 }
1290                 lloopend(listener_list, j);
1291
1292 /* core operation */
1293                 tv.tv_sec = 10;
1294                 tv.tv_usec = 0;
1295                 n = select(n + 1, &rd, &wr, NULL, &tv);
1296                 if (n == -1 && errno == EINTR)
1297                         continue;
1298                 if (n < 0) {
1299                         perror("select()");
1300                         exit(1);
1301                 }
1302
1303 /* read or write to each connection as indicated by select()'s return argument */
1304                 lloopstart(listener_list, j) {
1305
1306                         /* a new connection has arrived */
1307                         if (FD_ISSET(j->fd, &rd) && j->listen_socket) {
1308                                 calen = sizeof(client_address);
1309                                 memset(&client_address, 0, calen);
1310                                 accept_fd =
1311                                     accept(j->fd,
1312                                            (struct sockaddr *)
1313                                            &client_address, &calen);
1314
1315                                 if (accept_fd < 0) {
1316                                         perror("accept()");
1317                                 } else {
1318                                         time_t tt = time(0);
1319                                         char *ctt;
1320
1321                                         /* new list entry for the connection */
1322                                         lappend(listener_list);
1323                                         j = listener_list.tail;
1324                                         j->http_request =
1325                                             (char *) strdup("");
1326                                         j->http_state = HTTP_STATE_REQUEST;
1327                                         j->fd = accept_fd;
1328                                         j->start = tt;
1329
1330                                         j->tls_session = initialize_session(0);
1331                                         gnutls_session_set_ptr(j->tls_session, j);
1332                                         gnutls_transport_set_int
1333                                             (j->tls_session, accept_fd);
1334                                         set_read_funcs(j->tls_session);
1335                                         j->handshake_ok = 0;
1336
1337                                         if (verbose != 0) {
1338                                                 ctt = ctime(&tt);
1339                                                 ctt[strlen(ctt) - 1] = 0;
1340
1341                                                 printf
1342                                                     ("\n* Accepted connection from %s on %s\n",
1343                                                      human_addr((struct
1344                                                                  sockaddr
1345                                                                  *)
1346                                                                 &client_address,
1347                                                                 calen,
1348                                                                 topbuf,
1349                                                                 sizeof
1350                                                                 (topbuf)),
1351                                                      ctt);
1352                                         }
1353                                 }
1354                         }
1355
1356                         if (FD_ISSET(j->fd, &rd) && !j->listen_socket) {
1357 /* read partial GET request */
1358                                 char buf[1024];
1359                                 int r;
1360
1361                                 if (j->handshake_ok == 0) {
1362                                         retry_handshake(j);
1363                                 }
1364
1365                                 if (j->handshake_ok == 1) {
1366                                         r = gnutls_record_recv(j->
1367                                                                tls_session,
1368                                                                buf,
1369                                                                MIN(1024,
1370                                                                    SMALL_READ_TEST));
1371                                         if (r == GNUTLS_E_INTERRUPTED || r == GNUTLS_E_AGAIN) {
1372                                                 /* do nothing */
1373                                         } else if (r <= 0) {
1374                                                 if (r == GNUTLS_E_HEARTBEAT_PING_RECEIVED) {
1375                                                         gnutls_heartbeat_pong(j->tls_session, 0);
1376                                                 } else if (r == GNUTLS_E_REHANDSHAKE) {
1377                                                         try_rehandshake(j);
1378                                                 } else {
1379                                                         j->http_state = HTTP_STATE_CLOSING;
1380                                                         if (r < 0) {
1381                                                                 check_alert(j->tls_session, r);
1382                                                                 fprintf(stderr,
1383                                                                      "Error while receiving data\n");
1384                                                                 GERR(r);
1385                                                         }
1386                                                 }
1387                                         } else {
1388                                                 j->http_request =
1389                                                     realloc(j->
1390                                                             http_request,
1391                                                             j->
1392                                                             request_length
1393                                                             + r + 1);
1394                                                 if (j->http_request !=
1395                                                     NULL) {
1396                                                         memcpy(j->
1397                                                                http_request
1398                                                                +
1399                                                                j->
1400                                                                request_length,
1401                                                                buf, r);
1402                                                         j->request_length
1403                                                             += r;
1404                                                         j->http_request[j->
1405                                                                         request_length]
1406                                                             = '\0';
1407                                                 } else {
1408                                                         j->http_state =
1409                                                             HTTP_STATE_CLOSING;
1410                                                 }
1411                                         }
1412 /* check if we have a full HTTP header */
1413
1414                                         j->http_response = NULL;
1415                                         if (j->http_state == HTTP_STATE_REQUEST && j->http_request != NULL) {
1416                                                 if ((http == 0
1417                                                      && strchr(j->
1418                                                                http_request,
1419                                                                '\n'))
1420                                                     || strstr(j->
1421                                                               http_request,
1422                                                               "\r\n\r\n")
1423                                                     || strstr(j->
1424                                                               http_request,
1425                                                               "\n\n")) {
1426                                                         get_response(j->
1427                                                                      tls_session,
1428                                                                      j->
1429                                                                      http_request,
1430                                                                      &j->
1431                                                                      http_response,
1432                                                                      &j->
1433                                                                      response_length);
1434                                                         j->http_state =
1435                                                             HTTP_STATE_RESPONSE;
1436                                                         j->response_written
1437                                                             = 0;
1438                                                 }
1439                                         }
1440                                 }
1441                         }
1442
1443                         if (FD_ISSET(j->fd, &wr)) {
1444 /* write partial response request */
1445                                 int r;
1446
1447                                 if (j->handshake_ok == 0) {
1448                                         retry_handshake(j);
1449                                 }
1450
1451                                 if (j->handshake_ok == 1 && j->http_response == NULL) {
1452                                         j->http_state = HTTP_STATE_CLOSING;
1453                                 } else if (j->handshake_ok == 1 && j->http_response != NULL) {
1454                                         r = gnutls_record_send(j->tls_session,
1455                                                                j->http_response
1456                                                                +
1457                                                                j->response_written,
1458                                                                MIN(j->response_length
1459                                                                    -
1460                                                                    j->response_written,
1461                                                                    SMALL_READ_TEST));
1462                                         if (r == GNUTLS_E_INTERRUPTED || r == GNUTLS_E_AGAIN) {
1463                                                 /* do nothing */
1464                                         } else if (r <= 0) {
1465                                                 j->http_state = HTTP_STATE_CLOSING;
1466                                                 if (r < 0) {
1467                                                         fprintf(stderr,
1468                                                                 "Error while sending data\n");
1469                                                         GERR(r);
1470                                                 }
1471                                                 check_alert(j->tls_session,
1472                                                             r);
1473                                         } else {
1474                                                 j->response_written += r;
1475 /* check if we have written a complete response */
1476                                                 if (j->response_written ==
1477                                                     j->response_length) {
1478                                                         if (http != 0)
1479                                                                 j->http_state = HTTP_STATE_CLOSING;
1480                                                         else {
1481                                                                 j->http_state = HTTP_STATE_REQUEST;
1482                                                                 free(j->
1483                                                                      http_response);
1484                                                                 j->response_length = 0;
1485                                                                 j->request_length = 0;
1486                                                                 j->http_request[0] = 0;
1487                                                         }
1488                                                 }
1489                                         }
1490                                 } else {
1491                                         j->request_length = 0;
1492                                         j->http_request[0] = 0;
1493                                         j->http_state = HTTP_STATE_REQUEST;
1494                                 }
1495                         }
1496                 }
1497                 lloopend(listener_list, j);
1498
1499 /* loop through all connections, closing those that are in error */
1500                 lloopstart(listener_list, j) {
1501                         if (j->http_state == HTTP_STATE_CLOSING) {
1502                                 ldeleteinc(listener_list, j);
1503                         }
1504                 }
1505                 lloopend(listener_list, j);
1506         }
1507
1508
1509         gnutls_certificate_free_credentials(cert_cred);
1510
1511 #ifdef ENABLE_SRP
1512         if (srp_cred)
1513                 gnutls_srp_free_server_credentials(srp_cred);
1514 #endif
1515
1516 #ifdef ENABLE_PSK
1517         if (psk_cred)
1518                 gnutls_psk_free_server_credentials(psk_cred);
1519 #endif
1520
1521 #ifdef ENABLE_ANON
1522         gnutls_anon_free_server_credentials(dh_cred);
1523 #endif
1524
1525         if (noticket == 0)
1526                 gnutls_free(session_ticket_key.data);
1527
1528         if (nodb == 0)
1529                 wrap_db_deinit();
1530         gnutls_global_deinit();
1531
1532 }
1533
1534 static void cmd_parser(int argc, char **argv)
1535 {
1536         optionProcess(&gnutls_servOptions, argc, argv);
1537
1538         disable_client_cert = HAVE_OPT(DISABLE_CLIENT_CERT);
1539         require_cert = ENABLED_OPT(REQUIRE_CLIENT_CERT);
1540         if (HAVE_OPT(DEBUG))
1541                 debug = OPT_VALUE_DEBUG;
1542
1543         if (HAVE_OPT(QUIET))
1544                 verbose = 0;
1545
1546         if (HAVE_OPT(PRIORITY))
1547                 priorities = OPT_ARG(PRIORITY);
1548
1549         if (HAVE_OPT(LIST)) {
1550                 print_list(priorities, verbose);
1551                 exit(0);
1552         }
1553
1554         nodb = HAVE_OPT(NODB);
1555         noticket = HAVE_OPT(NOTICKET);
1556
1557         if (HAVE_OPT(ECHO))
1558                 http = 0;
1559         else
1560                 http = 1;
1561
1562         if (HAVE_OPT(X509FMTDER))
1563                 x509ctype = GNUTLS_X509_FMT_DER;
1564         else
1565                 x509ctype = GNUTLS_X509_FMT_PEM;
1566
1567         generate = HAVE_OPT(GENERATE);
1568
1569         if (HAVE_OPT(DHPARAMS))
1570                 dh_params_file = OPT_ARG(DHPARAMS);
1571
1572         if (HAVE_OPT(X509KEYFILE))
1573                 x509_keyfile = OPT_ARG(X509KEYFILE);
1574         if (HAVE_OPT(X509CERTFILE))
1575                 x509_certfile = OPT_ARG(X509CERTFILE);
1576
1577         if (HAVE_OPT(X509DSAKEYFILE))
1578                 x509_dsakeyfile = OPT_ARG(X509DSAKEYFILE);
1579         if (HAVE_OPT(X509DSACERTFILE))
1580                 x509_dsacertfile = OPT_ARG(X509DSACERTFILE);
1581
1582
1583         if (HAVE_OPT(X509ECCKEYFILE))
1584                 x509_ecckeyfile = OPT_ARG(X509ECCKEYFILE);
1585         if (HAVE_OPT(X509ECCCERTFILE))
1586                 x509_ecccertfile = OPT_ARG(X509ECCCERTFILE);
1587
1588         if (HAVE_OPT(X509CAFILE))
1589                 x509_cafile = OPT_ARG(X509CAFILE);
1590         if (HAVE_OPT(X509CRLFILE))
1591                 x509_crlfile = OPT_ARG(X509CRLFILE);
1592
1593         if (HAVE_OPT(PGPKEYFILE))
1594                 pgp_keyfile = OPT_ARG(PGPKEYFILE);
1595         if (HAVE_OPT(PGPCERTFILE))
1596                 pgp_certfile = OPT_ARG(PGPCERTFILE);
1597
1598         if (HAVE_OPT(PGPKEYRING))
1599                 pgp_keyring = OPT_ARG(PGPKEYRING);
1600
1601         if (HAVE_OPT(SRPPASSWD))
1602                 srp_passwd = OPT_ARG(SRPPASSWD);
1603         if (HAVE_OPT(SRPPASSWDCONF))
1604                 srp_passwd_conf = OPT_ARG(SRPPASSWDCONF);
1605
1606         if (HAVE_OPT(PSKPASSWD))
1607                 psk_passwd = OPT_ARG(PSKPASSWD);
1608
1609         if (HAVE_OPT(OCSP_RESPONSE))
1610                 status_response_ocsp = OPT_ARG(OCSP_RESPONSE);
1611
1612 }
1613
1614 /* session resuming support */
1615
1616 #define SESSION_ID_SIZE 32
1617 #define SESSION_DATA_SIZE 1024
1618
1619 typedef struct {
1620         char session_id[SESSION_ID_SIZE];
1621         unsigned int session_id_size;
1622
1623         char session_data[SESSION_DATA_SIZE];
1624         unsigned int session_data_size;
1625 } CACHE;
1626
1627 static CACHE *cache_db;
1628 int cache_db_ptr = 0;
1629
1630 static void wrap_db_init(void)
1631 {
1632         /* allocate cache_db */
1633         cache_db = calloc(1, ssl_session_cache * sizeof(CACHE));
1634 }
1635
1636 static void wrap_db_deinit(void)
1637 {
1638 }
1639
1640 static int
1641 wrap_db_store(void *dbf, gnutls_datum_t key, gnutls_datum_t data)
1642 {
1643
1644         if (cache_db == NULL)
1645                 return -1;
1646
1647         if (key.size > SESSION_ID_SIZE)
1648                 return -1;
1649         if (data.size > SESSION_DATA_SIZE)
1650                 return -1;
1651
1652         memcpy(cache_db[cache_db_ptr].session_id, key.data, key.size);
1653         cache_db[cache_db_ptr].session_id_size = key.size;
1654
1655         memcpy(cache_db[cache_db_ptr].session_data, data.data, data.size);
1656         cache_db[cache_db_ptr].session_data_size = data.size;
1657
1658         cache_db_ptr++;
1659         cache_db_ptr %= ssl_session_cache;
1660
1661         return 0;
1662 }
1663
1664 static gnutls_datum_t wrap_db_fetch(void *dbf, gnutls_datum_t key)
1665 {
1666         gnutls_datum_t res = { NULL, 0 };
1667         int i;
1668
1669         if (cache_db == NULL)
1670                 return res;
1671
1672         for (i = 0; i < ssl_session_cache; i++) {
1673                 if (key.size == cache_db[i].session_id_size &&
1674                     memcmp(key.data, cache_db[i].session_id,
1675                            key.size) == 0) {
1676                         res.size = cache_db[i].session_data_size;
1677
1678                         res.data = gnutls_malloc(res.size);
1679                         if (res.data == NULL)
1680                                 return res;
1681
1682                         memcpy(res.data, cache_db[i].session_data,
1683                                res.size);
1684
1685                         return res;
1686                 }
1687         }
1688         return res;
1689 }
1690
1691 static int wrap_db_delete(void *dbf, gnutls_datum_t key)
1692 {
1693         int i;
1694
1695         if (cache_db == NULL)
1696                 return -1;
1697
1698         for (i = 0; i < ssl_session_cache; i++) {
1699                 if (key.size == (unsigned int) cache_db[i].session_id_size
1700                     && memcmp(key.data, cache_db[i].session_id,
1701                               key.size) == 0) {
1702
1703                         cache_db[i].session_id_size = 0;
1704                         cache_db[i].session_data_size = 0;
1705
1706                         return 0;
1707                 }
1708         }
1709
1710         return -1;
1711 }