1 /* ====================================================================
2  * The Kannel Software License, Version 1.0
3  *
4  * Copyright (c) 2001-2014 Kannel Group
5  * Copyright (c) 1998-2001 WapIT Ltd.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  *    if any, must include the following acknowledgment:
22  *       "This product includes software developed by the
23  *        Kannel Group (http://www.kannel.org/)."
24  *    Alternately, this acknowledgment may appear in the software itself,
25  *    if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "Kannel" and "Kannel Group" must not be used to
28  *    endorse or promote products derived from this software without
29  *    prior written permission. For written permission, please
30  *    contact org@kannel.org.
31  *
32  * 5. Products derived from this software may not be called "Kannel",
33  *    nor may "Kannel" appear in their name, without prior written
34  *    permission of the Kannel Group.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED.  IN NO EVENT SHALL THE KANNEL GROUP OR ITS CONTRIBUTORS
40  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
41  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
42  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
43  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
44  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
45  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
46  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Kannel Group.  For more information on
51  * the Kannel Group, please see <http://www.kannel.org/>.
52  *
53  * Portions of this software are based upon software originally written at
54  * WapIT Ltd., Helsinki, Finland for the Kannel project.
55  */
56 
57 /* conn.c - implement Connection type
58  *
59  * This file implements the interface defined in conn.h.
60  *
61  * Richard Braakman
62  *
63  * SSL client implementation contributed by
64  * Jarkko Kovala <jarkko.kovala@iki.fi>
65  *
66  * SSL server implementation contributed by
67  * Stipe Tolj <stolj@wapme.de> for Wapme Systems AG
68  */
69 
70 /* TODO: unlocked_close() on error */
71 /* TODO: have I/O functions check if connection is open */
72 /* TODO: have conn_open_tcp do a non-blocking connect() */
73 
74 #include <signal.h>
75 #include <unistd.h>
76 #include <errno.h>
77 
78 #include <sys/types.h>
79 #include <sys/socket.h>
80 #include <string.h>
81 
82 #include "gwlib/gwlib.h"
83 
84 #ifdef HAVE_LIBSSL
85 #include <openssl/ssl.h>
86 #include <openssl/err.h>
87 
88 static SSL_CTX *global_ssl_context = NULL;
89 static SSL_CTX *global_server_ssl_context = NULL;
90 #endif /* HAVE_LIBSSL */
91 
92 typedef unsigned long (*CRYPTO_CALLBACK_PTR)(void);
93 
94 /*
95  * This used to be 4096.  It is now 0 so that callers don't have to
96  * deal with the complexities of buffering (i.e. deciding when to
97  * flush) unless they want to.
98  * FIXME: Figure out how to combine buffering sensibly with use of
99  * conn_register.
100  */
101 #define DEFAULT_OUTPUT_BUFFERING 0
102 #define SSL_CONN_TIMEOUT         30
103 
104 struct Connection
105 {
106     /* We use separate locks for input and ouput fields, so that
107      * read and write activities don't have to get in each other's
108      * way.  If you need both, then acquire the outlock first. */
109     Mutex *inlock;
110     Mutex *outlock;
111     volatile sig_atomic_t claimed;
112 #ifndef NO_GWASSERT
113     long claiming_thread;
114 #endif
115 
116     /* fd value is read-only and is not locked */
117     int fd;
118 
119     /* socket state */
120     enum {yes,no} connected;
121 
122     /* Protected by outlock */
123     Octstr *outbuf;
124     long outbufpos;   /* start of unwritten data in outbuf */
125 
126     /* Try to buffer writes until there are this many octets to send.
127      * Set it to 0 to get an unbuffered connection. */
128     unsigned int output_buffering;
129 
130     /* Protected by inlock */
131     Octstr *inbuf;
132     long inbufpos;    /* start of unread data in inbuf */
133 
134     int read_eof;     /* we encountered eof on read */
135     int io_error;   /* we encountered error on IO operation */
136 
137     /* Protected by both locks when updating, so you need only one
138      * of the locks when reading. */
139     FDSet *registered;
140     conn_callback_t *callback;
141     void *callback_data;
142     conn_callback_data_destroyer_t *callback_data_destroyer;
143     /* Protected by inlock */
144     int listening_pollin;
145     /* Protected by outlock */
146     int listening_pollout;
147 
148 #ifdef HAVE_LIBSSL
149     SSL *ssl;
150     X509 *peer_certificate;
151 #endif /* HAVE_LIBSSL */
152 };
153 
154 static void unlocked_register_pollin(Connection *conn, int onoff);
155 static void unlocked_register_pollout(Connection *conn, int onoff);
156 
157 /* There are a number of functions that play with POLLIN and POLLOUT flags.
158  * The general rule is that we always want to poll for POLLIN except when
159  * we have detected eof (which may be reported as eternal POLLIN), and
160  * we want to poll for POLLOUT only if there's data waiting in the
161  * output buffer.  If output buffering is set, we may not want to poll for
162  * POLLOUT if there's not enough data waiting, which is why we have
163  * unlocked_try_write. */
164 
165 /* Macros to get more information for debugging purposes */
166 #define unlock_in(conn) unlock_in_real(conn, __FILE__, __LINE__, __func__)
167 #define unlock_out(conn) unlock_out_real(conn, __FILE__, __LINE__, __func__)
168 
169 /* Lock a Connection's read direction, if the Connection is unclaimed */
lock_in(Connection * conn)170 static void inline lock_in(Connection *conn)
171 {
172     gw_assert(conn != NULL);
173 
174     if (conn->claimed)
175         gw_assert(gwthread_self() == conn->claiming_thread);
176     else
177         mutex_lock(conn->inlock);
178 }
179 
180 /* Unlock a Connection's read direction, if the Connection is unclaimed */
unlock_in_real(Connection * conn,char * file,int line,const char * func)181 static void inline unlock_in_real(Connection *conn, char *file, int line, const char *func)
182 {
183     int ret;
184     gw_assert(conn != NULL);
185 
186     if (!conn->claimed && (ret = mutex_unlock(conn->inlock)) != 0) {
187         panic(0, "%s:%ld: %s: Mutex unlock failed. "
188             "(Called from %s:%ld:%s.)",
189             __FILE__, (long) __LINE__, __func__,
190             file, (long) line, func);
191     }
192 }
193 
194 /* Lock a Connection's write direction, if the Connection is unclaimed */
lock_out(Connection * conn)195 static void inline lock_out(Connection *conn)
196 {
197     gw_assert(conn != NULL);
198 
199     if (conn->claimed)
200         gw_assert(gwthread_self() == conn->claiming_thread);
201     else
202         mutex_lock(conn->outlock);
203 }
204 
205 /* Unlock a Connection's write direction, if the Connection is unclaimed */
unlock_out_real(Connection * conn,char * file,int line,const char * func)206 static void inline unlock_out_real(Connection *conn, char *file, int line, const char *func)
207 {
208     int ret;
209     gw_assert(conn != NULL);
210 
211     if (!conn->claimed && (ret = mutex_unlock(conn->outlock)) != 0) {
212         panic(0, "%s:%ld: %s: Mutex unlock failed. "
213             "(Called from %s:%ld:%s.)",
214             __FILE__, (long) __LINE__, __func__,
215             file, (long) line, func);
216     }
217 }
218 
219 /* Return the number of bytes in the Connection's output buffer */
unlocked_outbuf_len(Connection * conn)220 static long inline unlocked_outbuf_len(Connection *conn)
221 {
222     return octstr_len(conn->outbuf) - conn->outbufpos;
223 }
224 
225 /* Return the number of bytes in the Connection's input buffer */
unlocked_inbuf_len(Connection * conn)226 static long inline unlocked_inbuf_len(Connection *conn)
227 {
228     return octstr_len(conn->inbuf) - conn->inbufpos;
229 }
230 
231 /* Send as much data as can be sent without blocking.  Return the number
232  * of bytes written, or -1 in case of error. */
unlocked_write(Connection * conn)233 static long unlocked_write(Connection *conn)
234 {
235     long ret = 0;
236 
237 #ifdef HAVE_LIBSSL
238     if (conn->ssl != NULL) {
239         if (octstr_len(conn->outbuf) - conn->outbufpos > 0)
240             ret = SSL_write(conn->ssl,
241                         octstr_get_cstr(conn->outbuf) + conn->outbufpos,
242                         octstr_len(conn->outbuf) - conn->outbufpos);
243 
244         if (ret < 0) {
245             int SSL_error = SSL_get_error(conn->ssl, ret);
246 
247             if (SSL_error == SSL_ERROR_WANT_READ || SSL_error == SSL_ERROR_WANT_WRITE) {
248                   ret = 0; /* no error */
249             } else {
250                 error(errno, "SSL write failed: OpenSSL error %d: %s",
251                       SSL_error, ERR_error_string(SSL_error, NULL));
252                 return -1;
253             }
254         }
255     } else
256 #endif /* HAVE_LIBSSL */
257         ret = octstr_write_data(conn->outbuf, conn->fd, conn->outbufpos);
258 
259     if (ret < 0) {
260         conn->io_error = 1;
261         return -1;
262     }
263 
264     conn->outbufpos += ret;
265 
266     /* Heuristic: Discard the already-written data if it's more than
267      * half of the total.  This should keep the buffer size small
268      * without wasting too many cycles on moving data around. */
269     if (conn->outbufpos > octstr_len(conn->outbuf) / 2) {
270         octstr_delete(conn->outbuf, 0, conn->outbufpos);
271         conn->outbufpos = 0;
272     }
273 
274     if (conn->registered)
275         unlocked_register_pollout(conn, unlocked_outbuf_len(conn) > 0);
276 
277     return ret;
278 }
279 
280 /* Try to empty the output buffer without blocking.  Return 0 for success,
281  * 1 if there is still data left in the buffer, and -1 for errors. */
unlocked_try_write(Connection * conn)282 static int unlocked_try_write(Connection *conn)
283 {
284     long len;
285 
286     len = unlocked_outbuf_len(conn);
287     if (len == 0)
288         return 0;
289 
290     if (len < (long) conn->output_buffering)
291         return 1;
292 
293     if (unlocked_write(conn) < 0)
294         return -1;
295 
296     if (unlocked_outbuf_len(conn) > 0)
297         return 1;
298 
299     return 0;
300 }
301 
302 /* Read whatever data is currently available, up to an internal maximum. */
unlocked_read(Connection * conn)303 static void unlocked_read(Connection *conn)
304 {
305     unsigned char buf[4096];
306     long len;
307 
308     if (conn->inbufpos > 0) {
309         octstr_delete(conn->inbuf, 0, conn->inbufpos);
310         conn->inbufpos = 0;
311     }
312 
313 #ifdef HAVE_LIBSSL
314     if (conn->ssl != NULL) {
315         len = SSL_read(conn->ssl, buf, sizeof(buf));
316     } else
317 #endif /* HAVE_LIBSSL */
318         len = read(conn->fd, buf, sizeof(buf));
319 
320     if (len < 0) {
321         if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
322             return;
323 #ifdef HAVE_LIBSSL
324         if (conn->ssl) {
325             int SSL_error = SSL_get_error(conn->ssl, len);
326             if (SSL_error == SSL_ERROR_WANT_WRITE || SSL_error == SSL_ERROR_WANT_READ)
327                 return; /* no error */
328             error(errno, "SSL read failed: OpenSSL error %d: %s",
329                       SSL_error, ERR_error_string(SSL_error, NULL));
330         }
331         else
332 #endif /* HAVE_LIBSSL */
333             error(errno, "Error reading from fd %d:", conn->fd);
334         conn->io_error = 1;
335         if (conn->registered)
336             unlocked_register_pollin(conn, 0);
337         return;
338     } else if (len == 0) {
339         conn->read_eof = 1;
340         if (conn->registered)
341             unlocked_register_pollin(conn, 0);
342     } else {
343         octstr_append_data(conn->inbuf, buf, len);
344     }
345 }
346 
347 /* Cut "length" octets from the input buffer and return them as an Octstr */
unlocked_get(Connection * conn,long length)348 static Octstr *unlocked_get(Connection *conn, long length)
349 {
350     Octstr *result = NULL;
351 
352     gw_assert(unlocked_inbuf_len(conn) >= length);
353     result = octstr_copy(conn->inbuf, conn->inbufpos, length);
354     conn->inbufpos += length;
355 
356     return result;
357 }
358 
359 /* Tell the fdset whether we are interested in POLLIN events, but only
360  * if the status changed.  (Calling fdset_listen can be expensive if
361  * it requires synchronization with the polling thread.)
362  * We must already have the inlock.
363  */
unlocked_register_pollin(Connection * conn,int onoff)364 static void unlocked_register_pollin(Connection *conn, int onoff)
365 {
366     gw_assert(conn->registered);
367 
368     if (onoff == 1 && !conn->listening_pollin) {
369         /* Turn it on */
370         conn->listening_pollin = 1;
371         fdset_listen(conn->registered, conn->fd, POLLIN, POLLIN);
372     } else if (onoff == 0 && conn->listening_pollin) {
373         /* Turn it off */
374         conn->listening_pollin = 0;
375         fdset_listen(conn->registered, conn->fd, POLLIN, 0);
376     }
377 }
378 
379 /* Tell the fdset whether we are interested in POLLOUT events, but only
380  * if the status changed.  (Calling fdset_listen can be expensive if
381  * it requires synchronization with the polling thread.)
382  * We must already have the outlock.
383  */
unlocked_register_pollout(Connection * conn,int onoff)384 static void unlocked_register_pollout(Connection *conn, int onoff)
385 {
386     gw_assert(conn->registered);
387 
388     if (onoff == 1 && !conn->listening_pollout) {
389         /* Turn it on */
390         conn->listening_pollout = 1;
391         fdset_listen(conn->registered, conn->fd, POLLOUT, POLLOUT);
392     } else if (onoff == 0 && conn->listening_pollout) {
393         /* Turn it off */
394         conn->listening_pollout = 0;
395         fdset_listen(conn->registered, conn->fd, POLLOUT, 0);
396     }
397 }
398 
399 #ifdef HAVE_LIBSSL
conn_init_client_ssl(Connection * ret,Octstr * certkeyfile)400 static int conn_init_client_ssl(Connection *ret, Octstr *certkeyfile)
401 {
402     ret->ssl = SSL_new(global_ssl_context);
403 
404     /*
405      * The current thread's error queue must be empty before
406      * the TLS/SSL I/O operation is attempted, or SSL_get_error()
407      * will not work reliably.
408      */
409     ERR_clear_error();
410 
411     if (certkeyfile != NULL) {
412         SSL_use_certificate_file(ret->ssl, octstr_get_cstr(certkeyfile),
413                                  SSL_FILETYPE_PEM);
414         SSL_use_PrivateKey_file(ret->ssl, octstr_get_cstr(certkeyfile),
415                                 SSL_FILETYPE_PEM);
416         if (SSL_check_private_key(ret->ssl) != 1) {
417             error(0, "conn_open_ssl: private key isn't consistent with the "
418                      "certificate from file %s (or failed reading the file)",
419                   octstr_get_cstr(certkeyfile));
420             return -1;
421         }
422     }
423 
424     /* SSL_set_fd can fail, so check it */
425     if (SSL_set_fd(ret->ssl, ret->fd) == 0) {
426         /* SSL_set_fd failed, log error */
427         error(errno, "SSL: OpenSSL: %.256s", ERR_error_string(ERR_get_error(), NULL));
428         return -1;
429     }
430 
431     /*
432      * make sure the socket is non-blocking while we do SSL_connect
433      */
434     if (socket_set_blocking(ret->fd, 0) < 0) {
435         return -1;
436     }
437     BIO_set_nbio(SSL_get_rbio(ret->ssl), 1);
438     BIO_set_nbio(SSL_get_wbio(ret->ssl), 1);
439 
440     SSL_set_connect_state(ret->ssl);
441 
442     return 0;
443 }
444 
conn_open_ssl_nb(Octstr * host,int port,Octstr * certkeyfile,Octstr * our_host)445 Connection *conn_open_ssl_nb(Octstr *host, int port, Octstr *certkeyfile,
446                           Octstr *our_host)
447 {
448     Connection *ret;
449 
450     /* open the TCP connection */
451     if (!(ret = conn_open_tcp_nb(host, port, our_host))) {
452         return NULL;
453     }
454 
455     if (conn_init_client_ssl(ret, certkeyfile) == -1) {
456         conn_destroy(ret);
457         return NULL;
458     }
459 
460     return ret;
461 }
462 
conn_open_ssl(Octstr * host,int port,Octstr * certkeyfile,Octstr * our_host)463 Connection *conn_open_ssl(Octstr *host, int port, Octstr *certkeyfile,
464 			  Octstr *our_host)
465 {
466     Connection *ret;
467 
468     /* open the TCP connection */
469     if (!(ret = conn_open_tcp(host, port, our_host))) {
470         return NULL;
471     }
472 
473     if (conn_init_client_ssl(ret, certkeyfile) == -1) {
474         conn_destroy(ret);
475         return NULL;
476     }
477 
478     return ret;
479 }
480 
481 #endif /* HAVE_LIBSSL */
482 
conn_open_tcp(Octstr * host,int port,Octstr * our_host)483 Connection *conn_open_tcp(Octstr *host, int port, Octstr *our_host)
484 {
485     return conn_open_tcp_with_port(host, port, 0, our_host);
486 }
487 
conn_open_tcp_nb(Octstr * host,int port,Octstr * our_host)488 Connection *conn_open_tcp_nb(Octstr *host, int port, Octstr *our_host)
489 {
490   return conn_open_tcp_nb_with_port(host, port, 0, our_host);
491 }
492 
conn_open_tcp_nb_with_port(Octstr * host,int port,int our_port,Octstr * our_host)493 Connection *conn_open_tcp_nb_with_port(Octstr *host, int port, int our_port,
494 				       Octstr *our_host)
495 {
496   int sockfd;
497   int done = -1;
498   Connection *c;
499 
500   sockfd = tcpip_connect_nb_to_server_with_port(octstr_get_cstr(host), port,
501 						our_port, our_host == NULL ?
502 						NULL : octstr_get_cstr(our_host), &done);
503   if (sockfd < 0)
504     return NULL;
505   c = conn_wrap_fd(sockfd, 0);
506   if (done != 0) {
507     c->connected = no;
508   }
509   return c;
510 }
511 
conn_is_connected(Connection * conn)512 int conn_is_connected(Connection *conn)
513 {
514   return conn->connected == yes ? 0 : -1;
515 }
516 
conn_get_connect_result(Connection * conn)517 int conn_get_connect_result(Connection *conn)
518 {
519   int err;
520   socklen_t len;
521 
522   len = sizeof(err);
523   if (getsockopt(conn->fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0) {
524     return -1;
525   }
526 
527   if (err) {
528     return -1;
529   }
530 
531   conn->connected = yes;
532   return 0;
533 }
534 
conn_open_tcp_with_port(Octstr * host,int port,int our_port,Octstr * our_host)535 Connection *conn_open_tcp_with_port(Octstr *host, int port, int our_port,
536 		Octstr *our_host)
537 {
538     int sockfd;
539 
540     sockfd = tcpip_connect_to_server_with_port(octstr_get_cstr(host), port,
541 					       our_port, our_host == NULL ?
542 					       NULL : octstr_get_cstr(our_host));
543     if (sockfd < 0)
544 	return NULL;
545     return conn_wrap_fd(sockfd, 0);
546 }
547 
548 
549 /*
550  * XXX bad assumption here that conn_wrap_fd for SSL can only happens
551  * for the server side!!!! FIXME !!!!
552  */
conn_wrap_fd(int fd,int ssl)553 Connection *conn_wrap_fd(int fd, int ssl)
554 {
555     Connection *conn;
556 
557     if (socket_set_blocking(fd, 0) < 0)
558         return NULL;
559 
560     conn = gw_malloc(sizeof(*conn));
561     conn->inlock = mutex_create();
562     conn->outlock = mutex_create();
563     conn->claimed = 0;
564 
565     conn->outbuf = octstr_create("");
566     conn->outbufpos = 0;
567     conn->inbuf = octstr_create("");
568     conn->inbufpos = 0;
569 
570     conn->fd = fd;
571     conn->connected = yes;
572     conn->read_eof = 0;
573     conn->io_error = 0;
574     conn->output_buffering = DEFAULT_OUTPUT_BUFFERING;
575 
576     conn->registered = NULL;
577     conn->callback = NULL;
578     conn->callback_data = NULL;
579     conn->callback_data_destroyer = NULL;
580     conn->listening_pollin = 0;
581     conn->listening_pollout = 0;
582 #ifdef HAVE_LIBSSL
583     /*
584      * do all the SSL magic for this connection
585      */
586     if (ssl) {
587         conn->ssl = SSL_new(global_server_ssl_context);
588         conn->peer_certificate = NULL;
589 
590         /* SSL_set_fd can fail, so check it */
591         if (SSL_set_fd(conn->ssl, conn->fd) == 0) {
592             /* SSL_set_fd failed, log error and return NULL */
593             error(errno, "SSL: OpenSSL: %.256s", ERR_error_string(ERR_get_error(), NULL));
594             conn_destroy(conn);
595             return NULL;
596         }
597         /* SSL_set_verify(conn->ssl, 0, NULL); */
598 
599         /* set read/write BIO layer to non-blocking mode */
600         BIO_set_nbio(SSL_get_rbio(conn->ssl), 1);
601         BIO_set_nbio(SSL_get_wbio(conn->ssl), 1);
602 
603         /* set accept state , SSL-Handshake will be handled transparent while SSL_[read|write] */
604          SSL_set_accept_state(conn->ssl);
605     } else {
606         conn->ssl = NULL;
607         conn->peer_certificate = NULL;
608     }
609 #endif /* HAVE_LIBSSL */
610 
611     return conn;
612 }
613 
conn_destroy(Connection * conn)614 void conn_destroy(Connection *conn)
615 {
616     int ret;
617 
618     if (conn == NULL)
619         return;
620 
621     /* No locking done here.  conn_destroy should not be called
622      * if any thread might still be interested in the connection. */
623 
624     if (conn->registered) {
625         fdset_unregister(conn->registered, conn->fd);
626         /* call data destroyer if any */
627         if (conn->callback_data != NULL && conn->callback_data_destroyer != NULL)
628             conn->callback_data_destroyer(conn->callback_data);
629     }
630 
631     if (conn->fd >= 0) {
632         /* Try to flush any remaining data */
633         unlocked_try_write(conn);
634 
635 #ifdef HAVE_LIBSSL
636         if (conn->ssl != NULL) {
637             SSL_smart_shutdown(conn->ssl);
638             SSL_free(conn->ssl);
639             if (conn->peer_certificate != NULL)
640                 X509_free(conn->peer_certificate);
641 	}
642 #endif /* HAVE_LIBSSL */
643 
644         ret = close(conn->fd);
645         if (ret < 0)
646             error(errno, "conn_destroy: error on close");
647         conn->fd = -1;
648     }
649 
650     octstr_destroy(conn->outbuf);
651     octstr_destroy(conn->inbuf);
652     mutex_destroy(conn->inlock);
653     mutex_destroy(conn->outlock);
654 
655     gw_free(conn);
656 }
657 
conn_claim(Connection * conn)658 void conn_claim(Connection *conn)
659 {
660     gw_assert(conn != NULL);
661 
662     if (conn->claimed)
663         panic(0, "Connection is being claimed twice!");
664     conn->claimed = 1;
665 #ifndef NO_GWASSERT
666     conn->claiming_thread = gwthread_self();
667 #endif
668 }
669 
conn_outbuf_len(Connection * conn)670 long conn_outbuf_len(Connection *conn)
671 {
672     long len;
673 
674     lock_out(conn);
675     len = unlocked_outbuf_len(conn);
676     unlock_out(conn);
677 
678     return len;
679 }
680 
conn_inbuf_len(Connection * conn)681 long conn_inbuf_len(Connection *conn)
682 {
683     long len;
684 
685     lock_in(conn);
686     len = unlocked_inbuf_len(conn);
687     unlock_in(conn);
688 
689     return len;
690 }
691 
conn_eof(Connection * conn)692 int conn_eof(Connection *conn)
693 {
694     int eof;
695 
696     lock_in(conn);
697     eof = conn->read_eof;
698     unlock_in(conn);
699 
700     return eof;
701 }
702 
conn_error(Connection * conn)703 int conn_error(Connection *conn)
704 {
705     int err;
706 
707     lock_out(conn);
708     lock_in(conn);
709     err = conn->io_error;
710     unlock_in(conn);
711     unlock_out(conn);
712 
713     return err;
714 }
715 
conn_set_output_buffering(Connection * conn,unsigned int size)716 void conn_set_output_buffering(Connection *conn, unsigned int size)
717 {
718     lock_out(conn);
719     conn->output_buffering = size;
720     /* If the buffer size is smaller, we may have to write immediately. */
721     unlocked_try_write(conn);
722     unlock_out(conn);
723 }
724 
poll_callback(int fd,int revents,void * data)725 static void poll_callback(int fd, int revents, void *data)
726 {
727     Connection *conn;
728     int do_callback = 0;
729 
730     conn = data;
731 
732     if (conn == NULL) {
733         error(0, "poll_callback called with NULL connection.");
734         return;
735     }
736 
737     if (conn->fd != fd) {
738         error(0, "poll_callback called on wrong connection.");
739         return;
740     }
741 
742     /* Get result of nonblocking connect, before any reads and writes
743      * we must check result (it must be handled in initial callback) */
744     if (conn->connected == no) {
745         if (conn->callback)
746             conn->callback(conn, conn->callback_data);
747         return;
748     }
749 
750     /* If got POLLERR or POLHUP, then unregister the descriptor from the
751      * fdset and set the error condition variable to let the upper layer
752      * close and destroy the connection. */
753     if (revents & (POLLERR|POLLHUP)) {
754         lock_out(conn);
755         lock_in(conn);
756         if (conn->listening_pollin)
757             unlocked_register_pollin(conn, 0);
758         if (conn->listening_pollout)
759             unlocked_register_pollout(conn, 0);
760         conn->io_error = 1;
761         unlock_in(conn);
762         unlock_out(conn);
763         do_callback = 1;
764     }
765 
766     /* If unlocked_write manages to write all pending data, it will
767      * tell the fdset to stop listening for POLLOUT. */
768     if (revents & POLLOUT) {
769         lock_out(conn);
770         unlocked_write(conn);
771         if (unlocked_outbuf_len(conn) == 0)
772             do_callback = 1;
773         unlock_out(conn);
774     }
775 
776     /* We read only in unlocked_read in we received POLLIN, cause the
777      * descriptor is already broken and of no use anymore. */
778     if (revents & POLLIN) {
779         lock_in(conn);
780         unlocked_read(conn);
781         unlock_in(conn);
782         do_callback = 1;
783     }
784 
785     if (do_callback && conn->callback)
786         conn->callback(conn, conn->callback_data);
787 }
788 
conn_register_real(Connection * conn,FDSet * fdset,conn_callback_t callback,void * data,conn_callback_data_destroyer_t * data_destroyer)789 int conn_register_real(Connection *conn, FDSet *fdset,
790                   conn_callback_t callback, void *data, conn_callback_data_destroyer_t *data_destroyer)
791 {
792     int events;
793     int result = 0;
794 
795     gw_assert(conn != NULL);
796 
797     if (conn->fd < 0)
798         return -1;
799 
800     /* We need both locks if we want to update the registration
801      * information. */
802     lock_out(conn);
803     lock_in(conn);
804 
805     if (conn->registered == fdset) {
806         /* Re-registering.  Change only the callback info. */
807         conn->callback = callback;
808         /* call data destroyer if new data supplied */
809         if (conn->callback_data != NULL && conn->callback_data != data && conn->callback_data_destroyer != NULL)
810             conn->callback_data_destroyer(conn->callback_data);
811         conn->callback_data = data;
812         conn->callback_data_destroyer = data_destroyer;
813         result = 0;
814     } else if (conn->registered) {
815         /* Already registered to a different fdset. */
816         result = -1;
817     } else {
818         events = 0;
819 	/* For nonconnected socket we must lesten both directions */
820         if (conn->connected == yes) {
821             if (conn->read_eof == 0 && conn->io_error == 0)
822                 events |= POLLIN;
823             if (unlocked_outbuf_len(conn) > 0)
824                 events |= POLLOUT;
825         } else {
826           events |= POLLIN | POLLOUT;
827         }
828 
829         conn->registered = fdset;
830         conn->callback = callback;
831         conn->callback_data = data;
832         conn->callback_data_destroyer = data_destroyer;
833         conn->listening_pollin = (events & POLLIN) != 0;
834         conn->listening_pollout = (events & POLLOUT) != 0;
835         fdset_register(fdset, conn->fd, events, poll_callback, conn);
836         result = 0;
837     }
838 
839     unlock_in(conn);
840     unlock_out(conn);
841 
842     return result;
843 }
844 
conn_unregister(Connection * conn)845 void conn_unregister(Connection *conn)
846 {
847     FDSet *set = NULL;
848     int fd = -1;
849     void *data = NULL;
850     conn_callback_data_destroyer_t *destroyer = NULL;
851 
852     gw_assert(conn != NULL);
853 
854     if (conn == NULL || conn->fd < 0)
855         return;
856 
857     /* We need both locks to update the registration information */
858     lock_out(conn);
859     lock_in(conn);
860 
861     if (conn->registered) {
862         set = conn->registered;
863         fd = conn->fd;
864         conn->registered = NULL;
865         conn->callback = NULL;
866         /*
867          * remember and don't destroy data and data_destroyer because we
868          * may be in callback right now. So destroy only after fdset_unregister
869          * call which guarantee us we are not in callback anymore.
870          */
871         data = conn->callback_data;
872         conn->callback_data = NULL;
873         destroyer = conn->callback_data_destroyer;
874         conn->callback_data_destroyer = NULL;
875         conn->listening_pollin = 0;
876         conn->listening_pollout = 0;
877     }
878 
879     unlock_in(conn);
880     unlock_out(conn);
881 
882     /* now unregister from FDSet */
883     if (set != NULL)
884         fdset_unregister(set, fd);
885 
886     /* ok we are not in callback anymore, destroy data if any */
887     if (data != NULL && destroyer != NULL)
888         destroyer(data);
889 }
890 
conn_wait(Connection * conn,double seconds)891 int conn_wait(Connection *conn, double seconds)
892 {
893     int events;
894     int ret;
895     int fd;
896 
897     lock_out(conn);
898 
899     /* Try to write any data that might still be waiting to be sent */
900     ret = unlocked_write(conn);
901     if (ret < 0) {
902         unlock_out(conn);
903         return -1;
904     }
905     if (ret > 0) {
906         /* We did something useful.  No need to poll or wait now. */
907         unlock_out(conn);
908         return 0;
909     }
910 
911     fd = conn->fd;
912 
913     /* Normally, we block until there is more data available.  But
914      * if any data still needs to be sent, we block until we can
915      * send it (or there is more data available).  We always block
916      * for reading, unless we know there is no more data coming.
917      * (Because in that case, poll will keep reporting POLLIN to
918      * signal the end of the file).  If the caller explicitly wants
919      * to wait even though there is no data to write and we're at
920      * end of file, then poll for new data anyway because the caller
921      * apparently doesn't trust eof. */
922     events = 0;
923     if (unlocked_outbuf_len(conn) > 0)
924         events |= POLLOUT;
925     /* Don't keep the connection locked while we wait */
926     unlock_out(conn);
927 
928     /* We need the in lock to query read_eof */
929     lock_in(conn);
930     if ((conn->read_eof == 0 && conn->io_error == 0) || events == 0)
931         events |= POLLIN;
932     unlock_in(conn);
933 
934     ret = gwthread_pollfd(fd, events, seconds);
935     if (ret < 0) {
936         if (errno == EINTR)
937             return 0;
938         error(0, "conn_wait: poll failed on fd %d:", fd);
939         return -1;
940     }
941 
942     if (ret == 0)
943         return 1;
944 
945     if (ret & POLLNVAL) {
946         error(0, "conn_wait: fd %d not open.", fd);
947         return -1;
948     }
949 
950     if (ret & (POLLERR | POLLHUP)) {
951         /* Call unlocked_read to report the specific error,
952          * and handle the results of the error.  We can't be
953          * certain that the error still exists, because we
954          * released the lock for a while. */
955         lock_in(conn);
956         unlocked_read(conn);
957         unlock_in(conn);
958         return -1;
959     }
960 
961     /* If POLLOUT is on, then we must have wanted
962      * to write something. */
963     if (ret & POLLOUT) {
964         lock_out(conn);
965         unlocked_write(conn);
966         unlock_out(conn);
967     }
968 
969     /* Since we normally select for reading, we must
970      * try to read here.  Otherwise, if the caller loops
971      * around conn_wait without making conn_read* calls
972      * in between, we will keep polling this same data. */
973     if (ret & POLLIN) {
974         lock_in(conn);
975         unlocked_read(conn);
976         unlock_in(conn);
977     }
978 
979     return 0;
980 }
981 
conn_flush(Connection * conn)982 int conn_flush(Connection *conn)
983 {
984     int ret;
985     int revents;
986     int fd;
987 
988     lock_out(conn);
989     ret = unlocked_write(conn);
990     if (ret < 0) {
991         unlock_out(conn);
992         return -1;
993     }
994 
995     while (unlocked_outbuf_len(conn) != 0) {
996         fd = conn->fd;
997 
998         unlock_out(conn);
999         revents = gwthread_pollfd(fd, POLLOUT, -1.0);
1000 
1001         /* Note: Make sure we have the "out" lock when
1002          * going through the loop again, because the
1003          * loop condition needs it. */
1004 
1005         if (revents < 0) {
1006             if (errno == EINTR)
1007                 return 1;
1008             error(0, "conn_flush: poll failed on fd %d:", fd);
1009             return -1;
1010         }
1011 
1012         if (revents == 0) {
1013             /* We were woken up */
1014             return 1;
1015         }
1016 
1017         if (revents & POLLNVAL) {
1018             error(0, "conn_flush: fd %d not open.", fd);
1019             return -1;
1020         }
1021 
1022         lock_out(conn);
1023 
1024         if (revents & (POLLOUT | POLLERR | POLLHUP)) {
1025             ret = unlocked_write(conn);
1026             if (ret < 0) {
1027                 unlock_out(conn);
1028                 return -1;
1029             }
1030         }
1031     }
1032 
1033     unlock_out(conn);
1034 
1035     return 0;
1036 }
1037 
conn_write(Connection * conn,Octstr * data)1038 int conn_write(Connection *conn, Octstr *data)
1039 {
1040     int ret;
1041 
1042     lock_out(conn);
1043     octstr_append(conn->outbuf, data);
1044     ret = unlocked_try_write(conn);
1045     unlock_out(conn);
1046 
1047     return ret;
1048 }
1049 
conn_write_data(Connection * conn,unsigned char * data,long length)1050 int conn_write_data(Connection *conn, unsigned char *data, long length)
1051 {
1052     int ret;
1053 
1054     lock_out(conn);
1055     octstr_append_data(conn->outbuf, data, length);
1056     ret = unlocked_try_write(conn);
1057     unlock_out(conn);
1058 
1059     return ret;
1060 }
1061 
conn_write_withlen(Connection * conn,Octstr * data)1062 int conn_write_withlen(Connection *conn, Octstr *data)
1063 {
1064     int ret;
1065     unsigned char lengthbuf[4];
1066 
1067     encode_network_long(lengthbuf, octstr_len(data));
1068     lock_out(conn);
1069     octstr_append_data(conn->outbuf, lengthbuf, 4);
1070     octstr_append(conn->outbuf, data);
1071     ret = unlocked_try_write(conn);
1072     unlock_out(conn);
1073 
1074     return ret;
1075 }
1076 
conn_read_everything(Connection * conn)1077 Octstr *conn_read_everything(Connection *conn)
1078 {
1079     Octstr *result = NULL;
1080 
1081     lock_in(conn);
1082     if (unlocked_inbuf_len(conn) == 0) {
1083         unlocked_read(conn);
1084         if (unlocked_inbuf_len(conn) == 0) {
1085             unlock_in(conn);
1086             return NULL;
1087         }
1088     }
1089 
1090     result = unlocked_get(conn, unlocked_inbuf_len(conn));
1091     gw_claim_area(result);
1092     unlock_in(conn);
1093 
1094     return result;
1095 }
1096 
conn_read_fixed(Connection * conn,long length)1097 Octstr *conn_read_fixed(Connection *conn, long length)
1098 {
1099     Octstr *result = NULL;
1100 
1101     if (length < 1)
1102         return NULL;
1103 
1104     /* See if the data is already available.  If not, try a read(),
1105      * then see if we have enough data after that.  If not, give up. */
1106     lock_in(conn);
1107     if (unlocked_inbuf_len(conn) < length) {
1108         unlocked_read(conn);
1109         if (unlocked_inbuf_len(conn) < length) {
1110             unlock_in(conn);
1111             return NULL;
1112         }
1113     }
1114     result = unlocked_get(conn, length);
1115     gw_claim_area(result);
1116     unlock_in(conn);
1117 
1118     return result;
1119 }
1120 
conn_read_line(Connection * conn)1121 Octstr *conn_read_line(Connection *conn)
1122 {
1123     Octstr *result = NULL;
1124     long pos;
1125 
1126     lock_in(conn);
1127     /* 10 is the code for linefeed.  We don't rely on \n because that
1128      * might be a different value on some (strange) systems, and
1129      * we are reading from a network connection. */
1130     pos = octstr_search_char(conn->inbuf, 10, conn->inbufpos);
1131     if (pos < 0) {
1132         unlocked_read(conn);
1133         pos = octstr_search_char(conn->inbuf, 10, conn->inbufpos);
1134         if (pos < 0) {
1135             unlock_in(conn);
1136             return NULL;
1137         }
1138     }
1139 
1140     result = unlocked_get(conn, pos - conn->inbufpos);
1141     gw_claim_area(result);
1142 
1143     /* Skip the LF, which we left in the buffer */
1144     conn->inbufpos++;
1145 
1146     /* If the line was terminated with CR LF, we have to remove
1147      * the CR from the result. */
1148     if (octstr_len(result) > 0 &&
1149         octstr_get_char(result, octstr_len(result) - 1) == 13)
1150         octstr_delete(result, octstr_len(result) - 1, 1);
1151 
1152     unlock_in(conn);
1153     return result;
1154 }
1155 
conn_read_withlen(Connection * conn)1156 Octstr *conn_read_withlen(Connection *conn)
1157 {
1158     Octstr *result = NULL;
1159     unsigned char lengthbuf[4];
1160     long length = 0; /* for compiler please */
1161     int try, retry;
1162 
1163     lock_in(conn);
1164 
1165     for (try = 1; try <= 2; try++) {
1166         if (try > 1)
1167             unlocked_read(conn);
1168 
1169         do {
1170             retry = 0;
1171             /* First get the length. */
1172             if (unlocked_inbuf_len(conn) < 4)
1173                 continue;
1174 
1175             octstr_get_many_chars(lengthbuf, conn->inbuf, conn->inbufpos, 4);
1176             length = decode_network_long(lengthbuf);
1177 
1178             if (length < 0) {
1179                 warning(0, "conn_read_withlen: got negative length, skipping");
1180                 conn->inbufpos += 4;
1181                 retry = 1;
1182              }
1183         } while(retry == 1);
1184 
1185         /* Then get the data. */
1186         if (unlocked_inbuf_len(conn) - 4 < length)
1187             continue;
1188 
1189         conn->inbufpos += 4;
1190         result = unlocked_get(conn, length);
1191         gw_claim_area(result);
1192         break;
1193     }
1194 
1195     unlock_in(conn);
1196     return result;
1197 }
1198 
conn_read_packet(Connection * conn,int startmark,int endmark)1199 Octstr *conn_read_packet(Connection *conn, int startmark, int endmark)
1200 {
1201     int startpos, endpos;
1202     Octstr *result = NULL;
1203     int try;
1204 
1205     lock_in(conn);
1206 
1207     for (try = 1; try <= 2; try++) {
1208         if (try > 1)
1209             unlocked_read(conn);
1210 
1211         /* Find startmark, and discard everything up to it */
1212         if (startmark >= 0) {
1213             startpos = octstr_search_char(conn->inbuf, startmark, conn->inbufpos);
1214             if (startpos < 0) {
1215                 conn->inbufpos = octstr_len(conn->inbuf);
1216                 continue;
1217             } else {
1218                 conn->inbufpos = startpos;
1219             }
1220         } else {
1221            startpos = conn->inbufpos;
1222         }
1223 
1224         /* Find first endmark after startmark */
1225         endpos = octstr_search_char(conn->inbuf, endmark, conn->inbufpos);
1226         if (endpos < 0)
1227             continue;
1228 
1229         result = unlocked_get(conn, endpos - startpos + 1);
1230         gw_claim_area(result);
1231         break;
1232     }
1233 
1234     unlock_in(conn);
1235     return result;
1236 }
1237 
1238 #ifdef HAVE_LIBSSL
conn_get_peer_certificate(Connection * conn)1239 X509 *conn_get_peer_certificate(Connection *conn)
1240 {
1241     /* Don't know if it needed to be locked , but better safe as crash */
1242     lock_out(conn);
1243     lock_in(conn);
1244     if (conn->peer_certificate == NULL && conn->ssl != NULL)
1245         conn->peer_certificate = SSL_get_peer_certificate(conn->ssl);
1246     unlock_in(conn);
1247     unlock_out(conn);
1248 
1249     return conn->peer_certificate;
1250 }
1251 
1252 /*
1253  * XXX Alex decalred the RSA callback routine static and now we're getting
1254  * warning messages for our automatic compilation tests. So we are commenting
1255  * the function out to avoid the warnings.
1256  *
1257 
1258 static RSA *tmp_rsa_callback(SSL *ssl, int export, int key_len)
1259 {
1260     static RSA *rsa = NULL;
1261     debug("gwlib.http", 0, "SSL: Generating new RSA key (export=%d, keylen=%d)", export, key_len);
1262     if (export) {
1263 	   rsa = RSA_generate_key(key_len, RSA_F4, NULL, NULL);
1264     } else {
1265 	   debug("gwlib.http", 0, "SSL: Export not set");
1266     }
1267     return rsa;
1268 }
1269 */
1270 
1271 static Mutex **ssl_static_locks = NULL;
1272 
1273 /* the call-back function for the openssl crypto thread locking */
openssl_locking_function(int mode,int n,const char * file,int line)1274 static void openssl_locking_function(int mode, int n, const char *file, int line)
1275 {
1276     if (mode & CRYPTO_LOCK)
1277         mutex_lock(ssl_static_locks[n-1]);
1278     else
1279         mutex_unlock(ssl_static_locks[n-1]);
1280 }
1281 
openssl_init_locks(void)1282 void openssl_init_locks(void)
1283 {
1284     int c, maxlocks = CRYPTO_num_locks();
1285 
1286     gw_assert(ssl_static_locks == NULL);
1287 
1288     ssl_static_locks = gw_malloc(sizeof(Mutex *) * maxlocks);
1289     for (c = 0; c < maxlocks; c++)
1290         ssl_static_locks[c] = mutex_create();
1291 
1292     /* after the mutexes have been created, apply the call-back to it */
1293     CRYPTO_set_locking_callback(openssl_locking_function);
1294     CRYPTO_set_id_callback((CRYPTO_CALLBACK_PTR)gwthread_self);
1295 }
1296 
openssl_shutdown_locks(void)1297 void openssl_shutdown_locks(void)
1298 {
1299     int c, maxlocks = CRYPTO_num_locks();
1300 
1301     gw_assert(ssl_static_locks != NULL);
1302 
1303     /* remove call-back from the locks */
1304     CRYPTO_set_locking_callback(NULL);
1305 
1306     for (c = 0; c < maxlocks; c++)
1307         mutex_destroy(ssl_static_locks[c]);
1308 
1309     gw_free(ssl_static_locks);
1310     ssl_static_locks = NULL;
1311 }
1312 
conn_init_ssl(void)1313 void conn_init_ssl(void)
1314 {
1315     SSL_library_init();
1316     SSL_load_error_strings();
1317     global_ssl_context = SSL_CTX_new(SSLv23_client_method());
1318     SSL_CTX_set_mode(global_ssl_context,
1319         SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1320 }
1321 
server_ssl_init(void)1322 void server_ssl_init(void)
1323 {
1324     SSLeay_add_ssl_algorithms();
1325     SSL_load_error_strings();
1326     global_server_ssl_context = SSL_CTX_new(SSLv23_server_method());
1327     SSL_CTX_set_mode(global_server_ssl_context,
1328         SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1329     if (!SSL_CTX_set_default_verify_paths(global_server_ssl_context)) {
1330 	   panic(0, "can not set default path for server");
1331     }
1332 }
1333 
conn_shutdown_ssl(void)1334 void conn_shutdown_ssl(void)
1335 {
1336     if (global_ssl_context)
1337         SSL_CTX_free(global_ssl_context);
1338 
1339     ERR_free_strings();
1340     EVP_cleanup();
1341 }
1342 
server_shutdown_ssl(void)1343 void server_shutdown_ssl(void)
1344 {
1345     if (global_server_ssl_context)
1346         SSL_CTX_free(global_server_ssl_context);
1347 
1348     ERR_free_strings();
1349     EVP_cleanup();
1350 }
1351 
use_global_client_certkey_file(Octstr * certkeyfile)1352 void use_global_client_certkey_file(Octstr *certkeyfile)
1353 {
1354     SSL_CTX_use_certificate_file(global_ssl_context,
1355                                  octstr_get_cstr(certkeyfile),
1356                                  SSL_FILETYPE_PEM);
1357     SSL_CTX_use_PrivateKey_file(global_ssl_context,
1358                                 octstr_get_cstr(certkeyfile),
1359                                 SSL_FILETYPE_PEM);
1360     if (SSL_CTX_check_private_key(global_ssl_context) != 1)
1361         panic(0, "reading global client certificate file `%s', the certificate "
1362 	      "isn't consistent with the private key (or failed reading the file)",
1363               octstr_get_cstr(certkeyfile));
1364     info(0, "Using global SSL certificate and key from file `%s'",
1365          octstr_get_cstr(certkeyfile));
1366 }
1367 
use_global_server_certkey_file(Octstr * certfile,Octstr * keyfile)1368 void use_global_server_certkey_file(Octstr *certfile, Octstr *keyfile)
1369 {
1370     SSL_CTX_use_certificate_file(global_server_ssl_context,
1371                                   octstr_get_cstr(certfile),
1372                                   SSL_FILETYPE_PEM);
1373     SSL_CTX_use_PrivateKey_file(global_server_ssl_context,
1374                                  octstr_get_cstr(keyfile),
1375                                  SSL_FILETYPE_PEM);
1376     if (SSL_CTX_check_private_key(global_server_ssl_context) != 1) {
1377         error(0, "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
1378         panic(0, "reading global server certificate file %s, the certificate \
1379                   isn't consistent with the private key in file %s \
1380                   (or failed reading the file)",
1381                   octstr_get_cstr(certfile), octstr_get_cstr(keyfile));
1382     }
1383     info(0, "Using global server SSL certificate from file `%s'", octstr_get_cstr(certfile));
1384     info(0, "Using global server SSL key from file `%s'", octstr_get_cstr(keyfile));
1385 }
1386 
verify_callback(int preverify_ok,X509_STORE_CTX * ctx)1387 static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
1388 {
1389     char    subject[256];
1390     char    issuer [256];
1391     char   *status;
1392 
1393     X509_NAME_oneline(X509_get_subject_name(ctx->current_cert), subject, sizeof(subject));
1394     X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer, sizeof (issuer));
1395 
1396     status = preverify_ok ? "Accepting" : "Rejecting";
1397 
1398     info(0, "%s certificate for \"%s\" signed by \"%s\"", status, subject, issuer);
1399 
1400     return preverify_ok;
1401 }
1402 
use_global_trusted_ca_file(Octstr * ssl_trusted_ca_file)1403 void use_global_trusted_ca_file(Octstr *ssl_trusted_ca_file)
1404 {
1405     if (ssl_trusted_ca_file != NULL) {
1406 	if (!SSL_CTX_load_verify_locations(global_ssl_context,
1407 					   octstr_get_cstr(ssl_trusted_ca_file),
1408 					   NULL)) {
1409 	    panic(0, "Failed to load SSL CA file: %s", octstr_get_cstr(ssl_trusted_ca_file));
1410 	} else {
1411 	    info(0, "Using CA root certificates from file %s",
1412 		 octstr_get_cstr(ssl_trusted_ca_file));
1413 	    SSL_CTX_set_verify(global_ssl_context,
1414 			       SSL_VERIFY_PEER,
1415 			       verify_callback);
1416 	}
1417 
1418     } else {
1419 	SSL_CTX_set_verify(global_ssl_context,
1420 			   SSL_VERIFY_NONE,
1421 			   NULL);
1422     }
1423 }
1424 
conn_config_ssl(CfgGroup * grp)1425 void conn_config_ssl (CfgGroup *grp)
1426 {
1427     Octstr *ssl_client_certkey_file = NULL;
1428     Octstr *ssl_server_cert_file    = NULL;
1429     Octstr *ssl_server_key_file     = NULL;
1430     Octstr *ssl_trusted_ca_file     = NULL;
1431 
1432     /*
1433      * check if SSL is desired for HTTP servers and then
1434      * load SSL client and SSL server public certificates
1435      * and private keys
1436      */
1437     ssl_client_certkey_file = cfg_get(grp, octstr_imm("ssl-client-certkey-file"));
1438     if (ssl_client_certkey_file != NULL)
1439         use_global_client_certkey_file(ssl_client_certkey_file);
1440 
1441     ssl_server_cert_file = cfg_get(grp, octstr_imm("ssl-server-cert-file"));
1442     ssl_server_key_file = cfg_get(grp, octstr_imm("ssl-server-key-file"));
1443 
1444     if (ssl_server_cert_file != NULL && ssl_server_key_file != NULL) {
1445         use_global_server_certkey_file(ssl_server_cert_file,
1446 				       ssl_server_key_file);
1447     }
1448 
1449     ssl_trusted_ca_file = cfg_get(grp, octstr_imm("ssl-trusted-ca-file"));
1450 
1451     use_global_trusted_ca_file(ssl_trusted_ca_file);
1452 
1453     octstr_destroy(ssl_client_certkey_file);
1454     octstr_destroy(ssl_server_cert_file);
1455     octstr_destroy(ssl_server_key_file);
1456     octstr_destroy(ssl_trusted_ca_file);
1457 }
1458 
conn_get_ssl(Connection * conn)1459 SSL *conn_get_ssl(Connection *conn)
1460 {
1461     if (conn != NULL)
1462         return conn->ssl;
1463     else
1464         return NULL;
1465 }
1466 
1467 #else
1468 
conn_config_ssl(CfgGroup * grp)1469 void conn_config_ssl (CfgGroup *grp)
1470 {
1471     info(0, "SSL not supported, no SSL initialization done.");
1472 }
1473 #endif /* HAVE_LIBSSL */
1474 
conn_get_id(Connection * conn)1475 int conn_get_id(Connection *conn) {
1476     if(conn == NULL)
1477 	return 0;
1478     else
1479 	return conn->fd;
1480 }
1481