make outgoing SSL_connect() non-blocking
[freeradius.git] / src / main / tls_listen.c
1 /*
2  * tls.c
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2001  hereUare Communications, Inc. <raghud@hereuare.com>
21  * Copyright 2003  Alan DeKok <aland@freeradius.org>
22  * Copyright 2006  The FreeRADIUS server project
23  */
24
25 RCSID("$Id$")
26 USES_APPLE_DEPRECATED_API       /* OpenSSL API has been deprecated by Apple */
27
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/process.h>
30 #include <freeradius-devel/rad_assert.h>
31
32 #ifdef HAVE_SYS_STAT_H
33 #include <sys/stat.h>
34 #endif
35
36 #ifdef WITH_TCP
37 #ifdef WITH_TLS
38 #ifdef HAVE_OPENSSL_RAND_H
39 #include <openssl/rand.h>
40 #endif
41
42 #ifdef HAVE_OPENSSL_OCSP_H
43 #include <openssl/ocsp.h>
44 #endif
45
46 #ifdef HAVE_PTHREAD_H
47 #define PTHREAD_MUTEX_LOCK pthread_mutex_lock
48 #define PTHREAD_MUTEX_UNLOCK pthread_mutex_unlock
49 #else
50 #define PTHREAD_MUTEX_LOCK(_x)
51 #define PTHREAD_MUTEX_UNLOCK(_x)
52 #endif
53
54 static void dump_hex(char const *msg, uint8_t const *data, size_t data_len)
55 {
56         size_t i;
57
58         if (rad_debug_lvl < 3) return;
59
60         printf("%s %d\n", msg, (int) data_len);
61         if (data_len > 256) data_len = 256;
62
63         for (i = 0; i < data_len; i++) {
64                 if ((i & 0x0f) == 0x00) printf ("%02x: ", (unsigned int) i);
65                 printf("%02x ", data[i]);
66                 if ((i & 0x0f) == 0x0f) printf ("\n");
67         }
68         printf("\n");
69         fflush(stdout);
70 }
71
72 static void tls_socket_close(rad_listen_t *listener)
73 {
74         listen_socket_t *sock = listener->data;
75
76         SSL_shutdown(sock->ssn->ssl);
77
78         listener->status = RAD_LISTEN_STATUS_EOL;
79         listener->tls = NULL; /* parent owns this! */
80
81         /*
82          *      Tell the event handler that an FD has disappeared.
83          */
84         DEBUG("Client has closed connection");
85         radius_update_listener(listener);
86
87         /*
88          *      Do NOT free the listener here.  It's in use by
89          *      a request, and will need to hang around until
90          *      all of the requests are done.
91          *
92          *      It is instead free'd in remove_from_request_hash()
93          */
94 }
95
96 static int CC_HINT(nonnull) tls_socket_write(rad_listen_t *listener, REQUEST *request)
97 {
98         uint8_t *p;
99         ssize_t rcode;
100         listen_socket_t *sock = listener->data;
101
102         p = sock->ssn->dirty_out.data;
103
104         while (p < (sock->ssn->dirty_out.data + sock->ssn->dirty_out.used)) {
105                 RDEBUG3("Writing to socket %d", request->packet->sockfd);
106                 rcode = write(request->packet->sockfd, p,
107                               (sock->ssn->dirty_out.data + sock->ssn->dirty_out.used) - p);
108                 if (rcode <= 0) {
109                         RDEBUG("Error writing to TLS socket: %s", fr_syserror(errno));
110
111                         tls_socket_close(listener);
112                         return 0;
113                 }
114                 p += rcode;
115         }
116
117         sock->ssn->dirty_out.used = 0;
118
119         return 1;
120 }
121
122
123 static int tls_socket_recv(rad_listen_t *listener)
124 {
125         bool doing_init = false;
126         ssize_t rcode;
127         RADIUS_PACKET *packet;
128         REQUEST *request;
129         listen_socket_t *sock = listener->data;
130         fr_tls_status_t status;
131         RADCLIENT *client = sock->client;
132
133         if (!sock->packet) {
134                 sock->packet = rad_alloc(sock, false);
135                 if (!sock->packet) return 0;
136
137                 sock->packet->sockfd = listener->fd;
138                 sock->packet->src_ipaddr = sock->other_ipaddr;
139                 sock->packet->src_port = sock->other_port;
140                 sock->packet->dst_ipaddr = sock->my_ipaddr;
141                 sock->packet->dst_port = sock->my_port;
142
143                 if (sock->request) sock->request->packet = talloc_steal(sock->request, sock->packet);
144         }
145
146         /*
147          *      Allocate a REQUEST for debugging, and initialize the TLS session.
148          */
149         if (!sock->request) {
150                 sock->request = request = request_alloc(sock);
151                 if (!sock->request) {
152                         ERROR("Out of memory");
153                         return 0;
154                 }
155
156                 rad_assert(request->packet == NULL);
157                 rad_assert(sock->packet != NULL);
158                 request->packet = talloc_steal(request, sock->packet);
159
160                 request->component = "<tls-connect>";
161
162                 request->reply = rad_alloc(request, false);
163                 if (!request->reply) return 0;
164
165                 rad_assert(sock->ssn == NULL);
166
167                 sock->ssn = tls_new_session(sock, listener->tls, sock->request,
168                                             listener->tls->require_client_cert);
169                 if (!sock->ssn) {
170                         TALLOC_FREE(sock->request);
171                         sock->packet = NULL;
172                         return 0;
173                 }
174
175                 SSL_set_ex_data(sock->ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
176                 SSL_set_ex_data(sock->ssn->ssl, fr_tls_ex_index_certs, (void *) &sock->certs);
177                 SSL_set_ex_data(sock->ssn->ssl, FR_TLS_EX_INDEX_TALLOC, NULL);
178
179                 doing_init = true;
180         }
181
182         rad_assert(sock->request != NULL);
183         rad_assert(sock->request->packet != NULL);
184         rad_assert(sock->packet != NULL);
185         rad_assert(sock->ssn != NULL);
186
187         request = sock->request;
188
189         RDEBUG3("Reading from socket %d", request->packet->sockfd);
190         PTHREAD_MUTEX_LOCK(&sock->mutex);
191         rcode = read(request->packet->sockfd,
192                      sock->ssn->dirty_in.data,
193                      sizeof(sock->ssn->dirty_in.data));
194         if ((rcode < 0) && (errno == ECONNRESET)) {
195         do_close:
196                 DEBUG("Closing TLS socket from client port %u", sock->other_port);
197                 tls_socket_close(listener);
198                 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
199                 return 0;
200         }
201
202         if (rcode < 0) {
203                 RDEBUG("Error reading TLS socket: %s", fr_syserror(errno));
204                 goto do_close;
205         }
206
207         /*
208          *      Normal socket close.
209          */
210         if (rcode == 0) goto do_close;
211
212         sock->ssn->dirty_in.used = rcode;
213
214         dump_hex("READ FROM SSL", sock->ssn->dirty_in.data, sock->ssn->dirty_in.used);
215
216         /*
217          *      Catch attempts to use non-SSL.
218          */
219         if (doing_init && (sock->ssn->dirty_in.data[0] != handshake)) {
220                 RDEBUG("Non-TLS data sent to TLS socket: closing");
221                 goto do_close;
222         }
223
224         /*
225          *      If we need to do more initialization, do that here.
226          */
227         if (!SSL_is_init_finished(sock->ssn->ssl)) {
228                 if (!tls_handshake_recv(request, sock->ssn)) {
229                         RDEBUG("FAILED in TLS handshake receive");
230                         goto do_close;
231                 }
232
233                 /*
234                  *      More ACK data to send.  Do so.
235                  */
236                 if (sock->ssn->dirty_out.used > 0) {
237                         tls_socket_write(listener, request);
238                         PTHREAD_MUTEX_UNLOCK(&sock->mutex);
239                         return 0;
240                 }
241
242                 /*
243                  *      FIXME: Run the request through a virtual
244                  *      server in order to see if we like the
245                  *      certificate presented by the client.
246                  */
247         }
248
249         /*
250          *      Try to get application data.
251          */
252         status = tls_application_data(sock->ssn, request);
253         RDEBUG("Application data status %d", status);
254
255         if (status == FR_TLS_MORE_FRAGMENTS) {
256                 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
257                 return 0;
258         }
259
260         if (sock->ssn->clean_out.used == 0) {
261                 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
262                 return 0;
263         }
264
265         /*
266          *      We now have a bunch of application data.
267          */
268         dump_hex("TUNNELED DATA > ", sock->ssn->clean_out.data, sock->ssn->clean_out.used);
269
270         /*
271          *      If the packet is a complete RADIUS packet, return it to
272          *      the caller.  Otherwise...
273          */
274         if ((sock->ssn->clean_out.used < 20) ||
275             (((sock->ssn->clean_out.data[2] << 8) | sock->ssn->clean_out.data[3]) != (int) sock->ssn->clean_out.used)) {
276                 RDEBUG("Received bad packet: Length %zd contents %d",
277                        sock->ssn->clean_out.used,
278                        (sock->ssn->clean_out.data[2] << 8) | sock->ssn->clean_out.data[3]);
279                 goto do_close;
280         }
281
282         packet = sock->packet;
283         packet->data = talloc_array(packet, uint8_t, sock->ssn->clean_out.used);
284         packet->data_len = sock->ssn->clean_out.used;
285         sock->ssn->record_minus(&sock->ssn->clean_out, packet->data, packet->data_len);
286         packet->vps = NULL;
287         PTHREAD_MUTEX_UNLOCK(&sock->mutex);
288
289         if (!rad_packet_ok(packet, 0, NULL)) {
290                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
291                 DEBUG("Closing TLS socket from client");
292                 PTHREAD_MUTEX_LOCK(&sock->mutex);
293                 tls_socket_close(listener);
294                 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
295                 return 0;       /* do_close unlocks the mutex */
296         }
297
298         /*
299          *      Copied from src/lib/radius.c, rad_recv();
300          */
301         if (fr_debug_lvl) {
302                 char host_ipaddr[128];
303
304                 if (is_radius_code(packet->code)) {
305                         RDEBUG("tls_recv: %s packet from host %s port %d, id=%d, length=%d",
306                                fr_packet_codes[packet->code],
307                                inet_ntop(packet->src_ipaddr.af,
308                                          &packet->src_ipaddr.ipaddr,
309                                          host_ipaddr, sizeof(host_ipaddr)),
310                                packet->src_port,
311                                packet->id, (int) packet->data_len);
312                 } else {
313                         RDEBUG("tls_recv: Packet from host %s port %d code=%d, id=%d, length=%d",
314                                inet_ntop(packet->src_ipaddr.af,
315                                          &packet->src_ipaddr.ipaddr,
316                                          host_ipaddr, sizeof(host_ipaddr)),
317                                packet->src_port,
318                                packet->code,
319                                packet->id, (int) packet->data_len);
320                 }
321         }
322
323         FR_STATS_INC(auth, total_requests);
324
325         return 1;
326 }
327
328
329 int dual_tls_recv(rad_listen_t *listener)
330 {
331         RADIUS_PACKET *packet;
332         RAD_REQUEST_FUNP fun = NULL;
333         listen_socket_t *sock = listener->data;
334         RADCLIENT       *client = sock->client;
335
336         if (listener->status != RAD_LISTEN_STATUS_KNOWN) return 0;
337
338         if (!tls_socket_recv(listener)) {
339                 return 0;
340         }
341
342         rad_assert(sock->packet != NULL);
343         rad_assert(sock->ssn != NULL);
344         rad_assert(client != NULL);
345
346         packet = talloc_steal(NULL, sock->packet);
347         sock->packet = NULL;
348
349         /*
350          *      Some sanity checks, based on the packet code.
351          *
352          *      "auth+acct" are marked as "auth", with the "dual" flag
353          *      set.
354          */
355         switch (packet->code) {
356         case PW_CODE_ACCESS_REQUEST:
357                 if (listener->type != RAD_LISTEN_AUTH) goto bad_packet;
358                 FR_STATS_INC(auth, total_requests);
359                 fun = rad_authenticate;
360                 break;
361
362 #ifdef WITH_ACCOUNTING
363         case PW_CODE_ACCOUNTING_REQUEST:
364                 if (listener->type != RAD_LISTEN_ACCT) {
365                         /*
366                          *      Allow auth + dual.  Disallow
367                          *      everything else.
368                          */
369                         if (!((listener->type == RAD_LISTEN_AUTH) &&
370                               (listener->dual))) {
371                                     goto bad_packet;
372                         }
373                 }
374                 FR_STATS_INC(acct, total_requests);
375                 fun = rad_accounting;
376                 break;
377 #endif
378
379         case PW_CODE_STATUS_SERVER:
380                 if (!main_config.status_server) {
381                         FR_STATS_INC(auth, total_unknown_types);
382                         WARN("Ignoring Status-Server request due to security configuration");
383                         rad_free(&packet);
384                         return 0;
385                 }
386                 fun = rad_status_server;
387                 break;
388
389         default:
390         bad_packet:
391                 FR_STATS_INC(auth, total_unknown_types);
392
393                 DEBUG("Invalid packet code %d sent from client %s port %d : IGNORED",
394                       packet->code, client->shortname, packet->src_port);
395                 rad_free(&packet);
396                 return 0;
397         } /* switch over packet types */
398
399         if (!request_receive(NULL, listener, packet, client, fun)) {
400                 FR_STATS_INC(auth, total_packets_dropped);
401                 rad_free(&packet);
402                 return 0;
403         }
404
405         return 1;
406 }
407
408
409 /*
410  *      Send a response packet
411  */
412 int dual_tls_send(rad_listen_t *listener, REQUEST *request)
413 {
414         listen_socket_t *sock = listener->data;
415
416         VERIFY_REQUEST(request);
417
418         rad_assert(request->listener == listener);
419         rad_assert(listener->send == dual_tls_send);
420
421         if (listener->status != RAD_LISTEN_STATUS_KNOWN) return 0;
422
423         /*
424          *      Accounting reject's are silently dropped.
425          *
426          *      We do it here to avoid polluting the rest of the
427          *      code with this knowledge
428          */
429         if (request->reply->code == 0) return 0;
430
431         /*
432          *      Pack the VPs
433          */
434         if (rad_encode(request->reply, request->packet,
435                        request->client->secret) < 0) {
436                 RERROR("Failed encoding packet: %s", fr_strerror());
437                 return 0;
438         }
439
440         if (request->reply->data_len > (MAX_PACKET_LEN - 100)) {
441                 RWARN("Packet is large, and possibly truncated - %zd vs max %d",
442                       request->reply->data_len, MAX_PACKET_LEN);
443         }
444
445         /*
446          *      Sign the packet.
447          */
448         if (rad_sign(request->reply, request->packet,
449                        request->client->secret) < 0) {
450                 RERROR("Failed signing packet: %s", fr_strerror());
451                 return 0;
452         }
453
454         PTHREAD_MUTEX_LOCK(&sock->mutex);
455
456         /*
457          *      Write the packet to the SSL buffers.
458          */
459         sock->ssn->record_plus(&sock->ssn->clean_in,
460                                request->reply->data, request->reply->data_len);
461
462         dump_hex("TUNNELED DATA < ", sock->ssn->clean_in.data, sock->ssn->clean_in.used);
463
464         /*
465          *      Do SSL magic to get encrypted data.
466          */
467         tls_handshake_send(request, sock->ssn);
468
469         /*
470          *      And finally write the data to the socket.
471          */
472         if (sock->ssn->dirty_out.used > 0) {
473                 dump_hex("WRITE TO SSL", sock->ssn->dirty_out.data, sock->ssn->dirty_out.used);
474
475                 tls_socket_write(listener, request);
476         }
477         PTHREAD_MUTEX_UNLOCK(&sock->mutex);
478
479         return 0;
480 }
481
482 static int try_connect(tls_session_t *ssn)
483 {
484         int ret;
485         ret = SSL_connect(ssn->ssl);
486         if (ret < 0) {
487                 switch (SSL_get_error(ssn->ssl, ret)) {
488                         default:
489                                 break;
490
491
492
493                 case SSL_ERROR_WANT_READ:
494                 case SSL_ERROR_WANT_WRITE:
495                         ssn->connected = false;
496                         return 0;
497                 }
498         }
499
500         if (ret <= 0) {
501                 tls_error_io_log(NULL, ssn, ret, "Failed in " STRINGIFY(__FUNCTION__) " (SSL_connect)");
502                 talloc_free(ssn);
503
504                 return -1;
505         }
506
507         return 1;
508 }
509
510
511 #ifdef WITH_PROXY
512 /*
513  *      Read from the SSL socket.  Safe with either blocking or
514  *      non-blocking IO.  This level of complexity is probably not
515  *      necessary, as each packet gets put into one SSL application
516  *      record.  When SSL has a full record, we should be able to read
517  *      the entire packet via one SSL_read().
518  *
519  *      When SSL has a partial record, SSL_read() will return
520  *      WANT_READ or WANT_WRITE, and zero application data.
521  *
522  *      Called with the mutex held.
523  */
524 static ssize_t proxy_tls_read(rad_listen_t *listener)
525 {
526         int rcode;
527         size_t length;
528         uint8_t *data;
529         listen_socket_t *sock = listener->data;
530
531         if (!sock->ssn->connected) {
532                 rcode = try_connect(sock->ssn);
533                 if (rcode == 0) return 0;
534
535                 if (rcode < 0) {
536                         SSL_shutdown(sock->ssn->ssl);
537                         return -1;
538                 }
539
540                 sock->ssn->connected = true;
541         }
542
543         /*
544          *      Get the maximum size of data to receive.
545          */
546         if (!sock->data) sock->data = talloc_array(sock, uint8_t,
547                                                    sock->ssn->mtu);
548
549         data = sock->data;
550
551         if (sock->partial < 4) {
552                 rcode = SSL_read(sock->ssn->ssl, data + sock->partial,
553                                  4 - sock->partial);
554                 if (rcode <= 0) {
555                         int err = SSL_get_error(sock->ssn->ssl, rcode);
556                         switch (err) {
557                         case SSL_ERROR_WANT_READ:
558                         case SSL_ERROR_WANT_WRITE:
559                                 return 0; /* do some more work later */
560
561                         case SSL_ERROR_ZERO_RETURN:
562                                 /* remote end sent close_notify, send one back */
563                                 SSL_shutdown(sock->ssn->ssl);
564
565                         case SSL_ERROR_SYSCALL:
566                         do_close:
567                                 return -1;
568
569                         default:
570                                 tls_error_log(NULL, "Failed in proxy receive");
571
572                                 goto do_close;
573                         }
574                 }
575
576                 sock->partial = rcode;
577         } /* try reading the packet header */
578
579         if (sock->partial < 4) return 0; /* read more data */
580
581         length = (data[2] << 8) | data[3];
582
583         /*
584          *      Do these checks only once, when we read the header.
585          */
586         if (sock->partial == 4) {
587                 DEBUG3("Proxy received header saying we have a packet of %u bytes",
588                        (unsigned int) length);
589
590                 /*
591                  *      FIXME: allocate a RADIUS_PACKET, and set
592                  *      "data" to be as large as necessary.
593                  */
594                 if (length > sock->ssn->mtu) {
595                         INFO("Received packet will be too large! Set \"fragment_size = %u\"",
596                              (data[2] << 8) | data[3]);
597                         goto do_close;
598                 }
599         }
600
601         /*
602          *      Try to read some more.
603          */
604         if (sock->partial < length) {
605                 rcode = SSL_read(sock->ssn->ssl, data + sock->partial,
606                                  length - sock->partial);
607                 if (rcode <= 0) {
608                         switch (SSL_get_error(sock->ssn->ssl, rcode)) {
609                         case SSL_ERROR_WANT_READ:
610                         case SSL_ERROR_WANT_WRITE:
611                                 return 0;
612
613                         case SSL_ERROR_ZERO_RETURN:
614                                 /* remote end sent close_notify, send one back */
615                                 SSL_shutdown(sock->ssn->ssl);
616                                 goto do_close;
617                         default:
618                                 goto do_close;
619                         }
620                 }
621
622                 sock->partial += rcode;
623         }
624
625         /*
626          *      If we're not done, say so.
627          *
628          *      Otherwise, reset the partially read data flag, and say
629          *      we have a packet.
630          */
631         if (sock->partial < length) {
632                 return 0;
633         }
634
635         sock->partial = 0;      /* we've now read the packet */
636         return length;
637 }
638
639
640 int proxy_tls_recv(rad_listen_t *listener)
641 {
642         listen_socket_t *sock = listener->data;
643         char buffer[256];
644         RADIUS_PACKET *packet;
645         uint8_t *data;
646         ssize_t data_len;
647
648         if (listener->status != RAD_LISTEN_STATUS_KNOWN) return 0;
649
650         DEBUG3("Proxy SSL socket has data to read");
651         PTHREAD_MUTEX_LOCK(&sock->mutex);
652         data_len = proxy_tls_read(listener);
653         PTHREAD_MUTEX_UNLOCK(&sock->mutex);
654
655         if (data_len < 0) {
656                 DEBUG("Closing TLS socket to home server");
657                 PTHREAD_MUTEX_LOCK(&sock->mutex);
658                 tls_socket_close(listener);
659                 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
660                 return 0;
661         }
662
663         if (data_len == 0) return 0; /* not done yet */
664
665         data = sock->data;
666
667         packet = rad_alloc(sock, false);
668         packet->sockfd = listener->fd;
669         packet->src_ipaddr = sock->other_ipaddr;
670         packet->src_port = sock->other_port;
671         packet->dst_ipaddr = sock->my_ipaddr;
672         packet->dst_port = sock->my_port;
673         packet->code = data[0];
674         packet->id = data[1];
675         packet->data_len = data_len;
676         packet->data = talloc_array(packet, uint8_t, packet->data_len);
677         memcpy(packet->data, data, packet->data_len);
678         memcpy(packet->vector, packet->data + 4, 16);
679
680         /*
681          *      FIXME: Client MIB updates?
682          */
683         switch (packet->code) {
684         case PW_CODE_ACCESS_ACCEPT:
685         case PW_CODE_ACCESS_CHALLENGE:
686         case PW_CODE_ACCESS_REJECT:
687                 break;
688
689 #ifdef WITH_ACCOUNTING
690         case PW_CODE_ACCOUNTING_RESPONSE:
691                 break;
692 #endif
693
694         default:
695                 /*
696                  *      FIXME: Update MIB for packet types?
697                  */
698                 ERROR("Invalid packet code %d sent to a proxy port "
699                        "from home server %s port %d - ID %d : IGNORED",
700                        packet->code,
701                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
702                        packet->src_port, packet->id);
703                 rad_free(&packet);
704                 return 0;
705         }
706
707         if (!request_proxy_reply(packet)) {
708                 rad_free(&packet);
709                 return 0;
710         }
711
712         return 1;
713 }
714
715
716 int proxy_tls_send(rad_listen_t *listener, REQUEST *request)
717 {
718         int rcode;
719         listen_socket_t *sock = listener->data;
720
721         VERIFY_REQUEST(request);
722
723         if ((listener->status != RAD_LISTEN_STATUS_INIT) &&
724             (listener->status != RAD_LISTEN_STATUS_KNOWN)) return 0;
725
726         /*
727          *      Normal proxying calls us with the data already
728          *      encoded.  The "ping home server" code does not.  So,
729          *      if there's no packet, encode it here.
730          */
731         if (!request->proxy->data) {
732                 request->proxy_listener->encode(request->proxy_listener,
733                                                 request);
734         }
735
736         if (!sock->ssn->connected) {
737                 PTHREAD_MUTEX_LOCK(&sock->mutex);
738                 rcode = try_connect(sock->ssn);
739                 PTHREAD_MUTEX_LOCK(&sock->mutex);
740                 if (rcode == 0) return 0;
741
742                 if (rcode < 0) {
743                         SSL_shutdown(sock->ssn->ssl);
744                         return -1;
745                 }
746
747                 sock->ssn->connected = true;
748         }
749
750         DEBUG3("Proxy is writing %u bytes to SSL",
751                (unsigned int) request->proxy->data_len);
752         PTHREAD_MUTEX_LOCK(&sock->mutex);
753         rcode = SSL_write(sock->ssn->ssl, request->proxy->data,
754                           request->proxy->data_len);
755         if (rcode < 0) {
756                 int err;
757
758                 err = ERR_get_error();
759                 switch (err) {
760                 case SSL_ERROR_NONE:
761                 case SSL_ERROR_WANT_READ:
762                 case SSL_ERROR_WANT_WRITE:
763                         break;  /* let someone else retry */
764
765                 default:
766                         tls_error_log(NULL, "Failed in proxy send");
767                         DEBUG("Closing TLS socket to home server");
768                         tls_socket_close(listener);
769                         PTHREAD_MUTEX_UNLOCK(&sock->mutex);
770                         return 0;
771                 }
772         }
773         PTHREAD_MUTEX_UNLOCK(&sock->mutex);
774
775         return 1;
776 }
777 #endif  /* WITH_PROXY */
778
779 #endif  /* WITH_TLS */
780 #endif  /* WITH_TCP */