1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.] */
56 
57 #include <openssl/bio.h>
58 
59 #include <assert.h>
60 #include <errno.h>
61 #include <stdio.h>
62 #include <string.h>
63 
64 #if !defined(OPENSSL_WINDOWS)
65 #include <sys/socket.h>
66 #include <netinet/in.h>
67 #include <arpa/inet.h>
68 #include <unistd.h>
69 #else
70 #pragma warning(push, 3)
71 #include <winsock2.h>
72 #include <ws2tcpip.h>
73 #pragma warning(pop)
74 #endif
75 
76 #include <openssl/buf.h>
77 #include <openssl/err.h>
78 #include <openssl/mem.h>
79 
80 #include "internal.h"
81 
82 
83 enum {
84   BIO_CONN_S_BEFORE,
85   BIO_CONN_S_BLOCKED_CONNECT,
86   BIO_CONN_S_OK,
87 };
88 
89 typedef struct bio_connect_st {
90   int state;
91 
92   char *param_hostname;
93   char *param_port;
94   int nbio;
95 
96   uint8_t ip[4];
97   unsigned short port;
98 
99   struct sockaddr_storage them;
100   socklen_t them_length;
101 
102   /* the file descriptor is kept in bio->num in order to match the socket
103    * BIO. */
104 
105   /* info_callback is called when the connection is initially made
106    * callback(BIO,state,ret);  The callback should return 'ret', state is for
107    * compatibility with the SSL info_callback. */
108   int (*info_callback)(const BIO *bio, int state, int ret);
109 } BIO_CONNECT;
110 
111 #if !defined(OPENSSL_WINDOWS)
closesocket(int sock)112 static int closesocket(int sock) {
113   return close(sock);
114 }
115 #endif
116 
117 /* maybe_copy_ipv4_address sets |*ipv4| to the IPv4 address from |ss| (in
118  * big-endian order), if |ss| contains an IPv4 socket address. */
maybe_copy_ipv4_address(uint8_t * ipv4,const struct sockaddr_storage * ss)119 static void maybe_copy_ipv4_address(uint8_t *ipv4,
120                                     const struct sockaddr_storage *ss) {
121   const struct sockaddr_in *sin;
122 
123   if (ss->ss_family != AF_INET) {
124     return;
125   }
126 
127   sin = (const struct sockaddr_in*) ss;
128   memcpy(ipv4, &sin->sin_addr, 4);
129 }
130 
conn_state(BIO * bio,BIO_CONNECT * c)131 static int conn_state(BIO *bio, BIO_CONNECT *c) {
132   int ret = -1, i;
133   char *p, *q;
134   int (*cb)(const BIO *, int, int) = NULL;
135 
136   if (c->info_callback != NULL) {
137     cb = c->info_callback;
138   }
139 
140   for (;;) {
141     switch (c->state) {
142       case BIO_CONN_S_BEFORE:
143         p = c->param_hostname;
144         if (p == NULL) {
145           OPENSSL_PUT_ERROR(BIO, conn_state, BIO_R_NO_HOSTNAME_SPECIFIED);
146           goto exit_loop;
147         }
148         for (; *p != 0; p++) {
149           if (*p == ':' || *p == '/') {
150             break;
151           }
152         }
153 
154         i = *p;
155         if (i == ':' || i == '/') {
156           *(p++) = 0;
157           if (i == ':') {
158             for (q = p; *q; q++) {
159               if (*q == '/') {
160                 *q = 0;
161                 break;
162               }
163             }
164             OPENSSL_free(c->param_port);
165             c->param_port = BUF_strdup(p);
166           }
167         }
168 
169         if (c->param_port == NULL) {
170           OPENSSL_PUT_ERROR(BIO, conn_state, BIO_R_NO_PORT_SPECIFIED);
171           ERR_add_error_data(2, "host=", c->param_hostname);
172           goto exit_loop;
173         }
174 
175         if (!bio_ip_and_port_to_socket_and_addr(
176                 &bio->num, &c->them, &c->them_length, c->param_hostname,
177                 c->param_port)) {
178           OPENSSL_PUT_ERROR(BIO, conn_state, BIO_R_UNABLE_TO_CREATE_SOCKET);
179           ERR_add_error_data(4, "host=", c->param_hostname, ":", c->param_port);
180           goto exit_loop;
181         }
182 
183         memset(c->ip, 0, 4);
184         maybe_copy_ipv4_address(c->ip, &c->them);
185 
186         if (c->nbio) {
187           if (!bio_socket_nbio(bio->num, 1)) {
188             OPENSSL_PUT_ERROR(BIO, conn_state, BIO_R_ERROR_SETTING_NBIO);
189             ERR_add_error_data(4, "host=", c->param_hostname, ":",
190                                c->param_port);
191             goto exit_loop;
192           }
193         }
194 
195         i = 1;
196         ret = setsockopt(bio->num, SOL_SOCKET, SO_KEEPALIVE, (char *)&i,
197                          sizeof(i));
198         if (ret < 0) {
199           OPENSSL_PUT_SYSTEM_ERROR(setsockopt);
200           OPENSSL_PUT_ERROR(BIO, conn_state, BIO_R_KEEPALIVE);
201           ERR_add_error_data(4, "host=", c->param_hostname, ":", c->param_port);
202           goto exit_loop;
203         }
204 
205         BIO_clear_retry_flags(bio);
206         ret = connect(bio->num, (struct sockaddr*) &c->them, c->them_length);
207         if (ret < 0) {
208           if (bio_fd_should_retry(ret)) {
209             BIO_set_flags(bio, (BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY));
210             c->state = BIO_CONN_S_BLOCKED_CONNECT;
211             bio->retry_reason = BIO_RR_CONNECT;
212           } else {
213             OPENSSL_PUT_SYSTEM_ERROR(connect);
214             OPENSSL_PUT_ERROR(BIO, conn_state, BIO_R_CONNECT_ERROR);
215             ERR_add_error_data(4, "host=", c->param_hostname, ":",
216                                c->param_port);
217           }
218           goto exit_loop;
219         } else {
220           c->state = BIO_CONN_S_OK;
221         }
222         break;
223 
224       case BIO_CONN_S_BLOCKED_CONNECT:
225         i = bio_sock_error(bio->num);
226         if (i) {
227           if (bio_fd_should_retry(ret)) {
228             BIO_set_flags(bio, (BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY));
229             c->state = BIO_CONN_S_BLOCKED_CONNECT;
230             bio->retry_reason = BIO_RR_CONNECT;
231             ret = -1;
232           } else {
233             BIO_clear_retry_flags(bio);
234             OPENSSL_PUT_SYSTEM_ERROR(connect);
235             OPENSSL_PUT_ERROR(BIO, conn_state, BIO_R_NBIO_CONNECT_ERROR);
236             ERR_add_error_data(4, "host=", c->param_hostname, ":", c->param_port);
237             ret = 0;
238           }
239           goto exit_loop;
240         } else {
241           c->state = BIO_CONN_S_OK;
242         }
243         break;
244 
245       case BIO_CONN_S_OK:
246         ret = 1;
247         goto exit_loop;
248       default:
249         assert(0);
250         goto exit_loop;
251     }
252 
253     if (cb != NULL) {
254       ret = cb((BIO *)bio, c->state, ret);
255       if (ret == 0) {
256         goto end;
257       }
258     }
259   }
260 
261 exit_loop:
262   if (cb != NULL) {
263     ret = cb((BIO *)bio, c->state, ret);
264   }
265 
266 end:
267   return ret;
268 }
269 
BIO_CONNECT_new(void)270 static BIO_CONNECT *BIO_CONNECT_new(void) {
271   BIO_CONNECT *ret = OPENSSL_malloc(sizeof(BIO_CONNECT));
272 
273   if (ret == NULL) {
274     return NULL;
275   }
276   memset(ret, 0, sizeof(BIO_CONNECT));
277 
278   ret->state = BIO_CONN_S_BEFORE;
279   return ret;
280 }
281 
BIO_CONNECT_free(BIO_CONNECT * c)282 static void BIO_CONNECT_free(BIO_CONNECT *c) {
283   if (c == NULL) {
284     return;
285   }
286 
287   OPENSSL_free(c->param_hostname);
288   OPENSSL_free(c->param_port);
289   OPENSSL_free(c);
290 }
291 
conn_new(BIO * bio)292 static int conn_new(BIO *bio) {
293   bio->init = 0;
294   bio->num = -1;
295   bio->flags = 0;
296   bio->ptr = (char *)BIO_CONNECT_new();
297   return bio->ptr != NULL;
298 }
299 
conn_close_socket(BIO * bio)300 static void conn_close_socket(BIO *bio) {
301   BIO_CONNECT *c = (BIO_CONNECT *) bio->ptr;
302 
303   if (bio->num == -1) {
304     return;
305   }
306 
307   /* Only do a shutdown if things were established */
308   if (c->state == BIO_CONN_S_OK) {
309     shutdown(bio->num, 2);
310   }
311   closesocket(bio->num);
312   bio->num = -1;
313 }
314 
conn_free(BIO * bio)315 static int conn_free(BIO *bio) {
316   if (bio == NULL) {
317     return 0;
318   }
319 
320   if (bio->shutdown) {
321     conn_close_socket(bio);
322   }
323 
324   BIO_CONNECT_free((BIO_CONNECT*) bio->ptr);
325 
326   return 1;
327 }
328 
conn_read(BIO * bio,char * out,int out_len)329 static int conn_read(BIO *bio, char *out, int out_len) {
330   int ret = 0;
331   BIO_CONNECT *data;
332 
333   data = (BIO_CONNECT *)bio->ptr;
334   if (data->state != BIO_CONN_S_OK) {
335     ret = conn_state(bio, data);
336     if (ret <= 0) {
337       return ret;
338     }
339   }
340 
341   bio_clear_socket_error();
342   ret = recv(bio->num, out, out_len, 0);
343   BIO_clear_retry_flags(bio);
344   if (ret <= 0) {
345     if (bio_fd_should_retry(ret)) {
346       BIO_set_retry_read(bio);
347     }
348   }
349 
350   return ret;
351 }
352 
conn_write(BIO * bio,const char * in,int in_len)353 static int conn_write(BIO *bio, const char *in, int in_len) {
354   int ret;
355   BIO_CONNECT *data;
356 
357   data = (BIO_CONNECT *)bio->ptr;
358   if (data->state != BIO_CONN_S_OK) {
359     ret = conn_state(bio, data);
360     if (ret <= 0) {
361       return ret;
362     }
363   }
364 
365   bio_clear_socket_error();
366   ret = send(bio->num, in, in_len, 0);
367   BIO_clear_retry_flags(bio);
368   if (ret <= 0) {
369     if (bio_fd_should_retry(ret)) {
370       BIO_set_retry_write(bio);
371     }
372   }
373 
374   return ret;
375 }
376 
conn_ctrl(BIO * bio,int cmd,long num,void * ptr)377 static long conn_ctrl(BIO *bio, int cmd, long num, void *ptr) {
378   int *ip;
379   const char **pptr;
380   long ret = 1;
381   BIO_CONNECT *data;
382 
383   data = (BIO_CONNECT *)bio->ptr;
384 
385   switch (cmd) {
386     case BIO_CTRL_RESET:
387       ret = 0;
388       data->state = BIO_CONN_S_BEFORE;
389       conn_close_socket(bio);
390       bio->flags = 0;
391       break;
392     case BIO_C_DO_STATE_MACHINE:
393       /* use this one to start the connection */
394       if (data->state != BIO_CONN_S_OK) {
395         ret = (long)conn_state(bio, data);
396       } else {
397         ret = 1;
398       }
399       break;
400     case BIO_C_GET_CONNECT:
401       /* TODO(fork): can this be removed? (Or maybe this whole file). */
402       if (ptr != NULL) {
403         pptr = (const char **)ptr;
404         if (num == 0) {
405           *pptr = data->param_hostname;
406         } else if (num == 1) {
407           *pptr = data->param_port;
408         } else if (num == 2) {
409           *pptr = (char *) &data->ip[0];
410         } else if (num == 3) {
411           *((int *)ptr) = data->port;
412         }
413         if (!bio->init) {
414           *pptr = "not initialized";
415         }
416         ret = 1;
417       }
418       break;
419     case BIO_C_SET_CONNECT:
420       if (ptr != NULL) {
421         bio->init = 1;
422         if (num == 0) {
423           OPENSSL_free(data->param_hostname);
424           data->param_hostname = BUF_strdup(ptr);
425           if (data->param_hostname == NULL) {
426             ret = 0;
427           }
428         } else if (num == 1) {
429           OPENSSL_free(data->param_port);
430           data->param_port = BUF_strdup(ptr);
431           if (data->param_port == NULL) {
432             ret = 0;
433           }
434         } else {
435           ret = 0;
436         }
437       }
438       break;
439     case BIO_C_SET_NBIO:
440       data->nbio = (int)num;
441       break;
442     case BIO_C_GET_FD:
443       if (bio->init) {
444         ip = (int *)ptr;
445         if (ip != NULL) {
446           *ip = bio->num;
447         }
448         ret = 1;
449       } else {
450         ret = 0;
451       }
452       break;
453     case BIO_CTRL_GET_CLOSE:
454       ret = bio->shutdown;
455       break;
456     case BIO_CTRL_SET_CLOSE:
457       bio->shutdown = (int)num;
458       break;
459     case BIO_CTRL_PENDING:
460     case BIO_CTRL_WPENDING:
461       ret = 0;
462       break;
463     case BIO_CTRL_FLUSH:
464       break;
465     case BIO_CTRL_SET_CALLBACK: {
466 #if 0 /* FIXME: Should this be used?  -- Richard Levitte */
467 		OPENSSL_PUT_ERROR(BIO, XXX, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
468 		ret = -1;
469 #else
470       ret = 0;
471 #endif
472     } break;
473     case BIO_CTRL_GET_CALLBACK: {
474       int (**fptr)(const BIO *bio, int state, int xret);
475       fptr = (int (**)(const BIO *bio, int state, int xret))ptr;
476       *fptr = data->info_callback;
477     } break;
478     default:
479       ret = 0;
480       break;
481   }
482   return (ret);
483 }
484 
conn_callback_ctrl(BIO * bio,int cmd,bio_info_cb fp)485 static long conn_callback_ctrl(BIO *bio, int cmd, bio_info_cb fp) {
486   long ret = 1;
487   BIO_CONNECT *data;
488 
489   data = (BIO_CONNECT *)bio->ptr;
490 
491   switch (cmd) {
492     case BIO_CTRL_SET_CALLBACK: {
493       data->info_callback = (int (*)(const struct bio_st *, int, int))fp;
494     } break;
495     default:
496       ret = 0;
497       break;
498   }
499   return ret;
500 }
501 
conn_puts(BIO * bp,const char * str)502 static int conn_puts(BIO *bp, const char *str) {
503   return conn_write(bp, str, strlen(str));
504 }
505 
BIO_new_connect(const char * hostname)506 BIO *BIO_new_connect(const char *hostname) {
507   BIO *ret;
508 
509   ret = BIO_new(BIO_s_connect());
510   if (ret == NULL) {
511     return NULL;
512   }
513   if (!BIO_set_conn_hostname(ret, hostname)) {
514     BIO_free(ret);
515     return NULL;
516   }
517   return ret;
518 }
519 
520 static const BIO_METHOD methods_connectp = {
521     BIO_TYPE_CONNECT, "socket connect",         conn_write, conn_read,
522     conn_puts,        NULL /* connect_gets, */, conn_ctrl,  conn_new,
523     conn_free,        conn_callback_ctrl,
524 };
525 
BIO_s_connect(void)526 const BIO_METHOD *BIO_s_connect(void) { return &methods_connectp; }
527 
BIO_set_conn_hostname(BIO * bio,const char * name)528 int BIO_set_conn_hostname(BIO *bio, const char *name) {
529   return BIO_ctrl(bio, BIO_C_SET_CONNECT, 0, (void*) name);
530 }
531 
BIO_set_conn_port(BIO * bio,const char * port_str)532 int BIO_set_conn_port(BIO *bio, const char *port_str) {
533   return BIO_ctrl(bio, BIO_C_SET_CONNECT, 1, (void*) port_str);
534 }
535 
BIO_set_nbio(BIO * bio,int on)536 int BIO_set_nbio(BIO *bio, int on) {
537   return BIO_ctrl(bio, BIO_C_SET_NBIO, on, NULL);
538 }
539