summaryrefslogtreecommitdiff
path: root/res/res_pjsip_endpoint_identifier_ip.c
blob: b1ffd2cc35e84b26c767ff1632b917dd8e79a7f7 (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
/*
 * Asterisk -- An open source telephony toolkit.
 *
 * Copyright (C) 2013, Digium, Inc.
 *
 * Mark Michelson <mmichelson@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.
 */

/*** MODULEINFO
	<depend>pjproject</depend>
	<depend>res_pjsip</depend>
	<support_level>core</support_level>
 ***/

#include "asterisk.h"

#include <pjsip.h>

#include "asterisk/res_pjsip.h"
#include "asterisk/res_pjsip_cli.h"
#include "asterisk/module.h"
#include "asterisk/acl.h"
#include "asterisk/manager.h"
#include "res_pjsip/include/res_pjsip_private.h"

/*** DOCUMENTATION
	<configInfo name="res_pjsip_endpoint_identifier_ip" language="en_US">
		<synopsis>Module that identifies endpoints via source IP address</synopsis>
		<configFile name="pjsip.conf">
			<configObject name="identify">
				<synopsis>Identifies endpoints via source IP address</synopsis>
				<configOption name="endpoint">
					<synopsis>Name of Endpoint</synopsis>
				</configOption>
				<configOption name="match">
					<synopsis>IP addresses or networks to match against</synopsis>
					<description><para>
						The value is a comma-delimited list of IP addresses. IP addresses may
						have a subnet mask appended. The subnet mask may be written in either
						CIDR or dot-decimal notation. Separate the IP address and subnet
						mask with a slash ('/')
					</para></description>
				</configOption>
				<configOption name="type">
					<synopsis>Must be of type 'identify'.</synopsis>
				</configOption>
			</configObject>
		</configFile>
	</configInfo>
 ***/

/*! \brief Structure for an IP identification matching object */
struct ip_identify_match {
	/*! \brief Sorcery object details */
	SORCERY_OBJECT(details);
	/*! \brief Stringfields */
	AST_DECLARE_STRING_FIELDS(
		/*! The name of the endpoint */
		AST_STRING_FIELD(endpoint_name);
	);
	/*! \brief Networks or addresses that should match this */
	struct ast_ha *matches;
};

/*! \brief Destructor function for a matching object */
static void ip_identify_destroy(void *obj)
{
	struct ip_identify_match *identify = obj;

	ast_string_field_free_memory(identify);
	ast_free_ha(identify->matches);
}

/*! \brief Allocator function for a matching object */
static void *ip_identify_alloc(const char *name)
{
	struct ip_identify_match *identify = ast_sorcery_generic_alloc(sizeof(*identify), ip_identify_destroy);

	if (!identify || ast_string_field_init(identify, 256)) {
		ao2_cleanup(identify);
		return NULL;
	}

	return identify;
}

/*! \brief Comparator function for a matching object */
static int ip_identify_match_check(void *obj, void *arg, int flags)
{
	struct ip_identify_match *identify = obj;
	struct ast_sockaddr *addr = arg;
	int sense;

	sense = ast_apply_ha(identify->matches, addr);
	if (sense != AST_SENSE_ALLOW) {
		ast_debug(3, "Source address %s matches identify '%s'\n",
				ast_sockaddr_stringify(addr),
				ast_sorcery_object_get_id(identify));
		return CMP_MATCH | CMP_STOP;
	} else {
		ast_debug(3, "Source address %s does not match identify '%s'\n",
				ast_sockaddr_stringify(addr),
				ast_sorcery_object_get_id(identify));
		return 0;
	}
}

static struct ast_sip_endpoint *ip_identify(pjsip_rx_data *rdata)
{
	struct ast_sockaddr addr = { { 0, } };
	RAII_VAR(struct ao2_container *, candidates, NULL, ao2_cleanup);
	RAII_VAR(struct ip_identify_match *, match, NULL, ao2_cleanup);
	struct ast_sip_endpoint *endpoint;

	/* If no possibilities exist return early to save some time */
	if (!(candidates = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "identify", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL)) ||
		!ao2_container_count(candidates)) {
		ast_debug(3, "No identify sections to match against\n");
		return NULL;
	}

	ast_sockaddr_parse(&addr, rdata->pkt_info.src_name, PARSE_PORT_FORBID);
	ast_sockaddr_set_port(&addr, rdata->pkt_info.src_port);

	if (!(match = ao2_callback(candidates, 0, ip_identify_match_check, &addr))) {
		ast_debug(3, "'%s' did not match any identify section rules\n",
				ast_sockaddr_stringify(&addr));
		return NULL;
	}

	endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", match->endpoint_name);
	if (endpoint) {
		ast_debug(3, "Retrieved endpoint %s\n", ast_sorcery_object_get_id(endpoint));
	} else {
		ast_log(LOG_WARNING, "Identify section '%s' points to endpoint '%s' but endpoint could not be looked up\n",
				ast_sorcery_object_get_id(match), match->endpoint_name);
	}

	return endpoint;
}

