summaryrefslogtreecommitdiff
path: root/res/res_stasis.c
blob: de432e409bd2dcb6acc7f6457b7004b1d9e81c96 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
/*
 * Asterisk -- An open source telephony toolkit.
 *
 * Copyright (C) 2012 - 2013, Digium, Inc.
 *
 * David M. Lee, II <dlee@digium.com>
 *
 * See http://www.asterisk.org for more information about
 * the Asterisk project. Please do not directly contact
 * any of the maintainers of this project for assistance;
 * the project provides a web site, mailing lists and IRC
 * channels for your use.
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License Version 2. See the LICENSE file
 * at the top of the source tree.
 */

/*! \file
 *
 * \brief Stasis application support.
 *
 * \author David M. Lee, II <dlee@digium.com>
 *
 * <code>res_stasis.so</code> brings together the various components of the
 * Stasis application infrastructure.
 *
 * First, there's the Stasis application handler, stasis_app_exec(). This is
 * called by <code>app_stasis.so</code> to give control of a channel to the
 * Stasis application code from the dialplan.
 *
 * While a channel is in stasis_app_exec(), it has a \ref stasis_app_control
 * object, which may be used to control the channel.
 *
 * To control the channel, commands may be sent to channel using
 * stasis_app_send_command() and stasis_app_send_async_command().
 *
 * Alongside this, applications may be registered/unregistered using
 * stasis_app_register()/stasis_app_unregister(). While a channel is in Stasis,
 * events received on the channel's topic are converted to JSON and forwarded to
 * the \ref stasis_app_cb. The application may also subscribe to the channel to
 * continue to receive messages even after the channel has left Stasis, but it
 * will not be able to control it.
 *
 * Given all the stuff that comes together in this module, it's been broken up
 * into several pieces that are in <code>res/stasis/</code> and compiled into
 * <code>res_stasis.so</code>.
 */

/*** MODULEINFO
	<depend>res_stasis_json_events</depend>
	<support_level>core</support_level>
 ***/

#include "asterisk.h"

ASTERISK_FILE_VERSION(__FILE__, "$Revision$")

#include "asterisk/astobj2.h"
#include "asterisk/callerid.h"
#include "asterisk/module.h"
#include "asterisk/stasis_app_impl.h"
#include "asterisk/stasis_channels.h"
#include "asterisk/stasis_bridging.h"
#include "asterisk/stasis_message_router.h"
#include "asterisk/strings.h"
#include "stasis/app.h"
#include "stasis/control.h"
#include "stasis_json/resource_events.h"

/*! Time to wait for a frame in the application */
#define MAX_WAIT_MS 200

/*!
 * \brief Number of buckets for the Stasis application hash table.  Remember to
 * keep it a prime number!
 */
#define APPS_NUM_BUCKETS 127

/*!
 * \brief Number of buckets for the Stasis application hash table.  Remember to
 * keep it a prime number!
 */
#define CONTROLS_NUM_BUCKETS 127

/*!
 * \brief Stasis application container.
 */
struct ao2_container *apps_registry;

struct ao2_container *app_controls;

struct ao2_container *app_bridges;

/*! \brief Message router for the channel caching topic */
struct stasis_message_router *channel_router;

/*! \brief Message router for the bridge caching topic */
struct stasis_message_router *bridge_router;

/*! AO2 hash function for \ref app */
static int app_hash(const void *obj, const int flags)
{
	const struct app *app = obj;
	const char *name = flags & OBJ_KEY ? obj : app_name(app);

	return ast_str_hash(name);
}

/*! AO2 comparison function for \ref app */
static int app_compare(void *lhs, void *rhs, int flags)
{
	const struct app *lhs_app = lhs;
	const struct app *rhs_app = rhs;
	const char *lhs_name = app_name(lhs_app);
	const char *rhs_name = flags & OBJ_KEY ? rhs : app_name(rhs_app);

	if (strcmp(lhs_name, rhs_name) == 0) {
		return CMP_MATCH | CMP_STOP;
	} else {
		return 0;
	}
}

/*! AO2 hash function for \ref stasis_app_control */
static int control_hash(const void *obj, const int flags)
{
	const struct stasis_app_control *control = obj;
	const char *id = flags & OBJ_KEY ?
		obj : stasis_app_control_get_channel_id(control);

	return ast_str_hash(id);
}

