blob: 80be6ec6a4eeb793de44f2fe66d91541919c8d2b [file] [log] [blame]
Jens Wiklander817466c2018-05-22 13:49:31 +02001/*
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
70static 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 */
104static 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 */
128void 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 */
136int mbedtls_net_connect( mbedtls_net_context *ctx, const char *host,
137 const char *port, int proto )
138{
139 int ret;
140 struct addrinfo hints, *addr_list, *cur;
141
142 if( ( ret = net_prepare() ) != 0 )
143 return( ret );
144
145 /* Do name resolution with both IPv6 and IPv4 */
146 memset( &hints, 0, sizeof( hints ) );
147 hints.ai_family = AF_UNSPEC;
148 hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
149 hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
150
151 if( getaddrinfo( host, port, &hints, &addr_list ) != 0 )
152 return( MBEDTLS_ERR_NET_UNKNOWN_HOST );
153
154 /* Try the sockaddrs until a connection succeeds */
155 ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
156 for( cur = addr_list; cur != NULL; cur = cur->ai_next )
157 {
158 ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,
159 cur->ai_protocol );
160 if( ctx->fd < 0 )
161 {
162 ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
163 continue;
164 }
165
166 if( connect( ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen ) == 0 )
167 {
168 ret = 0;
169 break;
170 }
171
172 close( ctx->fd );
173 ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
174 }
175
176 freeaddrinfo( addr_list );
177
178 return( ret );
179}
180
181/*
182 * Create a listening socket on bind_ip:port
183 */
184int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto )
185{
186 int n, ret;
187 struct addrinfo hints, *addr_list, *cur;
188
189 if( ( ret = net_prepare() ) != 0 )
190 return( ret );
191
192 /* Bind to IPv6 and/or IPv4, but only in the desired protocol */
193 memset( &hints, 0, sizeof( hints ) );
194 hints.ai_family = AF_UNSPEC;
195 hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
196 hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
197 if( bind_ip == NULL )
198 hints.ai_flags = AI_PASSIVE;
199
200 if( getaddrinfo( bind_ip, port, &hints, &addr_list ) != 0 )
201 return( MBEDTLS_ERR_NET_UNKNOWN_HOST );
202
203 /* Try the sockaddrs until a binding succeeds */
204 ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
205 for( cur = addr_list; cur != NULL; cur = cur->ai_next )
206 {
207 ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,
208 cur->ai_protocol );
209 if( ctx->fd < 0 )
210 {
211 ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
212 continue;
213 }
214
215 n = 1;
216 if( setsockopt( ctx->fd, SOL_SOCKET, SO_REUSEADDR,
217 (const char *) &n, sizeof( n ) ) != 0 )
218 {
219 close( ctx->fd );
220 ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
221 continue;
222 }
223
224 if( bind( ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen ) != 0 )
225 {
226 close( ctx->fd );
227 ret = MBEDTLS_ERR_NET_BIND_FAILED;
228 continue;
229 }
230
231 /* Listen only makes sense for TCP */
232 if( proto == MBEDTLS_NET_PROTO_TCP )
233 {
234 if( listen( ctx->fd, MBEDTLS_NET_LISTEN_BACKLOG ) != 0 )
235 {
236 close( ctx->fd );
237 ret = MBEDTLS_ERR_NET_LISTEN_FAILED;
238 continue;
239 }
240 }
241
242 /* Bind was successful */
243 ret = 0;
244 break;
245 }
246
247 freeaddrinfo( addr_list );
248
249 return( ret );
250
251}
252
253#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
254 !defined(EFI32)
255/*
256 * Check if the requested operation would be blocking on a non-blocking socket
257 * and thus 'failed' with a negative return value.
258 */
259static int net_would_block( const mbedtls_net_context *ctx )
260{
261 ((void) ctx);
262 return( WSAGetLastError() == WSAEWOULDBLOCK );
263}
264#else
265/*
266 * Check if the requested operation would be blocking on a non-blocking socket
267 * and thus 'failed' with a negative return value.
268 *
269 * Note: on a blocking socket this function always returns 0!
270 */
271static int net_would_block( const mbedtls_net_context *ctx )
272{
273 /*
274 * Never return 'WOULD BLOCK' on a non-blocking socket
275 */
276 if( ( fcntl( ctx->fd, F_GETFL ) & O_NONBLOCK ) != O_NONBLOCK )
277 return( 0 );
278
279 switch( errno )
280 {
281#if defined EAGAIN
282 case EAGAIN:
283#endif
284#if defined EWOULDBLOCK && EWOULDBLOCK != EAGAIN
285 case EWOULDBLOCK:
286#endif
287 return( 1 );
288 }
289 return( 0 );
290}
291#endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
292
293/*
294 * Accept a connection from a remote client
295 */
296int mbedtls_net_accept( mbedtls_net_context *bind_ctx,
297 mbedtls_net_context *client_ctx,
298 void *client_ip, size_t buf_size, size_t *ip_len )
299{
300 int ret;
301 int type;
302
303 struct sockaddr_storage client_addr;
304
305#if defined(__socklen_t_defined) || defined(_SOCKLEN_T) || \
306 defined(_SOCKLEN_T_DECLARED) || defined(__DEFINED_socklen_t)
307 socklen_t n = (socklen_t) sizeof( client_addr );
308 socklen_t type_len = (socklen_t) sizeof( type );
309#else
310 int n = (int) sizeof( client_addr );
311 int type_len = (int) sizeof( type );
312#endif
313
314 /* Is this a TCP or UDP socket? */
315 if( getsockopt( bind_ctx->fd, SOL_SOCKET, SO_TYPE,
316 (void *) &type, &type_len ) != 0 ||
317 ( type != SOCK_STREAM && type != SOCK_DGRAM ) )
318 {
319 return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
320 }
321
322 if( type == SOCK_STREAM )
323 {
324 /* TCP: actual accept() */
325 ret = client_ctx->fd = (int) accept( bind_ctx->fd,
326 (struct sockaddr *) &client_addr, &n );
327 }
328 else
329 {
330 /* UDP: wait for a message, but keep it in the queue */
331 char buf[1] = { 0 };
332
333 ret = (int) recvfrom( bind_ctx->fd, buf, sizeof( buf ), MSG_PEEK,
334 (struct sockaddr *) &client_addr, &n );
335
336#if defined(_WIN32)
337 if( ret == SOCKET_ERROR &&
338 WSAGetLastError() == WSAEMSGSIZE )
339 {
340 /* We know buf is too small, thanks, just peeking here */
341 ret = 0;
342 }
343#endif
344 }
345
346 if( ret < 0 )
347 {
348 if( net_would_block( bind_ctx ) != 0 )
349 return( MBEDTLS_ERR_SSL_WANT_READ );
350
351 return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
352 }
353
354 /* UDP: hijack the listening socket to communicate with the client,
355 * then bind a new socket to accept new connections */
356 if( type != SOCK_STREAM )
357 {
358 struct sockaddr_storage local_addr;
359 int one = 1;
360
361 if( connect( bind_ctx->fd, (struct sockaddr *) &client_addr, n ) != 0 )
362 return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
363
364 client_ctx->fd = bind_ctx->fd;
365 bind_ctx->fd = -1; /* In case we exit early */
366
367 n = sizeof( struct sockaddr_storage );
368 if( getsockname( client_ctx->fd,
369 (struct sockaddr *) &local_addr, &n ) != 0 ||
370 ( bind_ctx->fd = (int) socket( local_addr.ss_family,
371 SOCK_DGRAM, IPPROTO_UDP ) ) < 0 ||
372 setsockopt( bind_ctx->fd, SOL_SOCKET, SO_REUSEADDR,
373 (const char *) &one, sizeof( one ) ) != 0 )
374 {
375 return( MBEDTLS_ERR_NET_SOCKET_FAILED );
376 }
377
378 if( bind( bind_ctx->fd, (struct sockaddr *) &local_addr, n ) != 0 )
379 {
380 return( MBEDTLS_ERR_NET_BIND_FAILED );
381 }
382 }
383
384 if( client_ip != NULL )
385 {
386 if( client_addr.ss_family == AF_INET )
387 {
388 struct sockaddr_in *addr4 = (struct sockaddr_in *) &client_addr;
389 *ip_len = sizeof( addr4->sin_addr.s_addr );
390
391 if( buf_size < *ip_len )
392 return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );
393
394 memcpy( client_ip, &addr4->sin_addr.s_addr, *ip_len );
395 }
396 else
397 {
398 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) &client_addr;
399 *ip_len = sizeof( addr6->sin6_addr.s6_addr );
400
401 if( buf_size < *ip_len )
402 return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );
403
404 memcpy( client_ip, &addr6->sin6_addr.s6_addr, *ip_len);
405 }
406 }
407
408 return( 0 );
409}
410
411/*
412 * Set the socket blocking or non-blocking
413 */
414int mbedtls_net_set_block( mbedtls_net_context *ctx )
415{
416#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
417 !defined(EFI32)
418 u_long n = 0;
419 return( ioctlsocket( ctx->fd, FIONBIO, &n ) );
420#else
421 return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) & ~O_NONBLOCK ) );
422#endif
423}
424
425int mbedtls_net_set_nonblock( mbedtls_net_context *ctx )
426{
427#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
428 !defined(EFI32)
429 u_long n = 1;
430 return( ioctlsocket( ctx->fd, FIONBIO, &n ) );
431#else
432 return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) | O_NONBLOCK ) );
433#endif
434}
435
436/*
437 * Portable usleep helper
438 */
439void mbedtls_net_usleep( unsigned long usec )
440{
441#if defined(_WIN32)
442 Sleep( ( usec + 999 ) / 1000 );
443#else
444 struct timeval tv;
445 tv.tv_sec = usec / 1000000;
446#if defined(__unix__) || defined(__unix) || \
447 ( defined(__APPLE__) && defined(__MACH__) )
448 tv.tv_usec = (suseconds_t) usec % 1000000;
449#else
450 tv.tv_usec = usec % 1000000;
451#endif
452 select( 0, NULL, NULL, NULL, &tv );
453#endif
454}
455
456/*
457 * Read at most 'len' characters
458 */
459int mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len )
460{
461 int ret;
462 int fd = ((mbedtls_net_context *) ctx)->fd;
463
464 if( fd < 0 )
465 return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
466
467 ret = (int) read( fd, buf, len );
468
469 if( ret < 0 )
470 {
471 if( net_would_block( ctx ) != 0 )
472 return( MBEDTLS_ERR_SSL_WANT_READ );
473
474#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
475 !defined(EFI32)
476 if( WSAGetLastError() == WSAECONNRESET )
477 return( MBEDTLS_ERR_NET_CONN_RESET );
478#else
479 if( errno == EPIPE || errno == ECONNRESET )
480 return( MBEDTLS_ERR_NET_CONN_RESET );
481
482 if( errno == EINTR )
483 return( MBEDTLS_ERR_SSL_WANT_READ );
484#endif
485
486 return( MBEDTLS_ERR_NET_RECV_FAILED );
487 }
488
489 return( ret );
490}
491
492/*
493 * Read at most 'len' characters, blocking for at most 'timeout' ms
494 */
495int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len,
496 uint32_t timeout )
497{
498 int ret;
499 struct timeval tv;
500 fd_set read_fds;
501 int fd = ((mbedtls_net_context *) ctx)->fd;
502
503 if( fd < 0 )
504 return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
505
506 FD_ZERO( &read_fds );
507 FD_SET( fd, &read_fds );
508
509 tv.tv_sec = timeout / 1000;
510 tv.tv_usec = ( timeout % 1000 ) * 1000;
511
512 ret = select( fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv );
513
514 /* Zero fds ready means we timed out */
515 if( ret == 0 )
516 return( MBEDTLS_ERR_SSL_TIMEOUT );
517
518 if( ret < 0 )
519 {
520#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
521 !defined(EFI32)
522 if( WSAGetLastError() == WSAEINTR )
523 return( MBEDTLS_ERR_SSL_WANT_READ );
524#else
525 if( errno == EINTR )
526 return( MBEDTLS_ERR_SSL_WANT_READ );
527#endif
528
529 return( MBEDTLS_ERR_NET_RECV_FAILED );
530 }
531
532 /* This call will not block */
533 return( mbedtls_net_recv( ctx, buf, len ) );
534}
535
536/*
537 * Write at most 'len' characters
538 */
539int mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len )
540{
541 int ret;
542 int fd = ((mbedtls_net_context *) ctx)->fd;
543
544 if( fd < 0 )
545 return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
546
547 ret = (int) write( fd, buf, len );
548
549 if( ret < 0 )
550 {
551 if( net_would_block( ctx ) != 0 )
552 return( MBEDTLS_ERR_SSL_WANT_WRITE );
553
554#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
555 !defined(EFI32)
556 if( WSAGetLastError() == WSAECONNRESET )
557 return( MBEDTLS_ERR_NET_CONN_RESET );
558#else
559 if( errno == EPIPE || errno == ECONNRESET )
560 return( MBEDTLS_ERR_NET_CONN_RESET );
561
562 if( errno == EINTR )
563 return( MBEDTLS_ERR_SSL_WANT_WRITE );
564#endif
565
566 return( MBEDTLS_ERR_NET_SEND_FAILED );
567 }
568
569 return( ret );
570}
571
572/*
573 * Gracefully close the connection
574 */
575void mbedtls_net_free( mbedtls_net_context *ctx )
576{
577 if( ctx->fd == -1 )
578 return;
579
580 shutdown( ctx->fd, 2 );
581 close( ctx->fd );
582
583 ctx->fd = -1;
584}
585
586#endif /* MBEDTLS_NET_C */