summaryrefslogtreecommitdiff
path: root/res/res_stasis_websocket.c
blob: 5b21ebbd4760ee1421e2fba0ac19f377de82b007 (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
/*
 * 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 HTTP binding for the Stasis API
 *
 * \author David M. Lee, II <dlee@digium.com>
 */

/*** MODULEINFO
	<depend type="module">res_stasis</depend>
	<depend type="module">res_http_websocket</depend>
	<support_level>core</support_level>
 ***/

#include "asterisk.h"

ASTERISK_FILE_VERSION(__FILE__, "$Revision$")

#include "asterisk/astobj2.h"
#include "asterisk/http_websocket.h"
#include "asterisk/json.h"
#include "asterisk/module.h"
#include "asterisk/stasis_app.h"
#include "asterisk/strings.h"
#include "asterisk/utils.h"

/*! WebSocket protocol for Stasis */
static const char * const ws_protocol = "stasis";

/*! Message to send when out of memory */
static struct ast_json *oom_json;

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

struct websocket_app {
	char *name;
};

/*!
 * \internal
 * \brief Helper to write a JSON object to a WebSocket.
 * \param session WebSocket session.
 * \param message JSON message.
 * \return 0 on success.
 * \return -1 on error.
 */
static int websocket_write_json(struct ast_websocket *session,
				struct ast_json *message)
{
	RAII_VAR(char *, str, ast_json_dump_string(message), ast_free);

	if (str == NULL) {
		ast_log(LOG_ERROR, "Failed to encode JSON object\n");
		return -1;
	}

	return ast_websocket_write(session, AST_WEBSOCKET_OPCODE_TEXT, str,
				   strlen(str));
}

/*! Hash function for websocket_app */
static int hash_app(const void *obj, const int flags)
{
	const struct websocket_app *app = obj;
	const char *name = flags & OBJ_KEY ? obj : app->name;

	return ast_str_hash(name);
}

/*! Comparison function for websocket_app */
static int compare_app(void *lhs, void *rhs, int flags)
{
	const struct websocket_app *lhs_app = lhs;
	const struct websocket_app *rhs_app = rhs;
	const char *rhs_name = flags & OBJ_KEY ? rhs : rhs_app->name;

	if (strcmp(lhs_app->name, rhs_name) == 0) {
		return CMP_MATCH;
	} else {
		return 0;
	}
}

static void app_dtor(void *obj)
{
	struct websocket_app *app = obj;
	ast_free(app->name);
}

struct stasis_ws_session_info {
	struct ast_websocket *ws_session;
	struct ao2_container *websocket_apps;
};

static void session_dtor(void *obj)
{
#ifdef AST_DEVMODE /* Avoid unused variable warning */
	struct stasis_ws_session_info *session = obj;
#endif

	/* session_shutdown should have been called before */
	ast_assert(session->ws_session == NULL);
	ast_assert(session->websocket_apps == NULL);
}

static struct stasis_ws_session_info *session_create(
	struct ast_websocket *ws_session)
{
	RAII_VAR(struct stasis_ws_session_info *, session, NULL, ao2_cleanup);

	session = ao2_alloc(sizeof(*session), session_dtor);

	session->ws_session = ws_session;
	session->websocket_apps =
		ao2_container_alloc(APPS_NUM_BUCKETS, hash_app, compare_app);

	if (!session->websocket_apps) {
		return NULL;
	}

	ao2_ref(session, +1);
	return session;
}

/*!
 * \brief Explicitly shutdown a session.
 *
 * An explicit shutdown is necessary, since stasis-app has a reference to this
 * session. We also need to be sure to null out the \c ws_session field, since
 * the websocket is about to go away.
 *
 * \param session Session info struct.
 */
static void session_shutdown(struct stasis_ws_session_info *session)
{
        struct ao2_iterator i;
	struct websocket_app *app;
	SCOPED_AO2LOCK(lock, session);

	i = ao2_iterator_init(session->websocket_apps, 0);
	while ((app = ao2_iterator_next(&i))) {
		stasis_app_unregister(app->name);
		ao2_cleanup(app);
	}
	ao2_iterator_destroy(&i);
	ao2_cleanup(session->websocket_apps);

	session->websocket_apps = NULL;
	session->ws_session = NULL;
}

/*!
 * \brief Callback handler for Stasis application messages.
 */
static void app_handler(void *data, const char *app_name,
			struct ast_json *message)
{
	struct stasis_ws_session_info *session = data;
	int res;

	res = ast_json_object_set(message, "application",
				  ast_json_string_create(app_name));
	if(res != 0) {
		return;
	}

	ao2_lock(session);
	if (session->ws_session) {
		websocket_write_json(session->ws_session, message);
	}
	ao2_unlock(session);
}

/*!
 * \brief Register for all of the apps given.
 * \param session Session info struct.
 * \param app_list Comma seperated list of app names to register.
 */
static int session_register_apps(struct stasis_ws_session_info *session,
				 const char *app_list)
{
	RAII_VAR(char *, to_free, NULL, ast_free);
	char *apps, *app_name;
	SCOPED_AO2LOCK(lock, session);

	ast_assert(session->ws_session != NULL);
	ast_assert(session->websocket_apps != NULL);

	to_free = apps = ast_strdup(app_list);
	if (!apps) {
		websocket_write_json(session->ws_session, oom_json);
		return -1;
	}
	while ((app_name = strsep(&apps, ","))) {
		RAII_VAR(struct websocket_app *, app, NULL, ao2_cleanup);

		app = ao2_alloc(sizeof(*app), app_dtor);
		if (!app) {
			websocket_write_json(session->ws_session, oom_json);
			return -1;
		}
		app->name = ast_strdup(app_name);
		ao2_link(session->websocket_apps, app);

		stasis_app_register(app_name, app_handler, session);
	}
	return 0;
}

static void websocket_callback(struct ast_websocket *ws_session,
			       struct ast_variable *parameters,
			       struct ast_variable *headers)
{
	RAII_VAR(struct stasis_ws_session_info *, stasis_session, NULL, ao2_cleanup);
	struct ast_variable *param = NULL;
	int res;

	ast_debug(3, "Stasis web socket connection\n");

	if (ast_websocket_set_nonblock(ws_session) != 0) {
		ast_log(LOG_ERROR,
			"Stasis web socket failed to set nonblock; closing\n");
		goto end;
	}

	stasis_session = session_create(ws_session);

	if (!stasis_session) {
		websocket_write_json(ws_session, oom_json);
		goto end;
	}

	for (param = parameters; param; param = param->next) {
		if (strcmp(param->name, "app") == 0) {
			int ret = session_register_apps(
				stasis_session, param->value);
			if (ret != 0) {
				goto end;
			}
		}
	}

	if (ao2_container_count(stasis_session->websocket_apps) == 0) {
		RAII_VAR(struct ast_json *, msg, NULL, ast_json_unref);

		msg = ast_json_pack("{s: s, s: [s]}",
				    "error", "MissingParams",
				    "params", "app");
		if (msg) {
			websocket_write_json(ws_session, msg);
		}

		goto end;
	}

	while ((res = ast_wait_for_input(ast_websocket_fd(ws_session), -1)) > 0) {
		char *payload;
		uint64_t payload_len;
		enum ast_websocket_opcode opcode;
		int fragmented;
		int read = ast_websocket_read(ws_session, &payload, &payload_len,
					      &opcode, &fragmented);

		if (read) {
			ast_log(LOG_ERROR,
				"Stasis WebSocket read error; closing\n");
			break;
		}

		if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
			break;
		}
	}

end:
	session_shutdown(stasis_session);
	ast_websocket_unref(ws_session);
}

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

	oom_json = ast_json_pack("{s: s}",
				 "error", "OutOfMemory");
	if (!oom_json) {
		/* ironic */
		return AST_MODULE_LOAD_FAILURE;
	}
	r |= ast_websocket_add_protocol(ws_protocol, websocket_callback);
	return r;
}

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

	ast_json_unref(oom_json);
	oom_json = NULL;
	r |= ast_websocket_remove_protocol(ws_protocol, websocket_callback);
	return r;
}

AST_MODULE_INFO(ASTERISK_GPL_KEY, 0, "Stasis HTTP bindings",
                .load = load_module,
                .unload = unload_module,
                .nonoptreq = "res_stasis,res_http_websocket",
                .load_pri = AST_MODPRI_APP_DEPEND,
        );