Debian Codegraph @

crt/aws-c-io/include/aws/io/socket.h

raw symbols SCIP
1 #ifndef AWS_IO_SOCKET_H
2 #define AWS_IO_SOCKET_H
3 /**
4 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 * SPDX-License-Identifier: Apache-2.0.
6 */
7
8 #include <aws/io/channel.h>
9 #include <aws/io/io.h>
10
11 AWS_PUSH_SANE_WARNING_LEVEL
12
13 enum aws_socket_domain {
14 AWS_SOCKET_IPV4,
15 AWS_SOCKET_IPV6,
16 /* Unix domain sockets (or at least something like them) */
17 AWS_SOCKET_LOCAL,
18 /* VSOCK used in inter-VM communication */
19 AWS_SOCKET_VSOCK,
20 };
21
22 enum aws_socket_type {
23 /* A streaming socket sends reliable messages over a two-way connection.
24 * This means TCP when used with IPV4/6, and Unix domain sockets, when used with
25 * AWS_SOCKET_LOCAL*/
26 AWS_SOCKET_STREAM,
27 /* A datagram socket is connectionless and sends unreliable messages.
28 * This means UDP when used with IPV4/6.
29 * LOCAL and VSOCK sockets are not compatible with DGRAM.*/
30 AWS_SOCKET_DGRAM,
31 };
32
33 /**
34 * Socket Implementation type. Decides which socket implementation is used. If set to
35 * `AWS_SOCKET_IMPL_PLATFORM_DEFAULT`, it will automatically use the platform’s default.
36 *
37 * PLATFORM DEFAULT SOCKET IMPLEMENTATION TYPE
38 * Linux | AWS_SOCKET_IMPL_POSIX
39 * Windows | AWS_SOCKET_IMPL_WINSOCK
40 * BSD Variants| AWS_SOCKET_IMPL_POSIX
41 * MacOS | AWS_SOCKET_IMPL_POSIX
42 * iOS | AWS_SOCKET_IMPL_APPLE_NETWORK_FRAMEWORK
43 */
44 enum aws_socket_impl_type {
45 AWS_SOCKET_IMPL_PLATFORM_DEFAULT = 0,
46 AWS_SOCKET_IMPL_POSIX,
47 AWS_SOCKET_IMPL_WINSOCK,
48 AWS_SOCKET_IMPL_APPLE_NETWORK_FRAMEWORK,
49 };
50
51 #define AWS_NETWORK_INTERFACE_NAME_MAX 16
52
53 typedef void(aws_socket_on_shutdown_complete_fn)(void *user_data);
54
55 struct aws_socket_options {
56 enum aws_socket_type type;
57 enum aws_socket_domain domain;
58 enum aws_socket_impl_type impl_type;
59 uint32_t connect_timeout_ms;
60 /* Keepalive properties are TCP only.
61 * Set keepalive true to periodically transmit messages for detecting a disconnected peer.
62 * If interval or timeout are zero, then default values are used. */
63 uint16_t keep_alive_interval_sec;
64 uint16_t keep_alive_timeout_sec;
65 /* If set, sets the number of keep alive probes allowed to fail before the connection is considered
66 * lost. If zero OS defaults are used. On Windows, this option is meaningless until Windows 10 1703.*/
67 uint16_t keep_alive_max_failed_probes;
68 bool keepalive;
69
70 /**
71 * THIS IS AN EXPERIMENTAL AND UNSTABLE API
72 * (Optional)
73 * This property is used to bind the socket to a particular network interface by name, such as eth0 and ens32.
74 * If this is empty, the socket will not be bound to any interface and will use OS defaults. If the provided name
75 * is invalid, `aws_socket_init()` will error out with AWS_IO_SOCKET_INVALID_OPTIONS. This option is only
76 * supported on Linux, macOS(bsd socket), and platforms that have either SO_BINDTODEVICE or IP_BOUND_IF. It is not
77 * supported on Windows and Apple Network Framework. `AWS_ERROR_PLATFORM_NOT_SUPPORTED` will be raised on
78 * unsupported platforms.
79 */
80 char network_interface_name[AWS_NETWORK_INTERFACE_NAME_MAX];
81 };
82
83 struct aws_socket;
84
85 /**
86 * Called in client mode when an outgoing connection has succeeded or an error has occurred.
87 * If the connection was successful error_code will be AWS_ERROR_SUCCESS and the socket has already been assigned
88 * to the event loop specified in aws_socket_connect().
89 *
90 * If an error occurred error_code will be non-zero.
91 */
92 typedef void(aws_socket_on_connection_result_fn)(struct aws_socket *socket, int error_code, void *user_data);
93
94 /**
95 * Called by a listening socket when a listener accept has successfully initialized or an error has occurred.
96 * If the listener was successful error_code will be AWS_ERROR_SUCCESS and the socket has already been assigned
97 * to the event loop specified in aws_socket_start_accept().
98 *
99 * If an error occurred error_code will be non-zero.
100 */
101 typedef void(aws_socket_on_accept_started_fn)(struct aws_socket *socket, int error_code, void *user_data);
102
103 /**
104 * Called by a listening socket when either an incoming connection has been received or an error occurred.
105 *
106 * In the normal use-case, this function will be called multiple times over the lifetime of a single listening socket.
107 * new_socket is already connected and initialized, and is using the same options and allocator as the listening socket.
108 * A user may want to call aws_socket_set_options() on the new socket if different options are desired.
109 *
110 * new_socket is not yet assigned to an event-loop. The user should call aws_socket_assign_to_event_loop() before
111 * performing IO operations. The user must call `aws_socket_clean_up()` and "aws_mem_release()" when they're done with
112 * the new_socket, to free it.
113 *
114 * When error_code is AWS_ERROR_SUCCESS, new_socket is the recently accepted connection.
115 * If error_code is non-zero, an error occurred and you should aws_socket_close() the socket.
116 *
117 * Do not call aws_socket_clean_up() from this callback.
118 */
119 typedef void(aws_socket_on_accept_result_fn)(
120 struct aws_socket *socket,
121 int error_code,
122 struct aws_socket *new_socket,
123 void *user_data);
124
125 /**
126 * Callback for when the data passed to a call to aws_socket_write() has either completed or failed.
127 * On success, error_code will be AWS_ERROR_SUCCESS.
128 *
129 * `socket` may be NULL in the callback if the socket is released and cleaned up before the callback is triggered.
130 */
131 typedef void(
132 aws_socket_on_write_completed_fn)(struct aws_socket *socket, int error_code, size_t bytes_written, void *user_data);
133 /**
134 * Callback for when socket is either readable (edge-triggered) or when an error has occurred. If the socket is
135 * readable, error_code will be AWS_ERROR_SUCCESS.
136 *
137 * `socket` may be NULL in the callback if the socket is released and cleaned up before the callback is triggered.
138 */
139 typedef void(aws_socket_on_readable_fn)(struct aws_socket *socket, int error_code, void *user_data);
140
141 #ifdef _WIN32
142 # define AWS_ADDRESS_MAX_LEN 256
143 #else
144 # include <sys/un.h>
145 # define AWS_ADDRESS_MAX_LEN sizeof(((struct sockaddr_un *)0)->sun_path)
146 #endif
147 struct aws_socket_endpoint {
148 char address[AWS_ADDRESS_MAX_LEN];
149 uint32_t port;
150 };
151
152 struct aws_socket {
153 struct aws_socket_vtable *vtable;
154 struct aws_allocator *allocator;
155 struct aws_socket_endpoint local_endpoint;
156 struct aws_socket_endpoint remote_endpoint;
157 struct aws_socket_options options;
158 struct aws_io_handle io_handle;
159 struct aws_event_loop *event_loop;
160 struct aws_channel_handler *handler;
161 int state;
162 aws_socket_on_readable_fn *readable_fn;
163 void *readable_user_data;
164 aws_socket_on_connection_result_fn *connection_result_fn;
165 aws_socket_on_accept_result_fn *accept_result_fn;
166 void *connect_accept_user_data;
167 void *impl;
168 };
169
170 struct aws_socket_connect_options {
171 const struct aws_socket_endpoint *remote_endpoint;
172 struct aws_event_loop *event_loop;
173 aws_socket_on_connection_result_fn *on_connection_result;
174 void *user_data;
175
176 /*
177 * This is only set when using Apple SecItem for TLS negotiation.
178 * Apple Network Connections using SecItem require all TLS configuration options at the point of
179 * creating the socket slot as it handles both the TCP and TLS negotiation before returning a
180 * valid socket for use.
181 */
182 struct aws_tls_connection_options *tls_connection_options;
183 };
184
185 struct aws_socket_listener_options {
186 aws_socket_on_accept_result_fn *on_accept_result;
187 void *on_accept_result_user_data;
188
189 // This callback is invoked when the listener starts accepting incoming connections.
190 // If the callback set, the socket must not be released before the callback invoked.
191 aws_socket_on_accept_started_fn *on_accept_start;
192 void *on_accept_start_user_data;
193 };
194
195 struct aws_socket_bind_options {
196 const struct aws_socket_endpoint *local_endpoint;
197 void *user_data;
198
199 /*
200 * This is only set when using Apple SecItem for TLS negotiation.
201 * Apple Network Connections using SecItem require all TLS configuration options at the point of
202 * creating the socket slot as it handles both the TCP and TLS negotiation before returning a
203 * valid socket for use.
204 * Socket bind also needs an event loop to run its verification block.
205 */
206 struct aws_event_loop *event_loop;
207 struct aws_tls_connection_options *tls_connection_options;
208 };
209
210 struct aws_byte_buf;
211 struct aws_byte_cursor;
212 struct aws_string;
213
214 AWS_EXTERN_C_BEGIN
215
216 /**
217 * Initializes a socket object with socket options. options will be copied.
218 */
219 AWS_IO_API int aws_socket_init(
220 struct aws_socket *socket,
221 struct aws_allocator *alloc,
222 const struct aws_socket_options *options);
223
224 /**
225 * Shuts down any pending operations on the socket, and cleans up state. The socket object can be re-initialized after
226 * this operation. This function calls aws_socket_close. If you have not already called aws_socket_close() on the
227 * socket, all of the rules for aws_socket_close() apply here. In this case it will not fail if you use the function
228 * improperly, but on some platforms you will certainly leak memory.
229 *
230 * If the socket has already been closed, you can safely, call this from any thread.
231 */
232 AWS_IO_API void aws_socket_clean_up(struct aws_socket *socket);
233
234 /**
235 * Connects to a remote endpoint. In UDP, this simply binds the socket to a remote address for use with
236 * `aws_socket_write()`, and if the operation is successful, the socket can immediately be used for write operations.
237 *
238 * In TCP, LOCAL and VSOCK this function will not block. If the return value is successful, then you must wait on the
239 * `on_connection_result()` callback to be invoked before using the socket.
240 *
241 * If an event_loop is provided for UDP sockets, a notification will be sent on
242 * on_connection_result in the event-loop's thread. Upon completion, the socket will already be assigned
243 * an event loop. If NULL is passed for UDP, it will immediately return upon success, but you must call
244 * aws_socket_assign_to_event_loop before use.
245 */
246 AWS_IO_API int aws_socket_connect(struct aws_socket *socket, struct aws_socket_connect_options *socket_connect_options);
247
248 /**
249 * Binds the socket to a local address. In UDP mode, the socket is ready for `aws_socket_read()` operations. In
250 * connection oriented modes, you still must call `aws_socket_listen()` and `aws_socket_start_accept()` before using the
251 * socket. local_endpoint is copied.
252 */
253 AWS_IO_API int aws_socket_bind(struct aws_socket *socket, struct aws_socket_bind_options *socket_bind_options);
254
255 /**
256 * Get the local address which the socket is bound to.
257 * Raises an error if no address is bound.
258 */
259 AWS_IO_API int aws_socket_get_bound_address(const struct aws_socket *socket, struct aws_socket_endpoint *out_address);
260
261 /**
262 * TCP, LOCAL and VSOCK only. Sets up the socket to listen on the address bound to in `aws_socket_bind()`.
263 */
264 AWS_IO_API int aws_socket_listen(struct aws_socket *socket, int backlog_size);
265
266 /**
267 * TCP, LOCAL and VSOCK only. The socket will begin accepting new connections. This is an asynchronous operation. New
268 * connections or errors will arrive via the `on_accept_result` callback.
269 *
270 * aws_socket_bind() and aws_socket_listen() must be called before calling this function.
271 *
272 */
273 AWS_IO_API int aws_socket_start_accept(
274 struct aws_socket *socket,
275 struct aws_event_loop *accept_loop,
276 struct aws_socket_listener_options options);
277
278 /**
279 * TCP, LOCAL and VSOCK only. The listening socket will stop accepting new connections.
280 * It is safe to call `aws_socket_start_accept()` again after
281 * this operation. This can be called from any thread but be aware,
282 * on some platforms, if you call this from outside of the current event loop's thread, it will block
283 * until the event loop finishes processing the request for unsubscribe in it's own thread.
284 */
285 AWS_IO_API int aws_socket_stop_accept(struct aws_socket *socket);
286
287 /**
288 * Calls `close()` on the socket and unregisters all io operations from the event loop. This function must be called
289 * from the event-loop's thread unless this is a listening socket. If it's a listening socket it can be called from any
290 * non-event-loop thread or the event-loop the socket is currently assigned to. If called from outside the event-loop,
291 * this function will block waiting on the socket to close. If this is called from an event-loop thread other than
292 * the one it's assigned to, it presents the possibility of a deadlock, so don't do it.
293 *
294 * If you are using Apple Network Framework, you should always call this function from an event-loop thread regardless
295 * it is a server or client socket.
296 */
297 AWS_IO_API int aws_socket_close(struct aws_socket *socket);
298
299 /**
300 * Calls `shutdown()` on the socket based on direction.
301 */
302 AWS_IO_API int aws_socket_shutdown_dir(struct aws_socket *socket, enum aws_channel_direction dir);
303
304 /**
305 * Sets new socket options on the underlying socket.
306 */
307 AWS_IO_API int aws_socket_set_options(struct aws_socket *socket, const struct aws_socket_options *options);
308
309 /**
310 * Assigns the socket to the event-loop. The socket will begin receiving read/write/error notifications after this call.
311 *
312 * Note: If you called connect for TCP or Unix Domain Sockets and received a connection_success callback, this has
313 * already happened. You only need to call this function when:
314 *
315 * a.) This socket is a server socket (e.g. a result of a call to start_accept())
316 * b.) This socket is a UDP socket.
317 */
318 AWS_IO_API int aws_socket_assign_to_event_loop(struct aws_socket *socket, struct aws_event_loop *event_loop);
319
320 /**
321 * Gets the event-loop the socket is assigned to.
322 */
323 AWS_IO_API struct aws_event_loop *aws_socket_get_event_loop(struct aws_socket *socket);
324
325 /**
326 * Subscribes on_readable to notifications when the socket goes readable (edge-triggered). Errors will also be received
327 * in the callback.
328 *
329 * Note! This function is technically not thread safe, but we do not enforce which thread you call from.
330 * It's your responsibility to either call this in safely (e.g. just don't call it in parallel from multiple threads) or
331 * schedule a task to call it. If you call it before your first call to read, it will be fine.
332 */
333 AWS_IO_API int aws_socket_subscribe_to_readable_events(
334 struct aws_socket *socket,
335 aws_socket_on_readable_fn *on_readable,
336 void *user_data);
337
338 /**
339 * Reads from the socket. This call is non-blocking and will return `AWS_IO_SOCKET_READ_WOULD_BLOCK` if no data is
340 * available. `read` is the amount of data read into `buffer`.
341 *
342 * Attempts to read enough to fill all remaining space in the buffer, from `buffer->len` to `buffer->capacity`.
343 * `buffer->len` is updated to reflect the buffer's new length.
344 *
345 *
346 * Use aws_socket_subscribe_to_readable_events() to receive notifications of when the socket goes readable.
347 *
348 * NOTE! This function must be called from the event-loop used in aws_socket_assign_to_event_loop
349 */
350 AWS_IO_API int aws_socket_read(struct aws_socket *socket, struct aws_byte_buf *buffer, size_t *amount_read);
351
352 /**
353 * Writes to the socket. This call is non-blocking and will attempt to write as much as it can, but will queue any
354 * remaining portion of the data for write when available. written_fn will be invoked once the entire cursor has been
355 * written, or the write failed or was cancelled.
356 *
357 * NOTE! This function must be called from the event-loop used in aws_socket_assign_to_event_loop
358 *
359 * For client sockets, connect() and aws_socket_assign_to_event_loop() must be called before calling this.
360 *
361 * For incoming sockets from a listener, aws_socket_assign_to_event_loop() must be called first.
362 */
363 AWS_IO_API int aws_socket_write(
364 struct aws_socket *socket,
365 const struct aws_byte_cursor *cursor,
366 aws_socket_on_write_completed_fn *written_fn,
367 void *user_data);
368
369 /**
370 * Apple Network Framework only. The callback that will triggered when aws_socket_close() finished. The callback
371 * will be called from the socket event loop.
372 */
373 AWS_IO_API int aws_socket_set_close_complete_callback(
374 struct aws_socket *socket,
375 aws_socket_on_shutdown_complete_fn fn,
376 void *user_data);
377
378 /**
379 * Apple Network Framework only. The callback that will triggered when aws_socket_cleanup() finished. And
380 * it is only safe to release the socket afterwards. The callback will be called from the socket event loop.
381 */
382 AWS_IO_API int aws_socket_set_cleanup_complete_callback(
383 struct aws_socket *socket,
384 aws_socket_on_shutdown_complete_fn fn,
385 void *user_data);
386
387 /**
388 * Gets the latest error from the socket. If no error has occurred AWS_OP_SUCCESS will be returned. This function does
389 * not raise any errors to the installed error handlers.
390 */
391 AWS_IO_API int aws_socket_get_error(struct aws_socket *socket);
392
393 /**
394 * Returns true if the socket is still open (doesn't mean connected or listening, only that it hasn't had close()
395 * called.
396 */
397 AWS_IO_API bool aws_socket_is_open(struct aws_socket *socket);
398
399 /**
400 * Raises AWS_IO_SOCKET_INVALID_ADDRESS and logs an error if connecting to this port is illegal.
401 * For example, port must be in range 1-65535 to connect with IPv4.
402 * These port values would fail eventually in aws_socket_connect(),
403 * but you can use this function to validate earlier.
404 */
405 AWS_IO_API int aws_socket_validate_port_for_connect(uint32_t port, enum aws_socket_domain domain);
406
407 /**
408 * Raises AWS_IO_SOCKET_INVALID_ADDRESS and logs an error if binding to this port is illegal.
409 * For example, port must in range 0-65535 to bind with IPv4.
410 * These port values would fail eventually in aws_socket_bind(),
411 * but you can use this function to validate earlier.
412 */
413 AWS_IO_API int aws_socket_validate_port_for_bind(uint32_t port, enum aws_socket_domain domain);
414
415 /**
416 * Assigns a random address (UUID) for use with AWS_SOCKET_LOCAL (Unix Domain Sockets).
417 * For use in internal tests only.
418 */
419 AWS_IO_API void aws_socket_endpoint_init_local_address_for_test(struct aws_socket_endpoint *endpoint);
420
421 /**
422 * Validates whether the network interface name is valid. On Windows, it will always return false since we don't support
423 * network_interface_name on Windows */
424 AWS_IO_API bool aws_is_network_interface_name_valid(const char *interface_name);
425
426 /**
427 * Get default impl type based on the platform.
428 * For user in internal tests only.
429 */
430 AWS_IO_API enum aws_socket_impl_type aws_socket_get_default_impl_type(void);
431
432 /**
433 * Parse an IPv4 address string and convert it to binary representation.
434 *
435 * This function converts a string representation of an IPv4 address
436 * into its binary network byte order (big-endian) representation.
437 *
438 * @param src The IPv4 address string to parse. Must be a valid IPv4 address in dotted decimal notation.
439 * @param dst Pointer to a uint32_t where the parsed address will be stored in network byte order.
440 *
441 * @return AWS_OP_SUCCESS on success, or AWS_OP_ERR on failure.
442 * On failure, aws_last_error() will be set to:
443 * - AWS_IO_SOCKET_INVALID_ADDRESS if the input string is not a valid IPv4 address
444 */
445 AWS_IO_API int aws_parse_ipv4_address(const struct aws_string *src, uint32_t *dst);
446
447 /**
448 * Parse an IPv6 address string and convert it to binary representation.
449 *
450 * This function converts a string representation of an IPv6 address
451 * into its binary network byte order(big-endian) representation.
452 *
453 * @param src The IPv6 address string to parse. Must be a valid IPv6 address in standard notation.
454 * @param dst Pointer to an aws_byte_buf where the parsed address will be appended.
455 * The buffer must have at least 16 bytes of available capacity.
456 * The parsed 16-byte IPv6 address will be appended to the buffer and
457 * the buffer's length will be increased by 16.
458 *
459 * @return AWS_OP_SUCCESS on success, or AWS_OP_ERR on failure.
460 * On failure, aws_last_error() will be set to:
461 * - AWS_IO_SOCKET_INVALID_ADDRESS if the input string is not a valid IPv6 address
462 * - AWS_ERROR_SHORT_BUFFER if the destination buffer doesn't have enough capacity
463 */
464 AWS_IO_API int aws_parse_ipv6_address(const struct aws_string *src, struct aws_byte_buf *dst);
465
466 AWS_EXTERN_C_END
467 AWS_POP_SANE_WARNING_LEVEL
468
469 #endif /* AWS_IO_SOCKET_H */