/*! AO2 comparison function for \ref stasis_app_control */
static int control_compare(void *lhs, void *rhs, int flags)
{
	const struct stasis_app_control *lhs_control = lhs;
	const struct stasis_app_control *rhs_control = rhs;
	const char *lhs_id = stasis_app_control_get_channel_id(lhs_control);
	const char *rhs_id = flags & OBJ_KEY ?
		rhs : stasis_app_control_get_channel_id(rhs_control);

	if (strcmp(lhs_id, rhs_id) == 0) {
		return CMP_MATCH | CMP_STOP;
	} else {
		return 0;
	}
}

struct stasis_app_control *stasis_app_control_find_by_channel(
	const struct ast_channel *chan)
{
	if (chan == NULL) {
		return NULL;
	}

	return stasis_app_control_find_by_channel_id(
		ast_channel_uniqueid(chan));
}

struct stasis_app_control *stasis_app_control_find_by_channel_id(
	const char *channel_id)
{
	return ao2_find(app_controls, channel_id, OBJ_KEY);
}

/*! AO2 hash function for bridges container  */
static int bridges_hash(const void *obj, const int flags)
{
	const struct ast_bridge *bridge = obj;
	const char *id = flags & OBJ_KEY ?
		obj : bridge->uniqueid;

	return ast_str_hash(id);
}

/*! AO2 comparison function for bridges container */
static int bridges_compare(void *lhs, void *rhs, int flags)
{
	const struct ast_bridge *lhs_bridge = lhs;
	const struct ast_bridge *rhs_bridge = rhs;
	const char *lhs_id = lhs_bridge->uniqueid;
	const char *rhs_id = flags & OBJ_KEY ?
		rhs : rhs_bridge->uniqueid;

	if (strcmp(lhs_id, rhs_id) == 0) {
		return CMP_MATCH | CMP_STOP;
	} else {
		return 0;
	}
}

struct ast_bridge *stasis_app_bridge_find_by_id(
	const char *bridge_id)
{
	return ao2_find(app_bridges, bridge_id, OBJ_KEY);
}

/*! \brief Typedef for blob handler callbacks */
typedef struct ast_json *(*channel_blob_handler_cb)(struct ast_channel_blob *);

/*! \brief Callback to check whether an app is watching a given channel */
static int app_watching_channel_cb(void *obj, void *arg, int flags)
{
	struct app *app = obj;
	char *uniqueid = arg;

	return app_is_watching_channel(app, uniqueid) ? CMP_MATCH : 0;
}

/*! \brief Get a container full of apps that are interested in the specified channel */
static struct ao2_container *get_apps_watching_channel(const char *uniqueid)
{
	struct ao2_container *watching_apps;
	char *uniqueid_dup;
	RAII_VAR(struct ao2_iterator *,watching_apps_iter, NULL, ao2_iterator_destroy);
	ast_assert(uniqueid != NULL);

	uniqueid_dup = ast_strdupa(uniqueid);

	watching_apps_iter = ao2_callback(apps_registry, OBJ_MULTIPLE, app_watching_channel_cb, uniqueid_dup);
	watching_apps = watching_apps_iter->c;

	if (!ao2_container_count(watching_apps)) {
		return NULL;
	}

	ao2_ref(watching_apps, +1);
	return watching_apps_iter->c;
}

/*! \brief Typedef for callbacks that get called on channel snapshot updates */
typedef struct ast_json *(*channel_snapshot_monitor)(
	struct ast_channel_snapshot *old_snapshot,
	struct ast_channel_snapshot *new_snapshot);

/*! \brief Handle channel state changes */
static struct ast_json *channel_state(
	struct ast_channel_snapshot *old_snapshot,
	struct ast_channel_snapshot *new_snapshot)
{
	RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
	struct ast_channel_snapshot *snapshot = new_snapshot ? new_snapshot : old_snapshot;

