1 /*
2  *  TCP/IP or UDP/IP networking functions
3  *
4  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  *  This file is part of mbed TLS (https://tls.mbed.org)
20  */
21 
22 #if !defined(MBEDTLS_CONFIG_FILE)
23 #include "mbedtls/config.h"
24 #else
25 #include MBEDTLS_CONFIG_FILE
26 #endif
27 
28 #if defined(MBEDTLS_NET_C)
29 
30 #if !defined(unix) && !defined(__unix__) && !defined(__unix) && \
31     !defined(__APPLE__) && !defined(_WIN32)
32 #error "This module only works on Unix and Windows, see MBEDTLS_NET_C in config.h"
33 #endif
34 
35 #if defined(MBEDTLS_PLATFORM_C)
36 #include "mbedtls/platform.h"
37 #else
38 #include <stdlib.h>
39 #endif
40 
41 #include "mbedtls/net_sockets.h"
42 
43 #include <string.h>
44 
45 #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
46     !defined(EFI32)
47 
48 #ifdef _WIN32_WINNT
49 #undef _WIN32_WINNT
50 #endif
51 /* Enables getaddrinfo() & Co */
52 #define _WIN32_WINNT 0x0501
53 #include <ws2tcpip.h>
54 
55 #include <winsock2.h>
56 #include <windows.h>
57 
58 #if defined(_MSC_VER)
59 #if defined(_WIN32_WCE)
60 #pragma comment( lib, "ws2.lib" )
61 #else
62 #pragma comment( lib, "ws2_32.lib" )
63 #endif
64 #endif /* _MSC_VER */
65 
66 #define read(fd,buf,len)        recv(fd,(char*)buf,(int) len,0)
67 #define write(fd,buf,len)       send(fd,(char*)buf,(int) len,0)
68 #define close(fd)               closesocket(fd)
69 
70 static int wsa_init_done = 0;
71 
72 #else /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
73 
74 #include <sys/types.h>
75 #include <sys/socket.h>
76 #include <netinet/in.h>
77 #include <arpa/inet.h>
78 #include <sys/time.h>
79 #include <unistd.h>
80 #include <signal.h>
81 #include <fcntl.h>
82 #include <netdb.h>
83 #include <errno.h>
84 
85 #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
86 
87 /* Some MS functions want int and MSVC warns if we pass size_t,
88  * but the standard fucntions use socklen_t, so cast only for MSVC */
89 #if defined(_MSC_VER)
90 #define MSVC_INT_CAST   (int)
91 #else
92 #define MSVC_INT_CAST
93 #endif
94 
95 #include <stdio.h>
96 
97 #include <time.h>
98 
99 #include <stdint.h>
100 
101 /*
102  * Prepare for using the sockets interface
103  */
net_prepare(void)104 static int net_prepare( void )
105 {
106 #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
107     !defined(EFI32)
108     WSADATA wsaData;
109 
110     if( wsa_init_done == 0 )
111     {
112         if( WSAStartup( MAKEWORD(2,0), &wsaData ) != 0 )
113             return( MBEDTLS_ERR_NET_SOCKET_FAILED );
114 
115         wsa_init_done = 1;
116     }
117 #else
118 #if !defined(EFIX64) && !defined(EFI32)
119     signal( SIGPIPE, SIG_IGN );
120 #endif
121 #endif
122     return( 0 );
123 }
124 
125 /*
126  * Initialize a context
127  */
mbedtls_net_init(mbedtls_net_context * ctx)128 void mbedtls_net_init( mbedtls_net_context *ctx )
129 {
130     ctx->fd = -1;
131 }
132 
133 /*
134  * Initiate a TCP connection with host:port and the given protocol
135  */
mbedtls_net_connect(mbedtls_net_context * ctx,const char * host,const char * port,int proto)136 int mbedtls_net_connect( mbedtls_net_context *ctx, const char *host, const char *port, int proto )
137 {
138     int ret;
139     struct addrinfo hints, *addr_list, *cur;
140 
141     if( ( ret = net_prepare() ) != 0 )
142         return( ret );
143 
144     /* Do name resolution with both IPv6 and IPv4 */
145     memset( &hints, 0, sizeof( hints ) );
146     hints.ai_family = AF_UNSPEC;
147     hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
148     hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
149 
150     if( getaddrinfo( host, port, &hints, &addr_list ) != 0 )
151         return( MBEDTLS_ERR_NET_UNKNOWN_HOST );
152 
153     /* Try the sockaddrs until a connection succeeds */
154     ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
155     for( cur = addr_list; cur != NULL; cur = cur->ai_next )
156     {
157         ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,
158                             cur->ai_protocol );
159         if( ctx->fd < 0 )
160         {
161             ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
162             continue;
163         }
164 
165         if( connect( ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen ) == 0 )
166         {
167             ret = 0;
168             break;
169         }
170 
171         close( ctx->fd );
172         ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
173     }
174 
175     freeaddrinfo( addr_list );
176 
177     return( ret );
178 }
179 
180 /*
181  * Create a listening socket on bind_ip:port
182  */
mbedtls_net_bind(mbedtls_net_context * ctx,const char * bind_ip,const char * port,int proto)183 int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto )
184 {
185     int n, ret;
186     struct addrinfo hints, *addr_list, *cur;
187 
188     if( ( ret = net_prepare() ) != 0 )
189         return( ret );
190 
191     /* Bind to IPv6 and/or IPv4, but only in the desired protocol */
192     memset( &hints, 0, sizeof( hints ) );
193     hints.ai_family = AF_UNSPEC;
194     hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
195     hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
196     if( bind_ip == NULL )
197         hints.ai_flags = AI_PASSIVE;
198 
199     if( getaddrinfo( bind_ip, port, &hints, &addr_list ) != 0 )
200         return( MBEDTLS_ERR_NET_UNKNOWN_HOST );
201 
202     /* Try the sockaddrs until a binding succeeds */
203     ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
204     for( cur = addr_list; cur != NULL; cur = cur->ai_next )
205     {
206         ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,
207                             cur->ai_protocol );
208         if( ctx->fd < 0 )
209         {
210             ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
211             continue;
212         }
213 
214         n = 1;
215         if( setsockopt( ctx->fd, SOL_SOCKET, SO_REUSEADDR,
216                         (const char *) &n, sizeof( n ) ) != 0 )
217         {
218             close( ctx->fd );
219             ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
220             continue;
221         }
222 
223         if( bind( ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen ) != 0 )
224         {
225             close( ctx->fd );
226             ret = MBEDTLS_ERR_NET_BIND_FAILED;
227             continue;
228         }
229 
230         /* Listen only makes sense for TCP */
231         if( proto == MBEDTLS_NET_PROTO_TCP )
232         {
233             if( listen( ctx->fd, MBEDTLS_NET_LISTEN_BACKLOG ) != 0 )
234             {
235                 close( ctx->fd );
236                 ret = MBEDTLS_ERR_NET_LISTEN_FAILED;
237                 continue;
238             }
239         }
240 
241         /* I we ever get there, it's a success */
242         ret = 0;
243         break;
244     }
245 
246     freeaddrinfo( addr_list );
247 
248     return( ret );
249 
250 }
251 
252 #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
253     !defined(EFI32)
254 /*
255  * Check if the requested operation would be blocking on a non-blocking socket
256  * and thus 'failed' with a negative return value.
257  */
net_would_block(const mbedtls_net_context * ctx)258 static int net_would_block( const mbedtls_net_context *ctx )
259 {
260     ((void) ctx);
261     return( WSAGetLastError() == WSAEWOULDBLOCK );
262 }
263 #else
264 /*
265  * Check if the requested operation would be blocking on a non-blocking socket
266  * and thus 'failed' with a negative return value.
267  *
268  * Note: on a blocking socket this function always returns 0!
269  */
net_would_block(const mbedtls_net_context * ctx)270 static int net_would_block( const mbedtls_net_context *ctx )
271 {
272     /*
273      * Never return 'WOULD BLOCK' on a non-blocking socket
274      */
275     if( ( fcntl( ctx->fd, F_GETFL ) & O_NONBLOCK ) != O_NONBLOCK )
276         return( 0 );
277 
278     switch( errno )
279     {
280 #if defined EAGAIN
281         case EAGAIN:
282 #endif
283 #if defined EWOULDBLOCK && EWOULDBLOCK != EAGAIN
284         case EWOULDBLOCK:
285 #endif
286             return( 1 );
287     }
288     return( 0 );
289 }
290 #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
291 
292 /*
293  * Accept a connection from a remote client
294  */
mbedtls_net_accept(mbedtls_net_context * bind_ctx,mbedtls_net_context * client_ctx,void * client_ip,size_t buf_size,size_t * ip_len)295 int mbedtls_net_accept( mbedtls_net_context *bind_ctx,
296                         mbedtls_net_context *client_ctx,
297                         void *client_ip, size_t buf_size, size_t *ip_len )
298 {
299     int ret;
300     int type;
301 
302     struct sockaddr_storage client_addr;
303 
304 #if defined(__socklen_t_defined) || defined(_SOCKLEN_T) ||  \
305     defined(_SOCKLEN_T_DECLARED) || defined(__DEFINED_socklen_t)
306     socklen_t n = (socklen_t) sizeof( client_addr );
307     socklen_t type_len = (socklen_t) sizeof( type );
308 #else
309     int n = (int) sizeof( client_addr );
310     int type_len = (int) sizeof( type );
311 #endif
312 
313     /* Is this a TCP or UDP socket? */
314     if( getsockopt( bind_ctx->fd, SOL_SOCKET, SO_TYPE,
315                     (void *) &type, &type_len ) != 0 ||
316         ( type != SOCK_STREAM && type != SOCK_DGRAM ) )
317     {
318         return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
319     }
320 
321     if( type == SOCK_STREAM )
322     {
323         /* TCP: actual accept() */
324         ret = client_ctx->fd = (int) accept( bind_ctx->fd,
325                                          (struct sockaddr *) &client_addr, &n );
326     }
327     else
328     {
329         /* UDP: wait for a message, but keep it in the queue */
330         char buf[1] = { 0 };
331 
332         ret = (int) recvfrom( bind_ctx->fd, buf, sizeof( buf ), MSG_PEEK,
333                         (struct sockaddr *) &client_addr, &n );
334 
335 #if defined(_WIN32)
336         if( ret == SOCKET_ERROR &&
337             WSAGetLastError() == WSAEMSGSIZE )
338         {
339             /* We know buf is too small, thanks, just peeking here */
340             ret = 0;
341         }
342 #endif
343     }
344 
345     if( ret < 0 )
346     {
347         if( net_would_block( bind_ctx ) != 0 )
348             return( MBEDTLS_ERR_SSL_WANT_READ );
349 
350         return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
351     }
352 
353     /* UDP: hijack the listening socket to communicate with the client,
354      * then bind a new socket to accept new connections */
355     if( type != SOCK_STREAM )
356     {
357         struct sockaddr_storage local_addr;
358         int one = 1;
359 
360         if( connect( bind_ctx->fd, (struct sockaddr *) &client_addr, n ) != 0 )
361             return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
362 
363         client_ctx->fd = bind_ctx->fd;
364         bind_ctx->fd   = -1; /* In case we exit early */
365 
366         n = sizeof( struct sockaddr_storage );
367         if( getsockname( client_ctx->fd,
368                          (struct sockaddr *) &local_addr, &n ) != 0 ||
369             ( bind_ctx->fd = (int) socket( local_addr.ss_family,
370                                            SOCK_DGRAM, IPPROTO_UDP ) ) < 0 ||
371             setsockopt( bind_ctx->fd, SOL_SOCKET, SO_REUSEADDR,
372                         (const char *) &one, sizeof( one ) ) != 0 )
373         {
374             return( MBEDTLS_ERR_NET_SOCKET_FAILED );
375         }
376 
377         if( bind( bind_ctx->fd, (struct sockaddr *) &local_addr, n ) != 0 )
378         {
379             return( MBEDTLS_ERR_NET_BIND_FAILED );
380         }
381     }
382 
383     if( client_ip != NULL )
384     {
385         if( client_addr.ss_family == AF_INET )
386         {
387             struct sockaddr_in *addr4 = (struct sockaddr_in *) &client_addr;
388             *ip_len = sizeof( addr4->sin_addr.s_addr );
389 
390             if( buf_size < *ip_len )
391                 return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );
392 
393             memcpy( client_ip, &addr4->sin_addr.s_addr, *ip_len );
394         }
395         else
396         {
397             struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) &client_addr;
398             *ip_len = sizeof( addr6->sin6_addr.s6_addr );
399 
400             if( buf_size < *ip_len )
401                 return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );
402 
403             memcpy( client_ip, &addr6->sin6_addr.s6_addr, *ip_len);
404         }
405     }
406 
407     return( 0 );
408 }
409 
410 /*
411  * Set the socket blocking or non-blocking
412  */
mbedtls_net_set_block(mbedtls_net_context * ctx)413 int mbedtls_net_set_block( mbedtls_net_context *ctx )
414 {
415 #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
416     !defined(EFI32)
417     u_long n = 0;
418     return( ioctlsocket( ctx->fd, FIONBIO, &n ) );
419 #else
420     return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) & ~O_NONBLOCK ) );
421 #endif
422 }
423 
mbedtls_net_set_nonblock(mbedtls_net_context * ctx)424 int mbedtls_net_set_nonblock( mbedtls_net_context *ctx )
425 {
426 #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
427     !defined(EFI32)
428     u_long n = 1;
429     return( ioctlsocket( ctx->fd, FIONBIO, &n ) );
430 #else
431     return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) | O_NONBLOCK ) );
432 #endif
433 }
434 
435 /*
436  * Portable usleep helper
437  */
mbedtls_net_usleep(unsigned long usec)438 void mbedtls_net_usleep( unsigned long usec )
439 {
440 #if defined(_WIN32)
441     Sleep( ( usec + 999 ) / 1000 );
442 #else
443     struct timeval tv;
444     tv.tv_sec  = usec / 1000000;
445 #if defined(__unix__) || defined(__unix) || \
446     ( defined(__APPLE__) && defined(__MACH__) )
447     tv.tv_usec = (suseconds_t) usec % 1000000;
448 #else
449     tv.tv_usec = usec % 1000000;
450 #endif
451     select( 0, NULL, NULL, NULL, &tv );
452 #endif
453 }
454 
455 /*
456  * Read at most 'len' characters
457  */
mbedtls_net_recv(void * ctx,unsigned char * buf,size_t len)458 int mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len )
459 {
460     int ret;
461     int fd = ((mbedtls_net_context *) ctx)->fd;
462 
463     if( fd < 0 )
464         return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
465 
466     ret = (int) read( fd, buf, len );
467 
468     if( ret < 0 )
469     {
470         if( net_would_block( ctx ) != 0 )
471             return( MBEDTLS_ERR_SSL_WANT_READ );
472 
473 #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
474     !defined(EFI32)
475         if( WSAGetLastError() == WSAECONNRESET )
476             return( MBEDTLS_ERR_NET_CONN_RESET );
477 #else
478         if( errno == EPIPE || errno == ECONNRESET )
479             return( MBEDTLS_ERR_NET_CONN_RESET );
480 
481         if( errno == EINTR )
482             return( MBEDTLS_ERR_SSL_WANT_READ );
483 #endif
484 
485         return( MBEDTLS_ERR_NET_RECV_FAILED );
486     }
487 
488     return( ret );
489 }
490 
491 /*
492  * Read at most 'len' characters, blocking for at most 'timeout' ms
493  */
mbedtls_net_recv_timeout(void * ctx,unsigned char * buf,size_t len,uint32_t timeout)494 int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len,
495                       uint32_t timeout )
496 {
497     int ret;
498     struct timeval tv;
499     fd_set read_fds;
500     int fd = ((mbedtls_net_context *) ctx)->fd;
501 
502     if( fd < 0 )
503         return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
504 
505     FD_ZERO( &read_fds );
506     FD_SET( fd, &read_fds );
507 
508     tv.tv_sec  = timeout / 1000;
509     tv.tv_usec = ( timeout % 1000 ) * 1000;
510 
511     ret = select( fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv );
512 
513     /* Zero fds ready means we timed out */
514     if( ret == 0 )
515         return( MBEDTLS_ERR_SSL_TIMEOUT );
516 
517     if( ret < 0 )
518     {
519 #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
520     !defined(EFI32)
521         if( WSAGetLastError() == WSAEINTR )
522             return( MBEDTLS_ERR_SSL_WANT_READ );
523 #else
524         if( errno == EINTR )
525             return( MBEDTLS_ERR_SSL_WANT_READ );
526 #endif
527 
528         return( MBEDTLS_ERR_NET_RECV_FAILED );
529     }
530 
531     /* This call will not block */
532     return( mbedtls_net_recv( ctx, buf, len ) );
533 }
534 
535 /*
536  * Write at most 'len' characters
537  */
mbedtls_net_send(void * ctx,const unsigned char * buf,size_t len)538 int mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len )
539 {
540     int ret;
541     int fd = ((mbedtls_net_context *) ctx)->fd;
542 
543     if( fd < 0 )
544         return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
545 
546     ret = (int) write( fd, buf, len );
547 
548     if( ret < 0 )
549     {
550         if( net_would_block( ctx ) != 0 )
551             return( MBEDTLS_ERR_SSL_WANT_WRITE );
552 
553 #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
554     !defined(EFI32)
555         if( WSAGetLastError() == WSAECONNRESET )
556             return( MBEDTLS_ERR_NET_CONN_RESET );
557 #else
558         if( errno == EPIPE || errno == ECONNRESET )
559             return( MBEDTLS_ERR_NET_CONN_RESET );
560 
561         if( errno == EINTR )
562             return( MBEDTLS_ERR_SSL_WANT_WRITE );
563 #endif
564 
565         return( MBEDTLS_ERR_NET_SEND_FAILED );
566     }
567 
568     return( ret );
569 }
570 
571 /*
572  * Gracefully close the connection
573  */
mbedtls_net_free(mbedtls_net_context * ctx)574 void mbedtls_net_free( mbedtls_net_context *ctx )
575 {
576     if( ctx->fd == -1 )
577         return;
578 
579     shutdown( ctx->fd, 2 );
580     close( ctx->fd );
581 
582     ctx->fd = -1;
583 }
584 
585 #endif /* MBEDTLS_NET_C */
586