Debian Codegraph @

main/channelstorage_cpp_map_name_id.cc

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 2024, Sangoma Technologies Corporation
5 *
6 * George Joseph <[email protected]>
7 *
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
13 *
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
17 */
18
19 #include <memory>
20 #include <string>
21 #include <map>
22 #include <cassert>
23 #include <utility>
24
25 #include "asterisk/logger.h"
26 #include "asterisk/lock.h"
27 #include "channelstorage.h"
28 #include "channel_private.h"
29
30 typedef std::map<std::string, struct ast_channel *> ChannelMap;
31
32 struct mni_channelstorage_driver_pvt {
33 ChannelMap by_name;
34 ChannelMap by_uniqueid;
35 };
36
37 #define getdb(driver) (((struct mni_channelstorage_driver_pvt *)driver->handle)->by_name)
38 #define map_by_id(driver) (((struct mni_channelstorage_driver_pvt *)driver->handle)->by_uniqueid)
39
40 static void rdlock(struct ast_channelstorage_instance *driver)
41 {
42 if (!driver || !driver->lock_handle) {
43 return;
44 }
45 ast_rwlock_rdlock((ast_rwlock_t*)driver->lock_handle);
46 }
47
48 static void wrlock(struct ast_channelstorage_instance *driver)
49 {
50 if (!driver || !driver->lock_handle) {
51 return;
52 }
53 ast_rwlock_wrlock((ast_rwlock_t*)driver->lock_handle);
54 }
55
56 static void unlock(struct ast_channelstorage_instance *driver)
57 {
58 if (!driver || !driver->lock_handle) {
59 return;
60 }
61 ast_rwlock_unlock((ast_rwlock_t*)driver->lock_handle);
62 }
63
64 static int insert_channel(struct ast_channelstorage_instance *driver,
65 struct ast_channel *chan, int flags, int lock)
66 {
67 char *l_name = NULL;
68 char *l_uniqueid = NULL;
69 bool success = false;
70 if (!chan) {
71 return -1;
72 }
73
74 if (lock) {
75 wrlock(driver);
76 }
77 l_name = ast_str_to_lower(ast_strdupa(ast_channel_name(chan)));
78 l_uniqueid = ast_str_to_lower(ast_strdupa(ast_channel_uniqueid(chan)));
79
80 auto rtn = getdb(driver).emplace(l_name, ao2_bump(chan));
81 if (rtn.second) {
82 rtn = map_by_id(driver).emplace(l_uniqueid, ao2_bump(chan));
83 if (!rtn.second) {
84 ast_log(LOG_ERROR, "Unable to insert channel '%s' '%s'\n",
85 ast_channel_name(chan), ast_channel_uniqueid(chan));
86 ast_channel_unref(chan);
87 getdb(driver).erase(l_name);
88 ast_channel_unref(chan);
89 }
90 success = rtn.second;
91 } else {
92 ast_log(LOG_ERROR, "Unable to insert channel '%s'\n", ast_channel_name(chan));
93 ast_channel_unref(chan);
94 }
95
96 if (success) {
97 chan->linked_in_container = 1;
98 }
99 if (lock) {
100 unlock(driver);
101 }
102 return success ? 0 : -1;
103 }
104
105 static int delete_channel(struct ast_channelstorage_instance *driver,
106 struct ast_channel *chan, int lock)
107 {
108 char *l_name = NULL;
109 char *l_uniqueid = NULL;
110 if (!chan) {
111 return -1;
112 }
113
114 if (!chan->linked_in_container) {
115 return 0;
116 }
117
118 if (lock) {
119 wrlock(driver);
120 }
121
122 l_name = ast_str_to_lower(ast_strdupa(ast_channel_name(chan)));
123 l_uniqueid = ast_str_to_lower(ast_strdupa(ast_channel_uniqueid(chan)));
124
125 auto deleted = getdb(driver).erase(l_name);
126 if (deleted) {
127 ast_channel_unref(chan);
128 }
129 deleted = map_by_id(driver).erase(l_uniqueid);
130 if (deleted) {
131 ast_channel_unref(chan);
132 }
133 chan->linked_in_container = 0;
134
135 if (lock) {
136 unlock(driver);
137 }
138 return 0;
139 }
140
141 /*! \brief returns number of active/allocated channels */
142 static int active_channels(struct ast_channelstorage_instance *driver, int lock)
143 {
144 int count = 0;
145
146 if (!driver) {
147 return 0;
148 }
149
150 if (lock) {
151 rdlock(driver);
152 }
153 count = getdb(driver).size();
154 if (lock) {
155 unlock(driver);
156 }
157
158 return count;
159 }
160
161 static struct ast_channel *callback(struct ast_channelstorage_instance *driver,
162 ao2_callback_data_fn *cb_fn, void *arg, void *data, int ao2_flags, int lock)
163 {
164 struct ast_channel *chan = NULL;
165 ChannelMap::const_iterator it;
166
167 if (!cb_fn) {
168 return NULL;
169 }
170
171 if (lock) {
172 rdlock(driver);
173 }
174 for (it = getdb(driver).begin(); it != getdb(driver).end(); it++) {
175 if (cb_fn(it->second, arg, data, ao2_flags) == (CMP_MATCH | CMP_STOP)) {
176 chan = ao2_bump(it->second);
177 break;
178 }
179 }
180 if (lock) {
181 unlock(driver);
182 }
183
184 return chan;
185 }
186
187 enum cpp_map_iterator_type {
188 ITERATOR_ALL,
189 ITERATOR_BY_NAME,
190 ITERATOR_BY_EXTEN,
191 };
192
193 struct mni_channel_iterator {
194 enum cpp_map_iterator_type it_type;
195 std::string l_name;
196 size_t l_name_len;
197 char *context;
198 char *exten;
199 std::string last_channel;
200 int counter;
201
202 mni_channel_iterator() :
203 it_type(ITERATOR_ALL), l_name(""), l_name_len(0),
204 context(NULL), exten(NULL),
205 last_channel(""), counter(0)
206 {
207 }
208
209 mni_channel_iterator(const char *l_name) :
210 it_type(ITERATOR_BY_NAME), l_name(l_name), l_name_len(strlen(l_name)),
211 context(NULL), exten(NULL),
212 last_channel(""), counter(0)
213 {
214 }
215
216 mni_channel_iterator(const char *context, const char *exten) :
217 it_type(ITERATOR_BY_EXTEN), l_name(""), l_name_len(0),
218 context(ast_strdup(context)), exten(ast_strdup(exten)),
219 last_channel(""), counter(0)
220 {
221 }
222
223 ~mni_channel_iterator()
224 {
225 ast_free(context);
226 ast_free(exten);
227 context = NULL;
228 exten = NULL;
229 l_name.clear();
230 last_channel.clear();
231 counter = 0;
232 }
233 };
234
235 static struct ast_channel_iterator *iterator_destroy(struct ast_channelstorage_instance *driver,
236 struct ast_channel_iterator *ai)
237 {
238 struct mni_channel_iterator *i = (struct mni_channel_iterator *)ai;
239 if (!driver || !i) {
240 return NULL;
241 }
242 delete i;
243 return NULL;
244 }
245
246 /*!
247 * \internal
248 * \brief Create a new iterator for all channels
249 *
250 * No I/O is done at this time. It's simply allocating the iterator
251 * structure and initializing it.
252 *
253 * \return struct mni_channel_iterator *
254 */
255 static struct ast_channel_iterator *iterator_all_new(struct ast_channelstorage_instance *driver)
256 {
257 struct mni_channel_iterator *i = new mni_channel_iterator();
258 if (!i) {
259 return NULL;
260 }
261
262 return (struct ast_channel_iterator *)i;
263 }
264
265 /*!
266 * \internal
267 * \brief Retrieve the next channel in the iterator.
268 *
269 * This function retrieves the next channel in the iterator, based on the
270 * type of iterator it is. If there are no more channels, it returns NULL.
271 *
272 * In a single-threaded environment, we'd simply use the std::map
273 * begin(), end(), lower_bound() and upper_bound() functions and use
274 * standard iterator operations to move through the map. This doesn't
275 * work well in a multi-threaded environment where deletes can happen
276 * in another thread because if you delete the object an iterator points
277 * to, it becomes invalid and there's no way to test that. If you try
278 * to access or operate on that iterator (like incrementing it), the
279 * result will be a SEGV or other undefined behavior.
280 *
281 * app_chanspy is particularly prone to triggering this issue because
282 * it opens an iterator and keeps it open for a long period of time
283 * looking for channels to spy on.
284 *
285 * The solution is to use a C++ iterator to find the next (or first)
286 * channel then save that channel's key in our iterator structure to
287 * use as the starting point the next time iterator_next() is called.
288 * We also put a read lock on the driver to prevent a driver from
289 * deleting a channel in the short time we use it. We NEVER keep
290 * C++ iterators across multiple calls to iterator_next().
291 *
292 * This sounds inefficient but in practice, it works very well
293 * because the C++ map is implemented as a red-black tree. This
294 * makes calling lower_bound() very efficient. Besides, even with
295 * this approach, the iterators are still at least an order of
296 * magnitude, and sometimes two orders, faster than the ao2_legacy
297 * driver. To check the results for yourself, build in development
298 * mode and run "test execute category /main/channelstorage/"
299 * from the CLI.
300 *
301 * \return struct ast_channel * or NULL
302 */
303
304 static struct ast_channel *iterator_next(struct ast_channelstorage_instance *driver,
305 struct ast_channel_iterator *ai)
306 {
307 struct mni_channel_iterator *i = (struct mni_channel_iterator *)ai;
308 struct ast_channel *chan = NULL;
309 ChannelMap::const_iterator it;
310
311 if (!driver || !i) {
312 return NULL;
313 }
314
315 i->counter++;
316 rdlock(driver);
317
318 if (i->counter == 1) {
319 /*
320 * When this is the first call to iterator_next(),
321 * lower_bound(i->l_name) will return the first
322 * channel in the map if i->l_name is empty
323 * (ITERATOR_ALL and ITERATOR_BY_EXTEN) or the
324 * first channel whose name starts with i->l_name
325 * (ITERATOR_BY_NAME). This is exactly what we want.
326 */
327 it = getdb(driver).lower_bound(i->l_name);
328 } else {
329 /*
330 * When this is not the first call to iterator_next(),
331 * we want to return the next channel after the last
332 * channel returned. We can do this by using the
333 * last_channel key stored in the iterator to get
334 * an iterator to directly to it, then advancing it.
335 * It's possible that last_channel was actually the
336 * last channel in the map and was deleted between the
337 * last call to iterator_next() and now so we need to
338 * check that it's still around before we try to advance it.
339 */
340 it = getdb(driver).lower_bound(i->last_channel);
341 if (it == getdb(driver).end()) {
342 unlock(driver);
343 return NULL;
344 }
345 std::advance(it, 1);
346 }
347
348 /*
349 * Whether this is the first call to iterator_next() or
350 * a subsequent call, if we reached the end of the map,
351 * return NULL.
352 */
353 if (it == getdb(driver).end()) {
354 unlock(driver);
355 return NULL;
356 }
357
358 if (i->it_type == ITERATOR_ALL) {
359 /*
360 * The simplest case. Save the channel key to last_channel
361 * and bump and return the channel.
362 */
363 i->last_channel = it->first;
364 chan = ao2_bump(it->second);
365
366 } else if (i->it_type == ITERATOR_BY_NAME) {
367 /*
368 * If this was a search by name, we need to check that
369 * the channel key still matches the name being searched for.
370 * If it does, save the channel key to last_channel and bump
371 * and return the channel.
372 * If it doesn't match, we're done because the map is sorted
373 * by channel name so any further channels in the map won't
374 * match either.
375 */
376 if (it->first.substr(0, i->l_name_len) == i->l_name) {
377 i->last_channel = it->first;
378 chan = ao2_bump(it->second);
379 }
380
381 } else if (i->it_type == ITERATOR_BY_EXTEN) {
382 /*
383 * Searching by context and extension is a bit more complex.
384 * Every time iterator_next() is called, we need to search for
385 * matching context and extension from the last_channel forward
386 * to the end of the map. It's f'ugly and we have to hold
387 * the read lock while we traverse but it works, it's safe,
388 * and it's STILL better than the ao2_legacy driver albeit not
389 * by much.
390 */
391 while (it != getdb(driver).end()) {
392 int ret = channelstorage_exten_cb(it->second, i->context, i->exten, 0);
393 if (ret & CMP_MATCH) {
394 i->last_channel = it->first;
395 chan = ao2_bump(it->second);
396 break;
397 }
398 std::advance(it, 1);
399 }
400 } else {
401 ast_log(LOG_ERROR, "Unknown iterator type %d\n", i->it_type);
402 }
403 unlock(driver);
404
405 return chan;
406 }
407
408 /*!
409 * \internal
410 * \brief Create a new iterator for retrieving all channels matching
411 * a specific name prefix. A full channel name can be supplied but calling
412 * get_by_name_exact() is more efficient for that.
413 *
414 * No I/O is done at this time. It's simply allocating the iterator
415 * structure and initializing it.
416 *
417 * \return struct mni_channel_iterator *
418 */
419 static struct ast_channel_iterator *iterator_by_name_new(
420 struct ast_channelstorage_instance *driver,
421 const char *name, size_t name_len)
422 {
423 char *l_name = NULL;
424 struct mni_channel_iterator *i;
425
426 if (ast_strlen_zero(name)) {
427 return NULL;
428 }
429
430 l_name = ast_str_to_lower(ast_strdupa(name));
431 if (name_len == 0) {
432 name_len = strlen(name);
433 }
434 l_name[name_len] = '\0';
435
436 i = new mni_channel_iterator(l_name);
437 if (!i) {
438 return NULL;
439 }
440
441 return (struct ast_channel_iterator *)i;
442 }
443
444 /*!
445 * \internal
446 * \brief Create a new iterator for retrieving all channels
447 * matching a specific context and optionally exten.
448 *
449 * No I/O is done at this time. It's simply allocating the iterator
450 * structure and initializing it.
451 *
452 * \return struct mni_channel_iterator *
453 */
454 static struct ast_channel_iterator *iterator_by_exten_new(struct ast_channelstorage_instance *driver,
455 const char *exten, const char *context)
456 {
457 struct mni_channel_iterator *i = new mni_channel_iterator(
458 ast_str_to_lower(ast_strdupa(context)),
459 ast_str_to_lower(ast_strdupa(exten)));
460
461 if (!i) {
462 return NULL;
463 }
464
465 return (struct ast_channel_iterator *)i;
466 }
467
468 static struct ast_channel *get_by_uniqueid(struct ast_channelstorage_instance *driver,
469 const char *uniqueid, int lock)
470 {
471 struct ast_channel *chan = NULL;
472 char *search = uniqueid ? ast_str_to_lower(ast_strdupa(uniqueid)) : NULL;
473
474 if (ast_strlen_zero(uniqueid)) {
475 return NULL;
476 }
477
478 if (lock) {
479 rdlock(driver);
480 }
481 auto rtn = map_by_id(driver).find(search);
482 if (rtn != map_by_id(driver).end()) {
483 chan = ao2_bump((struct ast_channel *)rtn->second);
484 }
485 if (lock) {
486 unlock(driver);
487 }
488
489 return chan;
490 }
491
492 static struct ast_channel *get_by_name_exact(struct ast_channelstorage_instance *driver,
493 const char *name, int lock)
494 {
495 struct ast_channel *chan = NULL;
496 char *search = name ? ast_str_to_lower(ast_strdupa(name)) : NULL;
497
498 if (ast_strlen_zero(name)) {
499 return NULL;
500 }
501
502 if (lock) {
503 rdlock(driver);
504 }
505 auto rtn = getdb(driver).find(search);
506 if (rtn != getdb(driver).end()) {
507 chan = ao2_bump((struct ast_channel *)rtn->second);
508 }
509 if (lock) {
510 unlock(driver);
511 }
512
513 return chan;
514 }
515
516 static struct ast_channel *get_by_name_prefix(struct ast_channelstorage_instance *driver,
517 const char *name, size_t name_len, int lock)
518 {
519 struct ast_channel *chan = NULL;
520 char *l_name = NULL;
521
522 if (name_len == 0) {
523 chan = get_by_name_exact(driver, name, lock);
524 return chan;
525 }
526
527 l_name = ast_str_to_lower(ast_strdupa(name));
528
529 if (lock) {
530 rdlock(driver);
531 }
532 auto rtn = getdb(driver).lower_bound(l_name);
533 if (rtn != getdb(driver).end()) {
534 /* Check if the channel name actually starts with the requested prefix */
535 if (rtn->first.compare(0, name_len, l_name, name_len) == 0) {
536 chan = ao2_bump((struct ast_channel *)rtn->second);
537 }
538 }
539 if (lock) {
540 unlock(driver);
541 }
542
543 return chan;
544 }
545
546
547 static void close_instance(struct ast_channelstorage_instance *driver)
548 {
549 ast_debug(1, "Closing channel storage driver %s\n", driver ? driver->name : "NULL");
550 if (!driver) {
551 return;
552 }
553
554 if (driver->handle) {
555 delete (struct mni_channelstorage_driver_pvt *)driver->handle;
556 driver->handle = NULL;
557 }
558 ast_free(driver->lock_handle);
559 driver->lock_handle = NULL;
560 ast_free(driver);
561 }
562
563 static struct ast_channelstorage_instance channelstorage_instance = {
564 .handle = NULL,
565 .lock_handle = NULL,
566 .close_instance = close_instance,
567 .insert = insert_channel,
568 .remove = delete_channel,
569 .rdlock = rdlock,
570 .wrlock = wrlock,
571 .unlock = unlock,
572 .active_channels = active_channels,
573 .callback = callback,
574 .get_by_name_prefix= get_by_name_prefix,
575 .get_by_name_prefix_or_uniqueid = channelstorage_by_name_prefix_or_uniqueid,
576 .get_by_exten = channelstorage_by_exten,
577 .get_by_uniqueid = get_by_uniqueid,
578 .iterator_all_new = iterator_all_new,
579 .iterator_by_exten_new = iterator_by_exten_new,
580 .iterator_by_name_new = iterator_by_name_new,
581 .iterator_next = iterator_next,
582 .iterator_destroy = iterator_destroy,
583 };
584
585 static struct ast_channelstorage_instance* get_instance(const char *name)
586 {
587 const char *_name = name ? name : "default";
588 struct ast_channelstorage_instance* driver =
589 (struct ast_channelstorage_instance*)ast_calloc(1,
590 sizeof(*driver) + strlen(_name) + 1);
591
592 ast_debug(1, "Opening channel storage driver %s\n", _name);
593
594 if (!driver) {
595 ast_log(LOG_ERROR, "Failed to allocate memory for channel storage driver %s\n",
596 _name);
597 return NULL;
598 }
599 memcpy(driver, &channelstorage_instance, sizeof(*driver));
600 strcpy(driver->name, _name); /* Safe */
601
602 driver->handle = (struct ast_channelstorage_driver_pvt *)new mni_channelstorage_driver_pvt();
603
604 if (!driver->handle) {
605 ast_log(LOG_ERROR, "Failed to create channel storage driver %s\n",
606 _name);
607 ast_free(driver);
608 return NULL;
609 }
610 driver->lock_handle = ast_calloc(1, sizeof(ast_rwlock_t));
611 if (!driver->lock_handle) {
612 ast_log(LOG_ERROR, "Failed to create container lock for channel storage driver %s\n",
613 _name);
614 close_instance(driver);
615 return NULL;
616 }
617 ast_rwlock_init((ast_rwlock_t *)driver->lock_handle);
618
619 return driver;
620 }
621
622 static struct ast_channelstorage_driver driver_type = {
623 .driver_name = "cpp_map_name_id",
624 .open_instance = get_instance,
625 };
626
627 static void __attribute__((constructor)) __startup(void)
628 {
629 ast_channelstorage_register_driver(&driver_type);
630 }