Debian Codegraph @

crt/s2n/docs/examples/s2n_recv.c

raw symbols SCIP
1 /*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License").
5 * You may not use this file except in compliance with the License.
6 * A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0
9 *
10 * or in the "license" file accompanying this file. This file is distributed
11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 * express or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
15
16 #include "s2n.h"
17
18 int s2n_example_recv(struct s2n_connection *conn, uint8_t *buffer, size_t buffer_size)
19 {
20 s2n_blocked_status blocked = S2N_NOT_BLOCKED;
21 int bytes_read = 0;
22 while (bytes_read < buffer_size) {
23 int r = s2n_recv(conn, buffer + bytes_read, buffer_size - bytes_read, &blocked);
24 if (r > 0) {
25 /* `r` bytes were successfully received. Update `bytes_read` so the next `s2n_recv()`
26 * call writes into the buffer with the correct offset.
27 */
28 bytes_read += r;
29 } else if (r == 0) {
30 /* The connection was closed. No more data will be received, so bail out of the loop. */
31 break;
32 } else if (s2n_error_get_type(s2n_errno) == S2N_ERR_T_BLOCKED) {
33 /* The return of `s2n_recv()` indicates an error. If this error is `S2N_ERR_T_BLOCKED`,
34 * the socket is blocked waiting to receive more data from the peer.
35 *
36 * In a typical non-blocking environment, `poll()` or `select()` would be used re-enter
37 * `s2n_example_recv()` and call `s2n_recv()` again after the socket has more data
38 * available. But this example just busy-waits, so we immediately call `s2n_recv()`
39 * again.
40 */
41 continue;
42 } else {
43 /* `s2n_recv()` encountered an irrecoverable error. Log the error and return. */
44 fprintf(stderr, "Error: %s. %s\n", s2n_strerror(s2n_errno, NULL), s2n_strerror_debug(s2n_errno, NULL));
45 return -1;
46 }
47 }
48 fprintf(stdout, "Received: %.*s\n", bytes_read, buffer);
49 return 0;
50 }
51
52 int s2n_example_recv_echo(struct s2n_connection *conn, uint8_t *buffer, size_t buffer_size)
53 {
54 s2n_blocked_status blocked = S2N_NOT_BLOCKED;
55 while (true) {
56 int r = s2n_recv(conn, buffer, buffer_size, &blocked);
57 if (r == 0) {
58 fprintf(stdout, "End of data.\n");
59 return 0;
60 } else if (r > 0) {
61 fprintf(stdout, "Received: %.*s\n", r, buffer);
62 } else if (r < 0 && s2n_error_get_type(s2n_errno) != S2N_ERR_T_BLOCKED) {
63 fprintf(stderr, "Error: %s. %s\n", s2n_strerror(s2n_errno, NULL), s2n_strerror_debug(s2n_errno, NULL));
64 return -1;
65 }
66 }
67 }