static struct ast_sip_endpoint_identifier ip_identifier = {
	.identify_endpoint = ip_identify,
};

/*! \brief Custom handler for match field */
static int ip_identify_match_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
{
	struct ip_identify_match *identify = obj;
	char *input_string = ast_strdupa(var->value);
	char *current_string;

	if (ast_strlen_zero(var->value)) {
		return 0;
	}

	while ((current_string = ast_strip(strsep(&input_string, ",")))) {
		struct ast_sockaddr *addrs;
		int num_addrs = 0, error = 0, i;
		char *mask = strrchr(current_string, '/');

		if (ast_strlen_zero(current_string)) {
			continue;
		}

		if (mask) {
			identify->matches = ast_append_ha("d", current_string, identify->matches, &error);

			if (!identify->matches || error) {
				ast_log(LOG_ERROR, "Failed to add address '%s' to ip endpoint identifier '%s'\n",
					current_string, ast_sorcery_object_get_id(obj));
				return -1;
			}

			continue;
		}

		num_addrs = ast_sockaddr_resolve(&addrs, current_string, PARSE_PORT_FORBID, AST_AF_UNSPEC);
		if (!num_addrs) {
			ast_log(LOG_ERROR, "Address '%s' provided on ip endpoint identifier '%s' did not resolve to any address\n",
				var->value, ast_sorcery_object_get_id(obj));
			return -1;
		}

		for (i = 0; i < num_addrs; ++i) {
			/* We deny what we actually want to match because there is an implicit permit all rule for ACLs */
			identify->matches = ast_append_ha("d", ast_sockaddr_stringify_addr(&addrs[i]), identify->matches, &error);

			if (!identify->matches || error) {
				ast_log(LOG_ERROR, "Failed to add address '%s' to ip endpoint identifier '%s'\n",
					ast_sockaddr_stringify_addr(&addrs[i]), ast_sorcery_object_get_id(obj));
				error = -1;
				break;
			}
		}

		ast_free(addrs);

		if (error) {
			return -1;
		}
	}

	return 0;
}


static int match_to_str(const void *obj, const intptr_t *args, char **buf)
{
	RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
	const struct ip_identify_match *identify = obj;

	ast_ha_join(identify->matches, &str);
	*buf = ast_strdup(ast_str_buffer(str));
	return 0;
}

static int match_to_var_list(const void *obj, struct ast_variable **fields)
{
	char str[MAX_OBJECT_FIELD];
	const struct ip_identify_match *identify = obj;
	struct ast_variable *head = NULL;
	struct ast_ha *ha = identify->matches;

	for (; ha; ha = ha->next) {
		const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&ha->addr));
		snprintf(str, MAX_OBJECT_FIELD, "%s%s/%s", ha->sense == AST_SENSE_ALLOW ? "!" : "",
			addr, ast_sockaddr_stringify_addr(&ha->netmask));

		ast_variable_list_append(&head, ast_variable_new("match", str, ""));

	}

	if (head) {
		*fields = head;
	}

	return 0;
}

static int sip_identify_to_ami(const struct ip_identify_match *identify,
			       struct ast_str **buf)
{
	return ast_sip_sorcery_object_to_ami(identify, buf);
}

static int find_identify_by_endpoint(void *obj, void *arg, int flags)
{
	struct ip_identify_match *identify = obj;
	const char *endpoint_name = arg;

	return strcmp(identify->endpoint_name, endpoint_name) ? 0 : CMP_MATCH;
}

static int format_ami_endpoint_identify(const struct ast_sip_endpoint *endpoint,
					struct ast_sip_ami *ami)
{
	RAII_VAR(struct ao2_container *, identifies, NULL, ao2_cleanup);
	RAII_VAR(struct ip_identify_match *, identify, NULL, ao2_cleanup);
	RAII_VAR(struct ast_str *, buf, NULL, ast_free);

