Debian Codegraph @

crt/aws-c-mqtt/source/topic_tree.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
6 #include <aws/mqtt/private/topic_tree.h>
7
8 #include <aws/io/logging.h>
9
10 #include <aws/common/byte_buf.h>
11 #include <aws/common/task_scheduler.h>
12
13 #ifdef _MSC_VER
14 /* disables warning non const declared initializers for Microsoft compilers */
15 # pragma warning(disable : 4204)
16 #endif /* _MSC_VER */
17
18 AWS_STATIC_STRING_FROM_LITERAL(s_single_level_wildcard, "+");
19 AWS_STATIC_STRING_FROM_LITERAL(s_multi_level_wildcard, "#");
20
21 /*******************************************************************************
22 * Transactions
23 ******************************************************************************/
24
25 struct topic_tree_action {
26 enum {
27 AWS_MQTT_TOPIC_TREE_ADD,
28 AWS_MQTT_TOPIC_TREE_UPDATE,
29 AWS_MQTT_TOPIC_TREE_REMOVE,
30 } mode;
31
32 /* All Nodes */
33 struct aws_mqtt_topic_node *node_to_update;
34
35 /* ADD/UPDATE */
36 struct aws_byte_cursor topic;
37 const struct aws_string *topic_filter;
38 enum aws_mqtt_qos qos;
39 aws_mqtt_publish_received_fn *callback;
40 aws_mqtt_userdata_cleanup_fn *cleanup;
41 void *userdata;
42
43 /* ADD */
44 struct aws_mqtt_topic_node *last_found;
45 struct aws_mqtt_topic_node *first_created;
46
47 /* REMOVE */
48 struct aws_array_list to_remove; /* topic_tree_node* */
49 };
50
51 size_t aws_mqtt_topic_tree_action_size = sizeof(struct topic_tree_action);
52
53 static struct topic_tree_action *s_topic_tree_action_create(struct aws_array_list *transaction) {
54
55 struct topic_tree_action *action = NULL;
56
57 /* Push an empty action into the transaction and get a pointer to it. */
58 struct topic_tree_action empty_action;
59 AWS_ZERO_STRUCT(empty_action);
60 if (aws_array_list_push_back(transaction, &empty_action)) {
61
62 AWS_LOGF_ERROR(AWS_LS_MQTT_TOPIC_TREE, "Failed to insert action into transaction, array_list_push_back failed");
63 goto push_back_failed;
64 }
65
66 if (aws_array_list_get_at_ptr(transaction, (void **)&action, aws_array_list_length(transaction) - 1)) {
67
68 AWS_LOGF_ERROR(AWS_LS_MQTT_TOPIC_TREE, "Failed to retrieve most recent action from transaction");
69 goto get_at_failed;
70 }
71
72 AWS_LOGF_TRACE(AWS_LS_MQTT_TOPIC_TREE, "action=%p: Created action", (void *)action);
73
74 return action;
75
76 get_at_failed:
77 aws_array_list_pop_back(transaction);
78
79 push_back_failed:
80 return NULL;
81 }
82
83 static void s_topic_tree_action_destroy(struct topic_tree_action *action) {
84
85 AWS_LOGF_TRACE(AWS_LS_MQTT_TOPIC_TREE, "action=%p: Destroying action", (void *)action);
86
87 if (action->mode == AWS_MQTT_TOPIC_TREE_REMOVE) {
88 aws_array_list_clean_up(&action->to_remove);
89 }
90
91 AWS_ZERO_STRUCT(*action);
92 }
93
94 static int s_topic_tree_action_to_remove(
95 struct topic_tree_action *action,
96 struct aws_allocator *allocator,
97 size_t size_hint) {
98
99 if (action->mode != AWS_MQTT_TOPIC_TREE_REMOVE) {
100 if (aws_array_list_init_dynamic(&action->to_remove, allocator, size_hint, sizeof(void *))) {
101
102 AWS_LOGF_ERROR(
103 AWS_LS_MQTT_TOPIC_TREE, "action=%p: Failed to initialize to_remove list in action", (void *)action);
104 return AWS_OP_ERR;
105 }
106 action->mode = AWS_MQTT_TOPIC_TREE_REMOVE;
107 }
108
109 return AWS_OP_SUCCESS;
110 }
111
112 static bool byte_cursor_eq(const void *a, const void *b) {
113 const struct aws_byte_cursor *cur_a = a;
114 const struct aws_byte_cursor *cur_b = b;
115
116 return aws_byte_cursor_eq(cur_a, cur_b);
117 }
118
119 /*******************************************************************************
120 * Init
121 ******************************************************************************/
122
123 static struct aws_mqtt_topic_node *s_topic_node_new(
124 struct aws_allocator *allocator,
125 const struct aws_byte_cursor *topic_filter,
126 const struct aws_string *full_topic) {
127
128 AWS_PRECONDITION(!topic_filter || full_topic);
129
130 struct aws_mqtt_topic_node *node = aws_mem_calloc(allocator, 1, sizeof(struct aws_mqtt_topic_node));
131 if (!node) {
132 AWS_LOGF_ERROR(AWS_LS_MQTT_TOPIC_TREE, "Failed to allocate new topic node");
133 return NULL;
134 }
135
136 if (topic_filter) {
137 AWS_LOGF_TRACE(
138 AWS_LS_MQTT_TOPIC_TREE,
139 "node=%p: Creating new node with topic filter " PRInSTR,
140 (void *)node,
141 AWS_BYTE_CURSOR_PRI(*topic_filter));
142 }
143
144 if (topic_filter) {
145 node->topic = *topic_filter;
146 node->topic_filter = full_topic;
147 }
148
149 /* Init the sub topics map */
150 if (aws_hash_table_init(&node->subtopics, allocator, 0, aws_hash_byte_cursor_ptr, byte_cursor_eq, NULL, NULL)) {
151
152 AWS_LOGF_ERROR(
153 AWS_LS_MQTT_TOPIC_TREE, "node=%p: Failed to initialize subtopics table in topic node", (void *)node);
154 aws_mem_release(allocator, node);
155 return NULL;
156 }
157
158 return node;
159 }
160
161 static int s_topic_node_destroy_hash_foreach_wrap(void *context, struct aws_hash_element *elem);
162
163 static void s_topic_node_destroy(struct aws_mqtt_topic_node *node, struct aws_allocator *allocator) {
164
165 AWS_LOGF_TRACE(AWS_LS_MQTT_TOPIC_TREE, "node=%p: Destroying topic tree node", (void *)node);
166
167 /* Traverse all children and remove */
168 aws_hash_table_foreach(&node->subtopics, s_topic_node_destroy_hash_foreach_wrap, allocator);
169
170 if (node->cleanup && node->userdata) {
171 node->cleanup(node->userdata);
172 }
173
174 if (node->owns_topic_filter) {
175 aws_string_destroy((void *)node->topic_filter);
176 }
177
178 aws_hash_table_clean_up(&node->subtopics);
179 aws_mem_release(allocator, node);
180 }
181
182 static int s_topic_node_destroy_hash_foreach_wrap(void *context, struct aws_hash_element *elem) {
183
184 s_topic_node_destroy(elem->value, context);
185
186 return AWS_COMMON_HASH_TABLE_ITER_CONTINUE | AWS_COMMON_HASH_TABLE_ITER_DELETE;
187 }
188
189 int aws_mqtt_topic_tree_init(struct aws_mqtt_topic_tree *tree, struct aws_allocator *allocator) {
190
191 AWS_PRECONDITION(tree);
192 AWS_PRECONDITION(allocator);
193
194 AWS_LOGF_DEBUG(AWS_LS_MQTT_TOPIC_TREE, "tree=%p: Creating new topic tree", (void *)tree);
195
196 tree->root = s_topic_node_new(allocator, NULL, NULL);
197 if (!tree->root) {
198 /* Error raised by s_topic_node_new */
199 return AWS_OP_ERR;
200 }
201 tree->allocator = allocator;
202
203 return AWS_OP_SUCCESS;
204 }
205
206 /*******************************************************************************
207 * Clean Up
208 ******************************************************************************/
209
210 void aws_mqtt_topic_tree_clean_up(struct aws_mqtt_topic_tree *tree) {
211
212 AWS_PRECONDITION(tree);
213
214 AWS_LOGF_DEBUG(AWS_LS_MQTT_TOPIC_TREE, "tree=%p: Cleaning up topic tree", (void *)tree);
215
216 if (tree->allocator && tree->root) {
217 s_topic_node_destroy(tree->root, tree->allocator);
218
219 AWS_ZERO_STRUCT(*tree);
220 }
221 }
222
223 /*******************************************************************************
224 * Iterate
225 ******************************************************************************/
226
227 bool s_topic_node_is_subscription(const struct aws_mqtt_topic_node *node) {
228 return node->callback;
229 }
230
231 struct topic_tree_iterate_context {
232 bool should_continue;
233 aws_mqtt_topic_tree_iterator_fn *iterator;
234 void *user_data;
235 };
236
237 static int s_topic_tree_iterate_do_recurse(void *context, struct aws_hash_element *current_elem) {
238
239 struct topic_tree_iterate_context *ctx = context;
240 struct aws_mqtt_topic_node *current = current_elem->value;
241
242 if (s_topic_node_is_subscription(current)) {
243 const struct aws_byte_cursor topic_filter = aws_byte_cursor_from_string(current->topic_filter);
244 ctx->should_continue = ctx->iterator(&topic_filter, current->qos, ctx->user_data);
245 }
246
247 if (ctx->should_continue) {
248 aws_hash_table_foreach(&current->subtopics, s_topic_tree_iterate_do_recurse, context);
249 }
250
251 /* One of the children could have updated should_continue, so check again */
252 if (ctx->should_continue) {
253 return AWS_COMMON_HASH_TABLE_ITER_CONTINUE;
254 }
255
256 /* If false returned, return immediately. */
257 return 0;
258 }
259
260 void aws_mqtt_topic_tree_iterate(
261 const struct aws_mqtt_topic_tree *tree,
262 aws_mqtt_topic_tree_iterator_fn *iterator,
263 void *user_data) {
264
265 AWS_PRECONDITION(tree);
266 AWS_PRECONDITION(tree->root);
267 AWS_PRECONDITION(iterator);
268
269 struct topic_tree_iterate_context itr;
270 itr.should_continue = true;
271 itr.iterator = iterator;
272 itr.user_data = user_data;
273
274 aws_hash_table_foreach(&tree->root->subtopics, s_topic_tree_iterate_do_recurse, &itr);
275 }
276
277 bool s_topic_tree_sub_count_iterator(const struct aws_byte_cursor *topic, enum aws_mqtt_qos qos, void *user_data) {
278 (void)topic;
279 (void)qos;
280 size_t *sub_count = user_data;
281 *sub_count += 1;
282
283 return true;
284 }
285
286 size_t aws_mqtt_topic_tree_get_sub_count(const struct aws_mqtt_topic_tree *tree) {
287
288 AWS_PRECONDITION(tree);
289 AWS_PRECONDITION(tree->root);
290
291 size_t sub_count = 0;
292 aws_mqtt_topic_tree_iterate(tree, s_topic_tree_sub_count_iterator, &sub_count);
293
294 return sub_count;
295 }
296
297 /*******************************************************************************
298 * Action Commit
299 ******************************************************************************/
300
301 /* Searches subtree until a topic_filter with a different pointer value is found. */
302 static int s_topic_node_string_finder(void *userdata, struct aws_hash_element *elem) {
303
304 const struct aws_string **topic_filter = userdata;
305 struct aws_mqtt_topic_node *node = elem->value;
306
307 /* We've found this node again, search it's children */
308 if (*topic_filter == node->topic_filter) {
309 if (0 == aws_hash_table_get_entry_count(&node->subtopics)) {
310 /* If no children, then there must be siblings, so we can use those */
311 return AWS_COMMON_HASH_TABLE_ITER_CONTINUE;
312 }
313
314 aws_hash_table_foreach(&node->subtopics, s_topic_node_string_finder, userdata);
315
316 if (*topic_filter == node->topic_filter) {
317 /* If the topic filter still hasn't changed, continue iterating */
318 return AWS_COMMON_HASH_TABLE_ITER_CONTINUE;
319 }
320
321 AWS_LOGF_TRACE(AWS_LS_MQTT_TOPIC_TREE, " Found matching topic string, using %s", node->topic_filter->bytes);
322
323 return 0;
324 }
325
326 AWS_LOGF_TRACE(AWS_LS_MQTT_TOPIC_TREE, " Found matching topic string, using %s", node->topic_filter->bytes);
327 *topic_filter = node->topic_filter;
328 return 0;
329 }
330
331 static void s_topic_tree_action_commit(struct topic_tree_action *action, struct aws_mqtt_topic_tree *tree) {
332 (void)tree;
333
334 AWS_PRECONDITION(action->node_to_update);
335
336 switch (action->mode) {
337 case AWS_MQTT_TOPIC_TREE_ADD:
338 case AWS_MQTT_TOPIC_TREE_UPDATE: {
339
340 AWS_LOGF_TRACE(
341 AWS_LS_MQTT_TOPIC_TREE,
342 "tree=%p action=%p: Committing %s topic tree action",
343 (void *)tree,
344 (void *)action,
345 (action->mode == AWS_MQTT_TOPIC_TREE_ADD) ? "add" : "update");
346
347 /* Destroy old userdata */
348 if (action->node_to_update->cleanup && action->node_to_update->userdata) {
349 /* If there was userdata assigned to this node, pass it out. */
350 action->node_to_update->cleanup(action->node_to_update->userdata);
351 }
352
353 /* Update data */
354 action->node_to_update->callback = action->callback;
355 action->node_to_update->cleanup = action->cleanup;
356 action->node_to_update->userdata = action->userdata;
357 action->node_to_update->qos = action->qos;
358 if (action->topic.ptr) {
359 action->node_to_update->topic = action->topic;
360 }
361 if (action->topic_filter) {
362 if (action->node_to_update->owns_topic_filter && action->node_to_update->topic_filter) {
363 /* The topic filer is already there, destory the new filter to keep all the byte cursor valid */
364 aws_string_destroy((void *)action->topic_filter);
365 } else {
366 action->node_to_update->topic_filter = action->topic_filter;
367 action->node_to_update->owns_topic_filter = true;
368 }
369 }
370 break;
371 }
372
373 case AWS_MQTT_TOPIC_TREE_REMOVE: {
374
375 AWS_LOGF_TRACE(
376 AWS_LS_MQTT_TOPIC_TREE,
377 "tree=%p action=%p: Committing remove topic tree action",
378 (void *)tree,
379 (void *)action);
380
381 struct aws_mqtt_topic_node *current = action->node_to_update;
382 const size_t sub_parts_len = aws_array_list_length(&action->to_remove) - 1;
383
384 if (current) {
385 /* If found the node, traverse up and remove each with no sub-topics.
386 * Then update all nodes that were using current's topic_filter for topic. */
387
388 /* "unsubscribe" current. */
389 if (current->cleanup && current->userdata) {
390 AWS_LOGF_TRACE(AWS_LS_MQTT_TOPIC_TREE, "node=%p: Cleaning up node's userdata", (void *)current);
391
392 /* If there was userdata assigned to this node, pass it out. */
393 current->cleanup(current->userdata);
394 }
395 current->callback = NULL;
396 current->cleanup = NULL;
397 current->userdata = NULL;
398
399 /* Set to true if current needs to be cleaned up. */
400 bool destroy_current = false;
401
402 /* How many nodes are left after the great purge. */
403 size_t nodes_left = sub_parts_len;
404
405 /* Remove all subscription-less and child-less nodes. */
406 for (size_t i = sub_parts_len; i > 0; --i) {
407 struct aws_mqtt_topic_node *node = NULL;
408 aws_array_list_get_at(&action->to_remove, &node, i);
409 AWS_ASSUME(node); /* Must be in bounds */
410
411 if (!s_topic_node_is_subscription(node) && 0 == aws_hash_table_get_entry_count(&node->subtopics)) {
412
413 /* No subscription and no children, this node needs to go. */
414 struct aws_mqtt_topic_node *grandma = NULL;
415 aws_array_list_get_at(&action->to_remove, &grandma, i - 1);
416 AWS_ASSUME(grandma); /* Must be in bounds */
417
418 AWS_LOGF_TRACE(
419 AWS_LS_MQTT_TOPIC_TREE,
420 "tree=%p node=%p: Removing child node %p with topic \"" PRInSTR "\"",
421 (void *)tree,
422 (void *)grandma,
423 (void *)node,
424 AWS_BYTE_CURSOR_PRI(node->topic));
425
426 aws_hash_table_remove(&grandma->subtopics, &node->topic, NULL, NULL);
427
428 /* Make sure the following loop doesn't hit this node. */
429 --nodes_left;
430
431 if (i != sub_parts_len) {
432
433 /* Clean up and delete */
434 s_topic_node_destroy(node, tree->allocator);
435 } else {
436 // We do not delete the current node immediately as we would like to use
437 // it to update the topic filter of the remaining nodes
438 destroy_current = true;
439 }
440 } else {
441
442 AWS_LOGF_TRACE(
443 AWS_LS_MQTT_TOPIC_TREE,
444 "tree=%p: Node %p with topic \"" PRInSTR
445 "\" has children or is a subscription, leaving in place",
446 (void *)tree,
447 (void *)node,
448 AWS_BYTE_CURSOR_PRI(node->topic));
449
450 /* Once we've found one node with children, the rest are guaranteed to. */
451 break;
452 }
453 }
454
455 /* If at least one node is destroyed and there is node(s) remaining in the branch,
456 * go fixup the topic filter reference . */
457 if (nodes_left > 0 && destroy_current) {
458
459 /* If a new viable topic filter is found once, it can be used for all parents. */
460 const struct aws_string *new_topic_filter = NULL;
461 const struct aws_string *const old_topic_filter = current->topic_filter;
462 /* How much of new_topic_filter should be lopped off the beginning. */
463
464 struct aws_mqtt_topic_node *parent = NULL;
465 aws_array_list_get_at(&action->to_remove, &parent, nodes_left);
466 AWS_ASSUME(parent);
467
468 size_t topic_offset =
469 parent->topic.ptr - aws_string_bytes(parent->topic_filter) + parent->topic.len + 1;
470
471 /* Loop through all remaining nodes to update the topic filters */
472 for (size_t i = nodes_left; i > 0; --i) {
473 aws_array_list_get_at(&action->to_remove, &parent, i);
474 AWS_ASSUME(parent); /* Must be in bounds */
475
476 /* Remove this topic and following / from offset. */
477 topic_offset -= (parent->topic.len + 1);
478
479 if (parent->topic_filter == old_topic_filter) {
480 /* Uh oh, Mom's using my topic string again! Steal it and replace it with a new one, Indiana
481 * Jones style. */
482
483 AWS_LOGF_TRACE(
484 AWS_LS_MQTT_TOPIC_TREE,
485 "tree=%p: Found node %p reusing topic filter part, replacing with next child",
486 (void *)tree,
487 (void *)parent);
488
489 if (!new_topic_filter) {
490 /* Set new_tf to old_tf so it's easier to check against the existing node.
491 * Basically, it's an INOUT param. */
492 new_topic_filter = old_topic_filter;
493
494 /* Search all subtopics until we find one that isn't current. */
495 aws_hash_table_foreach(
496 &parent->subtopics, s_topic_node_string_finder, (void *)&new_topic_filter);
497
498 /* This would only happen if there is only one topic in subtopics (current's) and
499 * it has no children (in which case it should have been removed above as
500 `destroy_current` is set to true). */
501 AWS_ASSERT(new_topic_filter != old_topic_filter);
502
503 /* Now that the new string has been found, the old one can be destroyed. */
504 aws_string_destroy((void *)current->topic_filter);
505 current->owns_topic_filter = false;
506 }
507
508 /* Update the pointers. */
509 parent->topic_filter = new_topic_filter;
510 parent->topic.ptr = (uint8_t *)aws_string_bytes(new_topic_filter) + topic_offset;
511 }
512 }
513 }
514
515 /* Now that the strings are update, remove current. */
516 if (destroy_current) {
517 s_topic_node_destroy(current, tree->allocator);
518 }
519 current = NULL;
520 }
521
522 break;
523 }
524 }
525
526 s_topic_tree_action_destroy(action);
527 }
528
529 /*******************************************************************************
530 * Action Roll Back
531 ******************************************************************************/
532
533 static void s_topic_tree_action_roll_back(struct topic_tree_action *action, struct aws_mqtt_topic_tree *tree) {
534
535 AWS_PRECONDITION(action);
536
537 switch (action->mode) {
538 case AWS_MQTT_TOPIC_TREE_ADD: {
539 AWS_LOGF_TRACE(
540 AWS_LS_MQTT_TOPIC_TREE,
541 "tree=%p action=%p: Rolling back add transaction action",
542 (void *)tree,
543 (void *)action);
544
545 /* Remove the first new node from it's parent's map */
546 aws_hash_table_remove(&action->last_found->subtopics, &action->first_created->topic, NULL, NULL);
547 /* Recursively destroy all other created nodes */
548 s_topic_node_destroy(action->first_created, tree->allocator);
549
550 if (action->topic_filter) {
551 aws_string_destroy((void *)action->topic_filter);
552 }
553
554 break;
555 }
556 case AWS_MQTT_TOPIC_TREE_REMOVE:
557 case AWS_MQTT_TOPIC_TREE_UPDATE: {
558 AWS_LOGF_TRACE(
559 AWS_LS_MQTT_TOPIC_TREE,
560 "tree=%p action=%p: Rolling back remove/update transaction, no changes made",
561 (void *)tree,
562 (void *)action);
563
564 /* Aborting a remove or update doesn't require any actions. */
565 break;
566 }
567 }
568
569 s_topic_tree_action_destroy(action);
570 }
571
572 /*******************************************************************************
573 * Insert
574 ******************************************************************************/
575
576 int aws_mqtt_topic_tree_transaction_insert(
577 struct aws_mqtt_topic_tree *tree,
578 struct aws_array_list *transaction,
579 const struct aws_string *topic_filter_ori,
580 enum aws_mqtt_qos qos,
581 aws_mqtt_publish_received_fn *callback,
582 aws_mqtt_userdata_cleanup_fn *cleanup,
583 void *userdata) {
584
585 AWS_PRECONDITION(tree);
586 AWS_PRECONDITION(transaction);
587 AWS_PRECONDITION(topic_filter_ori);
588 AWS_PRECONDITION(callback);
589
590 /* let topic tree take the ownership of the new string and leave the caller string alone. */
591 struct aws_string *topic_filter = aws_string_new_from_string(tree->allocator, topic_filter_ori);
592
593 AWS_LOGF_DEBUG(
594 AWS_LS_MQTT_TOPIC_TREE,
595 "tree=%p: Inserting topic filter %s into topic tree",
596 (void *)tree,
597 topic_filter->bytes);
598
599 struct aws_mqtt_topic_node *current = tree->root;
600
601 struct topic_tree_action *action = s_topic_tree_action_create(transaction);
602 if (!action) {
603 return AWS_OP_ERR;
604 }
605
606 /* Default to update unless a node was added */
607 action->mode = AWS_MQTT_TOPIC_TREE_UPDATE;
608 action->qos = qos;
609 action->callback = callback;
610 action->cleanup = cleanup;
611 action->userdata = userdata;
612
613 struct aws_byte_cursor topic_filter_cur = aws_byte_cursor_from_string(topic_filter);
614 struct aws_byte_cursor sub_part;
615 AWS_ZERO_STRUCT(sub_part);
616 struct aws_byte_cursor last_part;
617 AWS_ZERO_STRUCT(last_part);
618 while (aws_byte_cursor_next_split(&topic_filter_cur, '/', &sub_part)) {
619
620 last_part = sub_part;
621
622 /* Add or find mid-node */
623 struct aws_hash_element *elem = NULL;
624 int was_created = 0;
625 aws_hash_table_create(&current->subtopics, &sub_part, &elem, &was_created);
626
627 if (was_created) {
628 if (action->mode == AWS_MQTT_TOPIC_TREE_UPDATE) {
629 /* Store the last found node */
630 action->last_found = current;
631 }
632
633 /* Node does not exist, add new one */
634 current = s_topic_node_new(tree->allocator, &sub_part, topic_filter);
635 if (!current) {
636 /* Don't do handle_error logic, the action needs to persist to be rolled back */
637 return AWS_OP_ERR;
638 }
639
640 /* Stash in the hash map */
641 elem->key = &current->topic;
642 elem->value = current;
643
644 if (action->mode == AWS_MQTT_TOPIC_TREE_UPDATE) {
645 AWS_LOGF_TRACE(
646 AWS_LS_MQTT_TOPIC_TREE,
647 "tree=%p: Topic part \"" PRInSTR "\" is new, it and all children will be added as new nodes",
648 (void *)tree,
649 AWS_BYTE_CURSOR_PRI(sub_part));
650
651 /* Store the node we just made, and make sure we don't store again */
652 action->mode = AWS_MQTT_TOPIC_TREE_ADD;
653 action->first_created = current;
654 }
655 } else {
656 AWS_ASSERT(action->mode == AWS_MQTT_TOPIC_TREE_UPDATE); /* Can't have found an existing node while adding */
657
658 /* If the node exists, just traverse it */
659 current = elem->value;
660 }
661 }
662
663 action->node_to_update = current;
664
665 /* Node found (or created), add the topic filter and callbacks */
666 if (current->owns_topic_filter) {
667
668 AWS_LOGF_TRACE(
669 AWS_LS_MQTT_TOPIC_TREE,
670 "tree=%p node=%p: Updating existing node that already owns its topic_filter, throwing out parameter",
671 (void *)tree,
672 (void *)current);
673
674 /* If the topic filter was already here, this is already a subscription.
675 Free the new topic_filter so all existing byte_cursors remain valid. */
676 aws_string_destroy(topic_filter);
677 } else {
678 /* Node already existed (or was created) but wasn't subscription. */
679 action->topic = last_part;
680 action->topic_filter = topic_filter;
681 }
682
683 return AWS_OP_SUCCESS;
684 }
685
686 /*******************************************************************************
687 * Remove
688 ******************************************************************************/
689
690 int aws_mqtt_topic_tree_transaction_remove(
691 struct aws_mqtt_topic_tree *tree,
692 struct aws_array_list *transaction,
693 const struct aws_byte_cursor *topic_filter,
694 void **old_userdata) {
695
696 AWS_PRECONDITION(tree);
697 AWS_PRECONDITION(transaction);
698 AWS_PRECONDITION(topic_filter);
699
700 AWS_LOGF_DEBUG(
701 AWS_LS_MQTT_TOPIC_TREE,
702 "tree=%p: Removing topic filter \"" PRInSTR "\" from topic tree",
703 (void *)tree,
704 AWS_BYTE_CURSOR_PRI(*topic_filter));
705
706 /* Initialize output parameter to a safe default */
707 if (old_userdata) {
708 *old_userdata = NULL;
709 }
710
711 /* Default to error because that's what handle_error will do in all cases except node not found */
712 int result = AWS_OP_ERR;
713 struct topic_tree_action *action = s_topic_tree_action_create(transaction);
714 if (!action) {
715 return AWS_OP_ERR;
716 }
717
718 struct aws_array_list sub_topic_parts;
719 AWS_ZERO_STRUCT(sub_topic_parts);
720
721 if (aws_array_list_init_dynamic(&sub_topic_parts, tree->allocator, 1, sizeof(struct aws_byte_cursor))) {
722 AWS_LOGF_ERROR(AWS_LS_MQTT_TOPIC_TREE, "tree=%p: Failed to initialize topic parts array", (void *)tree);
723 goto handle_error;
724 }
725
726 if (aws_byte_cursor_split_on_char(topic_filter, '/', &sub_topic_parts)) {
727 AWS_LOGF_ERROR(AWS_LS_MQTT_TOPIC_TREE, "tree=%p: Failed to split topic filter", (void *)tree);
728 goto handle_error;
729 }
730 const size_t sub_parts_len = aws_array_list_length(&sub_topic_parts);
731 if (!sub_parts_len) {
732 AWS_LOGF_ERROR(AWS_LS_MQTT_TOPIC_TREE, "tree=%p: Failed to get topic parts length", (void *)tree);
733 goto handle_error;
734 }
735 s_topic_tree_action_to_remove(action, tree->allocator, sub_parts_len);
736
737 struct aws_mqtt_topic_node *current = tree->root;
738 if (aws_array_list_push_back(&action->to_remove, &current)) {
739 AWS_LOGF_ERROR(AWS_LS_MQTT_TOPIC_TREE, "tree=%p: Failed to insert root node into to_remove list", (void *)tree);
740 goto handle_error;
741 }
742
743 for (size_t i = 0; i < sub_parts_len; ++i) {
744
745 /* Get the current topic part */
746 struct aws_byte_cursor *sub_part = NULL;
747 aws_array_list_get_at_ptr(&sub_topic_parts, (void **)&sub_part, i);
748
749 /* Find mid-node */
750 struct aws_hash_element *elem = NULL;
751 aws_hash_table_find(&current->subtopics, sub_part, &elem);
752 if (elem) {
753 /* If the node exists, just traverse it */
754 current = elem->value;
755 if (aws_array_list_push_back(&action->to_remove, &current)) {
756 AWS_LOGF_ERROR(
757 AWS_LS_MQTT_TOPIC_TREE, "tree=%p: Failed to insert topic node into to_remove list", (void *)tree);
758 goto handle_error;
759 }
760 } else {
761 /* If not, abandon ship */
762 goto handle_not_found;
763 }
764 }
765
766 action->node_to_update = current;
767
768 aws_array_list_clean_up(&sub_topic_parts);
769
770 if (old_userdata) {
771 *old_userdata = current->userdata;
772 }
773
774 return AWS_OP_SUCCESS;
775
776 handle_not_found:
777 result = AWS_OP_SUCCESS;
778
779 handle_error:
780 aws_array_list_clean_up(&sub_topic_parts);
781
782 s_topic_tree_action_destroy(action);
783 aws_array_list_pop_back(transaction);
784
785 return result;
786 }
787
788 /*******************************************************************************
789 * Commit
790 ******************************************************************************/
791
792 void aws_mqtt_topic_tree_transaction_commit(struct aws_mqtt_topic_tree *tree, struct aws_array_list *transaction) {
793
794 const size_t num_actions = aws_array_list_length(transaction);
795 for (size_t i = 0; i < num_actions; ++i) {
796 struct topic_tree_action *action = NULL;
797 aws_array_list_get_at_ptr(transaction, (void **)&action, i);
798 AWS_ASSUME(action); /* Within bounds */
799
800 s_topic_tree_action_commit(action, tree);
801 }
802 aws_array_list_clear(transaction);
803 }
804
805 /*******************************************************************************
806 * Roll Back
807 ******************************************************************************/
808
809 void aws_mqtt_topic_tree_transaction_roll_back(struct aws_mqtt_topic_tree *tree, struct aws_array_list *transaction) {
810
811 const size_t num_actions = aws_array_list_length(transaction);
812 for (size_t i = 1; i <= num_actions; ++i) {
813 struct topic_tree_action *action = NULL;
814 aws_array_list_get_at_ptr(transaction, (void **)&action, num_actions - i);
815 AWS_ASSUME(action); /* Within bounds */
816
817 s_topic_tree_action_roll_back(action, tree);
818 }
819 aws_array_list_clear(transaction);
820 }
821
822 int aws_mqtt_topic_tree_insert(
823 struct aws_mqtt_topic_tree *tree,
824 const struct aws_string *topic_filter,
825 enum aws_mqtt_qos qos,
826 aws_mqtt_publish_received_fn *callback,
827 aws_mqtt_userdata_cleanup_fn *cleanup,
828 void *userdata) {
829
830 AWS_VARIABLE_LENGTH_ARRAY(uint8_t, transaction_buf, aws_mqtt_topic_tree_action_size);
831 struct aws_array_list transaction;
832 aws_array_list_init_static(&transaction, transaction_buf, 1, aws_mqtt_topic_tree_action_size);
833
834 if (aws_mqtt_topic_tree_transaction_insert(tree, &transaction, topic_filter, qos, callback, cleanup, userdata)) {
835
836 aws_mqtt_topic_tree_transaction_roll_back(tree, &transaction);
837 return AWS_OP_ERR;
838 }
839
840 aws_mqtt_topic_tree_transaction_commit(tree, &transaction);
841 return AWS_OP_SUCCESS;
842 }
843
844 int aws_mqtt_topic_tree_remove(struct aws_mqtt_topic_tree *tree, const struct aws_byte_cursor *topic_filter) {
845
846 AWS_PRECONDITION(tree);
847 AWS_PRECONDITION(topic_filter);
848
849 AWS_VARIABLE_LENGTH_ARRAY(uint8_t, transaction_buf, aws_mqtt_topic_tree_action_size);
850 struct aws_array_list transaction;
851 aws_array_list_init_static(&transaction, transaction_buf, 1, aws_mqtt_topic_tree_action_size);
852
853 if (aws_mqtt_topic_tree_transaction_remove(tree, &transaction, topic_filter, NULL)) {
854
855 aws_mqtt_topic_tree_transaction_roll_back(tree, &transaction);
856 return AWS_OP_ERR;
857 }
858
859 aws_mqtt_topic_tree_transaction_commit(tree, &transaction);
860 return AWS_OP_SUCCESS;
861 }
862
863 /*******************************************************************************
864 * Publish
865 ******************************************************************************/
866
867 static void s_topic_tree_publish_do_recurse(
868 const struct aws_byte_cursor *current_sub_part,
869 const struct aws_mqtt_topic_node *current,
870 const struct aws_mqtt_packet_publish *pub) {
871
872 struct aws_byte_cursor hash_cur = aws_byte_cursor_from_string(s_multi_level_wildcard);
873 struct aws_byte_cursor plus_cur = aws_byte_cursor_from_string(s_single_level_wildcard);
874
875 struct aws_hash_element *elem = NULL;
876
877 struct aws_byte_cursor sub_part = *current_sub_part;
878 if (!aws_byte_cursor_next_split(&pub->topic_name, '/', &sub_part)) {
879
880 /* If this is the last node and is a sub, call it */
881 if (s_topic_node_is_subscription(current)) {
882 bool dup = aws_mqtt_packet_publish_get_dup(pub);
883 enum aws_mqtt_qos qos = aws_mqtt_packet_publish_get_qos(pub);
884 bool retain = aws_mqtt_packet_publish_get_retain(pub);
885 current->callback(&pub->topic_name, &pub->payload, dup, qos, retain, current->userdata);
886 }
887 return;
888 }
889
890 /* Check multi-level wildcard */
891 aws_hash_table_find(&current->subtopics, &hash_cur, &elem);
892 if (elem) {
893 /* Match! */
894 struct aws_mqtt_topic_node *multi_wildcard = elem->value;
895 /* Must be a subscription and have no children */
896 AWS_ASSERT(s_topic_node_is_subscription(multi_wildcard));
897 AWS_ASSERT(0 == aws_hash_table_get_entry_count(&multi_wildcard->subtopics));
898 bool dup = aws_mqtt_packet_publish_get_dup(pub);
899 enum aws_mqtt_qos qos = aws_mqtt_packet_publish_get_qos(pub);
900 bool retain = aws_mqtt_packet_publish_get_retain(pub);
901 multi_wildcard->callback(&pub->topic_name, &pub->payload, dup, qos, retain, multi_wildcard->userdata);
902 }
903
904 /* Check single level wildcard */
905 aws_hash_table_find(&current->subtopics, &plus_cur, &elem);
906 if (elem) {
907 /* Recurse sub topics */
908 s_topic_tree_publish_do_recurse(&sub_part, elem->value, pub);
909 }
910
911 /* Check actual topic name */
912 aws_hash_table_find(&current->subtopics, &sub_part, &elem);
913 if (elem) {
914 /* Found the actual topic, recurse to it */
915 s_topic_tree_publish_do_recurse(&sub_part, elem->value, pub);
916 }
917 }
918
919 void aws_mqtt_topic_tree_publish(const struct aws_mqtt_topic_tree *tree, struct aws_mqtt_packet_publish *pub) {
920
921 AWS_PRECONDITION(tree);
922 AWS_PRECONDITION(pub);
923
924 AWS_LOGF_TRACE(
925 AWS_LS_MQTT_TOPIC_TREE,
926 "tree=%p: Publishing on topic " PRInSTR,
927 (void *)tree,
928 AWS_BYTE_CURSOR_PRI(pub->topic_name));
929
930 struct aws_byte_cursor sub_part;
931 AWS_ZERO_STRUCT(sub_part);
932 s_topic_tree_publish_do_recurse(&sub_part, tree->root, pub);
933 }