	if (!old_snapshot) {
		return stasis_json_event_channel_created_create(snapshot);
	} else if (!new_snapshot) {
		json = ast_json_pack("{s: i, s: s}",
			"cause", snapshot->hangupcause,
			"cause_txt", ast_cause2str(snapshot->hangupcause));
		if (!json) {
			return NULL;
		}
		return stasis_json_event_channel_destroyed_create(snapshot, json);
	} else if (old_snapshot->state != new_snapshot->state) {
		return stasis_json_event_channel_state_change_create(snapshot);
	}

	return NULL;
}

static struct ast_json *channel_dialplan(
	struct ast_channel_snapshot *old_snapshot,
	struct ast_channel_snapshot *new_snapshot)
{
	RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);

	/* No Newexten event on cache clear */
	if (!new_snapshot) {
		return NULL;
	}

	/* Empty application is not valid for a Newexten event */
	if (ast_strlen_zero(new_snapshot->appl)) {
		return NULL;
	}

	if (old_snapshot && ast_channel_snapshot_cep_equal(old_snapshot, new_snapshot)) {
		return NULL;
	}

	json = ast_json_pack("{s: s, s: s}",
		"application", new_snapshot->appl,
		"application_data", new_snapshot->data);
	if (!json) {
		return NULL;
	}

	return stasis_json_event_channel_dialplan_create(new_snapshot, json);
}

static struct ast_json *channel_callerid(
	struct ast_channel_snapshot *old_snapshot,
	struct ast_channel_snapshot *new_snapshot)
{
	RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);

	/* No NewCallerid event on cache clear or first event */
	if (!old_snapshot || !new_snapshot) {
		return NULL;
	}

	if (ast_channel_snapshot_caller_id_equal(old_snapshot, new_snapshot)) {
		return NULL;
	}

	json = ast_json_pack("{s: i, s: s}",
		"caller_presentation", new_snapshot->caller_pres,
		"caller_presentation_txt", ast_describe_caller_presentation(new_snapshot->caller_pres));
	if (!json) {
		return NULL;
	}

	return stasis_json_event_channel_caller_id_create(new_snapshot, json);
}

static struct ast_json *channel_snapshot(
	struct ast_channel_snapshot *old_snapshot,
	struct ast_channel_snapshot *new_snapshot)
{
	if (!new_snapshot) {
		return NULL;
	}

	return stasis_json_event_channel_snapshot_create(new_snapshot);
}

channel_snapshot_monitor channel_monitors[] = {
	channel_snapshot,
	channel_state,
	channel_dialplan,
	channel_callerid
};

static int app_send_cb(void *obj, void *arg, int flags)
{
	struct app *app = obj;
	struct ast_json *msg = arg;

	app_send(app, msg);
	return 0;
}

static void sub_channel_snapshot_handler(void *data,
		struct stasis_subscription *sub,
		struct stasis_topic *topic,
		struct stasis_message *message)
{
	RAII_VAR(struct ao2_container *, watching_apps, NULL, ao2_cleanup);
	struct stasis_cache_update *update = stasis_message_data(message);
	struct ast_channel_snapshot *new_snapshot = stasis_message_data(update->new_snapshot);
	struct ast_channel_snapshot *old_snapshot = stasis_message_data(update->old_snapshot);
	int i;

	watching_apps = get_apps_watching_channel(new_snapshot ? new_snapshot->uniqueid : old_snapshot->uniqueid);
	if (!watching_apps) {
		return;
	}

	for (i = 0; i < ARRAY_LEN(channel_monitors); ++i) {
		RAII_VAR(struct ast_json *, msg, NULL, ast_json_unref);

		msg = channel_monitors[i](old_snapshot, new_snapshot);
		if (msg) {
			ao2_callback(watching_apps, OBJ_NODATA, app_send_cb, msg);
		}
	}
}

static void distribute_message(struct ao2_container *apps, struct ast_json *msg)
{
	ao2_callback(apps, OBJ_NODATA, app_send_cb, msg);
}

static void generic_blob_handler(struct ast_channel_blob *obj, channel_blob_handler_cb handler_cb)
{
	RAII_VAR(struct ast_json *, msg, NULL, ast_json_unref);
	RAII_VAR(struct ao2_container *, watching_apps, NULL, ao2_cleanup);

	if (!obj->snapshot) {
		return;
	}

	watching_apps = get_apps_watching_channel(obj->snapshot->uniqueid);
	if (!watching_apps) {
		return;
	}

	msg = handler_cb(obj);
	if (!msg) {
		return;
	}

	distribute_message(watching_apps, msg);
}

