1 // Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <openssl/bio.h>
16 
17 #if !defined(OPENSSL_NO_SOCK)
18 
19 #include <assert.h>
20 #include <errno.h>
21 #include <string.h>
22 
23 #if !defined(OPENSSL_WINDOWS)
24 #include <arpa/inet.h>
25 #include <netinet/in.h>
26 #include <sys/socket.h>
27 #include <unistd.h>
28 #else
29 #include <winsock2.h>
30 #include <ws2tcpip.h>
31 #endif
32 
33 #include <openssl/err.h>
34 #include <openssl/mem.h>
35 
36 #include "../internal.h"
37 #include "internal.h"
38 
39 
40 enum {
41   BIO_CONN_S_BEFORE,
42   BIO_CONN_S_BLOCKED_CONNECT,
43   BIO_CONN_S_OK,
44 };
45 
46 namespace {
47 typedef struct bio_connect_st {
48   int state;
49 
50   char *param_hostname;
51   char *param_port;
52   int nbio;
53 
54   unsigned short port;
55 
56   struct sockaddr_storage them;
57   socklen_t them_length;
58 
59   // the file descriptor is kept in bio->num in order to match the socket
60   // BIO.
61 
62   // info_callback is called when the connection is initially made
63   // callback(BIO,state,ret);  The callback should return 'ret', state is for
64   // compatibility with the SSL info_callback.
65   int (*info_callback)(BIO *bio, int state, int ret);
66 } BIO_CONNECT;
67 }  // namespace
68 
69 #if !defined(OPENSSL_WINDOWS)
closesocket(int sock)70 static int closesocket(int sock) { return close(sock); }
71 #endif
72 
73 // split_host_and_port sets |*out_host| and |*out_port| to the host and port
74 // parsed from |name|. It returns one on success or zero on error. Even when
75 // successful, |*out_port| may be NULL on return if no port was specified.
split_host_and_port(char ** out_host,char ** out_port,const char * name)76 static int split_host_and_port(char **out_host, char **out_port,
77                                const char *name) {
78   const char *host, *port = NULL;
79   size_t host_len = 0;
80 
81   *out_host = NULL;
82   *out_port = NULL;
83 
84   if (name[0] == '[') {  // bracketed IPv6 address
85     const char *close = strchr(name, ']');
86     if (close == NULL) {
87       return 0;
88     }
89     host = name + 1;
90     host_len = close - host;
91     if (close[1] == ':') {  // [IP]:port
92       port = close + 2;
93     } else if (close[1] != 0) {
94       return 0;
95     }
96   } else {
97     const char *colon = strchr(name, ':');
98     if (colon == NULL || strchr(colon + 1, ':') != NULL) {  // IPv6 address
99       host = name;
100       host_len = strlen(name);
101     } else {  // host:port
102       host = name;
103       host_len = colon - name;
104       port = colon + 1;
105     }
106   }
107 
108   *out_host = OPENSSL_strndup(host, host_len);
109   if (*out_host == NULL) {
110     return 0;
111   }
112   if (port == NULL) {
113     *out_port = NULL;
114     return 1;
115   }
116   *out_port = OPENSSL_strdup(port);
117   if (*out_port == NULL) {
118     OPENSSL_free(*out_host);
119     *out_host = NULL;
120     return 0;
121   }
122   return 1;
123 }
124 
conn_state(BIO * bio,BIO_CONNECT * c)125 static int conn_state(BIO *bio, BIO_CONNECT *c) {
126   int ret = -1, i;
127   int (*cb)(BIO *, int, int) = NULL;
128 
129   if (c->info_callback != NULL) {
130     cb = c->info_callback;
131   }
132 
133   for (;;) {
134     switch (c->state) {
135       case BIO_CONN_S_BEFORE:
136         // If there's a hostname and a port, assume that both are
137         // exactly what they say. If there is only a hostname, try
138         // (just once) to split it into a hostname and port.
139 
140         if (c->param_hostname == NULL) {
141           OPENSSL_PUT_ERROR(BIO, BIO_R_NO_HOSTNAME_SPECIFIED);
142           goto exit_loop;
143         }
144 
145         if (c->param_port == NULL) {
146           char *host, *port;
147           if (!split_host_and_port(&host, &port, c->param_hostname) ||
148               port == NULL) {
149             OPENSSL_free(host);
150             OPENSSL_free(port);
151             OPENSSL_PUT_ERROR(BIO, BIO_R_NO_PORT_SPECIFIED);
152             ERR_add_error_data(2, "host=", c->param_hostname);
153             goto exit_loop;
154           }
155 
156           OPENSSL_free(c->param_port);
157           c->param_port = port;
158           OPENSSL_free(c->param_hostname);
159           c->param_hostname = host;
160         }
161 
162         if (!bio_ip_and_port_to_socket_and_addr(
163                 &bio->num, &c->them, &c->them_length, c->param_hostname,
164                 c->param_port)) {
165           OPENSSL_PUT_ERROR(BIO, BIO_R_UNABLE_TO_CREATE_SOCKET);
166           ERR_add_error_data(4, "host=", c->param_hostname, ":", c->param_port);
167           goto exit_loop;
168         }
169 
170         if (c->nbio) {
171           if (!bio_socket_nbio(bio->num, 1)) {
172             OPENSSL_PUT_ERROR(BIO, BIO_R_ERROR_SETTING_NBIO);
173             ERR_add_error_data(4, "host=", c->param_hostname, ":",
174                                c->param_port);
175             goto exit_loop;
176           }
177         }
178 
179         i = 1;
180         ret = setsockopt(bio->num, SOL_SOCKET, SO_KEEPALIVE, (char *)&i,
181                          sizeof(i));
182         if (ret < 0) {
183           OPENSSL_PUT_SYSTEM_ERROR();
184           OPENSSL_PUT_ERROR(BIO, BIO_R_KEEPALIVE);
185           ERR_add_error_data(4, "host=", c->param_hostname, ":", c->param_port);
186           goto exit_loop;
187         }
188 
189         BIO_clear_retry_flags(bio);
190         ret = connect(bio->num, (struct sockaddr *)&c->them, c->them_length);
191         if (ret < 0) {
192           if (bio_socket_should_retry(ret)) {
193             BIO_set_flags(bio, (BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY));
194             c->state = BIO_CONN_S_BLOCKED_CONNECT;
195             bio->retry_reason = BIO_RR_CONNECT;
196           } else {
197             OPENSSL_PUT_SYSTEM_ERROR();
198             OPENSSL_PUT_ERROR(BIO, BIO_R_CONNECT_ERROR);
199             ERR_add_error_data(4, "host=", c->param_hostname, ":",
200                                c->param_port);
201           }
202           goto exit_loop;
203         } else {
204           c->state = BIO_CONN_S_OK;
205         }
206         break;
207 
208       case BIO_CONN_S_BLOCKED_CONNECT:
209         i = bio_sock_error(bio->num);
210         if (i) {
211           if (bio_socket_should_retry(ret)) {
212             BIO_set_flags(bio, (BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY));
213             c->state = BIO_CONN_S_BLOCKED_CONNECT;
214             bio->retry_reason = BIO_RR_CONNECT;
215             ret = -1;
216           } else {
217             BIO_clear_retry_flags(bio);
218             OPENSSL_PUT_SYSTEM_ERROR();
219             OPENSSL_PUT_ERROR(BIO, BIO_R_NBIO_CONNECT_ERROR);
220             ERR_add_error_data(4, "host=", c->param_hostname, ":",
221                                c->param_port);
222             ret = 0;
223           }
224           goto exit_loop;
225         } else {
226           c->state = BIO_CONN_S_OK;
227         }
228         break;
229 
230       case BIO_CONN_S_OK:
231         ret = 1;
232         goto exit_loop;
233       default:
234         assert(0);
235         goto exit_loop;
236     }
237 
238     if (cb != NULL) {
239       ret = cb((BIO *)bio, c->state, ret);
240       if (ret == 0) {
241         goto end;
242       }
243     }
244   }
245 
246 exit_loop:
247   if (cb != NULL) {
248     ret = cb((BIO *)bio, c->state, ret);
249   }
250 
251 end:
252   return ret;
253 }
254 
BIO_CONNECT_new(void)255 static BIO_CONNECT *BIO_CONNECT_new(void) {
256   BIO_CONNECT *ret =
257       reinterpret_cast<BIO_CONNECT *>(OPENSSL_zalloc(sizeof(BIO_CONNECT)));
258   if (ret == NULL) {
259     return NULL;
260   }
261   ret->state = BIO_CONN_S_BEFORE;
262   return ret;
263 }
264 
BIO_CONNECT_free(BIO_CONNECT * c)265 static void BIO_CONNECT_free(BIO_CONNECT *c) {
266   if (c == nullptr) {
267     return;
268   }
269   OPENSSL_free(c->param_hostname);
270   OPENSSL_free(c->param_port);
271   OPENSSL_free(c);
272 }
273 
conn_new(BIO * bio)274 static int conn_new(BIO *bio) {
275   bio->init = 0;
276   bio->num = -1;
277   bio->flags = 0;
278   bio->ptr = BIO_CONNECT_new();
279   return bio->ptr != NULL;
280 }
281 
conn_close_socket(BIO * bio)282 static void conn_close_socket(BIO *bio) {
283   BIO_CONNECT *c = (BIO_CONNECT *)bio->ptr;
284 
285   if (bio->num == -1) {
286     return;
287   }
288 
289   // Only do a shutdown if things were established
290   if (c->state == BIO_CONN_S_OK) {
291     shutdown(bio->num, 2);
292   }
293   closesocket(bio->num);
294   bio->num = -1;
295 }
296 
conn_free(BIO * bio)297 static int conn_free(BIO *bio) {
298   if (bio->shutdown) {
299     conn_close_socket(bio);
300   }
301 
302   BIO_CONNECT_free((BIO_CONNECT *)bio->ptr);
303 
304   return 1;
305 }
306 
conn_read(BIO * bio,char * out,int out_len)307 static int conn_read(BIO *bio, char *out, int out_len) {
308   int ret = 0;
309   BIO_CONNECT *data;
310 
311   data = (BIO_CONNECT *)bio->ptr;
312   if (data->state != BIO_CONN_S_OK) {
313     ret = conn_state(bio, data);
314     if (ret <= 0) {
315       return ret;
316     }
317   }
318 
319   bio_clear_socket_error();
320   ret = (int)recv(bio->num, out, out_len, 0);
321   BIO_clear_retry_flags(bio);
322   if (ret <= 0) {
323     if (bio_socket_should_retry(ret)) {
324       BIO_set_retry_read(bio);
325     }
326   }
327 
328   return ret;
329 }
330 
conn_write(BIO * bio,const char * in,int in_len)331 static int conn_write(BIO *bio, const char *in, int in_len) {
332   int ret;
333   BIO_CONNECT *data;
334 
335   data = (BIO_CONNECT *)bio->ptr;
336   if (data->state != BIO_CONN_S_OK) {
337     ret = conn_state(bio, data);
338     if (ret <= 0) {
339       return ret;
340     }
341   }
342 
343   bio_clear_socket_error();
344   ret = (int)send(bio->num, in, in_len, 0);
345   BIO_clear_retry_flags(bio);
346   if (ret <= 0) {
347     if (bio_socket_should_retry(ret)) {
348       BIO_set_retry_write(bio);
349     }
350   }
351 
352   return ret;
353 }
354 
conn_ctrl(BIO * bio,int cmd,long num,void * ptr)355 static long conn_ctrl(BIO *bio, int cmd, long num, void *ptr) {
356   BIO_CONNECT *data = static_cast<BIO_CONNECT *>(bio->ptr);
357   switch (cmd) {
358     case BIO_CTRL_RESET:
359       data->state = BIO_CONN_S_BEFORE;
360       conn_close_socket(bio);
361       bio->flags = 0;
362       return 0;
363     case BIO_C_DO_STATE_MACHINE:
364       // use this one to start the connection
365       if (data->state != BIO_CONN_S_OK) {
366         return conn_state(bio, data);
367       } else {
368         return 1;
369       }
370     case BIO_C_SET_CONNECT:
371       if (ptr == nullptr) {
372         return 0;
373       }
374       bio->init = 1;
375       if (num == 0) {
376         OPENSSL_free(data->param_hostname);
377         data->param_hostname =
378             OPENSSL_strdup(reinterpret_cast<const char *>(ptr));
379         if (data->param_hostname == nullptr) {
380           return 0;
381         }
382       } else if (num == 1) {
383         OPENSSL_free(data->param_port);
384         data->param_port = OPENSSL_strdup(reinterpret_cast<const char *>(ptr));
385         if (data->param_port == nullptr) {
386           return 0;
387         }
388       } else {
389         return 0;
390       }
391       return 1;
392     case BIO_C_SET_NBIO:
393       data->nbio = static_cast<int>(num);
394       return 1;
395     case BIO_C_GET_FD:
396       if (bio->init) {
397         int *out = static_cast<int *>(ptr);
398         if (out != nullptr) {
399           *out = bio->num;
400         }
401         return bio->num;
402       } else {
403         return -1;
404       }
405     case BIO_CTRL_GET_CLOSE:
406       return bio->shutdown;
407     case BIO_CTRL_SET_CLOSE:
408       bio->shutdown = static_cast<int>(num);
409       return 1;
410     case BIO_CTRL_FLUSH:
411       return 1;
412     case BIO_CTRL_GET_CALLBACK: {
413       auto out = reinterpret_cast<int (**)(BIO *bio, int state, int xret)>(ptr);
414       *out = data->info_callback;
415       return 1;
416     }
417     default:
418       return 0;
419   }
420 }
421 
conn_callback_ctrl(BIO * bio,int cmd,BIO_info_cb * fp)422 static long conn_callback_ctrl(BIO *bio, int cmd, BIO_info_cb *fp) {
423   BIO_CONNECT *data = static_cast<BIO_CONNECT *>(bio->ptr);
424   switch (cmd) {
425     case BIO_CTRL_SET_CALLBACK:
426       data->info_callback = fp;
427       return 1;
428     default:
429       return 0;
430   }
431 }
432 
BIO_new_connect(const char * hostname)433 BIO *BIO_new_connect(const char *hostname) {
434   BIO *ret;
435 
436   ret = BIO_new(BIO_s_connect());
437   if (ret == NULL) {
438     return NULL;
439   }
440   if (!BIO_set_conn_hostname(ret, hostname)) {
441     BIO_free(ret);
442     return NULL;
443   }
444   return ret;
445 }
446 
447 static const BIO_METHOD methods_connectp = {
448     BIO_TYPE_CONNECT, "socket connect", conn_write,
449     conn_read,        /*gets=*/nullptr, conn_ctrl,
450     conn_new,         conn_free,        conn_callback_ctrl,
451 };
452 
BIO_s_connect(void)453 const BIO_METHOD *BIO_s_connect(void) { return &methods_connectp; }
454 
BIO_set_conn_hostname(BIO * bio,const char * name)455 int BIO_set_conn_hostname(BIO *bio, const char *name) {
456   return (int)BIO_ctrl(bio, BIO_C_SET_CONNECT, 0, (void *)name);
457 }
458 
BIO_set_conn_port(BIO * bio,const char * port_str)459 int BIO_set_conn_port(BIO *bio, const char *port_str) {
460   return (int)BIO_ctrl(bio, BIO_C_SET_CONNECT, 1, (void *)port_str);
461 }
462 
BIO_set_conn_int_port(BIO * bio,const int * port)463 int BIO_set_conn_int_port(BIO *bio, const int *port) {
464   char buf[DECIMAL_SIZE(int) + 1];
465   snprintf(buf, sizeof(buf), "%d", *port);
466   return BIO_set_conn_port(bio, buf);
467 }
468 
BIO_set_nbio(BIO * bio,int on)469 int BIO_set_nbio(BIO *bio, int on) {
470   return (int)BIO_ctrl(bio, BIO_C_SET_NBIO, on, NULL);
471 }
472 
BIO_do_connect(BIO * bio)473 int BIO_do_connect(BIO *bio) {
474   return (int)BIO_ctrl(bio, BIO_C_DO_STATE_MACHINE, 0, NULL);
475 }
476 
477 #endif  // OPENSSL_NO_SOCK
478