	identifies = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "identify",
		AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
	if (!identifies) {
		return -1;
	}

	identify = ao2_callback(identifies, 0, find_identify_by_endpoint,
		(void *) ast_sorcery_object_get_id(endpoint));
	if (!identify) {
		return 1;
	}

	if (!(buf = ast_sip_create_ami_event("IdentifyDetail", ami))) {
		return -1;
	}

	if (sip_identify_to_ami(identify, &buf)) {
		return -1;
	}

	ast_str_append(&buf, 0, "EndpointName: %s\r\n",
		ast_sorcery_object_get_id(endpoint));

	astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
	ami->count++;

	return 0;
}

struct ast_sip_endpoint_formatter endpoint_identify_formatter = {
	.format_ami = format_ami_endpoint_identify
};

static int cli_iterator(void *container, ao2_callback_fn callback, void *args)
{
	const struct ast_sip_endpoint *endpoint = container;
	struct ao2_container *identifies;

	struct ast_variable fields = {
		.name = "endpoint",
		.value = ast_sorcery_object_get_id(endpoint),
		.next = NULL,
	};

	identifies = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "identify",
		AST_RETRIEVE_FLAG_MULTIPLE, &fields);
	if (!identifies) {
		return -1;
	}

	ao2_callback(identifies, OBJ_NODATA, callback, args);
	ao2_cleanup(identifies);

	return 0;
}

static struct ao2_container *cli_get_container(const char *regex)
{
	RAII_VAR(struct ao2_container *, container, NULL, ao2_cleanup);
	struct ao2_container *s_container;

	container =  ast_sorcery_retrieve_by_regex(ast_sip_get_sorcery(), "identify", regex);
	if (!container) {
		return NULL;
	}

	s_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
		ast_sorcery_object_id_sort, ast_sorcery_object_id_compare);
	if (!s_container) {
		return NULL;
	}

	if (ao2_container_dup(s_container, container, 0)) {
		ao2_ref(s_container, -1);
		return NULL;
	}

	return s_container;
}

static void *cli_retrieve_by_id(const char *id)
{
	return ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "identify", id);
}

static int cli_print_header(void *obj, void *arg, int flags)
{
	struct ast_sip_cli_context *context = arg;
	int indent = CLI_INDENT_TO_SPACES(context->indent_level);
	int filler = CLI_MAX_WIDTH - indent - 22;

	ast_assert(context->output_buffer != NULL);

	ast_str_append(&context->output_buffer, 0,
		"%*s:  <Identify/Endpoint%*.*s>\n",
		indent, "Identify", filler, filler, CLI_HEADER_FILLER);

	if (context->recurse) {
		context->indent_level++;
		indent = CLI_INDENT_TO_SPACES(context->indent_level);
		filler = CLI_LAST_TABSTOP - indent - 24;

		ast_str_append(&context->output_buffer, 0,
			"%*s:  <ip/cidr%*.*s>\n",
			indent, "Match", filler, filler, CLI_HEADER_FILLER);

		context->indent_level--;
	}

	return 0;
}

static int cli_print_body(void *obj, void *arg, int flags)
{
	RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
	struct ip_identify_match *ident = obj;
	struct ast_sip_cli_context *context = arg;
	struct ast_ha *match;
	int indent;

	ast_assert(context->output_buffer != NULL);

	ast_str_append(&context->output_buffer, 0, "%*s:  %s/%s\n",
		CLI_INDENT_TO_SPACES(context->indent_level), "Identify",
		ast_sorcery_object_get_id(ident), ident->endpoint_name);

	if (context->recurse) {
		context->indent_level++;
		indent = CLI_INDENT_TO_SPACES(context->indent_level);

		for (match = ident->matches; match; match = match->next) {
			const char *addr = ast_sockaddr_stringify_addr(&match->addr);

			ast_str_append(&context->output_buffer, 0, "%*s: %s%s/%d\n",
				indent,
				"Match",
				match->sense == AST_SENSE_ALLOW ? "!" : "",
				addr, ast_sockaddr_cidr_bits(&match->netmask));
		}

		context->indent_level--;

		if (context->indent_level == 0) {
			ast_str_append(&context->output_buffer, 0, "\n");
		}
	}

	if (context->show_details
		|| (context->show_details_only_level_0 && context->indent_level == 0)) {
		ast_str_append(&context->output_buffer, 0, "\n");
		ast_sip_cli_print_sorcery_objectset(ident, context, 0);
	}

	return 0;
}