/*!
 * \brief In addition to running ao2_cleanup(), this function also removes the
 * object from the app_controls container.
 */
static void control_unlink(struct stasis_app_control *control)
{
	if (!control) {
		return;
	}

	ao2_unlink_flags(app_controls, control,
		OBJ_POINTER | OBJ_UNLINK | OBJ_NODATA);
	ao2_cleanup(control);
}

struct ast_bridge *stasis_app_bridge_create(const char *type)
{
	struct ast_bridge *bridge;
	int capabilities, flags = 0;
	if (ast_strlen_zero(type) || !strcmp(type, "mixing")) {
		capabilities = AST_BRIDGE_CAPABILITY_1TO1MIX |
			AST_BRIDGE_CAPABILITY_MULTIMIX |
			AST_BRIDGE_CAPABILITY_NATIVE;
		flags = AST_BRIDGE_FLAG_SMART;
	} else if (!strcmp(type, "holding")) {
		capabilities = AST_BRIDGE_CAPABILITY_HOLDING;
	} else {
		return NULL;
	}

	bridge = ast_bridge_base_new(capabilities, flags);
	if (bridge) {
		ao2_link(app_bridges, bridge);
	}
	return bridge;
}

void stasis_app_bridge_destroy(const char *bridge_id)
{
	struct ast_bridge *bridge = stasis_app_bridge_find_by_id(bridge_id);
	if (!bridge) {
		return;
	}
	ao2_unlink(app_bridges, bridge);
	ast_bridge_destroy(bridge);
}

int app_send_start_msg(struct app *app, struct ast_channel *chan,
	int argc, char *argv[])
{
	RAII_VAR(struct ast_json *, msg, NULL, ast_json_unref);
	RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
	RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);

	struct ast_json *json_args;
	int i;

	ast_assert(chan != NULL);

	/* Set channel info */
	snapshot = ast_channel_snapshot_create(chan);
	if (!snapshot) {
		return -1;
	}

	blob = ast_json_pack("{s: []}", "args");
	if (!blob) {
		return -1;
	}

	/* Append arguments to args array */
	json_args = ast_json_object_get(blob, "args");
	ast_assert(json_args != NULL);
	for (i = 0; i < argc; ++i) {
		int r = ast_json_array_append(json_args,
					      ast_json_string_create(argv[i]));
		if (r != 0) {
			ast_log(LOG_ERROR, "Error appending start message\n");
			return -1;
		}
	}

	msg = stasis_json_event_stasis_start_create(snapshot, blob);
	if (!msg) {
		return -1;
	}

	app_send(app, msg);
	return 0;
}

int app_send_end_msg(struct app *app, struct ast_channel *chan)
{
	RAII_VAR(struct ast_json *, msg, NULL, ast_json_unref);
	RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);

	ast_assert(chan != NULL);

	/* Set channel info */
	snapshot = ast_channel_snapshot_create(chan);
	if (snapshot == NULL) {
		return -1;
	}

	msg = stasis_json_event_stasis_end_create(snapshot);
	if (!msg) {
		return -1;
	}

	app_send(app, msg);
	return 0;
}

