1 /**
2  * \file net_sockets.h
3  *
4  * \brief   Network sockets abstraction layer to integrate Mbed TLS into a
5  *          BSD-style sockets API.
6  *
7  *          The network sockets module provides an example integration of the
8  *          Mbed TLS library into a BSD sockets implementation. The module is
9  *          intended to be an example of how Mbed TLS can be integrated into a
10  *          networking stack, as well as to be Mbed TLS's network integration
11  *          for its supported platforms.
12  *
13  *          The module is intended only to be used with the Mbed TLS library and
14  *          is not intended to be used by third party application software
15  *          directly.
16  *
17  *          The supported platforms are as follows:
18  *              * Microsoft Windows and Windows CE
19  *              * POSIX/Unix platforms including Linux, OS X
20  *
21  */
22 /*
23  *  Copyright The Mbed TLS Contributors
24  *  SPDX-License-Identifier: Apache-2.0
25  *
26  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
27  *  not use this file except in compliance with the License.
28  *  You may obtain a copy of the License at
29  *
30  *  http://www.apache.org/licenses/LICENSE-2.0
31  *
32  *  Unless required by applicable law or agreed to in writing, software
33  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
34  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
35  *  See the License for the specific language governing permissions and
36  *  limitations under the License.
37  */
38 #ifndef MBEDTLS_NET_SOCKETS_H
39 #define MBEDTLS_NET_SOCKETS_H
40 #include "mbedtls/private_access.h"
41 
42 #include "mbedtls/build_info.h"
43 
44 #include "mbedtls/ssl.h"
45 
46 #include <stddef.h>
47 #include <stdint.h>
48 
49 /** Failed to open a socket. */
50 #define MBEDTLS_ERR_NET_SOCKET_FAILED                     -0x0042
51 /** The connection to the given server / port failed. */
52 #define MBEDTLS_ERR_NET_CONNECT_FAILED                    -0x0044
53 /** Binding of the socket failed. */
54 #define MBEDTLS_ERR_NET_BIND_FAILED                       -0x0046
55 /** Could not listen on the socket. */
56 #define MBEDTLS_ERR_NET_LISTEN_FAILED                     -0x0048
57 /** Could not accept the incoming connection. */
58 #define MBEDTLS_ERR_NET_ACCEPT_FAILED                     -0x004A
59 /** Reading information from the socket failed. */
60 #define MBEDTLS_ERR_NET_RECV_FAILED                       -0x004C
61 /** Sending information through the socket failed. */
62 #define MBEDTLS_ERR_NET_SEND_FAILED                       -0x004E
63 /** Connection was reset by peer. */
64 #define MBEDTLS_ERR_NET_CONN_RESET                        -0x0050
65 /** Failed to get an IP address for the given hostname. */
66 #define MBEDTLS_ERR_NET_UNKNOWN_HOST                      -0x0052
67 /** Buffer is too small to hold the data. */
68 #define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL                  -0x0043
69 /** The context is invalid, eg because it was free()ed. */
70 #define MBEDTLS_ERR_NET_INVALID_CONTEXT                   -0x0045
71 /** Polling the net context failed. */
72 #define MBEDTLS_ERR_NET_POLL_FAILED                       -0x0047
73 /** Input invalid. */
74 #define MBEDTLS_ERR_NET_BAD_INPUT_DATA                    -0x0049
75 
76 #define MBEDTLS_NET_LISTEN_BACKLOG         10 /**< The backlog that listen() should use. */
77 
78 #define MBEDTLS_NET_PROTO_TCP 0 /**< The TCP transport protocol */
79 #define MBEDTLS_NET_PROTO_UDP 1 /**< The UDP transport protocol */
80 
81 #define MBEDTLS_NET_POLL_READ  1 /**< Used in \c mbedtls_net_poll to check for pending data  */
82 #define MBEDTLS_NET_POLL_WRITE 2 /**< Used in \c mbedtls_net_poll to check if write possible */
83 
84 #ifdef __cplusplus
85 extern "C" {
86 #endif
87 
88 /**
89  * Wrapper type for sockets.
90  *
91  * Currently backed by just a file descriptor, but might be more in the future
92  * (eg two file descriptors for combined IPv4 + IPv6 support, or additional
93  * structures for hand-made UDP demultiplexing).
94  */
95 typedef struct mbedtls_net_context {
96     /** The underlying file descriptor.
97      *
98      * This field is only guaranteed to be present on POSIX/Unix-like platforms.
99      * On other platforms, it may have a different type, have a different
100      * meaning, or be absent altogether.
101      */
102     int fd;
103 }
104 mbedtls_net_context;
105 
106 /**
107  * \brief          Initialize a context
108  *                 Just makes the context ready to be used or freed safely.
109  *
110  * \param ctx      Context to initialize
111  */
112 void mbedtls_net_init(mbedtls_net_context *ctx);
113 
114 /**
115  * \brief          Initiate a connection with host:port in the given protocol
116  *
117  * \param ctx      Socket to use
118  * \param host     Host to connect to
119  * \param port     Port to connect to
120  * \param proto    Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP
121  *
122  * \return         0 if successful, or one of:
123  *                      MBEDTLS_ERR_NET_SOCKET_FAILED,
124  *                      MBEDTLS_ERR_NET_UNKNOWN_HOST,
125  *                      MBEDTLS_ERR_NET_CONNECT_FAILED
126  *
127  * \note           Sets the socket in connected mode even with UDP.
128  */
129 int mbedtls_net_connect(mbedtls_net_context *ctx, const char *host, const char *port, int proto);
130 
131 /**
132  * \brief          Create a receiving socket on bind_ip:port in the chosen
133  *                 protocol. If bind_ip == NULL, all interfaces are bound.
134  *
135  * \param ctx      Socket to use
136  * \param bind_ip  IP to bind to, can be NULL
137  * \param port     Port number to use
138  * \param proto    Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP
139  *
140  * \return         0 if successful, or one of:
141  *                      MBEDTLS_ERR_NET_SOCKET_FAILED,
142  *                      MBEDTLS_ERR_NET_UNKNOWN_HOST,
143  *                      MBEDTLS_ERR_NET_BIND_FAILED,
144  *                      MBEDTLS_ERR_NET_LISTEN_FAILED
145  *
146  * \note           Regardless of the protocol, opens the sockets and binds it.
147  *                 In addition, make the socket listening if protocol is TCP.
148  */
149 int mbedtls_net_bind(mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto);
150 
151 /**
152  * \brief           Accept a connection from a remote client
153  *
154  * \param bind_ctx  Relevant socket
155  * \param client_ctx Will contain the connected client socket
156  * \param client_ip Will contain the client IP address, can be NULL
157  * \param buf_size  Size of the client_ip buffer
158  * \param ip_len    Will receive the size of the client IP written,
159  *                  can be NULL if client_ip is null
160  *
161  * \return          0 if successful, or
162  *                  MBEDTLS_ERR_NET_SOCKET_FAILED,
163  *                  MBEDTLS_ERR_NET_BIND_FAILED,
164  *                  MBEDTLS_ERR_NET_ACCEPT_FAILED, or
165  *                  MBEDTLS_ERR_NET_BUFFER_TOO_SMALL if buf_size is too small,
166  *                  MBEDTLS_ERR_SSL_WANT_READ if bind_fd was set to
167  *                  non-blocking and accept() would block.
168  */
169 int mbedtls_net_accept(mbedtls_net_context *bind_ctx,
170                        mbedtls_net_context *client_ctx,
171                        void *client_ip, size_t buf_size, size_t *ip_len);
172 
173 /**
174  * \brief          Check and wait for the context to be ready for read/write
175  *
176  * \note           The current implementation of this function uses
177  *                 select() and returns an error if the file descriptor
178  *                 is \c FD_SETSIZE or greater.
179  *
180  * \param ctx      Socket to check
181  * \param rw       Bitflag composed of MBEDTLS_NET_POLL_READ and
182  *                 MBEDTLS_NET_POLL_WRITE specifying the events
183  *                 to wait for:
184  *                 - If MBEDTLS_NET_POLL_READ is set, the function
185  *                   will return as soon as the net context is available
186  *                   for reading.
187  *                 - If MBEDTLS_NET_POLL_WRITE is set, the function
188  *                   will return as soon as the net context is available
189  *                   for writing.
190  * \param timeout  Maximal amount of time to wait before returning,
191  *                 in milliseconds. If \c timeout is zero, the
192  *                 function returns immediately. If \c timeout is
193  *                 -1u, the function blocks potentially indefinitely.
194  *
195  * \return         Bitmask composed of MBEDTLS_NET_POLL_READ/WRITE
196  *                 on success or timeout, or a negative return code otherwise.
197  */
198 int mbedtls_net_poll(mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout);
199 
200 /**
201  * \brief          Set the socket blocking
202  *
203  * \param ctx      Socket to set
204  *
205  * \return         0 if successful, or a non-zero error code
206  */
207 int mbedtls_net_set_block(mbedtls_net_context *ctx);
208 
209 /**
210  * \brief          Set the socket non-blocking
211  *
212  * \param ctx      Socket to set
213  *
214  * \return         0 if successful, or a non-zero error code
215  */
216 int mbedtls_net_set_nonblock(mbedtls_net_context *ctx);
217 
218 /**
219  * \brief          Portable usleep helper
220  *
221  * \param usec     Amount of microseconds to sleep
222  *
223  * \note           Real amount of time slept will not be less than
224  *                 select()'s timeout granularity (typically, 10ms).
225  */
226 void mbedtls_net_usleep(unsigned long usec);
227 
228 /**
229  * \brief          Read at most 'len' characters. If no error occurs,
230  *                 the actual amount read is returned.
231  *
232  * \param ctx      Socket
233  * \param buf      The buffer to write to
234  * \param len      Maximum length of the buffer
235  *
236  * \return         the number of bytes received,
237  *                 or a non-zero error code; with a non-blocking socket,
238  *                 MBEDTLS_ERR_SSL_WANT_READ indicates read() would block.
239  */
240 int mbedtls_net_recv(void *ctx, unsigned char *buf, size_t len);
241 
242 /**
243  * \brief          Write at most 'len' characters. If no error occurs,
244  *                 the actual amount read is returned.
245  *
246  * \param ctx      Socket
247  * \param buf      The buffer to read from
248  * \param len      The length of the buffer
249  *
250  * \return         the number of bytes sent,
251  *                 or a non-zero error code; with a non-blocking socket,
252  *                 MBEDTLS_ERR_SSL_WANT_WRITE indicates write() would block.
253  */
254 int mbedtls_net_send(void *ctx, const unsigned char *buf, size_t len);
255 
256 /**
257  * \brief          Read at most 'len' characters, blocking for at most
258  *                 'timeout' seconds. If no error occurs, the actual amount
259  *                 read is returned.
260  *
261  * \note           The current implementation of this function uses
262  *                 select() and returns an error if the file descriptor
263  *                 is \c FD_SETSIZE or greater.
264  *
265  * \param ctx      Socket
266  * \param buf      The buffer to write to
267  * \param len      Maximum length of the buffer
268  * \param timeout  Maximum number of milliseconds to wait for data
269  *                 0 means no timeout (wait forever)
270  *
271  * \return         The number of bytes received if successful.
272  *                 MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out.
273  *                 MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal.
274  *                 Another negative error code (MBEDTLS_ERR_NET_xxx)
275  *                 for other failures.
276  *
277  * \note           This function will block (until data becomes available or
278  *                 timeout is reached) even if the socket is set to
279  *                 non-blocking. Handling timeouts with non-blocking reads
280  *                 requires a different strategy.
281  */
282 int mbedtls_net_recv_timeout(void *ctx, unsigned char *buf, size_t len,
283                              uint32_t timeout);
284 
285 /**
286  * \brief          Closes down the connection and free associated data
287  *
288  * \param ctx      The context to close
289  */
290 void mbedtls_net_close(mbedtls_net_context *ctx);
291 
292 /**
293  * \brief          Gracefully shutdown the connection and free associated data
294  *
295  * \param ctx      The context to free
296  */
297 void mbedtls_net_free(mbedtls_net_context *ctx);
298 
299 #ifdef __cplusplus
300 }
301 #endif
302 
303 #endif /* net_sockets.h */
304