Debian Codegraph @

source/mqtt5_client.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 "mqtt5_client.h"
6 #include "http.h"
7 #include "io.h"
8
9 #include <aws/http/proxy.h>
10 #include <aws/io/socket.h>
11 #include <aws/io/tls_channel_handler.h>
12 #include <aws/mqtt/v5/mqtt5_client.h>
13 #include <aws/mqtt/v5/mqtt5_types.h>
14
15 #include <stdio.h>
16
17 static const char *s_capsule_name_mqtt5_client = "aws_mqtt5_client";
18 static const char *s_capsule_name_ws_handshake_transform_data = "aws_ws_handshake_transform_data";
19
20 static const char *AWS_PYOBJECT_KEY_CLIENT_OPTIONS = "ClientOptions";
21 static const char *AWS_PYOBJECT_KEY_UNSUBSCRIBE_PACKET = "UnsubscribePacket";
22 static const char *AWS_PYOBJECT_KEY_DISCONNECT_PACKET = "DisconnectPacket";
23 static const char *AWS_PYOBJECT_KEY_PUBLISH_PACKET = "PublishPacket";
24 static const char *AWS_PYOBJECT_KEY_SUBSCRIBE_PACKET = "SubscribePacket";
25 static const char *AWS_PYOBJECT_KEY_CONNECT_PACKET = "ConnectPacket";
26 static const char *AWS_PYOBJECT_KEY_WILL_PACKET = "WillPacket";
27 static const char *AWS_PYOBJECT_KEY_SUBSCRIPTION = "Subscription";
28 static const char *AWS_PYOBJECT_KEY_USER_PROPERTIES = "user_properties";
29 static const char *AWS_PYOBJECT_KEY_REASON_CODE = "reason_code";
30 static const char *AWS_PYOBJECT_KEY_NAME = "name";
31 static const char *AWS_PYOBJECT_KEY_VALUE = "value";
32 static const char *AWS_PYOBJECT_KEY_SESSION_EXPIRY_INTERVAL_SEC = "session_expiry_interval_sec";
33 static const char *AWS_PYOBJECT_KEY_MESSAGE_EXPIRY_INTERVAL_SEC = "message_expiry_interval_sec";
34 static const char *AWS_PYOBJECT_KEY_REQUEST_PROBLEM_INFORMATION = "request_problem_information";
35 static const char *AWS_PYOBJECT_KEY_REQUEST_RESPONSE_INFORMATION = "request_response_information";
36 static const char *AWS_PYOBJECT_KEY_RECEIVE_MAXIMUM = "receive_maximum";
37 static const char *AWS_PYOBJECT_KEY_MAXIMUM_PACKET_SIZE = "maximum_packet_size";
38 static const char *AWS_PYOBJECT_KEY_WILL_DELAY_INTERVAL = "will_delay_interval_sec";
39 static const char *AWS_PYOBJECT_KEY_KEEP_ALIVE_INTERVAL_SEC = "keep_alive_interval_sec";
40 static const char *AWS_PYOBJECT_KEY_SUBSCRIPTIONS = "subscriptions";
41 static const char *AWS_PYOBJECT_KEY_SUBSCRIPTION_IDENTIFIER = "subscription_identifier";
42 static const char *AWS_PYOBJECT_KEY_TOPIC_ALIAS = "topic_alias";
43 static const char *AWS_PYOBJECT_KEY_TOPIC_FILTER = "topic_filter";
44 static const char *AWS_PYOBJECT_KEY_TOPIC_FILTERS = "topic_filters";
45 static const char *AWS_PYOBJECT_KEY_QOS = "qos";
46 static const char *AWS_PYOBJECT_KEY_NO_LOCAL = "no_local";
47 static const char *AWS_PYOBJECT_KEY_RETAIN_AS_PUBLISHED = "retain_as_published";
48 static const char *AWS_PYOBJECT_KEY_RETAIN_HANDLING_TYPE = "retain_handling_type";
49 static const char *AWS_PYOBJECT_KEY_PAYLOAD_FORMAT_INDICATOR = "payload_format_indicator";
50 static const char *AWS_PYOBJECT_KEY_SESSION_BEHAVIOR = "session_behavior";
51 static const char *AWS_PYOBJECT_KEY_EXTENDED_VALIDATION_AND_FLOW_CONTROL =
52 "extended_validation_and_flow_control_options";
53 static const char *AWS_PYOBJECT_KEY_OFFLINE_QUEUE_BEHAVIOR = "offline_queue_behavior";
54 static const char *AWS_PYOBJECT_KEY_RETRY_JITTER_MODE = "retry_jitter_mode";
55 static const char *AWS_PYOBJECT_KEY_MIN_RECONNECT_DELAY_MS = "min_reconnect_delay_ms";
56 static const char *AWS_PYOBJECT_KEY_MAX_RECONNECT_DELAY_MS = "max_reconnect_delay_ms";
57 static const char *AWS_PYOBJECT_KEY_MIN_CONNECTED_TIME_TO_RESET_RECONNECT_DELAY_MS =
58 "min_connected_time_to_reset_reconnect_delay_ms";
59 static const char *AWS_PYOBJECT_KEY_PING_TIMEOUT_MS = "ping_timeout_ms";
60 static const char *AWS_PYOBJECT_KEY_CONNACK_TIMEOUT_MS = "connack_timeout_ms";
61 static const char *AWS_PYOBJECT_KEY_ACK_TIMEOUT_SECONDS = "ack_timeout_seconds";
62
63 #define KEEP_ALIVE_INTERVAL_SECONDS 1200
64
65 int PyObject_GetIntEnum(PyObject *o, const char *attr_name) {
66
67 if (!PyLong_Check(o)) {
68 PyErr_Format(PyExc_TypeError, "%s is not a valid enum", attr_name);
69 return -1;
70 }
71
72 return PyLong_AsLong(o);
73 }
74 struct mqtt5_client_binding {
75 struct aws_mqtt5_client *native;
76 PyObject *client_core;
77 };
78
79 /* Called on either failed client creation or by the client upon normal client termination */
80 static void s_mqtt5_client_on_terminate(void *user_data) {
81 struct mqtt5_client_binding *client = user_data;
82
83 PyGILState_STATE state;
84 if (aws_py_gilstate_ensure(&state)) {
85 return; /* Python has shut down. Nothing matters anymore, but don't crash */
86 }
87 if (client->client_core != NULL) {
88 // Make sure to release the python client object
89 Py_XDECREF(client->client_core);
90 }
91 aws_mem_release(aws_py_get_allocator(), client);
92 PyGILState_Release(state);
93 }
94
95 /* Called when capsule's refcount hits 0 */
96 static void s_mqtt5_python_client_destructor(PyObject *client_capsule) {
97 struct mqtt5_client_binding *client = PyCapsule_GetPointer(client_capsule, s_capsule_name_mqtt5_client);
98 assert(client);
99
100 if (client->native != NULL) {
101 /* If client is not NULL, it can be shutdown and cleaned normally */
102 aws_mqtt5_client_release(client->native);
103 client->native = NULL;
104 } else {
105 /* A failed client that must be cleaned up directly */
106 s_mqtt5_client_on_terminate(client);
107 }
108 }
109
110 /* PyErr_Occurred() must be called to check if anything went wrong after using this function. */
111 void aws_init_named_aws_byte_cursor_from_PyObject(
112 PyObject *o,
113 const char *class_name,
114 const char *attr_name,
115 struct aws_byte_cursor *byte_cursor_out) {
116 PyObject *attr = PyObject_GetAttrString(o, attr_name);
117 if (!attr) {
118 PyErr_Format(PyExc_AttributeError, "'%s.%s' attribute not found", class_name, attr_name);
119 return;
120 }
121
122 if (attr == Py_None) {
123 PyErr_Format(PyExc_TypeError, "'%s.%s' is set to None", class_name, attr_name);
124 goto done;
125 }
126
127 *byte_cursor_out = aws_byte_cursor_from_pyunicode(attr);
128 if (!byte_cursor_out->ptr) {
129 PyErr_Format(PyExc_TypeError, "'%s.%s' is not a valid string", class_name, attr_name);
130 goto done;
131 }
132
133 /* If the attribute doesn't exist or was set to None */
134 done:
135 Py_XDECREF(attr);
136 }
137
138 /* PyErr_Occurred() must be called to check if anything went wrong after using this function. */
139 static struct aws_mqtt5_user_property *aws_get_optional_user_properties_from_PyObject(
140 PyObject *attr,
141 size_t *user_property_count_out) {
142
143 if (attr == Py_None) {
144 /* This is not an error */
145 return NULL;
146 }
147
148 if (!PySequence_Check(attr)) {
149 PyErr_Format(PyExc_TypeError, "user_properties must be a list or tuple");
150 return NULL;
151 }
152
153 Py_ssize_t user_property_count = PySequence_Size(attr);
154 if (user_property_count <= 0) {
155 return NULL;
156 }
157
158 /*
159 * This allocated memory must be cleaned up within this function if NULL is returned or
160 * outside of this function if a pointer is successfully returned
161 */
162 struct aws_mqtt5_user_property *user_properties_tmp =
163 aws_mem_calloc(aws_py_get_allocator(), (size_t)user_property_count, sizeof(struct aws_mqtt5_user_property));
164
165 PyObject *property_py;
166 for (Py_ssize_t i = 0; i < user_property_count; ++i) {
167 property_py = PySequence_GetItem(attr, i);
168 aws_init_named_aws_byte_cursor_from_PyObject(
169 property_py, AWS_PYOBJECT_KEY_USER_PROPERTIES, AWS_PYOBJECT_KEY_NAME, &user_properties_tmp[i].name);
170 if (PyErr_Occurred()) {
171 Py_XDECREF(property_py);
172 goto error;
173 }
174 aws_init_named_aws_byte_cursor_from_PyObject(
175 property_py, AWS_PYOBJECT_KEY_USER_PROPERTIES, AWS_PYOBJECT_KEY_VALUE, &user_properties_tmp[i].value);
176 if (PyErr_Occurred()) {
177 Py_XDECREF(property_py);
178 goto error;
179 }
180 Py_XDECREF(property_py);
181 }
182
183 *user_property_count_out = (size_t)user_property_count;
184 return user_properties_tmp;
185
186 error:
187 aws_mem_release(aws_py_get_allocator(), user_properties_tmp);
188 user_properties_tmp = NULL;
189 return NULL;
190 }
191
192 static PyObject *s_aws_set_user_properties_to_PyObject(
193 const struct aws_mqtt5_user_property *user_properties,
194 size_t user_properties_count) {
195 PyObject *user_properties_list = PyList_New(user_properties_count);
196 if (!user_properties_list) {
197 return NULL;
198 }
199
200 for (size_t i = 0; i < user_properties_count; ++i) {
201 PyObject *tuple = Py_BuildValue(
202 "(s#s#)",
203 user_properties[i].name.ptr,
204 user_properties[i].name.len,
205 user_properties[i].value.ptr,
206 user_properties[i].value.len);
207 if (!tuple) {
208 PyErr_Format(PyExc_TypeError, "Publish Packet User Property index %zu is not a valid string", i);
209 Py_XDECREF(user_properties_list);
210 return NULL;
211 }
212 PyList_SetItem(user_properties_list, i, tuple); /* Steals reference to tuple */
213 }
214 return user_properties_list;
215 }
216
217 /*******************************************************************************
218 * Publish Handler
219 ******************************************************************************/
220
221 static void s_on_publish_received(const struct aws_mqtt5_packet_publish_view *publish_packet, void *user_data) {
222
223 if (!user_data) {
224 return;
225 }
226 struct mqtt5_client_binding *client = user_data;
227
228 PyGILState_STATE state;
229 if (aws_py_gilstate_ensure(&state)) {
230 return; /* Python has shut down. Nothing matters anymore, but don't crash */
231 }
232
233 /* These must be DECREF'd when function ends */
234 PyObject *result = NULL;
235 PyObject *subscription_identifier_list = NULL;
236 PyObject *user_properties_list = NULL;
237 PyObject *puback_control_id_py = NULL;
238
239 size_t subscription_identifier_count = publish_packet->subscription_identifier_count;
240 size_t user_property_count = publish_packet->user_property_count;
241
242 /* For QoS 1 messages, take manual control of the publish acknowledgement immediately.
243 * This gives us a pub_ack_control_id that we pass to Python as an opaque integer.
244 * Python's _on_publish will return True if the user called acquire_publish_acknowledgement_control(),
245 * in which case the user is responsible for calling invoke_publish_acknowledgement() later.
246 * If _on_publish returns False/None, we auto-invoke the publish acknowledgement here. */
247 uint64_t puback_control_id = 0;
248 if (publish_packet->qos == AWS_MQTT5_QOS_AT_LEAST_ONCE) {
249 puback_control_id = aws_mqtt5_client_acquire_publish_acknowledgement(client->native, publish_packet);
250 puback_control_id_py = PyLong_FromUnsignedLongLong((unsigned long long)puback_control_id);
251 if (!puback_control_id_py) {
252 PyErr_WriteUnraisable(PyErr_Occurred());
253 goto cleanup;
254 }
255 }
256
257 /* Create list of uint32_t subscription identifier tuples */
258 subscription_identifier_list = PyList_New(subscription_identifier_count);
259 if (!subscription_identifier_list) {
260 PyErr_WriteUnraisable(PyErr_Occurred());
261 goto cleanup;
262 }
263
264 for (size_t i = 0; i < subscription_identifier_count; ++i) {
265 PyList_SetItem(
266 subscription_identifier_list,
267 i,
268 PyLong_FromLongLong(publish_packet->subscription_identifiers[i])); /* Steals a reference */
269 }
270
271 user_properties_list = s_aws_set_user_properties_to_PyObject(publish_packet->user_properties, user_property_count);
272 if (PyErr_Occurred()) {
273 PyErr_WriteUnraisable(PyErr_Occurred());
274 goto cleanup;
275 }
276
277 result = PyObject_CallMethod(
278 client->client_core,
279 "_on_publish",
280 "(y#iOs#OiOIOHs#y#Os#OK)",
281 /* y */ publish_packet->payload.ptr,
282 /* # */ publish_packet->payload.len,
283 /* i */ (int)publish_packet->qos,
284 /* O */ publish_packet->retain ? Py_True : Py_False,
285 /* s */ publish_packet->topic.ptr,
286 /* # */ publish_packet->topic.len,
287 /* O */ publish_packet->payload_format ? Py_True : Py_False,
288 /* i */ (int)(publish_packet->payload_format ? *publish_packet->payload_format : 0),
289 /* O */ publish_packet->message_expiry_interval_seconds ? Py_True : Py_False,
290 /* I */
291 (unsigned int)(publish_packet->message_expiry_interval_seconds
292 ? *publish_packet->message_expiry_interval_seconds
293 : 0),
294 /* O */ publish_packet->topic_alias ? Py_True : Py_False,
295 /* H */ (unsigned short)(publish_packet->topic_alias ? *publish_packet->topic_alias : 0),
296 /* s */ publish_packet->response_topic ? publish_packet->response_topic->ptr : NULL,
297 /* # */ publish_packet->response_topic ? publish_packet->response_topic->len : 0,
298 /* y */ publish_packet->correlation_data ? publish_packet->correlation_data->ptr : NULL,
299 /* # */ publish_packet->correlation_data ? publish_packet->correlation_data->len : 0,
300 /* O */ subscription_identifier_count > 0 ? subscription_identifier_list : Py_None,
301 /* s */ publish_packet->content_type ? publish_packet->content_type->ptr : NULL,
302 /* # */ publish_packet->content_type ? publish_packet->content_type->len : 0,
303 /* O */ user_property_count > 0 ? user_properties_list : Py_None,
304 /* K */ (unsigned long long)puback_control_id);
305
306 if (!result) {
307 PyErr_WriteUnraisable(PyErr_Occurred());
308 /* On error, auto-invoke the publish acknowledgement so it is not lost */
309 if (puback_control_id != 0) {
310 aws_mqtt5_client_invoke_publish_acknowledgement(client->native, puback_control_id, NULL);
311 }
312 goto cleanup;
313 }
314
315 /* If _on_publish returned False/None, the user did not take control of the publish acknowledgement.
316 * Auto-invoke it now. */
317 if (puback_control_id != 0 && !PyObject_IsTrue(result)) {
318 aws_mqtt5_client_invoke_publish_acknowledgement(client->native, puback_control_id, NULL);
319 }
320
321 cleanup:
322 Py_XDECREF(result);
323 Py_XDECREF(subscription_identifier_list);
324 Py_XDECREF(user_properties_list);
325 Py_XDECREF(puback_control_id_py);
326 PyGILState_Release(state);
327 }
328
329 /*******************************************************************************
330 * Lifecycle Event Handler
331 ******************************************************************************/
332
333 static void s_lifecycle_event_stopped(struct mqtt5_client_binding *client) {
334 if (!client || !client->client_core) {
335 return;
336 }
337
338 PyGILState_STATE state;
339 if (aws_py_gilstate_ensure(&state)) {
340 return; /* Python has shut down. Nothing matters anymore, but don't crash */
341 }
342
343 PyObject *result = PyObject_CallMethod(client->client_core, "_on_lifecycle_stopped", NULL);
344 if (!result) {
345 PyErr_WriteUnraisable(PyErr_Occurred());
346 }
347 Py_XDECREF(result);
348
349 PyGILState_Release(state);
350 }
351
352 static void s_lifecycle_event_attempting_connect(struct mqtt5_client_binding *client) {
353 if (!client) {
354 return;
355 }
356
357 PyGILState_STATE state;
358 if (aws_py_gilstate_ensure(&state)) {
359 return; /* Python has shut down. Nothing matters anymore, but don't crash */
360 }
361
362 PyObject *result = PyObject_CallMethod(client->client_core, "_on_lifecycle_attempting_connect", NULL);
363 if (!result) {
364 PyErr_WriteUnraisable(PyErr_Occurred());
365 }
366 Py_XDECREF(result);
367
368 PyGILState_Release(state);
369 }
370
371 static void s_lifecycle_event_connection_success(
372 struct mqtt5_client_binding *client,
373 const struct aws_mqtt5_packet_connack_view *connack,
374 const struct aws_mqtt5_negotiated_settings *settings) {
375 if (!client) {
376 return;
377 }
378
379 /* These must be DECREF'd when function ends */
380 PyObject *user_properties_list = NULL;
381 PyObject *result = NULL;
382
383 PyGILState_STATE state;
384 if (aws_py_gilstate_ensure(&state)) {
385 return; /* Python has shut down. Nothing matters anymore, but don't crash */
386 }
387
388 size_t user_property_count = connack->user_property_count;
389
390 user_properties_list = s_aws_set_user_properties_to_PyObject(connack->user_properties, user_property_count);
391 if (PyErr_Occurred()) {
392 PyErr_WriteUnraisable(PyErr_Occurred());
393 goto cleanup;
394 }
395
396 result = PyObject_CallMethod(
397 client->client_core,
398 "_on_lifecycle_connection_success",
399 "(OiOIOHOiOOOIs#OIs#OOOOOOOOHs#s#iIHIHHHOOOOOs#)",
400 /* connack packet */
401 /* O */ connack->session_present ? Py_True : Py_False,
402 /* i */ (int)connack->reason_code,
403 /* O */ connack->session_expiry_interval ? Py_True : Py_False,
404 /* I */ (unsigned int)(connack->session_expiry_interval ? *connack->session_expiry_interval : 0),
405 /* O */ connack->receive_maximum ? Py_True : Py_False,
406 /* H */ (unsigned short)(connack->receive_maximum ? *connack->receive_maximum : 0),
407 /* O */ connack->maximum_qos ? Py_True : Py_False,
408 /* i */ (int)(connack->maximum_qos ? *connack->maximum_qos : 0),
409 /* O */ connack->retain_available ? Py_True : Py_False,
410 /* O */ (connack->retain_available && *connack->retain_available) ? Py_True : Py_False,
411 /* O */ connack->maximum_packet_size ? Py_True : Py_False,
412 /* I */ (unsigned int)(connack->maximum_packet_size ? *connack->maximum_packet_size : 0),
413 /* s */ connack->assigned_client_identifier ? connack->assigned_client_identifier->ptr : NULL,
414 /* # */ connack->assigned_client_identifier ? connack->assigned_client_identifier->len : 0,
415 /* O */ connack->topic_alias_maximum ? Py_True : Py_False,
416 /* I */ (unsigned int)(connack->topic_alias_maximum ? *connack->topic_alias_maximum : 0),
417 /* s */ connack->reason_string ? connack->reason_string->ptr : NULL,
418 /* # */ connack->reason_string ? connack->reason_string->len : 0,
419 /* O */ user_property_count > 0 ? user_properties_list : Py_None,
420 /* O */ connack->wildcard_subscriptions_available ? Py_True : Py_False,
421 /* O */
422 (connack->wildcard_subscriptions_available && *connack->wildcard_subscriptions_available) ? Py_True : Py_False,
423 /* O */ connack->subscription_identifiers_available ? Py_True : Py_False,
424 /* O */
425 (connack->subscription_identifiers_available && *connack->subscription_identifiers_available) ? Py_True
426 : Py_False,
427 /* O */ connack->shared_subscriptions_available ? Py_True : Py_False,
428 /* O */
429 (connack->shared_subscriptions_available && *connack->shared_subscriptions_available) ? Py_True : Py_False,
430 /* O */ connack->server_keep_alive ? Py_True : Py_False,
431 /* H */ (unsigned short)(connack->server_keep_alive ? *connack->server_keep_alive : 0),
432 /* s */ connack->response_information ? connack->response_information->ptr : NULL,
433 /* # */ connack->response_information ? connack->response_information->len : 0,
434 /* s */ connack->server_reference ? connack->server_reference->ptr : NULL,
435 /* # */ connack->server_reference ? connack->server_reference->len : 0,
436 /* negotiated settings */
437 /* i */ (int)settings->maximum_qos,
438 /* I */ (unsigned int)settings->session_expiry_interval,
439 /* H */ (unsigned short)settings->receive_maximum_from_server,
440 /* I */ (unsigned int)settings->maximum_packet_size_to_server,
441 /* H */ (unsigned short)settings->topic_alias_maximum_to_server,
442 /* H */ (unsigned short)settings->topic_alias_maximum_to_client,
443 /* H */ (unsigned short)settings->server_keep_alive,
444 /* O */ settings->retain_available ? Py_True : Py_False,
445 /* O */ settings->wildcard_subscriptions_available ? Py_True : Py_False,
446 /* O */ settings->subscription_identifiers_available ? Py_True : Py_False,
447 /* O */ settings->shared_subscriptions_available ? Py_True : Py_False,
448 /* O */ settings->rejoined_session ? Py_True : Py_False,
449 /* s */ settings->client_id_storage.len > 0 ? settings->client_id_storage.buffer : NULL,
450 /* # */ settings->client_id_storage.len);
451 if (!result) {
452 PyErr_WriteUnraisable(PyErr_Occurred());
453 }
454 cleanup:
455 Py_XDECREF(result);
456 Py_XDECREF(user_properties_list);
457
458 PyGILState_Release(state);
459 }
460
461 static void s_lifecycle_event_connection_failure(
462 struct mqtt5_client_binding *client,
463 const struct aws_mqtt5_packet_connack_view *connack,
464 int error_code) {
465 if (!client) {
466 return;
467 }
468
469 /* These must be DECREF'd when function ends */
470 PyObject *user_properties_list = NULL;
471 PyObject *result = NULL;
472
473 PyGILState_STATE state;
474 if (aws_py_gilstate_ensure(&state)) {
475 return; /* Python has shut down. Nothing matters anymore, but don't crash */
476 }
477
478 size_t user_property_count = 0;
479
480 if (connack) {
481 user_property_count = connack->user_property_count;
482
483 user_properties_list = s_aws_set_user_properties_to_PyObject(connack->user_properties, user_property_count);
484 if (PyErr_Occurred()) {
485 PyErr_WriteUnraisable(PyErr_Occurred());
486 goto cleanup;
487 }
488 }
489
490 result = PyObject_CallMethod(
491 client->client_core,
492 "_on_lifecycle_connection_failure",
493 "(iOOiOIOHOiOOOIs#s#OOOOOOOOHs#s#)",
494 /* i */ (int)error_code,
495 /* O */ connack ? Py_True : Py_False,
496 /* O */ (connack && connack->session_present) ? Py_True : Py_False,
497 /* i */ (int)(connack ? connack->reason_code : 0),
498 /* O */ (connack && connack->session_expiry_interval) ? Py_True : Py_False,
499 /* I */ (unsigned int)((connack && connack->session_expiry_interval) ? *connack->session_expiry_interval : 0),
500 /* O */ (connack && connack->receive_maximum) ? Py_True : Py_False,
501 /* H */ (unsigned short)((connack && connack->receive_maximum) ? *connack->receive_maximum : 0),
502 /* O */ (connack && connack->maximum_qos) ? Py_True : Py_False,
503 /* i */ (int)((connack && connack->maximum_qos) ? *connack->maximum_qos : 0),
504 /* O */ (connack && connack->retain_available) ? Py_True : Py_False,
505 /* O */ (connack && connack->retain_available && *connack->retain_available) ? Py_True : Py_False,
506 /* O */ (connack && connack->maximum_packet_size) ? Py_True : Py_False,
507 /* I */ (unsigned int)(connack && connack->maximum_packet_size) ? *connack->maximum_packet_size : 0,
508 /* s */ (connack && connack->assigned_client_identifier) ? connack->assigned_client_identifier->ptr : NULL,
509 /* # */ (connack && connack->assigned_client_identifier) ? connack->assigned_client_identifier->len : 0,
510 /* s */ (connack && connack->reason_string) ? connack->reason_string->ptr : NULL,
511 /* # */ (connack && connack->reason_string) ? connack->reason_string->len : 0,
512 /* O */ user_property_count > 0 ? user_properties_list : Py_None,
513 /* O */ (connack && connack->wildcard_subscriptions_available) ? Py_True : Py_False,
514 /* O */
515 (connack && connack->wildcard_subscriptions_available && *connack->wildcard_subscriptions_available) ? Py_True
516 : Py_False,
517 /* O */ (connack && connack->subscription_identifiers_available) ? Py_True : Py_False,
518 /* O */
519 (connack && connack->subscription_identifiers_available && *connack->subscription_identifiers_available)
520 ? Py_True
521 : Py_False,
522 /* O */ (connack && connack->shared_subscriptions_available) ? Py_True : Py_False,
523 /* O */
524 (connack && connack->shared_subscriptions_available && *connack->shared_subscriptions_available) ? Py_True
525 : Py_False,
526 /* O */ (connack && connack->server_keep_alive) ? Py_True : Py_False,
527 /* H */ (unsigned short)(connack && connack->server_keep_alive) ? *connack->server_keep_alive : 0,
528 /* s */ (connack && connack->response_information) ? connack->response_information->ptr : NULL,
529 /* # */ (connack && connack->response_information) ? connack->response_information->len : 0,
530 /* s */ (connack && connack->server_reference) ? connack->server_reference->ptr : NULL,
531 /* # */ (connack && connack->server_reference) ? connack->server_reference->len : 0);
532 if (!result) {
533 PyErr_WriteUnraisable(PyErr_Occurred());
534 }
535 cleanup:
536 Py_XDECREF(result);
537 Py_XDECREF(user_properties_list);
538
539 PyGILState_Release(state);
540 }
541
542 static void s_lifecycle_event_disconnection(
543 struct mqtt5_client_binding *client,
544 const struct aws_mqtt5_packet_disconnect_view *disconnect,
545 int error_code) {
546 if (!client) {
547 return;
548 }
549 /* These must be DECREF'd when function ends */
550 PyObject *user_properties_list = NULL;
551 PyObject *result = NULL;
552
553 PyGILState_STATE state;
554 if (aws_py_gilstate_ensure(&state)) {
555 return; /* Python has shut down. Nothing matters anymore, but don't crash */
556 }
557
558 size_t user_property_count = 0;
559
560 if (disconnect) {
561 user_property_count = disconnect->user_property_count;
562
563 user_properties_list = s_aws_set_user_properties_to_PyObject(disconnect->user_properties, user_property_count);
564 if (PyErr_Occurred()) {
565 PyErr_WriteUnraisable(PyErr_Occurred());
566 goto cleanup;
567 }
568 }
569
570 result = PyObject_CallMethod(
571 client->client_core,
572 "_on_lifecycle_disconnection",
573 "(iOiOIs#Os#)",
574 /* i */ (int)error_code,
575 /* O */ disconnect ? Py_True : Py_False,
576 /* i */ (int)(disconnect ? disconnect->reason_code : 0),
577 /* O */ (disconnect && disconnect->session_expiry_interval_seconds) ? Py_True : Py_False,
578 /* I */
579 (unsigned int)((disconnect && disconnect->session_expiry_interval_seconds)
580 ? *disconnect->session_expiry_interval_seconds
581 : 0),
582 /* s */ (disconnect && disconnect->reason_string) ? disconnect->reason_string->ptr : NULL,
583 /* # */ (disconnect && disconnect->reason_string) ? disconnect->reason_string->len : 0,
584 /* O */ user_property_count > 0 ? user_properties_list : Py_None,
585 /* s */ (disconnect && disconnect->server_reference) ? disconnect->server_reference->ptr : NULL,
586 /* # */ (disconnect && disconnect->server_reference) ? disconnect->server_reference->len : 0);
587 if (!result) {
588 PyErr_WriteUnraisable(PyErr_Occurred());
589 }
590 cleanup:
591 Py_XDECREF(result);
592 Py_XDECREF(user_properties_list);
593
594 PyGILState_Release(state);
595 }
596
597 static void s_lifecycle_event_callback(const struct aws_mqtt5_client_lifecycle_event *event) {
598 switch (event->event_type) {
599 case AWS_MQTT5_CLET_STOPPED:
600 s_lifecycle_event_stopped(event->user_data);
601 break;
602
603 case AWS_MQTT5_CLET_ATTEMPTING_CONNECT:
604 s_lifecycle_event_attempting_connect(event->user_data);
605 break;
606
607 case AWS_MQTT5_CLET_CONNECTION_SUCCESS:
608 s_lifecycle_event_connection_success(event->user_data, event->connack_data, event->settings);
609 break;
610
611 case AWS_MQTT5_CLET_CONNECTION_FAILURE:
612 s_lifecycle_event_connection_failure(event->user_data, event->connack_data, event->error_code);
613 break;
614
615 case AWS_MQTT5_CLET_DISCONNECTION:
616 s_lifecycle_event_disconnection(event->user_data, event->disconnect_data, event->error_code);
617 break;
618
619 default:
620 break;
621 }
622 }
623
624 /*******************************************************************************
625 * Websocket
626 ******************************************************************************/
627
628 /* persistent storage for the data needed to transform the websocket handshake*/
629 struct ws_handshake_transform_data {
630 /* Strong reference to Python Client so it can't go out of scope during transform */
631 PyObject *client_core;
632
633 struct aws_http_message *request;
634 aws_mqtt5_transform_websocket_handshake_complete_fn *complete_fn;
635 void *complete_ctx;
636
637 /* Python bindings we created to wrap the native request */
638 /* Necessary? */
639 PyObject *request_binding_py;
640 PyObject *headers_binding_py;
641 };
642
643 void s_mqtt5_ws_handshake_transform_data_destructor(PyObject *capsule) {
644 struct ws_handshake_transform_data *ws_data =
645 PyCapsule_GetPointer(capsule, s_capsule_name_ws_handshake_transform_data);
646
647 /* Note that binding may be only partially constructed, if error occurred during setup */
648 Py_XDECREF(ws_data->client_core);
649 Py_XDECREF(ws_data->request_binding_py);
650 Py_XDECREF(ws_data->headers_binding_py);
651
652 aws_mem_release(aws_py_get_allocator(), ws_data);
653 }
654
655 /* Invoke user's websocket handshake transform function */
656 static void s_ws_handshake_transform(
657 struct aws_http_message *request,
658 void *user_data,
659 aws_mqtt5_transform_websocket_handshake_complete_fn *complete_fn,
660 void *complete_ctx) {
661
662 // struct mqtt_connection_binding *connection_binding = user_data;
663 struct mqtt5_client_binding *client = user_data;
664
665 bool success = false;
666
667 /* We'll create a ws_handshake_transform_data object, place it in a capsule, and pass it to callback */
668 struct ws_handshake_transform_data *ws_transform_data = NULL;
669 PyObject *ws_transform_capsule = NULL;
670
671 /*************** GIL ACQUIRE ***************
672 * If error occurs, ensure an aws error is raised and goto done */
673 PyGILState_STATE state;
674 if (aws_py_gilstate_ensure(&state)) {
675 return; /* Python has shut down. Nothing matters anymore, but don't crash */
676 }
677
678 ws_transform_data = aws_mem_calloc(aws_py_get_allocator(), 1, sizeof(struct ws_handshake_transform_data));
679
680 ws_transform_capsule = PyCapsule_New(
681 ws_transform_data, s_capsule_name_ws_handshake_transform_data, s_mqtt5_ws_handshake_transform_data_destructor);
682 if (!ws_transform_capsule) {
683 aws_py_raise_error();
684 goto done;
685 }
686
687 /* From hereon, capsule destructor will clean up anything stored within it */
688
689 ws_transform_data->request = request;
690 ws_transform_data->complete_fn = complete_fn;
691 ws_transform_data->complete_ctx = complete_ctx;
692
693 ws_transform_data->client_core = client->client_core;
694 Py_INCREF(ws_transform_data->client_core);
695
696 ws_transform_data->request_binding_py = aws_py_http_message_new_request_from_native(request);
697 if (!ws_transform_data->request_binding_py) {
698 aws_py_raise_error();
699 goto done;
700 }
701
702 ws_transform_data->headers_binding_py = aws_py_http_headers_new_from_native(aws_http_message_get_headers(request));
703 if (!ws_transform_data->headers_binding_py) {
704 aws_py_raise_error();
705 goto done;
706 }
707
708 PyObject *result = PyObject_CallMethod(
709 client->client_core,
710 "_ws_handshake_transform",
711 "(OOO)",
712 /* O */ ws_transform_data->request_binding_py,
713 /* O */ ws_transform_data->headers_binding_py,
714 /* O */ ws_transform_capsule);
715
716 if (result) {
717 Py_DECREF(result);
718 } else {
719 aws_py_raise_error();
720 goto done;
721 }
722
723 success = true;
724 done:;
725 /* Save off error code, so it doesn't got stomped before we pass it to callback*/
726 int error_code = aws_last_error();
727
728 if (ws_transform_capsule) {
729 Py_DECREF(ws_transform_capsule);
730 } else if (ws_transform_data) {
731 aws_mem_release(aws_py_get_allocator(), ws_transform_data);
732 }
733
734 PyGILState_Release(state);
735 /*************** GIL RELEASE ***************/
736
737 /* Invoke completion cb if we failed to pass data to user. */
738 if (!success) {
739 complete_fn(request, error_code, complete_ctx);
740 }
741 }
742
743 /* Called when user finishes performing their websocket handshake transform */
744 PyObject *aws_py_mqtt5_ws_handshake_transform_complete(PyObject *self, PyObject *args) {
745 (void)self;
746
747 PyObject *exception_py;
748 PyObject *ws_transform_capsule;
749 int error_code = AWS_ERROR_SUCCESS;
750 if (!PyArg_ParseTuple(args, "OOi", &exception_py, &ws_transform_capsule, &error_code)) {
751 return NULL;
752 }
753
754 if (exception_py != Py_None && error_code == AWS_ERROR_SUCCESS) {
755 /* Fallback code for if the error source was outside the CRT native implementation */
756 error_code = AWS_ERROR_HTTP_CALLBACK_FAILURE;
757 }
758
759 struct ws_handshake_transform_data *ws_transform_data =
760 PyCapsule_GetPointer(ws_transform_capsule, s_capsule_name_ws_handshake_transform_data);
761 if (!ws_transform_data) {
762 return NULL;
763 }
764
765 /* Invoke complete_fn*/
766 ws_transform_data->complete_fn(ws_transform_data->request, error_code, ws_transform_data->complete_ctx);
767
768 Py_RETURN_NONE;
769 }
770
771 static bool s_py_topic_aliasing_options_init(
772 struct aws_mqtt5_client_topic_alias_options *topic_aliasing_options,
773 PyObject *py_topic_aliasing_options) {
774 AWS_ZERO_STRUCT(*topic_aliasing_options);
775
776 bool success = false;
777 PyObject *py_outbound_behavior = PyObject_GetAttrString(py_topic_aliasing_options, "outbound_behavior");
778 PyObject *py_outbound_cache_max_size = PyObject_GetAttrString(py_topic_aliasing_options, "outbound_cache_max_size");
779 PyObject *py_inbound_behavior = PyObject_GetAttrString(py_topic_aliasing_options, "inbound_behavior");
780 PyObject *py_inbound_cache_max_size = PyObject_GetAttrString(py_topic_aliasing_options, "inbound_cache_max_size");
781
782 if (py_outbound_behavior != NULL && !PyObject_GetAsOptionalIntEnum(
783 py_outbound_behavior,
784 "TopicAliasingOptions",
785 "outbound_behavior",
786 (int *)&topic_aliasing_options->outbound_topic_alias_behavior)) {
787 if (PyErr_Occurred()) {
788 goto done;
789 }
790 }
791
792 if (py_outbound_cache_max_size != NULL && !PyObject_GetAsOptionalUint16(
793 py_outbound_cache_max_size,
794 "TopicAliasingOptions",
795 "outbound_cache_max_size",
796 &topic_aliasing_options->outbound_alias_cache_max_size)) {
797 if (PyErr_Occurred()) {
798 goto done;
799 }
800 }
801
802 if (py_inbound_behavior != NULL && !PyObject_GetAsOptionalIntEnum(
803 py_inbound_behavior,
804 "TopicAliasingOptions",
805 "inbound_behavior",
806 (int *)&topic_aliasing_options->inbound_topic_alias_behavior)) {
807 if (PyErr_Occurred()) {
808 goto done;
809 }
810 }
811
812 if (py_inbound_cache_max_size != NULL && !PyObject_GetAsOptionalUint16(
813 py_inbound_cache_max_size,
814 "TopicAliasingOptions",
815 "inbound_cache_max_size",
816 &topic_aliasing_options->inbound_alias_cache_size)) {
817 if (PyErr_Occurred()) {
818 goto done;
819 }
820 }
821
822 success = true;
823
824 done:
825
826 Py_XDECREF(py_outbound_behavior);
827 Py_XDECREF(py_outbound_cache_max_size);
828 Py_XDECREF(py_inbound_behavior);
829 Py_XDECREF(py_inbound_cache_max_size);
830
831 return success;
832 }
833
834 /*******************************************************************************
835 * Metrics Parsing
836 ******************************************************************************/
837
838 bool aws_py_metrics_parse(PyObject *metrics_py, struct aws_mqtt_iot_metrics *out_metrics) {
839 AWS_ZERO_STRUCT(*out_metrics);
840
841 PyObject *library_name_py = PyObject_GetAttrString(metrics_py, "library_name");
842 out_metrics->library_name = aws_byte_cursor_from_pyunicode(library_name_py);
843 Py_XDECREF(library_name_py);
844
845 PyObject *metadata_entries_py = PyObject_GetAttrString(metrics_py, "metadata_entries");
846
847 if (metadata_entries_py && metadata_entries_py != Py_None && PyList_Check(metadata_entries_py)) {
848 Py_ssize_t count = PyList_Size(metadata_entries_py);
849 if (count > 0) {
850 struct aws_mqtt_metadata_entry *entries =
851 aws_mem_calloc(aws_py_get_allocator(), (size_t)count, sizeof(struct aws_mqtt_metadata_entry));
852
853 for (Py_ssize_t i = 0; i < count; ++i) {
854 PyObject *entry_py = PyList_GetItem(metadata_entries_py, i);
855 PyObject *key_py = PyObject_GetAttrString(entry_py, "key");
856 PyObject *value_py = PyObject_GetAttrString(entry_py, "value");
857
858 entries[i].key = aws_byte_cursor_from_pyunicode(key_py);
859 entries[i].value = aws_byte_cursor_from_pyunicode(value_py);
860
861 Py_XDECREF(key_py);
862 Py_XDECREF(value_py);
863 }
864 out_metrics->metadata_count = (size_t)count;
865 out_metrics->metadata_entries = entries;
866 }
867 }
868
869 Py_XDECREF(metadata_entries_py);
870 return true;
871 }
872
873 void aws_py_metrics_clean_up(struct aws_mqtt_iot_metrics *metrics) {
874 if (metrics->metadata_entries) {
875 aws_mem_release(aws_py_get_allocator(), (void *)metrics->metadata_entries);
876 }
877 }
878
879 /*******************************************************************************
880 * Client Init
881 ******************************************************************************/
882
883 PyObject *aws_py_mqtt5_client_new(PyObject *self, PyObject *args) {
884 (void)self;
885 bool success = false;
886
887 PyObject *self_py;
888
889 struct aws_byte_cursor host_name;
890 PyObject *bootstrap_py;
891 PyObject *socket_options_py;
892 PyObject *tls_ctx_py;
893 PyObject *proxy_options_py;
894 uint32_t port;
895
896 /* Connect Options */
897 struct aws_byte_cursor client_id; /* optional */
898 PyObject *keep_alive_interval_sec_py; /* optional uint16_t */
899 struct aws_byte_cursor username; /* optional */
900 struct aws_byte_cursor password; /* optional */
901 PyObject *session_expiry_interval_sec_py; /* optional uint32_t */
902 PyObject *request_response_information_py; /* optional bool */
903 PyObject *request_problem_information_py; /* optional bool */
904 PyObject *receive_maximum_py; /* optional uint16_t */
905 PyObject *maximum_packet_size_py; /* optional uint32_t */
906 PyObject *will_delay_interval_sec_py; /* optional uint32_t */
907 PyObject *user_properties_py; /* optional */
908
909 /* Will */
910 PyObject *is_will_none_py; /* optional PublishPacket */
911 PyObject *will_qos_val_py;
912 Py_buffer will_payload_stack; /* Py_buffers must be released after successful PyArg_ParseTuple() calls */
913 PyObject *will_retain_py;
914 struct aws_byte_cursor will_topic;
915 PyObject *will_payload_format_py; /* optional enum */
916 PyObject *will_message_expiry_interval_seconds_py; /* optional uint32_t */
917 PyObject *will_topic_alias_py; /* optional uint16_t */
918 struct aws_byte_cursor will_response_topic; /* optional */
919 Py_buffer will_correlation_data_stack; /* optional */
920 struct aws_byte_cursor will_content_type; /* optional */
921 PyObject *will_user_properties_py; /* optional */
922
923 PyObject *session_behavior_py; /* optional enum */
924 PyObject *extended_validation_and_flow_control_options_py; /* optional enum */
925 PyObject *offline_queue_behavior_py; /* optional enum */
926 PyObject *retry_jitter_mode_py; /* optional enum */
927 PyObject *min_reconnect_delay_ms_py; /* optional uint64_t */
928 PyObject *max_reconnect_delay_ms_py; /* optional uint64_t */
929 PyObject *min_connected_time_to_reset_reconnect_delay_ms_py; /* optional uint64_t */
930 PyObject *ping_timeout_ms_py; /* optional uint32_t */
931 PyObject *connack_timeout_ms_py; /* optional uint32_t */
932 PyObject *ack_timeout_seconds_py; /* optional uint32_t */
933 PyObject *topic_aliasing_options_py; /* optional TopicAliasingOptions */
934 /* Callbacks */
935 PyObject *is_websocket_none_py;
936 PyObject *client_core_py;
937 /* Metrics */
938 PyObject *is_metrics_enabled_py; /* optional enable metrics */
939 PyObject *metrics_py; /* optional AWSIoTMetrics object */
940
941 if (!PyArg_ParseTuple(
942 args,
943 "Os#IOOOOz#Oz#z#OOOOOOOOOz*Oz#OOOz#z*z#OOOOOOOOOOOOOOOO",
944 /* O */ &self_py,
945 /* s */ &host_name.ptr,
946 /* # */ &host_name.len,
947 /* I */ &port,
948 /* O */ &bootstrap_py,
949 /* O */ &socket_options_py,
950 /* O */ &tls_ctx_py,
951 /* O */ &proxy_options_py,
952
953 /* Connect Options */
954 /* z */ &client_id.ptr,
955 /* # */ &client_id.len,
956 /* O */ &keep_alive_interval_sec_py,
957 /* z */ &username.ptr,
958 /* # */ &username.len,
959 /* z */ &password.ptr,
960 /* # */ &password.len,
961 /* O */ &session_expiry_interval_sec_py,
962 /* O */ &request_response_information_py,
963 /* O */ &request_problem_information_py,
964 /* O */ &receive_maximum_py,
965 /* O */ &maximum_packet_size_py,
966 /* O */ &will_delay_interval_sec_py,
967 /* O */ &user_properties_py,
968
969 /* O */ &is_will_none_py,
970 /* O */ &will_qos_val_py,
971 /* z* */ &will_payload_stack,
972 /* O */ &will_retain_py,
973 /* z */ &will_topic.ptr,
974 /* # */ &will_topic.len,
975 /* O */ &will_payload_format_py,
976 /* O */ &will_message_expiry_interval_seconds_py,
977 /* O */ &will_topic_alias_py,
978 /* z */ &will_response_topic.ptr,
979 /* # */ &will_response_topic.len,
980 /* z* */ &will_correlation_data_stack,
981 /* z */ &will_content_type.ptr,
982 /* # */ &will_content_type.len,
983 /* O */ &will_user_properties_py,
984
985 /* O */ &session_behavior_py,
986 /* O */ &extended_validation_and_flow_control_options_py,
987 /* O */ &offline_queue_behavior_py,
988 /* O */ &retry_jitter_mode_py,
989 /* O */ &min_reconnect_delay_ms_py,
990 /* O */ &max_reconnect_delay_ms_py,
991 /* O */ &min_connected_time_to_reset_reconnect_delay_ms_py,
992 /* O */ &ping_timeout_ms_py,
993 /* O */ &connack_timeout_ms_py,
994 /* O */ &ack_timeout_seconds_py,
995 /* O */ &topic_aliasing_options_py,
996
997 /* O */ &is_websocket_none_py,
998
999 /* Metrics */
1000 /* O */ &is_metrics_enabled_py,
1001 /* O */ &metrics_py,
1002
1003 /* O */ &client_core_py)) {
1004 return NULL;
1005 }
1006
1007 struct aws_allocator *allocator = aws_py_get_allocator();
1008
1009 struct mqtt5_client_binding *client = aws_mem_calloc(allocator, 1, sizeof(struct mqtt5_client_binding));
1010 // Python object that wraps a c struct and a function to call when its reference goes to zero
1011 PyObject *capsule = PyCapsule_New(client, s_capsule_name_mqtt5_client, s_mqtt5_python_client_destructor);
1012 if (!capsule) {
1013 aws_mem_release(allocator, client);
1014 return NULL;
1015 }
1016
1017 /* From hereon, we need to clean up if errors occur */
1018 struct aws_tls_connection_options tls_options;
1019 AWS_ZERO_STRUCT(tls_options);
1020 struct aws_mqtt5_user_property *user_properties_tmp = NULL;
1021 struct aws_mqtt5_user_property *will_user_properties_tmp = NULL;
1022 struct aws_mqtt_iot_metrics metrics_tmp;
1023 AWS_ZERO_STRUCT(metrics_tmp);
1024
1025 struct aws_mqtt5_client_options client_options;
1026 AWS_ZERO_STRUCT(client_options);
1027
1028 struct aws_mqtt5_packet_connect_view connect_options;
1029 AWS_ZERO_STRUCT(connect_options);
1030
1031 struct aws_mqtt5_packet_publish_view will_options;
1032 AWS_ZERO_STRUCT(will_options);
1033
1034 struct aws_http_proxy_options proxy_options;
1035 struct aws_mqtt5_client_topic_alias_options topic_aliasing_options;
1036
1037 struct aws_tls_ctx *tls_ctx = NULL;
1038
1039 client_options.connect_options = &connect_options;
1040
1041 client_options.host_name = host_name;
1042
1043 /* port should default similar to existing ones based on protocol unless overridden by user */
1044 client_options.port = port;
1045
1046 struct aws_client_bootstrap *bootstrap = aws_py_get_client_bootstrap(bootstrap_py);
1047 if (!bootstrap) {
1048 goto done;
1049 }
1050 client_options.bootstrap = bootstrap;
1051
1052 struct aws_socket_options socket_options;
1053 if (!aws_py_socket_options_init(&socket_options, socket_options_py)) {
1054 goto done;
1055 }
1056 client_options.socket_options = &socket_options;
1057
1058 if (proxy_options_py != Py_None) {
1059 if (!aws_py_http_proxy_options_init(&proxy_options, proxy_options_py)) {
1060 goto done;
1061 }
1062 client_options.http_proxy_options = &proxy_options;
1063 }
1064
1065 if (tls_ctx_py != Py_None) {
1066 tls_ctx = aws_py_get_tls_ctx(tls_ctx_py);
1067 if (!tls_ctx) {
1068 goto done;
1069 }
1070
1071 aws_tls_connection_options_init_from_ctx(&tls_options, tls_ctx);
1072 client_options.tls_options = &tls_options;
1073 }
1074
1075 int session_behavior_tmp = 0;
1076 if (PyObject_GetAsOptionalIntEnum(
1077 session_behavior_py,
1078 AWS_PYOBJECT_KEY_CLIENT_OPTIONS,
1079 AWS_PYOBJECT_KEY_SESSION_BEHAVIOR,
1080 &session_behavior_tmp)) {
1081 client_options.session_behavior = (enum aws_mqtt5_client_session_behavior_type)session_behavior_tmp;
1082 }
1083 if (PyErr_Occurred()) {
1084 goto done;
1085 }
1086
1087 int extended_validation_and_flow_control_options_tmp = 0;
1088 if (PyObject_GetAsOptionalIntEnum(
1089 extended_validation_and_flow_control_options_py,
1090 AWS_PYOBJECT_KEY_CLIENT_OPTIONS,
1091 AWS_PYOBJECT_KEY_EXTENDED_VALIDATION_AND_FLOW_CONTROL,
1092 &extended_validation_and_flow_control_options_tmp)) {
1093 client_options.extended_validation_and_flow_control_options =
1094 (enum aws_mqtt5_extended_validation_and_flow_control_options)
1095 extended_validation_and_flow_control_options_tmp;
1096 }
1097 if (PyErr_Occurred()) {
1098 goto done;
1099 }
1100
1101 int offline_queue_behavior_tmp = 0;
1102 if (PyObject_GetAsOptionalIntEnum(
1103 offline_queue_behavior_py,
1104 AWS_PYOBJECT_KEY_CLIENT_OPTIONS,
1105 AWS_PYOBJECT_KEY_OFFLINE_QUEUE_BEHAVIOR,
1106 &offline_queue_behavior_tmp)) {
1107 client_options.offline_queue_behavior =
1108 (enum aws_mqtt5_client_operation_queue_behavior_type)offline_queue_behavior_tmp;
1109 }
1110 if (PyErr_Occurred()) {
1111 goto done;
1112 }
1113
1114 int retry_jitter_mode_tmp = 0;
1115 if (PyObject_GetAsOptionalIntEnum(
1116 retry_jitter_mode_py,
1117 AWS_PYOBJECT_KEY_CLIENT_OPTIONS,
1118 AWS_PYOBJECT_KEY_RETRY_JITTER_MODE,
1119 &retry_jitter_mode_tmp)) {
1120 client_options.retry_jitter_mode = (enum aws_exponential_backoff_jitter_mode)retry_jitter_mode_tmp;
1121 }
1122 if (PyErr_Occurred()) {
1123 goto done;
1124 }
1125
1126 uint64_t min_reconnect_delay_ms_tmp = 0;
1127 if (PyObject_GetAsOptionalUint64(
1128 min_reconnect_delay_ms_py,
1129 AWS_PYOBJECT_KEY_CLIENT_OPTIONS,
1130 AWS_PYOBJECT_KEY_MIN_RECONNECT_DELAY_MS,
1131 &min_reconnect_delay_ms_tmp)) {
1132 client_options.min_reconnect_delay_ms = min_reconnect_delay_ms_tmp;
1133 }
1134 if (PyErr_Occurred()) {
1135 goto done;
1136 }
1137
1138 uint64_t max_reconnect_delay_ms_tmp = 0;
1139 if (PyObject_GetAsOptionalUint64(
1140 max_reconnect_delay_ms_py,
1141 AWS_PYOBJECT_KEY_CLIENT_OPTIONS,
1142 AWS_PYOBJECT_KEY_MAX_RECONNECT_DELAY_MS,
1143 &max_reconnect_delay_ms_tmp)) {
1144 client_options.max_reconnect_delay_ms = max_reconnect_delay_ms_tmp;
1145 }
1146 if (PyErr_Occurred()) {
1147 goto done;
1148 }
1149
1150 uint64_t min_connected_time_to_reset_reconnect_delay_ms_tmp = 0;
1151 if (PyObject_GetAsOptionalUint64(
1152 min_connected_time_to_reset_reconnect_delay_ms_py,
1153 AWS_PYOBJECT_KEY_CLIENT_OPTIONS,
1154 AWS_PYOBJECT_KEY_MIN_CONNECTED_TIME_TO_RESET_RECONNECT_DELAY_MS,
1155 &min_connected_time_to_reset_reconnect_delay_ms_tmp)) {
1156 client_options.min_reconnect_delay_ms = min_connected_time_to_reset_reconnect_delay_ms_tmp;
1157 }
1158 if (PyErr_Occurred()) {
1159 goto done;
1160 }
1161
1162 uint32_t ping_timeout_ms_tmp = 0;
1163 if (PyObject_GetAsOptionalUint32(
1164 ping_timeout_ms_py,
1165 AWS_PYOBJECT_KEY_CLIENT_OPTIONS,
1166 AWS_PYOBJECT_KEY_PING_TIMEOUT_MS,
1167 &ping_timeout_ms_tmp)) {
1168 client_options.ping_timeout_ms = ping_timeout_ms_tmp;
1169 }
1170 if (PyErr_Occurred()) {
1171 goto done;
1172 }
1173
1174 uint32_t connack_timeout_ms_tmp = 0;
1175 if (PyObject_GetAsOptionalUint32(
1176 connack_timeout_ms_py,
1177 AWS_PYOBJECT_KEY_CLIENT_OPTIONS,
1178 AWS_PYOBJECT_KEY_CONNACK_TIMEOUT_MS,
1179 &connack_timeout_ms_tmp)) {
1180 client_options.connack_timeout_ms = connack_timeout_ms_tmp;
1181 }
1182 if (PyErr_Occurred()) {
1183 goto done;
1184 }
1185
1186 uint32_t ack_timeout_seconds_tmp = 0;
1187 if (PyObject_GetAsOptionalUint32(
1188 ack_timeout_seconds_py,
1189 AWS_PYOBJECT_KEY_CLIENT_OPTIONS,
1190 AWS_PYOBJECT_KEY_ACK_TIMEOUT_SECONDS,
1191 &ack_timeout_seconds_tmp)) {
1192 client_options.ack_timeout_seconds = ack_timeout_seconds_tmp;
1193 }
1194 if (PyErr_Occurred()) {
1195 goto done;
1196 }
1197
1198 if (topic_aliasing_options_py != Py_None) {
1199 if (!s_py_topic_aliasing_options_init(&topic_aliasing_options, topic_aliasing_options_py)) {
1200 goto done;
1201 }
1202 client_options.topic_aliasing_options = &topic_aliasing_options;
1203 }
1204
1205 /* CONNECT OPTIONS */
1206
1207 connect_options.client_id = client_id;
1208
1209 /* defaults to KEEP_ALIVE_INTERVAL_SECONDS unless specified by user */
1210 uint16_t keep_alive_interval_sec_tmp = 0;
1211 uint16_t *keep_alive_interval_sec_ptr = PyObject_GetAsOptionalUint16(
1212 keep_alive_interval_sec_py,
1213 AWS_PYOBJECT_KEY_CONNECT_PACKET,
1214 AWS_PYOBJECT_KEY_KEEP_ALIVE_INTERVAL_SEC,
1215 &keep_alive_interval_sec_tmp);
1216 if (PyErr_Occurred()) {
1217 goto done;
1218 }
1219 if (keep_alive_interval_sec_ptr) {
1220 connect_options.keep_alive_interval_seconds = keep_alive_interval_sec_tmp;
1221 } else {
1222 connect_options.keep_alive_interval_seconds = KEEP_ALIVE_INTERVAL_SECONDS;
1223 }
1224
1225 if (username.ptr != NULL) {
1226 connect_options.username = &username;
1227 }
1228
1229 if (password.ptr != NULL) {
1230 connect_options.password = &password;
1231 }
1232
1233 uint32_t session_expiry_interval_sec_tmp = 0;
1234 connect_options.session_expiry_interval_seconds = PyObject_GetAsOptionalUint32(
1235 session_expiry_interval_sec_py,
1236 AWS_PYOBJECT_KEY_CONNECT_PACKET,
1237 AWS_PYOBJECT_KEY_SESSION_EXPIRY_INTERVAL_SEC,
1238 &session_expiry_interval_sec_tmp);
1239 if (PyErr_Occurred()) {
1240 goto done;
1241 }
1242
1243 bool request_response_information_py_tmp = false;
1244 uint8_t request_response_information_py_tmp_int = 0;
1245 if (PyObject_GetAsOptionalBool(
1246 request_response_information_py,
1247 AWS_PYOBJECT_KEY_CONNECT_PACKET,
1248 AWS_PYOBJECT_KEY_REQUEST_RESPONSE_INFORMATION,
1249 &request_response_information_py_tmp) != NULL) {
1250 request_response_information_py_tmp_int = request_response_information_py_tmp;
1251 connect_options.request_response_information = &request_response_information_py_tmp_int;
1252 }
1253 if (PyErr_Occurred()) {
1254 goto done;
1255 }
1256
1257 bool request_problem_information_tmp = false;
1258 uint8_t request_problem_information_tmp_int = 0;
1259 if (PyObject_GetAsOptionalBool(
1260 request_problem_information_py,
1261 AWS_PYOBJECT_KEY_CONNECT_PACKET,
1262 AWS_PYOBJECT_KEY_REQUEST_PROBLEM_INFORMATION,
1263 &request_problem_information_tmp) != NULL) {
1264 request_problem_information_tmp_int = request_problem_information_tmp;
1265 connect_options.request_problem_information = &request_problem_information_tmp_int;
1266 }
1267 if (PyErr_Occurred()) {
1268 goto done;
1269 }
1270
1271 uint16_t receive_maximum_tmp = 0;
1272 connect_options.receive_maximum = PyObject_GetAsOptionalUint16(
1273 receive_maximum_py, AWS_PYOBJECT_KEY_CONNECT_PACKET, AWS_PYOBJECT_KEY_RECEIVE_MAXIMUM, &receive_maximum_tmp);
1274 if (PyErr_Occurred()) {
1275 goto done;
1276 }
1277
1278 uint32_t maximum_packet_size_tmp = 0;
1279 connect_options.maximum_packet_size_bytes = PyObject_GetAsOptionalUint32(
1280 maximum_packet_size_py,
1281 AWS_PYOBJECT_KEY_CONNECT_PACKET,
1282 AWS_PYOBJECT_KEY_MAXIMUM_PACKET_SIZE,
1283 &maximum_packet_size_tmp);
1284 if (PyErr_Occurred()) {
1285 goto done;
1286 }
1287
1288 uint32_t will_delay_interval_sec_tmp = 0;
1289 connect_options.will_delay_interval_seconds = PyObject_GetAsOptionalUint32(
1290 will_delay_interval_sec_py,
1291 AWS_PYOBJECT_KEY_CONNECT_PACKET,
1292 AWS_PYOBJECT_KEY_WILL_DELAY_INTERVAL,
1293 &will_delay_interval_sec_tmp);
1294 if (PyErr_Occurred()) {
1295 goto done;
1296 }
1297
1298 user_properties_tmp =
1299 aws_get_optional_user_properties_from_PyObject(user_properties_py, &connect_options.user_property_count);
1300 if (PyErr_Occurred()) {
1301 goto done;
1302 }
1303 connect_options.user_properties = user_properties_tmp;
1304
1305 /* WILL */
1306
1307 struct aws_mqtt5_packet_publish_view will;
1308 AWS_ZERO_STRUCT(will);
1309
1310 int will_payload_format_tmp = 0;
1311 enum aws_mqtt5_payload_format_indicator will_payload_format_enum_tmp = 0;
1312 uint32_t will_message_expiry_interval_seconds_tmp = 0;
1313 struct aws_byte_cursor will_correlation_data_tmp;
1314 if (!PyObject_IsTrue(is_will_none_py)) {
1315 will.qos = PyObject_GetIntEnum(will_qos_val_py, AWS_PYOBJECT_KEY_QOS);
1316 if (PyErr_Occurred()) {
1317 goto done;
1318 }
1319 will.payload = aws_byte_cursor_from_array(will_payload_stack.buf, will_payload_stack.len);
1320 will.retain = PyObject_IsTrue(will_retain_py);
1321 will.topic = will_topic;
1322 if (PyObject_GetAsOptionalIntEnum(
1323 will_payload_format_py,
1324 AWS_PYOBJECT_KEY_WILL_PACKET,
1325 AWS_PYOBJECT_KEY_PAYLOAD_FORMAT_INDICATOR,
1326 &will_payload_format_tmp)) {
1327 will_payload_format_enum_tmp = (enum aws_mqtt5_payload_format_indicator)will_payload_format_tmp;
1328 will.payload_format = &will_payload_format_enum_tmp;
1329 }
1330 if (PyErr_Occurred()) {
1331 goto done;
1332 }
1333
1334 will.message_expiry_interval_seconds = PyObject_GetAsOptionalUint32(
1335 will_message_expiry_interval_seconds_py,
1336 AWS_PYOBJECT_KEY_WILL_PACKET,
1337 AWS_PYOBJECT_KEY_MESSAGE_EXPIRY_INTERVAL_SEC,
1338 &will_message_expiry_interval_seconds_tmp);
1339 if (PyErr_Occurred()) {
1340 goto done;
1341 }
1342
1343 if (will_response_topic.ptr) {
1344 will.response_topic = &will_response_topic;
1345 }
1346
1347 if (will_correlation_data_stack.buf) {
1348 will_correlation_data_tmp =
1349 aws_byte_cursor_from_array(will_correlation_data_stack.buf, will_correlation_data_stack.len);
1350 will.correlation_data = &will_correlation_data_tmp;
1351 }
1352
1353 if (will_content_type.ptr) {
1354 will.content_type = &will_content_type;
1355 }
1356
1357 will_user_properties_tmp =
1358 aws_get_optional_user_properties_from_PyObject(will_user_properties_py, &will.user_property_count);
1359 if (PyErr_Occurred()) {
1360 goto done;
1361 }
1362 will.user_properties = will_user_properties_tmp;
1363
1364 connect_options.will = &will;
1365 }
1366
1367 /* METRICS */
1368 if (PyObject_IsTrue(is_metrics_enabled_py) && metrics_py != Py_None) {
1369 if (!aws_py_metrics_parse(metrics_py, &metrics_tmp)) {
1370 goto done;
1371 }
1372 client_options.metrics = &metrics_tmp;
1373 }
1374
1375 /* CALLBACKS */
1376
1377 Py_INCREF(client_core_py);
1378 client->client_core = client_core_py;
1379
1380 /* websocket */
1381 if (!PyObject_IsTrue(is_websocket_none_py)) {
1382 client_options.websocket_handshake_transform = s_ws_handshake_transform;
1383 client_options.websocket_handshake_transform_user_data = client;
1384 }
1385
1386 /* publish */
1387 client_options.publish_received_handler = s_on_publish_received;
1388 client_options.publish_received_handler_user_data = client;
1389
1390 /* lifecycle events*/
1391 client_options.lifecycle_event_handler = s_lifecycle_event_callback;
1392 client_options.lifecycle_event_handler_user_data = client;
1393
1394 /* termination */
1395 client_options.client_termination_handler = s_mqtt5_client_on_terminate;
1396 client_options.client_termination_handler_user_data = client;
1397
1398 /* set up the new mqtt5 client */
1399 client->native = aws_mqtt5_client_new(allocator, &client_options);
1400 if (client->native == NULL) {
1401 PyErr_SetAwsLastError();
1402 goto done;
1403 }
1404
1405 success = true;
1406
1407 done:
1408 aws_tls_connection_options_clean_up(&tls_options);
1409 if (user_properties_tmp) {
1410 aws_mem_release(aws_py_get_allocator(), user_properties_tmp);
1411 }
1412 if (will_user_properties_tmp) {
1413 aws_mem_release(aws_py_get_allocator(), will_user_properties_tmp);
1414 }
1415 PyBuffer_Release(&will_payload_stack);
1416 PyBuffer_Release(&will_correlation_data_stack);
1417
1418 /* Cleanup metrics */
1419 aws_py_metrics_clean_up(&metrics_tmp);
1420
1421 if (success) {
1422 return capsule;
1423 }
1424 Py_XDECREF(capsule);
1425
1426 return NULL;
1427 }
1428
1429 struct aws_mqtt5_client *aws_py_get_mqtt5_client(PyObject *mqtt5_client) {
1430 AWS_PY_RETURN_NATIVE_FROM_BINDING(mqtt5_client, s_capsule_name_mqtt5_client, "Client", mqtt5_client_binding);
1431 }
1432
1433 /*******************************************************************************
1434 * Start
1435 ******************************************************************************/
1436
1437 PyObject *aws_py_mqtt5_client_start(PyObject *self, PyObject *args) {
1438 (void)self;
1439 bool success = false;
1440
1441 PyObject *impl_capsule;
1442
1443 if (!PyArg_ParseTuple(args, "O", &impl_capsule)) {
1444 return NULL;
1445 }
1446
1447 struct mqtt5_client_binding *client = PyCapsule_GetPointer(impl_capsule, s_capsule_name_mqtt5_client);
1448 if (!client) {
1449 goto done;
1450 }
1451
1452 if (aws_mqtt5_client_start(client->native)) {
1453 PyErr_SetAwsLastError();
1454 goto done;
1455 }
1456 success = true;
1457
1458 done:
1459 if (success) {
1460 Py_RETURN_NONE;
1461 }
1462 return NULL;
1463 }
1464
1465 /*******************************************************************************
1466 * Stop
1467 ******************************************************************************/
1468
1469 PyObject *aws_py_mqtt5_client_stop(PyObject *self, PyObject *args) {
1470 (void)self;
1471 bool success = false;
1472
1473 PyObject *impl_capsule;
1474
1475 PyObject *is_disconnect_packet_none_py;
1476 PyObject *reason_code_py;
1477 PyObject *session_expiry_interval_sec_py; /* optional uint32_t */
1478 struct aws_byte_cursor reason_string; /* optional */
1479 PyObject *user_properties_py; /* optional */
1480 struct aws_byte_cursor server_reference; /* optional */
1481
1482 if (!PyArg_ParseTuple(
1483 args,
1484 "OOOOz#Oz#",
1485 /* O */ &impl_capsule,
1486 /* O */ &is_disconnect_packet_none_py,
1487 /* O */ &reason_code_py,
1488 /* O */ &session_expiry_interval_sec_py,
1489 /* z */ &reason_string.ptr,
1490 /* # */ &reason_string.len,
1491 /* O */ &user_properties_py,
1492 /* z */ &server_reference.ptr,
1493 /* # */ &server_reference.len)) {
1494 return NULL;
1495 }
1496
1497 struct mqtt5_client_binding *client = PyCapsule_GetPointer(impl_capsule, s_capsule_name_mqtt5_client);
1498 if (!client) {
1499 return NULL;
1500 }
1501 struct aws_mqtt5_user_property *user_properties_tmp = NULL;
1502
1503 /* stop can be called with a NULL disconnect_view */
1504 if (PyObject_IsTrue(is_disconnect_packet_none_py)) {
1505 if (aws_mqtt5_client_stop(client->native, NULL, NULL)) {
1506 PyErr_SetAwsLastError();
1507 goto done;
1508 }
1509 success = true;
1510 goto done;
1511 }
1512
1513 struct aws_mqtt5_packet_disconnect_view disconnect_view;
1514 AWS_ZERO_STRUCT(disconnect_view);
1515
1516 /* Fill out disconnect_view */
1517 disconnect_view.reason_code = PyObject_GetIntEnum(reason_code_py, AWS_PYOBJECT_KEY_REASON_CODE);
1518 if (PyErr_Occurred()) {
1519 goto done;
1520 }
1521
1522 uint32_t session_expiry_interval_sec_tmp = 0;
1523 disconnect_view.session_expiry_interval_seconds = PyObject_GetAsOptionalUint32(
1524 session_expiry_interval_sec_py,
1525 AWS_PYOBJECT_KEY_DISCONNECT_PACKET,
1526 AWS_PYOBJECT_KEY_SESSION_EXPIRY_INTERVAL_SEC,
1527 &session_expiry_interval_sec_tmp);
1528 if (PyErr_Occurred()) {
1529 goto done;
1530 }
1531
1532 if (reason_string.ptr != NULL) {
1533 disconnect_view.reason_string = &reason_string;
1534 }
1535
1536 user_properties_tmp =
1537 aws_get_optional_user_properties_from_PyObject(user_properties_py, &disconnect_view.user_property_count);
1538 if (PyErr_Occurred()) {
1539 goto done;
1540 }
1541 disconnect_view.user_properties = user_properties_tmp;
1542
1543 if (server_reference.ptr != NULL) {
1544 disconnect_view.server_reference = &server_reference;
1545 }
1546
1547 if (aws_mqtt5_client_stop(client->native, &disconnect_view, NULL)) {
1548 PyErr_SetAwsLastError();
1549 goto done;
1550 }
1551
1552 success = true;
1553 goto done;
1554
1555 done:
1556 if (user_properties_tmp) {
1557 aws_mem_release(aws_py_get_allocator(), user_properties_tmp);
1558 }
1559
1560 if (success) {
1561 Py_RETURN_NONE;
1562 }
1563 return NULL;
1564 }
1565
1566 /*******************************************************************************
1567 * Publish
1568 ******************************************************************************/
1569
1570 struct publish_complete_userdata {
1571 PyObject *callback;
1572 enum aws_mqtt5_qos qos;
1573 };
1574
1575 static void s_on_publish_complete_fn(
1576 enum aws_mqtt5_packet_type packet_type,
1577 const void *packet,
1578 int error_code,
1579 void *complete_ctx) {
1580 struct publish_complete_userdata *metadata = complete_ctx;
1581 assert(metadata);
1582
1583 PyGILState_STATE state;
1584 if (aws_py_gilstate_ensure(&state)) {
1585 return; /* Python has shut down. Nothing matters anymore, but don't crash */
1586 }
1587
1588 /* These must be DECREF'd when function ends */
1589 PyObject *user_properties_list = NULL;
1590 PyObject *result = NULL;
1591
1592 const struct aws_mqtt5_packet_puback_view *puback = NULL;
1593 enum aws_mqtt5_puback_reason_code reason_code = 0;
1594 const struct aws_byte_cursor *reason_string = NULL;
1595 size_t user_property_count = 0;
1596
1597 if (packet_type == AWS_MQTT5_PT_PUBACK) {
1598 if (packet != NULL) {
1599 puback = packet;
1600 reason_code = puback->reason_code;
1601 reason_string = puback->reason_string;
1602 user_property_count = puback->user_property_count;
1603
1604 user_properties_list = s_aws_set_user_properties_to_PyObject(puback->user_properties, user_property_count);
1605 if (PyErr_Occurred()) {
1606 PyErr_WriteUnraisable(PyErr_Occurred());
1607 goto cleanup;
1608 }
1609 }
1610 }
1611
1612 result = PyObject_CallFunction(
1613 metadata->callback,
1614 "(iiis#O)",
1615 /* i */ (int)error_code,
1616 /* i */ (int)metadata->qos,
1617 /* i */ (int)reason_code,
1618 /* s */ reason_string ? reason_string->ptr : NULL,
1619 /* # */ reason_string ? reason_string->len : 0,
1620 /* O */ (user_property_count > 0 && !error_code) ? user_properties_list : Py_None);
1621 if (!result) {
1622 PyErr_WriteUnraisable(PyErr_Occurred());
1623 }
1624 cleanup:
1625 Py_XDECREF(metadata->callback);
1626 Py_XDECREF(user_properties_list);
1627 Py_XDECREF(result);
1628
1629 PyGILState_Release(state);
1630
1631 aws_mem_release(aws_py_get_allocator(), metadata);
1632 }
1633
1634 PyObject *aws_py_mqtt5_client_publish(PyObject *self, PyObject *args) {
1635 (void)self;
1636 bool success = false;
1637
1638 PyObject *impl_capsule;
1639
1640 PyObject *qos_val_py;
1641 Py_buffer payload_stack; /* Py_buffers must be released after successful PyArg_ParseTuple() calls */
1642 PyObject *retain_py;
1643 struct aws_byte_cursor topic;
1644 PyObject *payload_format_py; /* optional enum */
1645 PyObject *message_expiry_interval_seconds_py; /* optional uint32_t */
1646 PyObject *topic_alias_py; /* optional uint16_t */
1647 struct aws_byte_cursor response_topic; /* optional */
1648 Py_buffer correlation_data_stack; /* optional */
1649 struct aws_byte_cursor content_type; /* optional */
1650 PyObject *user_properties_py; /* optional */
1651 PyObject *puback_callback_fn_py;
1652
1653 if (!PyArg_ParseTuple(
1654 args,
1655 "OOz*Oz#OOOz#z*z#OO",
1656 /* O */ &impl_capsule,
1657 /* O */ &qos_val_py,
1658 /* z* */ &payload_stack,
1659 /* O */ &retain_py,
1660 /* z */ &topic.ptr,
1661 /* # */ &topic.len,
1662 /* O */ &payload_format_py,
1663 /* O */ &message_expiry_interval_seconds_py,
1664 /* O */ &topic_alias_py,
1665 /* z */ &response_topic.ptr,
1666 /* # */ &response_topic.len,
1667 /* z* */ &correlation_data_stack,
1668 /* z */ &content_type.ptr,
1669 /* # */ &content_type.len,
1670 /* O */ &user_properties_py,
1671 /* O */ &puback_callback_fn_py)) {
1672 return NULL;
1673 }
1674
1675 /* from hereon, we need to clean up if errors occur */
1676 struct aws_mqtt5_user_property *user_properties_tmp = NULL;
1677
1678 struct mqtt5_client_binding *client = PyCapsule_GetPointer(impl_capsule, s_capsule_name_mqtt5_client);
1679 if (!client) {
1680 goto done;
1681 }
1682
1683 struct aws_mqtt5_packet_publish_view publish_view;
1684 AWS_ZERO_STRUCT(publish_view);
1685
1686 publish_view.qos = PyObject_GetIntEnum(qos_val_py, AWS_PYOBJECT_KEY_QOS);
1687 if (PyErr_Occurred()) {
1688 goto done;
1689 }
1690
1691 publish_view.payload = aws_byte_cursor_from_array(payload_stack.buf, payload_stack.len);
1692
1693 publish_view.retain = PyObject_IsTrue(retain_py);
1694
1695 publish_view.topic = topic;
1696
1697 int payload_format_tmp = 0;
1698 enum aws_mqtt5_payload_format_indicator payload_format_enum_tmp;
1699 if (PyObject_GetAsOptionalIntEnum(
1700 payload_format_py,
1701 AWS_PYOBJECT_KEY_PUBLISH_PACKET,
1702 AWS_PYOBJECT_KEY_PAYLOAD_FORMAT_INDICATOR,
1703 &payload_format_tmp)) {
1704 payload_format_enum_tmp = (enum aws_mqtt5_payload_format_indicator)payload_format_tmp;
1705 publish_view.payload_format = &payload_format_enum_tmp;
1706 }
1707 if (PyErr_Occurred()) {
1708 goto done;
1709 }
1710
1711 uint32_t message_expiry_interval_seconds_tmp = 0;
1712 publish_view.message_expiry_interval_seconds = PyObject_GetAsOptionalUint32(
1713 message_expiry_interval_seconds_py,
1714 AWS_PYOBJECT_KEY_PUBLISH_PACKET,
1715 AWS_PYOBJECT_KEY_MESSAGE_EXPIRY_INTERVAL_SEC,
1716 &message_expiry_interval_seconds_tmp);
1717 if (PyErr_Occurred()) {
1718 goto done;
1719 }
1720
1721 uint16_t topic_alias_tmp = 0;
1722 publish_view.topic_alias = PyObject_GetAsOptionalUint16(
1723 topic_alias_py, AWS_PYOBJECT_KEY_PUBLISH_PACKET, AWS_PYOBJECT_KEY_TOPIC_ALIAS, &topic_alias_tmp);
1724 if (PyErr_Occurred()) {
1725 goto done;
1726 }
1727
1728 if (response_topic.ptr) {
1729 publish_view.response_topic = &response_topic;
1730 }
1731
1732 struct aws_byte_cursor correlation_data_tmp;
1733 if (correlation_data_stack.buf) {
1734 correlation_data_tmp = aws_byte_cursor_from_array(correlation_data_stack.buf, correlation_data_stack.len);
1735 publish_view.correlation_data = &correlation_data_tmp;
1736 }
1737
1738 if (content_type.ptr) {
1739 publish_view.content_type = &content_type;
1740 }
1741
1742 user_properties_tmp =
1743 aws_get_optional_user_properties_from_PyObject(user_properties_py, &publish_view.user_property_count);
1744 if (PyErr_Occurred()) {
1745 goto done;
1746 }
1747 publish_view.user_properties = user_properties_tmp;
1748
1749 struct publish_complete_userdata *metadata = NULL;
1750 /* callback related must be cleaned up after this point */
1751 metadata = aws_mem_calloc(aws_py_get_allocator(), 1, sizeof(struct publish_complete_userdata));
1752
1753 metadata->callback = puback_callback_fn_py;
1754 metadata->qos = PyObject_GetIntEnum(qos_val_py, AWS_PYOBJECT_KEY_QOS);
1755 Py_INCREF(metadata->callback);
1756
1757 struct aws_mqtt5_publish_completion_options publish_completion_options = {
1758 .completion_callback = &s_on_publish_complete_fn, .completion_user_data = metadata};
1759
1760 if (aws_mqtt5_client_publish(client->native, &publish_view, &publish_completion_options)) {
1761 PyErr_SetAwsLastError();
1762 goto publish_failed;
1763 }
1764
1765 success = true;
1766 goto done;
1767
1768 publish_failed:
1769 Py_XDECREF(puback_callback_fn_py);
1770 aws_mem_release(aws_py_get_allocator(), metadata);
1771
1772 done:
1773 if (user_properties_tmp) {
1774 aws_mem_release(aws_py_get_allocator(), user_properties_tmp);
1775 }
1776 PyBuffer_Release(&payload_stack);
1777 PyBuffer_Release(&correlation_data_stack);
1778 if (success) {
1779 Py_RETURN_NONE;
1780 }
1781 return NULL;
1782 }
1783
1784 /*******************************************************************************
1785 * Invoke Publish Acknowledgement
1786 ******************************************************************************/
1787
1788 PyObject *aws_py_mqtt5_client_invoke_publish_acknowledgement(PyObject *self, PyObject *args) {
1789 (void)self;
1790 bool success = true;
1791
1792 PyObject *impl_capsule;
1793 unsigned long long control_id_ull = 0;
1794
1795 if (!PyArg_ParseTuple(
1796 args,
1797 "OK",
1798 /* O */ &impl_capsule,
1799 /* K */ &control_id_ull)) {
1800 return NULL;
1801 }
1802
1803 struct mqtt5_client_binding *client = PyCapsule_GetPointer(impl_capsule, s_capsule_name_mqtt5_client);
1804 if (!client) {
1805 return NULL;
1806 }
1807
1808 if (aws_mqtt5_client_invoke_publish_acknowledgement(client->native, (uint64_t)control_id_ull, NULL)) {
1809 PyErr_SetAwsLastError();
1810 success = false;
1811 }
1812
1813 if (success) {
1814 Py_RETURN_NONE;
1815 }
1816 return NULL;
1817 }
1818
1819 /*******************************************************************************
1820 * Subscribe
1821 ******************************************************************************/
1822
1823 struct subscribe_complete_userdata {
1824 PyObject *callback;
1825 };
1826
1827 static void s_on_subscribe_complete_fn(
1828 const struct aws_mqtt5_packet_suback_view *suback,
1829 int error_code,
1830 void *complete_ctx) {
1831 struct subscribe_complete_userdata *metadata = complete_ctx;
1832 assert(metadata);
1833
1834 PyGILState_STATE state;
1835 if (aws_py_gilstate_ensure(&state)) {
1836 return; /* Python has shut down. Nothing matters anymore, but don't crash */
1837 }
1838
1839 /* These must be DECREF'd when function ends */
1840 PyObject *result = NULL;
1841 PyObject *reason_codes_list = NULL;
1842 PyObject *user_properties_list = NULL;
1843 size_t user_property_count = 0;
1844 size_t reason_codes_count = 0;
1845
1846 if (suback != NULL) {
1847 user_property_count = suback->user_property_count;
1848 reason_codes_count = suback->reason_code_count;
1849
1850 user_properties_list = s_aws_set_user_properties_to_PyObject(suback->user_properties, user_property_count);
1851 if (PyErr_Occurred()) {
1852 PyErr_WriteUnraisable(PyErr_Occurred());
1853 goto cleanup;
1854 }
1855
1856 /* Create list of (reason_code) tuples */
1857 reason_codes_list = PyList_New(reason_codes_count);
1858 if (!reason_codes_list) {
1859 PyErr_WriteUnraisable(PyErr_Occurred());
1860 goto cleanup;
1861 }
1862
1863 for (size_t i = 0; i < reason_codes_count; ++i) {
1864 PyList_SetItem(reason_codes_list, i, PyLong_FromLong(suback->reason_codes[i])); /* Steals a reference */
1865 }
1866 }
1867
1868 result = PyObject_CallFunction(
1869 metadata->callback,
1870 "(iOs#O)",
1871 /* i */ (int)error_code,
1872 /* O */ (reason_codes_count > 0 && !error_code) ? reason_codes_list : Py_None,
1873 /* s */ (suback && suback->reason_string) ? suback->reason_string->ptr : NULL,
1874 /* # */ (suback && suback->reason_string) ? suback->reason_string->len : 0,
1875 /* O */ (user_property_count > 0 && !error_code) ? user_properties_list : Py_None);
1876 if (!result) {
1877 PyErr_WriteUnraisable(PyErr_Occurred());
1878 }
1879 cleanup:
1880 Py_XDECREF(metadata->callback);
1881 Py_XDECREF(user_properties_list);
1882 Py_XDECREF(reason_codes_list);
1883 Py_XDECREF(result);
1884
1885 PyGILState_Release(state);
1886
1887 aws_mem_release(aws_py_get_allocator(), metadata);
1888 }
1889
1890 /* Populates subscription_view_out from a PyObject user property.
1891 * PyErr_Occurred() must be called to check if anything went wrong after using this function. */
1892 void aws_init_subscription_from_PyObject(PyObject *o, struct aws_mqtt5_subscription_view *subscription_view_out) {
1893
1894 PyObject *attr_topic_filter = PyObject_GetAttrString(o, AWS_PYOBJECT_KEY_TOPIC_FILTER);
1895 if (!attr_topic_filter) {
1896 PyErr_Format(
1897 PyExc_AttributeError,
1898 "'%s.%s' attribute not found",
1899 AWS_PYOBJECT_KEY_SUBSCRIPTION,
1900 AWS_PYOBJECT_KEY_TOPIC_FILTER);
1901 return;
1902 }
1903 subscription_view_out->topic_filter = aws_byte_cursor_from_pyunicode(attr_topic_filter);
1904 Py_XDECREF(attr_topic_filter);
1905 if (PyErr_Occurred()) {
1906 return;
1907 }
1908
1909 subscription_view_out->qos = PyObject_GetAttrAsIntEnum(o, AWS_PYOBJECT_KEY_SUBSCRIPTION, AWS_PYOBJECT_KEY_QOS);
1910 if (PyErr_Occurred()) {
1911 return;
1912 }
1913
1914 subscription_view_out->no_local =
1915 PyObject_GetAttrAsBool(o, AWS_PYOBJECT_KEY_SUBSCRIPTION, AWS_PYOBJECT_KEY_NO_LOCAL);
1916 if (PyErr_Occurred()) {
1917 return;
1918 }
1919
1920 subscription_view_out->retain_as_published =
1921 PyObject_GetAttrAsBool(o, AWS_PYOBJECT_KEY_SUBSCRIPTION, AWS_PYOBJECT_KEY_RETAIN_AS_PUBLISHED);
1922 if (PyErr_Occurred()) {
1923 return;
1924 }
1925
1926 subscription_view_out->retain_handling_type =
1927 PyObject_GetAttrAsIntEnum(o, AWS_PYOBJECT_KEY_SUBSCRIPTION, AWS_PYOBJECT_KEY_RETAIN_HANDLING_TYPE);
1928 if (PyErr_Occurred()) {
1929 return;
1930 }
1931 }
1932
1933 PyObject *aws_py_mqtt5_client_subscribe(PyObject *self, PyObject *args) {
1934 (void)self;
1935 bool success = false;
1936
1937 PyObject *impl_capsule;
1938 PyObject *subscriptions_py;
1939 PyObject *subscription_identifier_py; /* optional uint32_t */
1940 PyObject *user_properties_py; /* optional */
1941 PyObject *suback_callback_fn_py;
1942
1943 if (!PyArg_ParseTuple(
1944 args,
1945 "OOOOO",
1946 /* O */ &impl_capsule,
1947 /* O */ &subscriptions_py,
1948 /* O */ &subscription_identifier_py,
1949 /* O */ &user_properties_py,
1950 /* O */ &suback_callback_fn_py)) {
1951 return NULL;
1952 }
1953
1954 struct mqtt5_client_binding *client = PyCapsule_GetPointer(impl_capsule, s_capsule_name_mqtt5_client);
1955 if (!client) {
1956 return NULL;
1957 }
1958
1959 struct aws_mqtt5_packet_subscribe_view subscribe_view;
1960 AWS_ZERO_STRUCT(subscribe_view);
1961 struct aws_mqtt5_user_property *user_properties_tmp = NULL;
1962
1963 struct aws_array_list subscriptions_list;
1964 AWS_ZERO_STRUCT(subscriptions_list);
1965
1966 if (!PySequence_Check(subscriptions_py)) {
1967 PyErr_Format(PyExc_TypeError, "'%s' argument must be of list or tuple", AWS_PYOBJECT_KEY_SUBSCRIPTIONS);
1968 goto done;
1969 }
1970
1971 Py_ssize_t subscription_count = PySequence_Size(subscriptions_py);
1972
1973 if (aws_array_list_init_dynamic(
1974 &subscriptions_list,
1975 aws_py_get_allocator(),
1976 subscription_count,
1977 sizeof(struct aws_mqtt5_subscription_view))) {
1978 PyErr_AwsLastError();
1979 goto done;
1980 }
1981
1982 PyObject *subscription_py;
1983 for (Py_ssize_t i = 0; i < subscription_count; ++i) {
1984 struct aws_mqtt5_subscription_view subscription_out;
1985 AWS_ZERO_STRUCT(subscription_out);
1986 subscription_py = PySequence_GetItem(subscriptions_py, i);
1987 aws_init_subscription_from_PyObject(subscription_py, &subscription_out);
1988 if (PyErr_Occurred()) {
1989 Py_XDECREF(subscription_py);
1990 goto done;
1991 }
1992 aws_array_list_push_back(&subscriptions_list, &subscription_out);
1993 Py_XDECREF(subscription_py);
1994 }
1995
1996 subscribe_view.subscription_count = (size_t)subscription_count;
1997 subscribe_view.subscriptions = subscriptions_list.data;
1998
1999 uint32_t subscription_identifier_tmp = 0;
2000 subscribe_view.subscription_identifier = PyObject_GetAsOptionalUint32(
2001 subscription_identifier_py,
2002 AWS_PYOBJECT_KEY_SUBSCRIBE_PACKET,
2003 AWS_PYOBJECT_KEY_SUBSCRIPTION_IDENTIFIER,
2004 &subscription_identifier_tmp);
2005 if (PyErr_Occurred()) {
2006 goto done;
2007 }
2008
2009 user_properties_tmp =
2010 aws_get_optional_user_properties_from_PyObject(user_properties_py, &subscribe_view.user_property_count);
2011 if (PyErr_Occurred()) {
2012 goto done;
2013 }
2014 subscribe_view.user_properties = user_properties_tmp;
2015
2016 struct subscribe_complete_userdata *metadata = NULL;
2017 /* callback related must be cleaned up after this point */
2018 metadata = aws_mem_calloc(aws_py_get_allocator(), 1, sizeof(struct subscribe_complete_userdata));
2019
2020 metadata->callback = suback_callback_fn_py;
2021 Py_INCREF(metadata->callback);
2022
2023 struct aws_mqtt5_subscribe_completion_options subscribe_completion_options = {
2024 .completion_callback = &s_on_subscribe_complete_fn, .completion_user_data = metadata};
2025
2026 if (aws_mqtt5_client_subscribe(client->native, &subscribe_view, &subscribe_completion_options)) {
2027 PyErr_SetAwsLastError();
2028 goto subscribe_failed;
2029 }
2030
2031 success = true;
2032 goto done;
2033
2034 subscribe_failed:
2035 Py_XDECREF(suback_callback_fn_py);
2036 aws_mem_release(aws_py_get_allocator(), metadata);
2037
2038 done:
2039 if (user_properties_tmp) {
2040 aws_mem_release(aws_py_get_allocator(), user_properties_tmp);
2041 }
2042 aws_array_list_clean_up(&subscriptions_list);
2043 if (success) {
2044 Py_RETURN_NONE;
2045 }
2046 return NULL;
2047 }
2048
2049 /*******************************************************************************
2050 * Unsubscribe
2051 ******************************************************************************/
2052
2053 struct unsubscribe_complete_userdata {
2054 PyObject *callback;
2055 };
2056
2057 static void s_on_unsubscribe_complete_fn(
2058 const struct aws_mqtt5_packet_unsuback_view *unsuback,
2059 int error_code,
2060 void *complete_ctx) {
2061 struct unsubscribe_complete_userdata *metadata = complete_ctx;
2062 assert(metadata);
2063
2064 /* These must be DECREF'd when function ends */
2065 PyObject *result = NULL;
2066 PyObject *reason_codes_list = NULL;
2067 PyObject *user_properties_list = NULL;
2068
2069 PyGILState_STATE state;
2070 if (aws_py_gilstate_ensure(&state)) {
2071 return; /* Python has shut down. Nothing matters anymore, but don't crash */
2072 }
2073
2074 size_t user_property_count = 0;
2075 size_t reason_codes_count = 0;
2076
2077 if (unsuback != NULL) {
2078 user_property_count = unsuback->user_property_count;
2079 reason_codes_count = unsuback->reason_code_count;
2080
2081 user_properties_list = s_aws_set_user_properties_to_PyObject(unsuback->user_properties, user_property_count);
2082 if (PyErr_Occurred()) {
2083 PyErr_WriteUnraisable(PyErr_Occurred());
2084 goto cleanup;
2085 }
2086
2087 /* Create list of (reason_code) tuples */
2088 reason_codes_list = PyList_New(reason_codes_count);
2089 if (!reason_codes_list) {
2090 error_code = aws_py_translate_py_error();
2091 goto cleanup;
2092 }
2093
2094 for (size_t i = 0; i < reason_codes_count; ++i) {
2095 PyList_SetItem(reason_codes_list, i, PyLong_FromLong(unsuback->reason_codes[i])); /* Steals a reference */
2096 }
2097 }
2098
2099 result = PyObject_CallFunction(
2100 metadata->callback,
2101 "(iOs#O)",
2102 /* i */ (int)error_code,
2103 /* O */ (reason_codes_count > 0 && !error_code) ? reason_codes_list : Py_None,
2104 /* s */ (unsuback && unsuback->reason_string) ? unsuback->reason_string->ptr : NULL,
2105 /* # */ (unsuback && unsuback->reason_string) ? unsuback->reason_string->len : 0,
2106 /* O */ (user_property_count > 0 && !error_code) ? user_properties_list : Py_None);
2107 if (!result) {
2108 PyErr_WriteUnraisable(PyErr_Occurred());
2109 }
2110 cleanup:
2111 Py_XDECREF(metadata->callback);
2112 Py_XDECREF(user_properties_list);
2113 Py_XDECREF(reason_codes_list);
2114 Py_XDECREF(result);
2115
2116 PyGILState_Release(state);
2117
2118 aws_mem_release(aws_py_get_allocator(), metadata);
2119 }
2120
2121 PyObject *aws_py_mqtt5_client_unsubscribe(PyObject *self, PyObject *args) {
2122 (void)self;
2123 bool success = false;
2124
2125 PyObject *impl_capsule;
2126 PyObject *topic_filters_py;
2127 PyObject *user_properties_py; /* optional */
2128 PyObject *unsuback_callback_fn_py;
2129
2130 if (!PyArg_ParseTuple(
2131 args,
2132 "OOOO",
2133 /* O */ &impl_capsule,
2134 /* O */ &topic_filters_py,
2135 /* O */ &user_properties_py,
2136 /* O */ &unsuback_callback_fn_py)) {
2137 return NULL;
2138 }
2139
2140 struct mqtt5_client_binding *client = PyCapsule_GetPointer(impl_capsule, s_capsule_name_mqtt5_client);
2141 if (!client) {
2142 return NULL;
2143 }
2144
2145 struct aws_mqtt5_packet_unsubscribe_view unsubscribe_view;
2146 AWS_ZERO_STRUCT(unsubscribe_view);
2147 struct aws_mqtt5_user_property *user_properties_tmp = NULL;
2148
2149 struct aws_array_list topic_filters_list;
2150 AWS_ZERO_STRUCT(topic_filters_list);
2151
2152 if (!PySequence_Check(topic_filters_py)) {
2153 PyErr_Format(PyExc_TypeError, "'%s' argument must be of list or tuple", AWS_PYOBJECT_KEY_TOPIC_FILTERS);
2154 goto done;
2155 }
2156
2157 Py_ssize_t topic_filters_count = PySequence_Size(topic_filters_py);
2158
2159 if (aws_array_list_init_dynamic(
2160 &topic_filters_list, aws_py_get_allocator(), topic_filters_count, sizeof(struct aws_byte_cursor))) {
2161 PyErr_AwsLastError();
2162 goto done;
2163 }
2164
2165 PyObject *topic_filter_py;
2166 for (Py_ssize_t i = 0; i < topic_filters_count; ++i) {
2167 struct aws_byte_cursor topic_filter_to_add;
2168 AWS_ZERO_STRUCT(topic_filter_to_add);
2169 topic_filter_py = PySequence_GetItem(topic_filters_py, i);
2170 topic_filter_to_add = aws_byte_cursor_from_pyunicode(topic_filter_py);
2171 if (!topic_filter_to_add.ptr) {
2172 PyErr_Format(
2173 PyExc_TypeError,
2174 "'%s.%s' at index %zu is not a valid string",
2175 AWS_PYOBJECT_KEY_UNSUBSCRIBE_PACKET,
2176 AWS_PYOBJECT_KEY_TOPIC_FILTERS,
2177 i);
2178 Py_XDECREF(topic_filter_py);
2179 goto done;
2180 }
2181 aws_array_list_push_back(&topic_filters_list, &topic_filter_to_add);
2182 Py_XDECREF(topic_filter_py);
2183 }
2184
2185 unsubscribe_view.topic_filter_count = (size_t)topic_filters_count;
2186 unsubscribe_view.topic_filters = topic_filters_list.data;
2187
2188 user_properties_tmp =
2189 aws_get_optional_user_properties_from_PyObject(user_properties_py, &unsubscribe_view.user_property_count);
2190 if (PyErr_Occurred()) {
2191 goto done;
2192 }
2193 unsubscribe_view.user_properties = user_properties_tmp;
2194
2195 struct unsubscribe_complete_userdata *metadata = NULL;
2196 /* callback related must be cleaned up after this point */
2197 metadata = aws_mem_calloc(aws_py_get_allocator(), 1, sizeof(struct unsubscribe_complete_userdata));
2198
2199 metadata->callback = unsuback_callback_fn_py;
2200 Py_INCREF(metadata->callback);
2201
2202 struct aws_mqtt5_unsubscribe_completion_options unsubscribe_completion_options = {
2203 .completion_callback = &s_on_unsubscribe_complete_fn, .completion_user_data = metadata};
2204
2205 if (aws_mqtt5_client_unsubscribe(client->native, &unsubscribe_view, &unsubscribe_completion_options)) {
2206 PyErr_SetAwsLastError();
2207 goto unsubscribe_failed;
2208 }
2209
2210 success = true;
2211 goto done;
2212
2213 unsubscribe_failed:
2214 Py_XDECREF(unsuback_callback_fn_py);
2215 aws_mem_release(aws_py_get_allocator(), metadata);
2216
2217 done:
2218 if (user_properties_tmp) {
2219 aws_mem_release(aws_py_get_allocator(), user_properties_tmp);
2220 }
2221 aws_array_list_clean_up(&topic_filters_list);
2222
2223 if (success) {
2224 Py_RETURN_NONE;
2225 }
2226 return NULL;
2227 }
2228
2229 /*******************************************************************************
2230 * Get Stats
2231 ******************************************************************************/
2232
2233 struct get_stats_complete_userdata {
2234 PyObject *callback;
2235 };
2236
2237 PyObject *aws_py_mqtt5_client_get_stats(PyObject *self, PyObject *args) {
2238 (void)self;
2239 bool success = false;
2240
2241 PyObject *impl_capsule;
2242
2243 if (!PyArg_ParseTuple(args, "O", &impl_capsule)) {
2244 return NULL;
2245 }
2246
2247 struct mqtt5_client_binding *client = PyCapsule_GetPointer(impl_capsule, s_capsule_name_mqtt5_client);
2248 if (!client) {
2249 return NULL;
2250 }
2251
2252 /* These must be DECREF'd when function ends on error */
2253 PyObject *result = NULL;
2254
2255 struct aws_mqtt5_client_operation_statistics stats;
2256 AWS_ZERO_STRUCT(stats);
2257
2258 aws_mqtt5_client_get_stats(client->native, &stats);
2259
2260 result = PyTuple_New(4);
2261 if (!result) {
2262 goto done;
2263 }
2264
2265 PyTuple_SetItem(
2266 result,
2267 0,
2268 PyLong_FromUnsignedLongLong((unsigned long long)stats.incomplete_operation_count)); /* Steals a reference */
2269 if (PyTuple_GetItem(result, 0) == NULL) { /* Borrowed reference */
2270 goto done;
2271 }
2272
2273 PyTuple_SetItem(
2274 result,
2275 1,
2276 PyLong_FromUnsignedLongLong((unsigned long long)stats.incomplete_operation_size)); /* Steals a reference */
2277 if (PyTuple_GetItem(result, 1) == NULL) { /* Borrowed reference */
2278 goto done;
2279 }
2280
2281 PyTuple_SetItem(
2282 result,
2283 2,
2284 PyLong_FromUnsignedLongLong((unsigned long long)stats.unacked_operation_count)); /* Steals a reference */
2285 if (PyTuple_GetItem(result, 2) == NULL) { /* Borrowed reference */
2286 goto done;
2287 }
2288
2289 PyTuple_SetItem(
2290 result,
2291 3,
2292 PyLong_FromUnsignedLongLong((unsigned long long)stats.unacked_operation_size)); /* Steals a reference */
2293 if (PyTuple_GetItem(result, 3) == NULL) { /* Borrowed reference */
2294 goto done;
2295 }
2296
2297 success = true;
2298
2299 done:
2300 if (success) {
2301 return result;
2302 }
2303 Py_XDECREF(result);
2304 return NULL;
2305 }