/*! /brief Stasis dialplan application callback */
int stasis_app_exec(struct ast_channel *chan, const char *app_name, int argc,
		    char *argv[])
{
	SCOPED_MODULE_USE(ast_module_info->self);

	RAII_VAR(struct app *, app, NULL, ao2_cleanup);
	RAII_VAR(struct stasis_app_control *, control, NULL, control_unlink);
	int res = 0;

	ast_assert(chan != NULL);

	app = ao2_find(apps_registry, app_name, OBJ_KEY);
	if (!app) {
		ast_log(LOG_ERROR,
			"Stasis app '%s' not registered\n", app_name);
		return -1;
	}

	control = control_create(chan);
	if (!control) {
		ast_log(LOG_ERROR, "Allocated failed\n");
		return -1;
	}
	ao2_link(app_controls, control);

	res = app_send_start_msg(app, chan, argc, argv);
	if (res != 0) {
		ast_log(LOG_ERROR,
			"Error sending start message to %s\n", app_name);
		return res;
	}

	if (app_add_channel(app, chan)) {
		ast_log(LOG_ERROR, "Error adding listener for channel %s to app %s\n", ast_channel_name(chan), app_name);
		return -1;
	}

	while (!control_is_done(control)) {
		RAII_VAR(struct ast_frame *, f, NULL, ast_frame_dtor);
		int r;
		int command_count;

		r = ast_waitfor(chan, MAX_WAIT_MS);

		if (r < 0) {
			ast_debug(3, "%s: Poll error\n",
				  ast_channel_uniqueid(chan));
			break;
		}

		command_count = control_dispatch_all(control, chan);

		if (command_count > 0 && ast_channel_fdno(chan) == -1) {
			/* Command drained the channel; wait for next frame */
			continue;
		}

		if (r == 0) {
			/* Timeout */
			continue;
		}

		f = ast_read(chan);
		if (!f) {
			ast_debug(3,
				"%s: No more frames. Must be done, I guess.\n",
				ast_channel_uniqueid(chan));
			break;
		}

		switch (f->frametype) {
		case AST_FRAME_CONTROL:
			if (f->subclass.integer == AST_CONTROL_HANGUP) {
				/* Continue on in the dialplan */
				ast_debug(3, "%s: Hangup\n",
					ast_channel_uniqueid(chan));
				control_continue(control);
			}
			break;
		default:
			/* Not handled; discard */
			break;
		}
	}

	app_remove_channel(app, chan);
	res = app_send_end_msg(app, chan);
	if (res != 0) {
		ast_log(LOG_ERROR,
			"Error sending end message to %s\n", app_name);
		return res;
	}

	return res;
}

int stasis_app_send(const char *app_name, struct ast_json *message)
{
	RAII_VAR(struct app *, app, NULL, ao2_cleanup);

	app = ao2_find(apps_registry, app_name, OBJ_KEY);

	if (!app) {
		/* XXX We can do a better job handling late binding, queueing up
		 * the call for a few seconds to wait for the app to register.
		 */
		ast_log(LOG_WARNING,
			"Stasis app '%s' not registered\n", app_name);
		return -1;
	}

	app_send(app, message);
	return 0;
}

int stasis_app_register(const char *app_name, stasis_app_cb handler, void *data)
{
	RAII_VAR(struct app *, app, NULL, ao2_cleanup);

	SCOPED_LOCK(apps_lock, apps_registry, ao2_lock, ao2_unlock);

	app = ao2_find(apps_registry, app_name, OBJ_KEY | OBJ_NOLOCK);

	if (app) {
		RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
		RAII_VAR(struct ast_json *, msg, NULL, ast_json_unref);

		blob = ast_json_pack("{s: s}", "application", app_name);
		if (blob) {
			msg = stasis_json_event_application_replaced_create(blob);
			if (msg) {
				app_send(app, msg);
			}
		}

		app_update(app, handler, data);
	} else {
		app = app_create(app_name, handler, data);
		if (app) {
			ao2_link_flags(apps_registry, app, OBJ_NOLOCK);
		} else {
			return -1;
		}
	}

	return 0;
}

void stasis_app_unregister(const char *app_name)
{
	if (app_name) {
		ao2_cleanup(ao2_find(
				apps_registry, app_name, OBJ_KEY | OBJ_UNLINK));
	}
}

static struct ast_json *handle_blob_dtmf(struct ast_channel_blob *obj)
{
	RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
	RAII_VAR(struct ast_json *, msg, NULL, ast_json_unref);
	const char *direction;

	/* To simplify events, we'll only generate on receive */
	direction = ast_json_string_get(
		ast_json_object_get(obj->blob, "direction"));

	if (strcmp("Received", direction) != 0) {
		return NULL;
	}

	extra = ast_json_pack(
		"{s: o}",
		"digit", ast_json_ref(ast_json_object_get(obj->blob, "digit")));
	if (!extra) {
		return NULL;
	}

	return stasis_json_event_channel_dtmf_received_create(obj->snapshot, extra);
}