/*
 * A function pointer to callback needs to be within the
 * module in order to avoid problems with an undefined
 * symbol when the module is loaded.
 */
static char *my_cli_traverse_objects(struct ast_cli_entry *e, int cmd,
	struct ast_cli_args *a)
{
	return ast_sip_cli_traverse_objects(e, cmd, a);
}

static struct ast_cli_entry cli_identify[] = {
AST_CLI_DEFINE(my_cli_traverse_objects, "List PJSIP Identifies",
	.command = "pjsip list identifies",
	.usage = "Usage: pjsip list identifies [ like <pattern> ]\n"
	"       List the configured PJSIP Identifies\n"
	"       Optional regular expression pattern is used to filter the list.\n"),
AST_CLI_DEFINE(my_cli_traverse_objects, "Show PJSIP Identifies",
	.command = "pjsip show identifies",
	.usage = "Usage: pjsip show identifies [ like <pattern> ]\n"
	"       Show the configured PJSIP Identifies\n"
	"       Optional regular expression pattern is used to filter the list.\n"),
AST_CLI_DEFINE(my_cli_traverse_objects, "Show PJSIP Identify",
	.command = "pjsip show identify",
	.usage = "Usage: pjsip show identify <id>\n"
	"       Show the configured PJSIP Identify\n"),
};

static struct ast_sip_cli_formatter_entry *cli_formatter;

static int load_module(void)
{
	CHECK_PJSIP_MODULE_LOADED();

	ast_sorcery_apply_config(ast_sip_get_sorcery(), "res_pjsip_endpoint_identifier_ip");
	ast_sorcery_apply_default(ast_sip_get_sorcery(), "identify", "config", "pjsip.conf,criteria=type=identify");

	if (ast_sorcery_object_register(ast_sip_get_sorcery(), "identify", ip_identify_alloc, NULL, NULL)) {
		return AST_MODULE_LOAD_DECLINE;
	}

	ast_sorcery_object_field_register(ast_sip_get_sorcery(), "identify", "type", "", OPT_NOOP_T, 0, 0);
	ast_sorcery_object_field_register(ast_sip_get_sorcery(), "identify", "endpoint", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ip_identify_match, endpoint_name));
	ast_sorcery_object_field_register_custom(ast_sip_get_sorcery(), "identify", "match", "", ip_identify_match_handler, match_to_str, match_to_var_list, 0, 0);
	ast_sorcery_load_object(ast_sip_get_sorcery(), "identify");

	ast_sip_register_endpoint_identifier_with_name(&ip_identifier, "ip");
	ast_sip_register_endpoint_formatter(&endpoint_identify_formatter);

	cli_formatter = ao2_alloc(sizeof(struct ast_sip_cli_formatter_entry), NULL);
	if (!cli_formatter) {
		ast_log(LOG_ERROR, "Unable to allocate memory for cli formatter\n");
		return AST_MODULE_LOAD_DECLINE;
	}
	cli_formatter->name = "identify";
	cli_formatter->print_header = cli_print_header;
	cli_formatter->print_body = cli_print_body;
	cli_formatter->get_container = cli_get_container;
	cli_formatter->iterate = cli_iterator;
	cli_formatter->get_id = ast_sorcery_object_get_id;
	cli_formatter->retrieve_by_id = cli_retrieve_by_id;

	ast_sip_register_cli_formatter(cli_formatter);
	ast_cli_register_multiple(cli_identify, ARRAY_LEN(cli_identify));

	return AST_MODULE_LOAD_SUCCESS;
}

static int reload_module(void)
{
	ast_sorcery_reload_object(ast_sip_get_sorcery(), "identify");

	return 0;
}

static int unload_module(void)
{
	ast_cli_unregister_multiple(cli_identify, ARRAY_LEN(cli_identify));
	ast_sip_unregister_cli_formatter(cli_formatter);
	ast_sip_unregister_endpoint_formatter(&endpoint_identify_formatter);
	ast_sip_unregister_endpoint_identifier(&ip_identifier);

	return 0;
}

AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP IP endpoint identifier",
		.support_level = AST_MODULE_SUPPORT_CORE,
		.load = load_module,
		.reload = reload_module,
		.unload = unload_module,
		.load_pri = AST_MODPRI_CHANNEL_DEPEND - 4,
	       );