2 #include <sys/socket.h>
5 #include <openssl/lhash.h>
6 #include <openssl/bn.h>
7 #include <openssl/err.h>
8 #include <openssl/pem.h>
9 #include <openssl/x509.h>
10 #include <openssl/ssl.h>
12 static SSL_CTX *tls_ctx = NULL;
13 static SSL *tls_conn = NULL;
16 tls_ssl_ctx_new (cert_file, key_file)
17 const char *cert_file, *key_file;
19 SSL_load_error_strings ();
20 SSLeay_add_ssl_algorithms ();
22 tls_ctx = SSL_CTX_new (TLSv1_client_method());
26 SSL_CTX_set_options (tls_ctx, SSL_OP_ALL /* Work around all known bugs */);
30 if (SSL_CTX_use_certificate_file (tls_ctx, cert_file,
31 SSL_FILETYPE_PEM) <= 0)
35 if (SSL_CTX_use_PrivateKey_file (tls_ctx, key_file,
36 SSL_FILETYPE_PEM) <= 0)
38 if (!SSL_CTX_check_private_key (tls_ctx))
42 SSL_CTX_set_verify (tls_ctx, SSL_VERIFY_NONE, NULL);
56 tls_conn = (SSL *) SSL_new (ctx);
61 if (!SSL_set_fd (tls_conn, s))
64 SSL_set_connect_state (tls_conn);
66 if (SSL_connect (tls_conn) <= 0)
68 session = SSL_get_session (tls_conn);
70 SSL_CTX_remove_session (ctx, session);
80 tls_connect (hostname, service)
81 const char *hostname, *service;
83 int server, false = 0;
85 struct addrinfo *in, *in0, hints;
89 struct sockaddr_in sin;
93 memset (&hints, 0, sizeof (hints));
94 hints.ai_family = AF_UNSPEC;
95 hints.ai_socktype = SOCK_STREAM;
96 if (getaddrinfo (hostname, service, &hints, &in0))
99 for (in = in0; in; in = in->ai_next)
101 server = socket (in->ai_family, in->ai_socktype, in->ai_protocol);
104 if (connect (server, in->ai_addr, in->ai_addrlen) < 0)
115 memset (&sin, 0, sizeof (sin));
116 host = gethostbyname (hostname);
119 memcpy (&sin.sin_addr, host->h_addr, host->h_length);
120 serv = getservbyname (service, "tcp");
122 sin.sin_port = serv->s_port;
123 else if (isdigit (service[0]))
124 sin.sin_port = htons (atoi (service));
125 sin.sin_family = AF_INET;
126 server = socket (sin.sin_family, SOCK_STREAM, 0);
130 if (connect (server, (struct sockaddr *)&sin, sizeof (sin)) < 0)
137 setsockopt (server, SOL_SOCKET, SO_KEEPALIVE, (const char *) &false,
144 tls_negotiate (fd, cert_file, key_file)
147 if (tls_ssl_ctx_new (cert_file, key_file) == -1)
150 (void) tls_ssl_new (tls_ctx, fd); /* Negotiation has done. */
154 tls_write(fd, buf, num)
159 return SSL_write (tls_conn, buf, num);
160 return write (fd, buf, num);
164 tls_read(fd, buf, num)
169 return SSL_read (tls_conn, buf, num);
170 return read (fd, buf, num);
176 return tls_conn && SSL_pending(tls_conn);