Debian Codegraph @

source/http_stream.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5 #include "http.h"
6 #include "io.h"
7
8 #include <aws/http/request_response.h>
9
10 static const char *s_capsule_name_http_stream = "aws_http_stream";
11
12 /* Amount of space to reserve ahead of time for buffering headers.
13 * http://dev.chromium.org/spdy/spdy-whitepaper - "typical header sizes of 700-800 bytes is common" */
14 #define HEADERS_RESERVED_BYTES 1024
15
16 struct http_stream_binding {
17 struct aws_http_stream *native;
18
19 /* Weak reference proxy to python self.
20 * NOTE: The python self is forced to stay alive until on_complete fires.
21 * We do this by INCREFing when activate() is called, and DECREFing when on_complete fires. */
22 PyObject *self_proxy;
23
24 /* Buffer up headers as they come in via repeated on_headers callacks.
25 * Then deliver them to python all at once from the header_block_done callback.
26 * Buffer contains null-terminated name,value pairs, for ex:
27 * b'Content-Length\x00123\x00Host\x00example.com\x00' */
28 struct aws_byte_buf received_headers;
29 size_t received_headers_count; /* Buffer contains 2x strings per header */
30
31 /* Dependencies that must outlive this */
32 PyObject *connection;
33 };
34
35 struct aws_http_stream *aws_py_get_http_stream(PyObject *stream) {
36 AWS_PY_RETURN_NATIVE_FROM_BINDING(stream, s_capsule_name_http_stream, "HttpStreamBase", http_stream_binding);
37 }
38
39 static int s_on_incoming_headers(
40 struct aws_http_stream *native_stream,
41 enum aws_http_header_block header_block,
42 const struct aws_http_header *header_array,
43 size_t num_headers,
44 void *user_data) {
45
46 (void)native_stream;
47 (void)header_block;
48 struct http_stream_binding *stream = user_data;
49 int aws_result = AWS_OP_SUCCESS;
50
51 /* Buffer up null-terminated strings as headers come in via repeated on_headers callacks. */
52 const uint8_t terminator_byte[] = {0};
53 const struct aws_byte_cursor terminator = aws_byte_cursor_from_array(terminator_byte, 1);
54 for (size_t i = 0; i < num_headers; ++i) {
55 const struct aws_http_header *header = &header_array[i];
56
57 if (aws_byte_buf_append_dynamic(&stream->received_headers, &header->name) ||
58 aws_byte_buf_append_dynamic(&stream->received_headers, &terminator) ||
59 aws_byte_buf_append_dynamic(&stream->received_headers, &header->value) ||
60 aws_byte_buf_append_dynamic(&stream->received_headers, &terminator)) {
61 return AWS_OP_ERR;
62 }
63
64 stream->received_headers_count += 1;
65 }
66
67 return aws_result;
68 }
69
70 static int s_on_incoming_header_block_done(
71 struct aws_http_stream *native_stream,
72 enum aws_http_header_block header_block,
73 void *user_data) {
74 struct http_stream_binding *stream = user_data;
75
76 int response_code = 0;
77 if (aws_http_stream_get_incoming_response_status(native_stream, &response_code)) {
78 return AWS_OP_ERR;
79 }
80
81 if (stream->received_headers_count > PY_SSIZE_T_MAX) {
82 return aws_raise_error(AWS_ERROR_OVERFLOW_DETECTED);
83 }
84 Py_ssize_t num_headers = (Py_ssize_t)stream->received_headers_count;
85
86 int aws_result = AWS_OP_SUCCESS;
87
88 /*************** GIL ACQUIRE ***************/
89 PyGILState_STATE state;
90 if (aws_py_gilstate_ensure(&state)) {
91 return AWS_OP_ERR; /* Python has shut down. Nothing matters anymore, but don't crash */
92 }
93
94 /* Build up a list of (name,value) tuples,
95 * extracting values from buffer of [name,value,name,value,...] null-terminated strings */
96 PyObject *header_list = PyList_New(num_headers);
97 if (!header_list) {
98 aws_result = aws_py_raise_error();
99 goto done;
100 }
101
102 struct aws_byte_cursor string_cursor = aws_byte_cursor_from_buf(&stream->received_headers);
103
104 for (Py_ssize_t i = 0; i < num_headers; ++i) {
105 const char *name_str = (const char *)string_cursor.ptr;
106
107 /* the entire header block remaining length is a safe bound for the next header name length */
108 size_t name_len = strnlen((const char *)string_cursor.ptr, string_cursor.len);
109
110 aws_byte_cursor_advance(&string_cursor, name_len + 1);
111
112 const char *value_str = (const char *)string_cursor.ptr;
113
114 /* the entire header block remaining length is a safe bound for the next header value length */
115 size_t value_len = strnlen((const char *)string_cursor.ptr, string_cursor.len);
116
117 aws_byte_cursor_advance(&string_cursor, value_len + 1);
118
119 PyObject *tuple = Py_BuildValue("(s#s#)", name_str, name_len, value_str, value_len);
120 if (!tuple) {
121 aws_result = aws_py_raise_error();
122 goto done;
123 }
124
125 PyList_SetItem(header_list, i, tuple); /* steals reference to tuple */
126 }
127
128 /* TODO: handle informational and trailing headers */
129 if (header_block == AWS_HTTP_HEADER_BLOCK_MAIN) {
130
131 /* Deliver the built up list of (name,value) tuples */
132 PyObject *result = PyObject_CallMethod(stream->self_proxy, "_on_response", "(iO)", response_code, header_list);
133 if (!result) {
134 aws_result = aws_py_raise_error();
135 goto done;
136 }
137 Py_DECREF(result);
138 }
139
140 /* Clear the buffer so we're ready for next header block */
141 stream->received_headers.len = 0;
142 stream->received_headers_count = 0;
143
144 done:
145 Py_XDECREF(header_list);
146 PyGILState_Release(state);
147 /*************** GIL RELEASE ***************/
148
149 return aws_result;
150 }
151
152 static int s_on_incoming_body(
153 struct aws_http_stream *native_stream,
154 const struct aws_byte_cursor *data,
155 void *user_data) {
156
157 (void)native_stream;
158
159 struct http_stream_binding *stream = user_data;
160
161 if (data->len > PY_SSIZE_T_MAX) {
162 return aws_raise_error(AWS_ERROR_OVERFLOW_DETECTED);
163 }
164 Py_ssize_t data_len = (Py_ssize_t)data->len;
165
166 int aws_result = AWS_OP_SUCCESS;
167
168 /*************** GIL ACQUIRE ***************/
169 PyGILState_STATE state;
170 if (aws_py_gilstate_ensure(&state)) {
171 return AWS_OP_ERR; /* Python has shut down. Nothing matters anymore, but don't crash */
172 }
173
174 PyObject *result = PyObject_CallMethod(stream->self_proxy, "_on_body", "(y#)", (const char *)data->ptr, data_len);
175 if (!result) {
176 aws_result = aws_py_raise_error();
177 goto done;
178 }
179 Py_DECREF(result);
180
181 done:
182 PyGILState_Release(state);
183 /*************** GIL RELEASE ***************/
184
185 return aws_result;
186 }
187
188 static void s_on_stream_complete(struct aws_http_stream *native_stream, int error_code, void *user_data) {
189 (void)native_stream;
190 struct http_stream_binding *stream = user_data;
191
192 /*************** GIL ACQUIRE ***************/
193 PyGILState_STATE state;
194 if (aws_py_gilstate_ensure(&state)) {
195 return; /* Python has shut down. Nothing matters anymore, but don't crash */
196 }
197
198 PyObject *result = PyObject_CallMethod(stream->self_proxy, "_on_complete", "(i)", error_code);
199 if (result) {
200 Py_DECREF(result);
201 } else {
202 /* Callback might fail during application shutdown */
203 PyErr_WriteUnraisable(PyErr_Occurred());
204 }
205
206 /* DECREF python self, we don't need to force it to stay alive any longer. */
207 PyObject *self = aws_py_weakref_get_ref(stream->self_proxy);
208 /* DECREF twice because `aws_py_weakref_get_ref` returns a strong reference */
209 Py_XDECREF(self);
210 Py_XDECREF(self);
211
212 PyGILState_Release(state);
213 /*************** GIL RELEASE ***************/
214 }
215
216 static void s_on_h2_remote_end_stream(struct aws_http_stream *native_stream, void *user_data) {
217 (void)native_stream;
218 struct http_stream_binding *stream = user_data;
219
220 /*************** GIL ACQUIRE ***************/
221 PyGILState_STATE state;
222 if (aws_py_gilstate_ensure(&state)) {
223 return; /* Python has shut down. Nothing matters anymore, but don't crash */
224 }
225
226 PyObject *result = PyObject_CallMethod(stream->self_proxy, "_on_h2_remote_end_stream", "()");
227 if (result) {
228 Py_DECREF(result);
229 }
230 PyGILState_Release(state);
231 /*************** GIL RELEASE ***************/
232 }
233
234 static void s_stream_capsule_destructor(PyObject *http_stream_capsule) {
235 struct http_stream_binding *stream = PyCapsule_GetPointer(http_stream_capsule, s_capsule_name_http_stream);
236
237 /* Destructor runs under 2 possible conditions:
238 * 1) Creation failed, so every possible resource might need to be cleaned up.
239 * 2) Stream successfully reached end of life, and on_complete has already fired. */
240
241 aws_http_stream_release(stream->native);
242 Py_XDECREF(stream->self_proxy);
243 aws_byte_buf_clean_up(&stream->received_headers);
244 Py_XDECREF(stream->connection);
245
246 aws_mem_release(aws_py_get_allocator(), stream);
247 }
248
249 PyObject *aws_py_http_client_stream_new(PyObject *self, PyObject *args) {
250 (void)self;
251
252 struct aws_allocator *allocator = aws_py_get_allocator();
253
254 PyObject *py_stream = NULL;
255 PyObject *py_connection = NULL;
256 PyObject *py_request = NULL;
257 int http2_manual_write = 0;
258 if (!PyArg_ParseTuple(args, "OOOp", &py_stream, &py_connection, &py_request, &http2_manual_write)) {
259 return NULL;
260 }
261
262 struct aws_http_connection *native_connection = aws_py_get_http_connection(py_connection);
263 if (!native_connection) {
264 return NULL;
265 }
266
267 struct aws_http_message *native_request = aws_py_get_http_message(py_request);
268 if (!native_request) {
269 return NULL;
270 }
271
272 struct http_stream_binding *stream = aws_mem_calloc(allocator, 1, sizeof(struct http_stream_binding));
273 if (!stream) {
274 return PyErr_AwsLastError();
275 }
276
277 /* From hereon, we need to clean up if errors occur.
278 * Fortunately, the capsule destructor will clean up anything stored inside http_stream_binding */
279
280 PyObject *capsule = PyCapsule_New(stream, s_capsule_name_http_stream, s_stream_capsule_destructor);
281 if (!capsule) {
282 goto error;
283 }
284
285 stream->connection = py_connection;
286 Py_INCREF(stream->connection);
287
288 stream->self_proxy = PyWeakref_NewProxy(py_stream, NULL);
289 if (!stream->self_proxy) {
290 goto error;
291 }
292
293 if (aws_byte_buf_init(&stream->received_headers, allocator, HEADERS_RESERVED_BYTES)) {
294 goto error;
295 }
296
297 struct aws_http_make_request_options request_options = {
298 .self_size = sizeof(request_options),
299 .request = native_request,
300 .on_response_headers = s_on_incoming_headers,
301 .on_response_header_block_done = s_on_incoming_header_block_done,
302 .on_response_body = s_on_incoming_body,
303 .on_complete = s_on_stream_complete,
304 .on_h2_remote_end_stream = s_on_h2_remote_end_stream,
305 .user_data = stream,
306 .http2_use_manual_data_writes = http2_manual_write,
307 };
308
309 stream->native = aws_http_connection_make_request(native_connection, &request_options);
310 if (!stream->native) {
311 PyErr_SetAwsLastError();
312 goto error;
313 }
314
315 return capsule;
316
317 error:
318 if (capsule) {
319 Py_DECREF(capsule);
320 } else {
321 aws_mem_release(allocator, stream);
322 }
323 return NULL;
324 }
325
326 PyObject *aws_py_http_client_stream_activate(PyObject *self, PyObject *args) {
327 (void)self;
328
329 PyObject *py_stream = NULL;
330 if (!PyArg_ParseTuple(args, "O", &py_stream)) {
331 return NULL;
332 }
333
334 struct aws_http_stream *native_stream = aws_py_get_http_stream(py_stream);
335 if (!native_stream) {
336 return NULL;
337 }
338
339 if (aws_http_stream_activate(native_stream)) {
340 return PyErr_AwsLastError();
341 }
342
343 /* Force python self to stay alive until on_complete callback */
344 Py_INCREF(py_stream);
345
346 Py_RETURN_NONE;
347 }
348
349 static void s_on_http2_write_data_complete(struct aws_http_stream *stream, int error_code, void *user_data) {
350 (void)stream;
351 PyObject *py_on_write_complete = (PyObject *)user_data;
352 AWS_FATAL_ASSERT(py_on_write_complete);
353 PyGILState_STATE state;
354 if (aws_py_gilstate_ensure(&state)) {
355 return; /* Python has shut down. Nothing matters anymore, but don't crash */
356 }
357
358 /* Invoke on_setup, then clear our reference to it */
359 PyObject *result = PyObject_CallFunction(py_on_write_complete, "(i)", error_code);
360 if (result) {
361 Py_DECREF(result);
362 } else {
363 /* Callback might fail during application shutdown */
364 PyErr_WriteUnraisable(PyErr_Occurred());
365 }
366 Py_DECREF(py_on_write_complete);
367 PyGILState_Release(state);
368 }
369
370 PyObject *aws_py_http2_client_stream_write_data(PyObject *self, PyObject *args) {
371 (void)self;
372
373 PyObject *py_stream = NULL;
374 PyObject *py_body_stream = NULL;
375 int end_stream = false;
376 PyObject *py_on_write_complete = NULL;
377 if (!PyArg_ParseTuple(args, "OOpO", &py_stream, &py_body_stream, &end_stream, &py_on_write_complete)) {
378 return NULL;
379 }
380
381 struct aws_http_stream *http_stream = aws_py_get_http_stream(py_stream);
382 if (!http_stream) {
383 return NULL;
384 }
385
386 struct aws_input_stream *body_stream = NULL;
387 // Write an empty stream is allowed.
388 if (py_body_stream != Py_None) {
389 /* The py_body_stream has the same lifetime as the C stream, no need to keep it alive from this binding. */
390 body_stream = aws_py_get_input_stream(py_body_stream);
391 if (!body_stream) {
392 return PyErr_AwsLastError();
393 }
394 }
395
396 /* Make sure the python callback live long enough for C to call. */
397 Py_INCREF(py_on_write_complete);
398
399 struct aws_http2_stream_write_data_options write_options = {
400 .data = body_stream,
401 .end_stream = end_stream,
402 .on_complete = s_on_http2_write_data_complete,
403 .user_data = py_on_write_complete,
404 };
405
406 int error = aws_http2_stream_write_data(http_stream, &write_options);
407 if (error) {
408 Py_DECREF(py_on_write_complete);
409 return PyErr_AwsLastError();
410 }
411 Py_RETURN_NONE;
412 }