/* To simplify events, we'll only generate on DTMF end (dtmf_end type) */
static void sub_dtmf_handler(void *data,
		struct stasis_subscription *sub,
		struct stasis_topic *topic,
		struct stasis_message *message)
{
	struct ast_channel_blob *obj = stasis_message_data(message);
	generic_blob_handler(obj, handle_blob_dtmf);
}

static struct ast_json *handle_blob_userevent(struct ast_channel_blob *obj)
{
	return stasis_json_event_channel_userevent_create(obj->snapshot, obj->blob);
}

static void sub_userevent_handler(void *data,
		struct stasis_subscription *sub,
		struct stasis_topic *topic,
		struct stasis_message *message)
{
	struct ast_channel_blob *obj = stasis_message_data(message);
	generic_blob_handler(obj, handle_blob_userevent);
}

static struct ast_json *handle_blob_hangup_request(struct ast_channel_blob *obj)
{
	return stasis_json_event_channel_hangup_request_create(obj->snapshot, obj->blob);
}

static void sub_hangup_request_handler(void *data,
		struct stasis_subscription *sub,
		struct stasis_topic *topic,
		struct stasis_message *message)
{
	struct ast_channel_blob *obj = stasis_message_data(message);
	generic_blob_handler(obj, handle_blob_hangup_request);
}

static struct ast_json *handle_blob_varset(struct ast_channel_blob *obj)
{
	return stasis_json_event_channel_varset_create(obj->snapshot, obj->blob);
}

static void sub_varset_handler(void *data,
		struct stasis_subscription *sub,
		struct stasis_topic *topic,
		struct stasis_message *message)
{
	struct ast_channel_blob *obj = stasis_message_data(message);
	generic_blob_handler(obj, handle_blob_varset);
}

void stasis_app_ref(void)
{
	ast_module_ref(ast_module_info->self);
}

void stasis_app_unref(void)
{
	ast_module_unref(ast_module_info->self);
}

/*! \brief Callback to check whether an app is watching a given bridge */
static int app_watching_bridge_cb(void *obj, void *arg, int flags)
{
	struct app *app = obj;
	char *uniqueid = arg;

	return app_is_watching_bridge(app, uniqueid) ? CMP_MATCH : 0;
}

/*! \brief Get a container full of apps that are interested in the specified bridge */
static struct ao2_container *get_apps_watching_bridge(const char *uniqueid)
{
	struct ao2_container *watching_apps;
	char *uniqueid_dup;
	RAII_VAR(struct ao2_iterator *,watching_apps_iter, NULL, ao2_iterator_destroy);
	ast_assert(uniqueid != NULL);

	uniqueid_dup = ast_strdupa(uniqueid);

	watching_apps_iter = ao2_callback(apps_registry, OBJ_MULTIPLE, app_watching_bridge_cb, uniqueid_dup);
	watching_apps = watching_apps_iter->c;

	if (!ao2_container_count(watching_apps)) {
		return NULL;
	}

	ao2_ref(watching_apps, +1);
	return watching_apps_iter->c;
}

/*! Callback used to remove an app's interest in a bridge */
static int remove_bridge_cb(void *obj, void *arg, int flags)
{
	app_remove_bridge(obj, arg);
	return 0;
}

static void sub_bridge_snapshot_handler(void *data,
		struct stasis_subscription *sub,
		struct stasis_topic *topic,
		struct stasis_message *message)
{
	RAII_VAR(struct ao2_container *, watching_apps, NULL, ao2_cleanup);
	struct stasis_cache_update *update = stasis_message_data(message);
	struct ast_bridge_snapshot *new_snapshot = stasis_message_data(update->new_snapshot);
	struct ast_bridge_snapshot *old_snapshot = stasis_message_data(update->old_snapshot);
	RAII_VAR(struct ast_json *, msg, NULL, ast_json_unref);

	watching_apps = get_apps_watching_bridge(new_snapshot ? new_snapshot->uniqueid : old_snapshot->uniqueid);
	if (!watching_apps || !ao2_container_count(watching_apps)) {
		return;
	}

