Debian Codegraph @

crt/aws-c-io/README.md

raw symbols SCIP
1 ## AWS-C-IO
2
3 This is a module for the AWS SDK for C. It handles all IO and TLS work for application protocols.
4
5 aws-c-io is an event driven framework for implementing application protocols. It is built on top of
6 cross-platform abstractions that allow you as a developer to think only about the state machine and API
7 for your protocols. A typical use-case would be to write something like Http on top of asynchronous-io
8 with TLS already baked in. All of the platform and security concerns are already handled for you.
9
10 It is designed to be light-weight, fast, portable, and flexible for multiple domain use-cases such as:
11 embedded, server, client, and mobile.
12
13 ## License
14
15 This library is licensed under the Apache 2.0 License.
16
17 ## Usage
18
19 ### Building
20
21 CMake 3.9+ is required to build.
22
23 `<install-path>` must be an absolute path in the following instructions.
24
25 #### Linux-Only Dependencies
26
27 If you are building on Linux, you will need to build aws-lc and s2n-tls first.
28
29 ```
30 git clone [email protected]:awslabs/aws-lc.git
31 cmake -S aws-lc -B aws-lc/build -DCMAKE_INSTALL_PREFIX=<install-path>
32 cmake --build aws-lc/build --target install
33
34 git clone [email protected]:aws/s2n-tls.git
35 cmake -S s2n-tls -B s2n-tls/build -DCMAKE_INSTALL_PREFIX=<install-path> -DCMAKE_PREFIX_PATH=<install-path>
36 cmake --build s2n-tls/build --target install
37 ```
38
39 #### Building aws-c-io and Remaining Dependencies
40
41 ```
42 git clone [email protected]:awslabs/aws-c-common.git
43 cmake -S aws-c-common -B aws-c-common/build -DCMAKE_INSTALL_PREFIX=<install-path>
44 cmake --build aws-c-common/build --target install
45
46 git clone [email protected]:awslabs/aws-c-cal.git
47 cmake -S aws-c-cal -B aws-c-cal/build -DCMAKE_INSTALL_PREFIX=<install-path> -DCMAKE_PREFIX_PATH=<install-path>
48 cmake --build aws-c-cal/build --target install
49
50 git clone [email protected]:awslabs/aws-c-io.git
51 cmake -S aws-c-io -B aws-c-io/build -DCMAKE_INSTALL_PREFIX=<install-path> -DCMAKE_PREFIX_PATH=<install-path>
52 cmake --build aws-c-io/build --target install
53 ```
54
55 ### Usage Patterns
56
57 This library contains many primitive building blocks that can be configured in a myriad of ways. However, most likely
58 you simply need to use the `aws_event_loop_group` and `aws_channel_bootstrap` APIs.
59
60 Typical Client API Usage Pattern:
61
62 /* setup */
63 aws_io_library_init(allocator);
64
65 struct aws_event_loop_group el_group;
66
67 if (aws_event_loop_group_init_default(&el_group, allocator)) {
68 goto cleanup;
69 }
70
71 struct aws_tls_ctx_options tls_options = { ... };
72 struct aws_tls_ctx *tls_ctx = aws_tls_client_ctx_new(allocator, &tls_options);
73
74 struct aws_tls_connection_options tls_client_conn_options = { ... };
75
76 struct aws_client_bootstrap client_bootstrap;
77
78 if (aws_client_bootstrap_init(&client_bootstrap, allocator, &el_group) {
79 goto cleanup;
80 }
81
82 aws_client_bootstrap_set_tls_ctx(&client_bootstrap, tls_ctx);
83 aws_client_bootstrap_set_alpn_callback(&client_bootstrap, your_alpn_callback);
84
85 /* throughout your application's lifetime */
86 struct aws_socket_options sock_options = { ... };
87 struct aws_socket_endpoint endpoint = { ... };
88
89 if (aws_client_bootstrap_new_tls_socket_channel(&client_bootstrap, &endpoint, &sock_options, &tls_options,
90 your_channel_setup_callback, your_channel_shutdown_callback, your_context_data) {
91 goto cleanup;
92 }
93
94 /* shutdown */
95 aws_client_bootstrap_clean_up(&client_bootstrap);
96 aws_tls_client_ctx_destroy(tls_ctx);
97 aws_event_loop_group_clean_up(&el_group);
98 aws_io_library_clean_up();
99
100 Typical Server API Usage Pattern:
101
102 /* setup */
103 aws_io_library_init(allocator);
104
105 struct aws_event_loop_group el_group;
106
107 if (aws_event_loop_group_init_default(&el_group, allocator)) {
108 goto cleanup;
109 }
110
111 struct aws_tls_ctx_options tls_options = { ... };
112 struct aws_tls_ctx *tls_ctx = aws_tls_server_ctx_new(allocator, &tls_options);
113
114 struct aws_tls_connection_options tls_server_conn_options = { ... };
115
116 struct aws_socket_options sock_options = { ... };
117 struct aws_socket_endpoint endpoint = { ... };
118
119 struct aws_server_bootstrap server_bootstrap;
120
121 if (aws_server_bootstrap_init(&server_bootstrap, allocator, &el_group) {
122 goto cleanup;
123 }
124
125 aws_server_bootstrap_set_tls_ctx(&server_bootstrap, tls_ctx);
126 aws_server_bootstrap_set_alpn_callback(&server_bootstrap, your_alpn_callback);
127
128 struct aws_socket *listener = aws_server_bootstrap_add_tls_socket_listener(&server_bootstrap, &endpoint, &sock_options, &tls_options,
129 your_incoming_channel_callback, your_channel_shutdown_callback, your_context_data);
130
131 if (!listener) {
132 goto cleanup;
133 }
134
135
136 /* shutdown */
137 aws_server_bootstrap_remove_socket_listener(listener);
138 aws_server_bootstrap_clean_up(&server_bootstrap);
139 aws_tls_server_ctx_destroy(tls_ctx);
140 aws_event_loop_group_clean_up(&el_group);
141 aws_io_library_clean_up();
142
143 If you are building a protocol on top of sockets without the use of TLS, you can still use this pattern as your starting point.
144 Simply call the `aws_client_bootstrap_new_socket_channel` `aws_server_bootstrap_add_socket_listener` respectively: instead of the TLS variants.
145
146 ## Concepts
147
148 ### Event Loop
149 Core to Async-IO is the event-loop. We provide an implementation for most platforms out of the box:
150
151 Platform | Implementation
152 --- | ---
153 Linux | Edge-Triggered Epoll
154 BSD Variants | KQueue
155 Apple Devices | KQueue or Apple Dispatch Queue
156 Windows | IOCP (IO Completion Ports)
157
158 Also, you can always implement your own as well.
159
160 An Event Loop has a few jobs.
161
162 1. Notify subscribers of IO Events
163 2. Execute and maintain a task scheduler
164 3. Maintain an opaque data store for consumers
165
166 The threading model for a channel (see below) is pinned to the thread of the event-loop. Each event-loop implementation
167 provides an API to move a cross-thread call into the event-loop thread if necessary.
168
169 ### Channels and Slots
170 A channel is simply a container that drives the slots. It is responsible for providing an interface
171 between slots and the underlying event-loop as well as invoking the slots to pass messages. As a channel
172 runs. It also provides utilities for making sure slots and their handlers run in the correct thread and moving execution
173 to that thread if necessary.
174
175 ![Channels and Slots Diagram](docs/images/channels_slots.png)
176
177 In this diagram, a channel is a collection of slots, and it knows how to make them communicate. It also controls the
178 lifetime of slots.
179
180 When a channel is being shutdown, it will issue shutdown_direction messages in the appropriate direction. If it is in the read
181 direction, it will call shutdown_direction on the first slot. Conversely, in the write direction, it will call shutdown_direction
182 on the last slot in the channel. When all slots have successfully shutdown, the channel can be safely cleaned up and de-allocated.
183
184 ### Slots
185 ![Slots Diagram](docs/images/slots.png)
186
187 Slots maintain their links to adjacent slots in the channel. So as the channel
188 is processed, each slot will read from its left-adjacent slot, send those messages to the handler, and call their right-adjacent
189 slot when it needs to send a message. Conversely, each slot will read from its right-adjacent slot,
190 send those messages to the handler, and send messages to the left-adjacent slot in the channel. Most importantly, slots contain a
191 reference to a handler. Handlers are responsible for doing most of the work (see below). Finally, slots have
192 utilities for manipulating the connections of the slots themselves.
193
194 Slots can also be added, removed, or replaced dynamically from a channel.
195
196 ### Channel Handlers
197 The channel handler is the fundamental unit that protocol developers will implement. It contains all of your
198 state machinery, framing, and optionally end-user APIs.
199
200 ![Handler Diagram](docs/images/handler.png)
201
202
203 #### Special, pre-defined handlers
204 Out of the box you get a few handlers pre-implemented.
205 1. Sockets. We've done the heavy lifting of implementing a consistent sockets interface for each platform.
206 Sockets interact directly with the underlying io and are invoked directly by the event-loop for io events.
207 2. Pipes (or something like them depending on platform), these are particularly useful for testing.
208 3. TLS. We provide TLS implementations for most platforms.
209
210 Platform | Implementation
211 --- | ---
212 Linux | Signal-to-noise (s2n) see: https://github.com/aws/s2n-tls
213 BSD Variants | s2n
214 Apple Devices | Security Framework/ Secure Transport. See https://developer.apple.com/documentation/security/secure_transport
215 Windows | Secure Channel. See https://msdn.microsoft.com/en-us/library/windows/desktop/aa380123(v=vs.85).aspx
216
217 In addition, you can always write your own handler around your favorite implementation and use that. To provide your own
218 TLS implementation, you must build this library with the cmake argument `-DBYO_CRYPTO=ON`. You will no longer need s2n or
219 libcrypto once you do this. Instead, your application provides an implementation of `aws_tls_ctx`, and `aws_channel_handler`.
220 At startup time, you must invoke the functions: `aws_tls_byo_crypto_set_client_setup_options()` and `aws_tls_byo_crypto_set_server_setup_options()`.
221
222 ### Typical Channel
223 ![Typical Channel Diagram](docs/images/typical_channel.png)
224
225 A typical channel will contain a socket handler, which receives io events from the event-loop.
226 It will read up to 16 kb and pass the data to the next handler. The next handler is typically
227 feeding a TLS implementation (see the above section on pre-defined handlers). The TLS handler
228 will then pass the data to an application protocol. The application protocol could then expose an
229 API to an application. When the application wants to send data, the whole process runs in reverse.
230
231 Channels can be much more complex though. For example, there could be nested channels for multiplexing/de-multiplexing,
232 or there could be more handlers to cut down on handler complexity.
233
234 Note however, that a channel is always pinned to a single thread. It provides utilities for applications and
235 handlers to move a task into that thread, but it is very important that handlers and application users
236 of your handlers never block.
237
238 ### Channel IO Operation Fairness
239
240 Since multiple channels run in the same event-loop, we need to make sure channels are not starved by other active channels.
241 To address this, the handlers consuming IO events from the event-loop should determine the appropriate max read and write
242 and context switch before continuing. A context switch is performed, simply by scheduling a task to run at the current timestamp,
243 to continue the IO operation.
244
245 A reasonable default is 16kb, but a savvy implementation may want to upgrade a few connections to 256kb if they notice a particularly
246 fast connection (e.g. you notice EAGAIN or EWOULDBLOCK is never returned from write() calls).
247
248 ### Read Back Pressure
249
250 One of the most challenging aspects of asynchronous io programming, is managing when back-pressure should be applied to
251 the underlying io layer. In the read direction, this is managed via update_window messages. Let's look at the below diagram
252 for an example of how this works.
253
254 In this example, we have a channel setup with an event-loop which manages io event notifications. The first slot contains a socket handler.
255 The socket handler will read directly from the socket. The second slot has a TLS handler.
256 Its only job is to encrypt/decrypt the data passed to it and pass it back to the channel.
257 The third and final slot contains the actual application protocol handler (could be Http, SIP, RTP it doesn't really matter).
258
259 The application protocol exposes an API to the application. As data is processed, we don't want to endlessly read, allocate,
260 and process data faster than the application can use it. As a result, it has a 20kb window.
261
262 ![Read Back Pressure Diagram](docs/images/read_backpressure.png)
263
264 1. The event-loop notifies the socket handler that it has data available to read. The handler knows it can read up to 20kb
265 so it reads a full 16kb from the socket and passes it to the next slot. Since the socket sees that there is still an open window,
266 it, schedules a task to read again after the other channels have had a chance to process their pending reads.
267
268 Likewise, the TLS handler decrypts the data and passes
269 it to the slot containing the application protocol.
270
271 The application protocol processes the 16 kb and hands it off to the application.
272 At this point, the application hasn't notified the channel it is finished with the data (suppose application queues it), so the
273 new window for the slot is 4 kb.
274
275 2. The event-loop runs the scheduled read task from (1) after processing the other channels. The socket handler sees it
276 can read 4kb more of data. Even though it can read 16kb at a time, to honor the window, it reads 4kb and passes it on. This
277 time however, the window is 0, so the socket does not schedule another read task.
278
279 The TLS handler decrypts the data and passes it on
280
281 The application protocol reads 4kb, passes it to the application and its window is 0kb.
282
283 The channel now goes idle waiting on the application to finish processing its data.
284
285 3. The application notifies the channel (via the API on the application protocol handler) it has processed 20kb
286 of data. This causes the protocol handler to issue an update_window message with an update of 20kb.
287
288 Slot 2 passes the message on to the TLS handler. It evaluates the message and simply, sends a 20kb window update message
289 to its slot.
290
291 The socket handler receives the update_window message and schedules a new read task.
292
293 4. The event-loop runs the scheduled read task from (3). The socket reads on the io-handle, but it returns EAGAIN or
294 EWOULD_BLOCK. The channel now goes back to an idle state waiting on the event-loop to notify it that the socket is readable.
295
296 ### Write Back Pressure
297
298 Write back pressure comes into play when the application can produce data more quickly than it can be sent to the
299 underlying io. To manage this, messages have members to attach a promise fn and context data to. When a handler exposes
300 an API, it has the responsibility to take a fn and data from the user if over write is a possibility. The io-handler will
301 invoke the promise after it has successfully written the last byte to the underlying io.
302
303 ### Thread Safety
304
305 In general, the plan for addressing thread-safety is to not share memory across threads. This library is designed around
306 single threaded event-loops which process one or more channels. Anywhere a handler or channel exposes a back-channel API,
307 it is responsible for checking which thread it was invoked from. If it is invoked from the event-loop's thread, then it may
308 proceed as planned. If it is not, it is required to queue a task to do the work. When the task is executed, it will be executed
309 in the correct thread.
310
311 The functions we specify as thread-safe, we do so because those functions are necessary for abiding by the stated threading model.
312 For example, since scheduling a task is the main function for addressing cross-threaded operations, it has to be thread-safe.
313
314 ## Terminology
315 We use a few terms in the following sections that are not necessarily "C concepts". We assume you know C, but here are some
316 definitions that may be helpful.
317
318 ### Run-time Polymorphic
319 This means that the API is driven by a virtual-table. This is simply a struct of function pointers. They are invoked via
320 a c extern style API, but ultimately those public functions simply invoke the corresponding function in the v-table.
321
322 These are reserved for types that:
323 a.) Need to be configurable, changable at runtime
324 b.) Do not have immediate performance concerns caused by an indirect function call.
325
326 ### Compile-time Polymorphic
327 This means that the API is not necessarily driven by a virtual-table. It is exposed as a c extern style API, but the
328 build system makes a decision about which symbols to compile based on factors such as platform and compile-time flags.
329
330 These are reserved for types that:
331 a.) Need to be configurable at compile-time based on platform or compile-time options.
332 b.) Have performance concerns caused by an indirect function call.
333
334 Note: that runtime configurability may still be something we need to expose here. In that case, a compiler flag
335 will be used to denote that we are using a custom implementation for x feature. Then we will expose an implementation
336 that indirectly invokes from a v-table and provides hooks for the application to plug into at runtime.
337
338 ### Promise, Promise Context
339 There are many phrases for this, callback, baton, event-handler etc... The key idea is that APIs that need to notify a
340 caller when an asynchronous action is completed, should take a callback function and a pointer to an opaque object
341 and invoke it upon completion. This term doesn't refer to the layout of the data. A promise in some instances may be a
342 collection of functions in a structure. It's simply the language we use for the concept.
343
344 ## API
345
346 **Note: unless otherwise stated,**
347
348 * no functions in this API are allowed to block.
349 * nothing is thread-safe unless explicitly stated.
350
351
352 ### Event Loop
353
354 Event Loops are run-time polymorphic. We provide some implementations out of the box and a way to get an implementation
355 without having to call a different function per platform. However, you can also create your own implementation and use it
356 on any API that takes an event-loop as a parameter.
357
358 From a design perspective, the event-loop is not aware of channels or any of its handlers. It interacts with other entities
359 only via its API.
360
361 #### Layout
362 struct aws_event_loop {
363 struct aws_event_loop_vtable vtable;
364 aws_clock clock;
365 struct aws_allocator *allocator;
366 struct aws_common_hash_table local_storage;
367 void *impl_data;
368 };
369
370 #### V-Table
371
372 struct aws_event_loop_vtable {
373 void (*destroy)(struct aws_event_loop *);
374 int (*run) (struct aws_event_loop *);
375 int (*stop) (struct aws_event_loop *, void (*on_stopped) (struct aws_event_loop *, void *), void *promise_user_data);
376 int (*schedule_task) (struct aws_event_loop *, struct aws_task *task, uint64_t run_at);
377 int (*subscribe_to_io_events) (struct aws_event_loop *, struct aws_io_handle *, int events,
378 void(*on_event)(struct aws_event_loop *, struct aws_io_handle *, void *), void *user_data);
379 int (*unsubscribe_from_io_events) (struct aws_event_loop *, struct aws_io_handle *);
380 BOOL (*is_on_callers_thread) (struct aws_event_loop *);
381 };
382
383 Every implementation of aws_event_loop must implement this table. Let's look at some details for what each entry does.
384
385 void (*destroy)(struct aws_event_loop *);
386
387 This function is invoked when the event-loop is finished processing and is ready to be cleaned up and deallocated.
388
389 int (*run) (struct aws_event_loop *);
390
391 This function starts the running of the event-loop and then immediately returns. This could kick off a thread, or setup some resources to run and
392 receive events in a back channel API. For example, you could have an epoll loop that runs in a thread, or you could have an event-loop pumped by a system
393 loop such as glib, or libevent etc... and then publish events to your event-loop implementation.
394
395 int (*stop) (struct aws_event_loop *,
396 void (*on_stopped) (struct aws_event_loop *, void *), void *promise_user_data);
397
398 The stop function signals the event-loop to shutdown. This function should not block but it should remove active io handles from the
399 currently monitored or polled set and should begin notifying current subscribers via the on_event callback that the handle was removed._
400 Once the event-loop has shutdown to a safe state, it should invoke the on_stopped function.
401
402 int (*schedule_task) (struct aws_event_loop *, struct aws_task *task, uint64_t run_at);
403
404 This function schedules a task to run in its task scheduler at the time specified by run_at. Each event-loop is responsible for implementing
405 a task scheduler. This function must not block, and must be thread-safe. How this is implemented will depend on platform. For example,
406 one reasonable implementation is if the call comes from the event-loop's thread, to queue it in the task scheduler directly. Otherwise,
407 write to a pipe that the event-loop is listening for events on. Upon noticing the write to the pipe, it can read the task from the pipe
408 and schedule the task.
409
410 `task` must be copied.
411
412 `run_at` is using the system `RAW_MONOTONIC` clock (or the closest thing to it for that platform). It is represented as nanos since unix epoch.
413
414 int (*subscribe_to_io_events) (struct aws_event_loop *, struct aws_io_handle *, int events,
415 void(*on_event)(struct aws_event_loop *, struct aws_io_handle *, int events, void *), void *user_data);
416
417 A subscriber will call this function to register an io_handle for event monitoring. This function is thread-safe.
418
419 `events` is a bit field of the events the subscriber wants to receive. A few events will always be registered (regardless of the value passed here), such
420 as `AWS_IO_EVENT_HANDLE_REMOVED`. The event-loop will invoke `on_event` anytime it receives one or more of the registered events.
421
422 **NOTE: The event-loop is not responsible for manipulating or setting io flags on io_handles. It will never call, read(), write(), connect(), accept(), close() etc...
423 on any io handle it does not explicitly own. It is the subscriber's responsibility to know how to respond to the event.**
424
425 **NOTE: The event-loop will not maintain any state other than the io handles it is polling. So, for example, in edge-triggered epoll, it does
426 not maintain a read ready list. It is the subscriber's responsibility to know it has more data to read or write and to schedule its tasks
427 appropriately.**
428
429 int (*unsubscribe_from_io_events) (struct aws_event_loop *, struct aws_io_handle *);
430
431 A subscriber will call this function to remove its io handle from the monitored events. For example, it would may this immediately before calling
432 close() on a socket or pipe. `on_event` will still be invoked with `AWS_IO_EVENT_HANDLE_REMOVED` when this occurs.
433
434 BOOL (*is_on_callers_thread) (struct aws_event_loop *);
435
436 Returns `TRUE` if the caller is on the same thread as the event-loop. Returns `FALSE` otherwise. This allows users of the event-loop to make a decision
437 about whether it is safe to interact with the loop directly, or if they need to schedule a task to run in the correct thread.
438 This function is thread-safe.
439
440 #### API
441
442 int aws_event_loop_init_base (struct aws_allocator *, aws_clock clock, ...);
443
444 Initializes common data for all event-loops regardless of implementation. All implementations must call this function before returning from their allocation function.
445
446 struct aws_event_loop *aws_event_loop_new_default (struct aws_allocator *, aws_clock clock, ...);
447
448 Allocates and initializes the default event-loop implementation for the current platform. Calls `aws_event_loop_init_base` before returning.
449
450 struct aws_event_loop *aws_event_loop_destroy (struct aws_event_loop *);
451
452 Cleans up internal state of the event-loop implementation, and then calls the v-table `destroy` function.
453
454 int aws_event_loop_fetch_local_object ( struct aws_event_loop *, void *key, void **item);
455
456 All event-loops contain local storage for all users of the event-loop to store common data into. This function is for fetching one of those objects by key. The key for this
457 store is of type `void *`. This function is NOT thread safe, and it expects the caller to be calling from the event-loop's thread. If this is not the case,
458 the caller must first schedule a task on the event-loop to enter the correct thread.
459
460 int aws_event_loop_put_local_object ( struct aws_event_loop *, void *key, void *item);
461
462 All event-loops contain local storage for all users of the event-loop to store common data into. This function is for putting one of those objects by key. The key for this
463 store is of type `size_t`. This function is NOT thread safe, and it expects the caller to be calling from the event-loop's thread. If this is not the case,
464 the caller must first schedule a task on the event-loop to enter the correct thread.
465
466 int aws_event_loop_remove_local_object ( struct aws_event_loop *, void *key, void **item);
467
468 All event loops contain local storage for all users of the event loop to store common data into. This function is for removing one of those objects by key. The key for this
469 store is of type `void *`. This function is NOT thread safe, and it expects the caller to be calling from the event loop's thread. If this is not the case,
470 the caller must first schedule a task on the event loop to enter the correct thread. If found, and item is not NULL, the removed item is moved to `item`.
471 It is the removers responsibility to free the memory pointed to by item. If it is NULL, the default deallocation strategy for the event loop will be used.
472
473 int aws_event_loop_current_ticks ( struct aws_event_loop *, uint64_t *ticks);
474
475 Gets the current tick count/timestamp for the event loop's clock. This function is thread-safe.
476
477 #### V-Table Shims
478 The remaining exported functions on event loop simply invoke the v-table functions and return. See the v-table section for more details.
479
480 ### Channels and Slots
481
482 #### Layout
483 struct aws_channel {
484 struct aws_allocator *alloc;
485 struct aws_event_loop *loop;
486 struct aws_channel_slot *first;
487 };
488
489 struct aws_channel_slot {
490 struct aws_allocator *alloc;
491 struct aws_channel *channel;
492 struct aws_channel_slot *adj_left;
493 struct aws_channel_slot *adj_right;
494 struct aws_channel_handler *handler;
495 };
496
497 #### API (Channel/Slot interaction)
498
499 struct aws_channel_slot_ref *aws_channel_slot_new (struct aws_channel *channel);
500
501 Creates a new slot using the channel's allocator, if it is the first slot in the channel, it will be added as the first
502 slot in the channel. Otherwise, you'll need to use the insert or replace APIs for slots.
503
504 int aws_channel_slot_set_handler ( struct aws_channel_slot *, struct aws_channel_handler *handler );
505
506 Sets the handler on the slot. This should only be called once per slot.
507
508 int aws_channel_slot_remove (struct aws_channel_slot *slot);
509
510 Removes a slot from its channel. The slot and its handler will be cleaned up and deallocated.
511
512 int aws_channel_slot_replace (struct aws_channel_slot *remove, struct aws_channel_slot *new);
513
514 Replaces `remove` in the channel with `new` and cleans up and deallocates `remove` and its handler.
515
516 int aws_channel_slot_insert_right (struct aws_channel_slot *slot, struct aws_channel_slot_ref *right);
517
518 Adds a slot to the right of slot.
519
520 int aws_channel_slot_insert_left (struct aws_channel_slot *slot, struct aws_channel_slot_ref *left);
521
522 Adds a slot to the left of slot.
523
524 int aws_channel_slot_send_message (struct aws_channel_slot *slot, struct aws_io_message *message, enum aws_channel_direction dir);
525
526 Usually called by a handler, this calls the adjacent slot in the channel based on the `dir` argument. You may want to return
527 any unneeded messages to the channel pool to avoid unnecessary allocations.
528
529 int aws_channel_slot_increment_read_window (struct aws_channel_slot *slot, size_t window);
530
531 Usually called by a handler, this function calls the left-adjacent slot.
532
533 int aws_channel_slot_on_handler_shutdown_complete(struct aws_channel_slot *slot, enum aws_channel_direction dir,
534 int err_code, bool abort_immediately);
535
536 Usually called by a handler, this function calls the adjacent slot's shutdown based on the `dir` argument.
537
538
539 ### API (Channel specific)
540
541 int aws_channel_init (struct aws_channel *channel, struct aws_allocator *alloc, struct aws_event_loop *el);
542
543 Initializes a channel for operation. The event loop will be used for driving the channel.
544
545 int aws_channel_clean_up (struct aws_channel *channel);
546
547 Cleans up resources for the channel.
548
549 int aws_channel_shutdown (struct aws_channel *channel,
550 void (*on_shutdown_completed)(struct aws_channel *channel, void *user_data), void *user_data);
551
552 Starts the shutdown process, invokes on_shutdown_completed once each handler has shutdown.
553
554 int aws_channel_current_clock_time( struct aws_channel *, uint64_t *ticks);
555
556 Gets the current ticks from the event loop's clock.
557
558 int aws_channel_fetch_local_object ( struct aws_channel *, void *key, void **item);
559
560 Fetches data from the event loop's data store. This data is shared by each channel using that event loop.
561
562 int aws_channel_put_local_object ( struct aws_channel *, void *key, void *item);
563
564 Puts data into the event loop's data store. This data is shared by each channel using that event loop.
565
566 int aws_channel_schedule_task (struct aws_channel *, struct aws_task *task, uint64_t run_at);
567
568 Schedules a task to run on the event loop. This function is thread-safe.
569
570 BOOL aws_channel_thread_is_callers_thread (struct aws_channel *);
571
572 Checks if the caller is on the event loop's thread. This function is thread-safe.
573
574 ### Channel Handlers
575 Channel Handlers are runtime polymorphic. Here's some details on the virtual table (v-table):
576
577 #### Layout
578 struct aws_channel_handler {
579 struct aws_channel_handler_vtable *vtable;
580 struct aws_allocator *alloc;
581 void *impl;
582 };
583
584 #### V-Table
585 struct aws_channel_handler_vtable {
586 int (*data_in) ( struct aws_channel_handler *handler, struct aws_channel_slot *slot,
587 struct aws_io_message *message );
588 int (*data_out) ( struct aws_channel_handler *handler, struct aws_channel_slot *slot,
589 struct aws_io_message *message );
590 int (*on_window_update) (struct aws_channel_handler *handler, struct aws_channel_slot *slot, size_t size)
591 int (*on_shutdown_notify) (struct aws_channel_handler *handler, struct aws_channel_slot *slot,
592 enum aws_channel_direction dir, int error_code);
593 int (*shutdown_direction) (struct aws_channel_handler *handler, struct aws_channel_slot *slot,
594 enum aws_channel_direction dir);
595 size_t (*initial_window_size) (struct aws_channel_handler *handler);
596 void (*destroy)(struct aws_channel_handler *handler);
597 };
598
599
600 `int data_in ( struct aws_channel_handler *handler, struct aws_channel_slot *slot,
601 struct aws_io_message *message)`
602
603 Data in is invoked by the slot when an application level message is received in the read direction (from the io).
604 The job of the implementer is to process the data in msg and either notify a user or queue a new message on the slot's
605 read queue.
606
607 `int data_out (struct aws_channel_handler *handler, struct aws_channel_slot *slot,
608 struct aws_io_message *message)`
609
610 Data Out is invoked by the slot when an application level message is received in the write direction (to the io).
611 The job of the implementer is to process the data in msg and either notify a user or queue a new message on the slot's
612 write queue.
613
614 `int increment_window (struct aws_channel_handler *handler, struct aws_channel_slot *slot, size_t size)`
615
616 Increment Window is invoked by the slot when a framework level message is received from a downstream handler.
617 It only applies in the read direction. This gives the handler a chance to make a programmatic decision about
618 what its read window should be. Upon receiving an update_window message, a handler decides what its window should be and
619 likely issues an increment window message to its slot. Shrinking a window has no effect. If a handler makes its window larger
620 than a downstream window, it is responsible for honoring the downstream window and buffering any data it produces that is
621 greater than that window.
622
623 `int (*shutdown) (struct aws_channel_handler *handler, struct aws_channel_slot *slot, enum aws_channel_direction dir,
624 int error_code, bool abort_immediately);`
625
626 Shutdown is invoked by the slot when a framework level message is received from an adjacent handler.
627 This notifies the handler that the previous handler in the chain has shutdown and will no longer be sending or
628 receiving messages. The handler should make a decision about what it wants to do in response, and likely begins
629 its shutdown process (if any). Once the handler has safely reached a safe state, if should call
630 'aws_channel_slot_on_handler_shutdown_complete'
631
632 `size_t initial_window_size (struct aws_channel_handler *handler)`
633
634 When a handler is added to a slot, the slot will call this function to determine the initial window size and will propagate
635 a window_update message down the channel.
636
637 `void destroy(struct aws_channel_handler *handler)`
638
639 Clean up any memory or resources owned by this handler, and then deallocate the handler itself.
640
641 #### API
642
643 All exported functions, simply shim into the v-table and return.
644
645 ### Sockets
646
647 We include a cross-platform API for sockets. We support TCP and UDP using IPv4 and IPv6, and Unix Domain sockets. On Windows,
648 we use Named Pipes to support the functionality of Unix Domain sockets. On Windows, this is implemented with winsock2, and on
649 all unix platforms we use the posix API. We also provides options to use Apple Network Framework on Apple.
650
651 Upon a connection being established, the new socket (either as the result of a `connect()` or `start_accept()` call)
652 will not be attached to any event loops. It is your responsibility to register it with an event loop to begin receiving
653 notifications.
654
655 #### API
656 typedef enum aws_socket_domain {
657 AWS_SOCKET_IPV4,
658 AWS_SOCKET_IPV6,
659 AWS_SOCKET_LOCAL,
660 AWS_SOCKET_VSOCK,
661 } aws_socket_domain;
662
663 `AWS_SOCKET_IPV4` means an IPv4 address will be used.
664
665 `AWS_SOCKET_IPV6` means an IPv6 address will be used.
666
667 `AWS_SOCKET_LOCAL` means a socket path will be used for either a Unix Domain Socket or a Named Pipe on Windows.
668
669 typedef enum aws_socket_type {
670 AWS_SOCKET_STREAM,
671 AWS_SOCKET_DGRAM
672 } aws_socket_type;
673
674 `AWS_SOCKET_VSOCK` means a CID address will be used. Note: VSOCK is currently only available on Linux with an appropriate VSOCK kernel driver installed. `-DUSE_VSOCK` needs to be passed during compilation to enable VSOCK support.
675
676 `AWS_SOCKET_STREAM` is TCP or a connection oriented socket.
677
678 `AWS_SOCKET_DGRAM` is UDP
679
680 struct aws_socket_creation_args {
681 void(*on_incoming_connection)(struct aws_socket *socket, struct aws_socket *new_socket, void *user_data);
682 void(*on_connection_established)(struct aws_socket *socket, void *user_data);
683 void(*on_error)(struct aws_socket *socket, int err_code, void *user_data);
684 void *user_data;
685 };
686
687 `on_incoming_connection()` will be invoked on a listening socket when new connections arrive. `socket` is the listening
688 socket. `new_socket` is the newly created socket. It is the connection to the remote endpoint.
689
690 NOTE: You are responsible for calling `aws_socket_clean_up()` and `aws_mem_release()` on `new_socket` when you are finished
691 with it.
692
693 `on_connection_established()` will be invoked after a connect call, upon a successful connection to the remote endpoint.
694
695 `on_error()` will be invoked on both listening and connecting sockets to indicate any error conditions.
696
697 struct aws_socket_endpoint {
698 char address[48];
699 char socket_name[108];
700 char port[10];
701 };
702
703 `address` can be either an IPv4, IPv6 or VSOCK CID address. This can be used for UDP or TCP.
704 `socket_name` is only used in LOCAL mode.
705 `port` can be used for TCP or UDP.
706
707 int aws_socket_init(struct aws_socket *socket, struct aws_allocator *alloc,
708 struct aws_socket_options *options,
709 struct aws_event_loop *connection_loop,
710 struct aws_socket_creation_args *creation_args);
711
712 Initializes a socket object with socket options, an event loop to use for non-blocking operations, and callbacks to invoke
713 upon completion of asynchronous operations. If you are using UDP or LOCAL, `connection_loop` may be `NULL`.
714
715 void aws_socket_clean_up(struct aws_socket *socket);
716
717 Shuts down any pending operations on the socket, and cleans up state. The socket object can be re initialized after this operation.
718
719 int aws_socket_set_cleanup_complete_callback(struct aws_socket *socket, aws_socket_on_shutdown_complete_fn fn, void *user_data);
720
721 Sets the clean up completion callback. The callback will be invoked if `aws_socket_clean_up()` finish to clean up the socket resources. It is safe to release the socket memory after this callback is invoked.
722
723 int aws_socket_connect(struct aws_socket *socket, const struct aws_socket_endpoint *remote_endpoint, struct aws_event_loop *event_loop, aws_socket_on_connection_result_fn *on_connection_result, void *user_data);
724
725 Connects to a remote endpoint. In TCP and all Apple Network Framework connections (regardless it is UDP, TCP or LOCAL), when the connection succeed, you still must wait on the `on_connection_result()` callback to be invoked before using the socket.
726
727 In UDP, this simply binds the socket to a remote address for use with `aws_socket_write()`, and if the operation is successful,
728 the socket can immediately be used for write operations.
729
730 For LOCAL (Unix Domain Sockets or Named Pipes), the socket will be immediately ready for use upon a successful return.
731
732 int aws_socket_bind(struct aws_socket *socket, struct aws_socket_endpoint *local_endpoint);
733
734 Binds the socket to a local address. In UDP mode, the socket is ready for `aws_socket_read()` operations. In connection oriented
735 modes or if you are using Apple Network Framework (regardless it is UDP or TCP), you still must call `aws_socket_listen()` and
736 `aws_socket_start_accept()` before using the socket.
737
738 int aws_socket_listen(struct aws_socket *socket, int backlog_size);
739
740 TCP, LOCAL, and Apple Network Framework only. Sets up the socket to listen on the address bound to in `aws_socket_bind()`.
741
742 int aws_socket_start_accept(struct aws_socket *socket, struct aws_event_loop *accept_loop, struct aws_socket_listener_options options);
743
744 TCP, LOCAL, and Apple Network Framework only. The socket will begin accepting new connections. This is an asynchronous operation. `on_accept_start()` will be invoked when the listener is ready to accept new connection. New connections will arrive via the `on_accept_result()` callback.
745
746 int aws_socket_stop_accept(struct aws_socket *socket);
747
748 TCP, LOCAL, and Apple Network Framework only. The socket will shutdown the listener. It is safe to call `aws_socket_start_accept()`
749 again after this operation.
750
751 int aws_socket_close(struct aws_socket *socket);
752
753 Calls `close()` on the socket and unregisters all io operations from the event loop.
754
755 int aws_socket_set_close_complete_callback(struct aws_socket *socket, aws_socket_on_shutdown_complete_fn fn, void *user_data);
756
757 Sets the close completion callback. The callback will be invoked if `aws_socket_close()` finish to process all the I/O events and close the socket.
758
759 struct aws_io_handle *aws_socket_get_io_handle(struct aws_socket *socket);
760
761 Fetches the underlying io handle for use in event loop registrations and channel handlers.
762
763 int aws_socket_set_options(struct aws_socket *socket, struct aws_socket_options *options);
764
765 Sets new socket options on the underlying socket.
766
767 int aws_socket_read(struct aws_socket *socket, struct aws_byte_buf *buffer, size_t *amount_read);
768
769 Reads from the socket. This call is non-blocking and will return `AWS_IO_SOCKET_READ_WOULD_BLOCK` if no data is available.
770 `amount_read` is the amount of data read into `buffer`.
771
772 int aws_socket_write(struct aws_socket *socket, const struct aws_byte_buf *buffer, size_t *written);
773
774 Writes to the socket. This call is non-blocking and will return `AWS_IO_SOCKET_WRITE_WOULD_BLOCK` if no data could be written.
775 `written` is the amount of data read from `buffer` and successfully written to `socket`.
776
777 ## Configuration
778
779 ### Build-Time Options
780
781 The following CMake options control how aws-c-io is built:
782
783 Option | Platform | Description | Default
784 --- | --- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| ---
785 `USE_S2N` | macOS | Compiles s2n-tls in as an available TLS implementation. User-overridable via `-DUSE_S2N=ON/OFF`.<br>Note that Apple Secure Transport remains the default backend even when `ON` (s2n-tls is only selected when `AWS_CRT_USE_NON_FIPS_TLS_13` is set); setting `OFF` removes s2n-tls from the macOS build entirely.<br>If `AWS_USE_SECITEM` is defined, s2n-tls is never used at runtime, so `USE_S2N` is forced to `OFF` (with a warning) even if explicitly set to `ON`, to avoid linking an unused s2n dependency. | ON when `AWS_USE_SECITEM` is not defined, otherwise OFF
786 `AWS_USE_SECITEM` | Apple | Uses Apple's SecItem/Secure Transport API instead of s2n-tls. When defined (regardless of value), the Apple Dispatch Queue event loop is used instead of kqueue. | Not defined
787 `USE_VSOCK` | Linux | Enables VSOCK socket domain support. Requires an appropriate VSOCK kernel driver. | OFF
788 `BYO_CRYPTO` | Linux/Non-Apple Unix | Disables the built-in TLS implementation and crypto linkage. Your application must provide its own `aws_tls_ctx` and `aws_channel_handler` implementations. | OFF
789
790 ### Runtime Environment Variables
791
792 The following environment variables influence runtime behavior:
793
794 Variable | Platform | Description
795 --- | --- | ---
796 `AWS_CRT_USE_NON_FIPS_TLS_13` | macOS | Requires `USE_S2N=ON` at build time.<br>When set to any non-empty value, the TLS implementation uses s2n-tls instead of Apple Secure Transport. This enables TLS 1.3 support but uses a non-FIPS-validated TLS implementation. If unset or empty, Apple Secure Transport is used by default (which provides FIPS-validated TLS but lacks TLS 1.3 support).
797
798 ### TLS Backend Selection
799
800 The TLS backend is selected at initialization time (`aws_tls_init_vtable`) based on the platform and configuration:
801
802 Platform | Condition | TLS Backend
803 --- | --- | ---
804 Linux | Default | s2n-tls
805 Windows | Default | Secure Channel (SChannel)
806 macOS | `AWS_USE_SECITEM` defined at build time | Apple Secure Transport (SecItem API)
807 macOS | `USE_S2N` defined, `AWS_CRT_USE_NON_FIPS_TLS_13` env var set | s2n-tls
808 macOS | `USE_S2N` defined, `AWS_CRT_USE_NON_FIPS_TLS_13` env var unset | Apple Secure Transport
809 macOS | Neither `AWS_USE_SECITEM` nor `USE_S2N` | Apple Secure Transport
810 Any | `BYO_CRYPTO` enabled | Application-provided implementation