	if (!new_snapshot) {
		RAII_VAR(char *, bridge_id, ast_strdup(old_snapshot->uniqueid), ast_free);

		/* The bridge has gone away. Create the message, make sure no apps are
		 * watching this bridge anymore, and destroy the bridge's control
		 * structure */
		msg = stasis_json_event_bridge_destroyed_create(old_snapshot);
		ao2_callback(watching_apps, OBJ_NODATA, remove_bridge_cb, bridge_id);
		stasis_app_bridge_destroy(old_snapshot->uniqueid);
	} else if (!old_snapshot) {
		msg = stasis_json_event_bridge_created_create(old_snapshot);
	}

	if (!msg) {
		return;
	}

	distribute_message(watching_apps, msg);
}

/*! \brief Callback used to merge two containers of applications */
static int list_merge_cb(void *obj, void *arg, int flags)
{
	/* remove any current entries for this app */
	ao2_find(arg, obj, OBJ_POINTER | OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE);
	/* relink as the only entry */
	ao2_link(arg, obj);
	return 0;
}

/*! \brief Merge container src into container dst without modifying src */
static void update_apps_list(struct ao2_container *dst, struct ao2_container *src)
{
	ao2_callback(src, OBJ_NODATA, list_merge_cb, dst);
}

/*! \brief Callback for adding to an app's bridges of interest */
static int app_add_bridge_cb(void *obj, void *arg, int flags)
{
	app_add_bridge(obj, arg);
	return 0;
}

/*! \brief Add interest in the given bridge to all apps in the container */
static void update_bridge_interest(struct ao2_container *apps, const char *bridge_id)
{
	RAII_VAR(char *, bridge_id_dup, ast_strdup(bridge_id), ast_free);
	ao2_callback(apps, OBJ_NODATA, app_add_bridge_cb, bridge_id_dup);
}

static void sub_bridge_merge_handler(void *data,
		struct stasis_subscription *sub,
		struct stasis_topic *topic,
		struct stasis_message *message)
{
	RAII_VAR(struct ao2_container *, watching_apps_to, NULL, ao2_cleanup);
	RAII_VAR(struct ao2_container *, watching_apps_from, NULL, ao2_cleanup);
	RAII_VAR(struct ao2_container *, watching_apps_all, ao2_container_alloc(1, NULL, NULL), ao2_cleanup);
	struct ast_bridge_merge_message *merge = stasis_message_data(message);
	RAII_VAR(struct ast_json *, msg, NULL, ast_json_unref);
	RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);

	watching_apps_to = get_apps_watching_bridge(merge->to->uniqueid);
	if (watching_apps_to) {
		update_apps_list(watching_apps_all, watching_apps_to);
	}

	watching_apps_from = get_apps_watching_bridge(merge->from->uniqueid);
	if (watching_apps_from) {
		update_bridge_interest(watching_apps_from, merge->to->uniqueid);
		update_apps_list(watching_apps_all, watching_apps_from);
	}

	if (!ao2_container_count(watching_apps_all)) {
		return;
	}

	/* The secondary bridge has to be packed into JSON by hand because the auto-generated
	 * JSON event generator can only handle one instance of a given snapshot type in an
	 * elegant way */
	blob = ast_json_pack("{s: o}", "bridge_from", ast_bridge_snapshot_to_json(merge->from));
	if (!blob) {
		return;
	}

	msg = stasis_json_event_bridge_merged_create(merge->to, blob);

	distribute_message(watching_apps_all, msg);
}

static void sub_bridge_enter_handler(void *data,
		struct stasis_subscription *sub,
		struct stasis_topic *topic,
		struct stasis_message *message)
{
	RAII_VAR(struct ao2_container *, watching_apps_channel, NULL, ao2_cleanup);
	RAII_VAR(struct ao2_container *, watching_apps_bridge, NULL, ao2_cleanup);
	RAII_VAR(struct ao2_container *, watching_apps_all, ao2_container_alloc(1, NULL, NULL), ao2_cleanup);
	struct ast_bridge_blob *obj = stasis_message_data(message);
	RAII_VAR(struct ast_json *, msg, NULL, ast_json_unref);

	watching_apps_bridge = get_apps_watching_bridge(obj->bridge->uniqueid);
	if (watching_apps_bridge) {
		update_apps_list(watching_apps_all, watching_apps_bridge);
	}

	watching_apps_channel = get_apps_watching_channel(obj->channel->uniqueid);
	if (watching_apps_channel) {
		update_bridge_interest(watching_apps_channel, obj->bridge->uniqueid);
		update_apps_list(watching_apps_all, watching_apps_channel);
	}

	if (!ao2_container_count(watching_apps_all)) {
		return;
	}

	msg = stasis_json_event_channel_entered_bridge_create(obj->bridge, obj->channel);

	distribute_message(watching_apps_all, msg);
}

static void sub_bridge_leave_handler(void *data,
		struct stasis_subscription *sub,
		struct stasis_topic *topic,
		struct stasis_message *message)
{
	RAII_VAR(struct ao2_container *, watching_apps_bridge, NULL, ao2_cleanup);
	struct ast_bridge_blob *obj = stasis_message_data(message);
	RAII_VAR(struct ast_json *, msg, NULL, ast_json_unref);

	watching_apps_bridge = get_apps_watching_bridge(obj->bridge->uniqueid);
	if (!watching_apps_bridge) {
		return;
	}

	msg = stasis_json_event_channel_left_bridge_create(obj->bridge, obj->channel);

	distribute_message(watching_apps_bridge, msg);
}

static int load_module(void)
{
	int r = 0;

	apps_registry =
		ao2_container_alloc(APPS_NUM_BUCKETS, app_hash, app_compare);
	if (apps_registry == NULL) {
		return AST_MODULE_LOAD_FAILURE;
	}

	app_controls = ao2_container_alloc(CONTROLS_NUM_BUCKETS,
					     control_hash, control_compare);
	if (app_controls == NULL) {
		return AST_MODULE_LOAD_FAILURE;
	}

	app_bridges = ao2_container_alloc(CONTROLS_NUM_BUCKETS,
					     bridges_hash, bridges_compare);
	if (app_bridges == NULL) {
		return AST_MODULE_LOAD_FAILURE;
	}

	channel_router = stasis_message_router_create(stasis_caching_get_topic(ast_channel_topic_all_cached()));
	if (!channel_router) {
		return AST_MODULE_LOAD_FAILURE;
	}

	r |= stasis_message_router_add(channel_router, stasis_cache_update_type(), sub_channel_snapshot_handler, NULL);
	r |= stasis_message_router_add(channel_router, ast_channel_user_event_type(), sub_userevent_handler, NULL);
	r |= stasis_message_router_add(channel_router, ast_channel_varset_type(), sub_varset_handler, NULL);
	r |= stasis_message_router_add(channel_router, ast_channel_dtmf_begin_type(), sub_dtmf_handler, NULL);
	r |= stasis_message_router_add(channel_router, ast_channel_hangup_request_type(), sub_hangup_request_handler, NULL);
	if (r) {
		return AST_MODULE_LOAD_FAILURE;
	}

	bridge_router = stasis_message_router_create(stasis_caching_get_topic(ast_bridge_topic_all_cached()));
	if (!bridge_router) {
		return AST_MODULE_LOAD_FAILURE;
	}

	r |= stasis_message_router_add(bridge_router, stasis_cache_update_type(), sub_bridge_snapshot_handler, NULL);
	r |= stasis_message_router_add(bridge_router, ast_bridge_merge_message_type(), sub_bridge_merge_handler, NULL);
	r |= stasis_message_router_add(bridge_router, ast_channel_entered_bridge_type(), sub_bridge_enter_handler, NULL);
	r |= stasis_message_router_add(bridge_router, ast_channel_left_bridge_type(), sub_bridge_leave_handler, NULL);
	if (r) {
		return AST_MODULE_LOAD_FAILURE;
	}

	return AST_MODULE_LOAD_SUCCESS;
}

static int unload_module(void)
{
	int r = 0;

	stasis_message_router_unsubscribe_and_join(channel_router);
	channel_router = NULL;

	stasis_message_router_unsubscribe_and_join(bridge_router);
	bridge_router = NULL;

	ao2_cleanup(apps_registry);
	apps_registry = NULL;

	ao2_cleanup(app_controls);
	app_controls = NULL;

	ao2_cleanup(app_bridges);
	app_bridges = NULL;

	return r;
}

AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Stasis application support",
	.load = load_module,
	.unload = unload_module,
	);