7a7af0b4e021b320747cc2d3ae44f9e32b5c36a0
[asterisk/asterisk.git] / res / res_pjsip_endpoint_identifier_ip.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Mark Michelson <mmichelson@digium.com>
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 /*** MODULEINFO
20         <depend>pjproject</depend>
21         <depend>res_pjsip</depend>
22         <support_level>core</support_level>
23  ***/
24
25 #include "asterisk.h"
26
27 #include <pjsip.h>
28
29 #include "asterisk/res_pjsip.h"
30 #include "asterisk/res_pjsip_cli.h"
31 #include "asterisk/module.h"
32 #include "asterisk/acl.h"
33 #include "asterisk/manager.h"
34 #include "res_pjsip/include/res_pjsip_private.h"
35
36 /*** DOCUMENTATION
37         <configInfo name="res_pjsip_endpoint_identifier_ip" language="en_US">
38                 <synopsis>Module that identifies endpoints via source IP address</synopsis>
39                 <configFile name="pjsip.conf">
40                         <configObject name="identify">
41                                 <synopsis>Identifies endpoints via source IP address</synopsis>
42                                 <configOption name="endpoint">
43                                         <synopsis>Name of Endpoint</synopsis>
44                                 </configOption>
45                                 <configOption name="match">
46                                         <synopsis>IP addresses or networks to match against</synopsis>
47                                         <description><para>
48                                                 The value is a comma-delimited list of IP addresses. IP addresses may
49                                                 have a subnet mask appended. The subnet mask may be written in either
50                                                 CIDR or dot-decimal notation. Separate the IP address and subnet
51                                                 mask with a slash ('/')
52                                         </para></description>
53                                 </configOption>
54                                 <configOption name="type">
55                                         <synopsis>Must be of type 'identify'.</synopsis>
56                                 </configOption>
57                         </configObject>
58                 </configFile>
59         </configInfo>
60  ***/
61
62 /*! \brief Structure for an IP identification matching object */
63 struct ip_identify_match {
64         /*! \brief Sorcery object details */
65         SORCERY_OBJECT(details);
66         /*! \brief Stringfields */
67         AST_DECLARE_STRING_FIELDS(
68                 /*! The name of the endpoint */
69                 AST_STRING_FIELD(endpoint_name);
70         );
71         /*! \brief Networks or addresses that should match this */
72         struct ast_ha *matches;
73 };
74
75 /*! \brief Destructor function for a matching object */
76 static void ip_identify_destroy(void *obj)
77 {
78         struct ip_identify_match *identify = obj;
79
80         ast_string_field_free_memory(identify);
81         ast_free_ha(identify->matches);
82 }
83
84 /*! \brief Allocator function for a matching object */
85 static void *ip_identify_alloc(const char *name)
86 {
87         struct ip_identify_match *identify = ast_sorcery_generic_alloc(sizeof(*identify), ip_identify_destroy);
88
89         if (!identify || ast_string_field_init(identify, 256)) {
90                 ao2_cleanup(identify);
91                 return NULL;
92         }
93
94         return identify;
95 }
96
97 /*! \brief Comparator function for a matching object */
98 static int ip_identify_match_check(void *obj, void *arg, int flags)
99 {
100         struct ip_identify_match *identify = obj;
101         struct ast_sockaddr *addr = arg;
102         int sense;
103
104         sense = ast_apply_ha(identify->matches, addr);
105         if (sense != AST_SENSE_ALLOW) {
106                 ast_debug(3, "Source address %s matches identify '%s'\n",
107                                 ast_sockaddr_stringify(addr),
108                                 ast_sorcery_object_get_id(identify));
109                 return CMP_MATCH | CMP_STOP;
110         } else {
111                 ast_debug(3, "Source address %s does not match identify '%s'\n",
112                                 ast_sockaddr_stringify(addr),
113                                 ast_sorcery_object_get_id(identify));
114                 return 0;
115         }
116 }
117
118 static struct ast_sip_endpoint *ip_identify(pjsip_rx_data *rdata)
119 {
120         struct ast_sockaddr addr = { { 0, } };
121         RAII_VAR(struct ao2_container *, candidates, NULL, ao2_cleanup);
122         RAII_VAR(struct ip_identify_match *, match, NULL, ao2_cleanup);
123         struct ast_sip_endpoint *endpoint;
124
125         /* If no possibilities exist return early to save some time */
126         if (!(candidates = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "identify", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL)) ||
127                 !ao2_container_count(candidates)) {
128                 ast_debug(3, "No identify sections to match against\n");
129                 return NULL;
130         }
131
132         ast_sockaddr_parse(&addr, rdata->pkt_info.src_name, PARSE_PORT_FORBID);
133         ast_sockaddr_set_port(&addr, rdata->pkt_info.src_port);
134
135         if (!(match = ao2_callback(candidates, 0, ip_identify_match_check, &addr))) {
136                 ast_debug(3, "'%s' did not match any identify section rules\n",
137                                 ast_sockaddr_stringify(&addr));
138                 return NULL;
139         }
140
141         endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", match->endpoint_name);
142         if (endpoint) {
143                 ast_debug(3, "Retrieved endpoint %s\n", ast_sorcery_object_get_id(endpoint));
144         } else {
145                 ast_log(LOG_WARNING, "Identify section '%s' points to endpoint '%s' but endpoint could not be looked up\n",
146                                 ast_sorcery_object_get_id(match), match->endpoint_name);
147         }
148
149         return endpoint;
150 }
151
152 static struct ast_sip_endpoint_identifier ip_identifier = {
153         .identify_endpoint = ip_identify,
154 };
155
156 /*! \brief Custom handler for match field */
157 static int ip_identify_match_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
158 {
159         struct ip_identify_match *identify = obj;
160         char *input_string = ast_strdupa(var->value);
161         char *current_string;
162
163         if (ast_strlen_zero(var->value)) {
164                 return 0;
165         }
166
167         while ((current_string = ast_strip(strsep(&input_string, ",")))) {
168                 struct ast_sockaddr *addrs;
169                 int num_addrs = 0, error = 0, i;
170                 char *mask = strrchr(current_string, '/');
171
172                 if (ast_strlen_zero(current_string)) {
173                         continue;
174                 }
175
176                 if (mask) {
177                         identify->matches = ast_append_ha("d", current_string, identify->matches, &error);
178
179                         if (!identify->matches || error) {
180                                 ast_log(LOG_ERROR, "Failed to add address '%s' to ip endpoint identifier '%s'\n",
181                                         current_string, ast_sorcery_object_get_id(obj));
182                                 return -1;
183                         }
184
185                         continue;
186                 }
187
188                 num_addrs = ast_sockaddr_resolve(&addrs, current_string, PARSE_PORT_FORBID, AST_AF_UNSPEC);
189                 if (!num_addrs) {
190                         ast_log(LOG_ERROR, "Address '%s' provided on ip endpoint identifier '%s' did not resolve to any address\n",
191                                 var->value, ast_sorcery_object_get_id(obj));
192                         return -1;
193                 }
194
195                 for (i = 0; i < num_addrs; ++i) {
196                         /* We deny what we actually want to match because there is an implicit permit all rule for ACLs */
197                         identify->matches = ast_append_ha("d", ast_sockaddr_stringify_addr(&addrs[i]), identify->matches, &error);
198
199                         if (!identify->matches || error) {
200                                 ast_log(LOG_ERROR, "Failed to add address '%s' to ip endpoint identifier '%s'\n",
201                                         ast_sockaddr_stringify_addr(&addrs[i]), ast_sorcery_object_get_id(obj));
202                                 error = -1;
203                                 break;
204                         }
205                 }
206
207                 ast_free(addrs);
208
209                 if (error) {
210                         return -1;
211                 }
212         }
213
214         return 0;
215 }
216
217
218 static int match_to_str(const void *obj, const intptr_t *args, char **buf)
219 {
220         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
221         const struct ip_identify_match *identify = obj;
222
223         ast_ha_join(identify->matches, &str);
224         *buf = ast_strdup(ast_str_buffer(str));
225         return 0;
226 }
227
228 static int match_to_var_list(const void *obj, struct ast_variable **fields)
229 {
230         char str[MAX_OBJECT_FIELD];
231         const struct ip_identify_match *identify = obj;
232         struct ast_variable *head = NULL;
233         struct ast_ha *ha = identify->matches;
234
235         for (; ha; ha = ha->next) {
236                 const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&ha->addr));
237                 snprintf(str, MAX_OBJECT_FIELD, "%s%s/%s", ha->sense == AST_SENSE_ALLOW ? "!" : "",
238                         addr, ast_sockaddr_stringify_addr(&ha->netmask));
239
240                 ast_variable_list_append(&head, ast_variable_new("match", str, ""));
241
242         }
243
244         if (head) {
245                 *fields = head;
246         }
247
248         return 0;
249 }
250
251 static int sip_identify_to_ami(const struct ip_identify_match *identify,
252                                struct ast_str **buf)
253 {
254         return ast_sip_sorcery_object_to_ami(identify, buf);
255 }
256
257 static int find_identify_by_endpoint(void *obj, void *arg, int flags)
258 {
259         struct ip_identify_match *identify = obj;
260         const char *endpoint_name = arg;
261
262         return strcmp(identify->endpoint_name, endpoint_name) ? 0 : CMP_MATCH;
263 }
264
265 static int format_ami_endpoint_identify(const struct ast_sip_endpoint *endpoint,
266                                         struct ast_sip_ami *ami)
267 {
268         RAII_VAR(struct ao2_container *, identifies, NULL, ao2_cleanup);
269         RAII_VAR(struct ip_identify_match *, identify, NULL, ao2_cleanup);
270         RAII_VAR(struct ast_str *, buf, NULL, ast_free);
271
272         identifies = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "identify",
273                 AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
274         if (!identifies) {
275                 return -1;
276         }
277
278         identify = ao2_callback(identifies, 0, find_identify_by_endpoint,
279                 (void *) ast_sorcery_object_get_id(endpoint));
280         if (!identify) {
281                 return 1;
282         }
283
284         if (!(buf = ast_sip_create_ami_event("IdentifyDetail", ami))) {
285                 return -1;
286         }
287
288         if (sip_identify_to_ami(identify, &buf)) {
289                 return -1;
290         }
291
292         ast_str_append(&buf, 0, "EndpointName: %s\r\n",
293                 ast_sorcery_object_get_id(endpoint));
294
295         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
296         ami->count++;
297
298         return 0;
299 }
300
301 struct ast_sip_endpoint_formatter endpoint_identify_formatter = {
302         .format_ami = format_ami_endpoint_identify
303 };
304
305 static int cli_iterator(void *container, ao2_callback_fn callback, void *args)
306 {
307         const struct ast_sip_endpoint *endpoint = container;
308         struct ao2_container *identifies;
309
310         struct ast_variable fields = {
311                 .name = "endpoint",
312                 .value = ast_sorcery_object_get_id(endpoint),
313                 .next = NULL,
314         };
315
316         identifies = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "identify",
317                 AST_RETRIEVE_FLAG_MULTIPLE, &fields);
318         if (!identifies) {
319                 return -1;
320         }
321
322         ao2_callback(identifies, OBJ_NODATA, callback, args);
323         ao2_cleanup(identifies);
324
325         return 0;
326 }
327
328 static struct ao2_container *cli_get_container(const char *regex)
329 {
330         RAII_VAR(struct ao2_container *, container, NULL, ao2_cleanup);
331         struct ao2_container *s_container;
332
333         container =  ast_sorcery_retrieve_by_regex(ast_sip_get_sorcery(), "identify", regex);
334         if (!container) {
335                 return NULL;
336         }
337
338         s_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
339                 ast_sorcery_object_id_sort, ast_sorcery_object_id_compare);
340         if (!s_container) {
341                 return NULL;
342         }
343
344         if (ao2_container_dup(s_container, container, 0)) {
345                 ao2_ref(s_container, -1);
346                 return NULL;
347         }
348
349         return s_container;
350 }
351
352 static void *cli_retrieve_by_id(const char *id)
353 {
354         return ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "identify", id);
355 }
356
357 static int cli_print_header(void *obj, void *arg, int flags)
358 {
359         struct ast_sip_cli_context *context = arg;
360         int indent = CLI_INDENT_TO_SPACES(context->indent_level);
361         int filler = CLI_MAX_WIDTH - indent - 22;
362
363         ast_assert(context->output_buffer != NULL);
364
365         ast_str_append(&context->output_buffer, 0,
366                 "%*s:  <Identify/Endpoint%*.*s>\n",
367                 indent, "Identify", filler, filler, CLI_HEADER_FILLER);
368
369         if (context->recurse) {
370                 context->indent_level++;
371                 indent = CLI_INDENT_TO_SPACES(context->indent_level);
372                 filler = CLI_LAST_TABSTOP - indent - 24;
373
374                 ast_str_append(&context->output_buffer, 0,
375                         "%*s:  <ip/cidr%*.*s>\n",
376                         indent, "Match", filler, filler, CLI_HEADER_FILLER);
377
378                 context->indent_level--;
379         }
380
381         return 0;
382 }
383
384 static int cli_print_body(void *obj, void *arg, int flags)
385 {
386         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
387         struct ip_identify_match *ident = obj;
388         struct ast_sip_cli_context *context = arg;
389         struct ast_ha *match;
390         int indent;
391
392         ast_assert(context->output_buffer != NULL);
393
394         ast_str_append(&context->output_buffer, 0, "%*s:  %s/%s\n",
395                 CLI_INDENT_TO_SPACES(context->indent_level), "Identify",
396                 ast_sorcery_object_get_id(ident), ident->endpoint_name);
397
398         if (context->recurse) {
399                 context->indent_level++;
400                 indent = CLI_INDENT_TO_SPACES(context->indent_level);
401
402                 for (match = ident->matches; match; match = match->next) {
403                         const char *addr = ast_sockaddr_stringify_addr(&match->addr);
404
405                         ast_str_append(&context->output_buffer, 0, "%*s: %s%s/%d\n",
406                                 indent,
407                                 "Match",
408                                 match->sense == AST_SENSE_ALLOW ? "!" : "",
409                                 addr, ast_sockaddr_cidr_bits(&match->netmask));
410                 }
411
412                 context->indent_level--;
413
414                 if (context->indent_level == 0) {
415                         ast_str_append(&context->output_buffer, 0, "\n");
416                 }
417         }
418
419         if (context->show_details
420                 || (context->show_details_only_level_0 && context->indent_level == 0)) {
421                 ast_str_append(&context->output_buffer, 0, "\n");
422                 ast_sip_cli_print_sorcery_objectset(ident, context, 0);
423         }
424
425         return 0;
426 }
427
428 /*
429  * A function pointer to callback needs to be within the
430  * module in order to avoid problems with an undefined
431  * symbol when the module is loaded.
432  */
433 static char *my_cli_traverse_objects(struct ast_cli_entry *e, int cmd,
434         struct ast_cli_args *a)
435 {
436         return ast_sip_cli_traverse_objects(e, cmd, a);
437 }
438
439 static struct ast_cli_entry cli_identify[] = {
440 AST_CLI_DEFINE(my_cli_traverse_objects, "List PJSIP Identifies",
441         .command = "pjsip list identifies",
442         .usage = "Usage: pjsip list identifies [ like <pattern> ]\n"
443         "       List the configured PJSIP Identifies\n"
444         "       Optional regular expression pattern is used to filter the list.\n"),
445 AST_CLI_DEFINE(my_cli_traverse_objects, "Show PJSIP Identifies",
446         .command = "pjsip show identifies",
447         .usage = "Usage: pjsip show identifies [ like <pattern> ]\n"
448         "       Show the configured PJSIP Identifies\n"
449         "       Optional regular expression pattern is used to filter the list.\n"),
450 AST_CLI_DEFINE(my_cli_traverse_objects, "Show PJSIP Identify",
451         .command = "pjsip show identify",
452         .usage = "Usage: pjsip show identify <id>\n"
453         "       Show the configured PJSIP Identify\n"),
454 };
455
456 static struct ast_sip_cli_formatter_entry *cli_formatter;
457
458 static int load_module(void)
459 {
460         CHECK_PJSIP_MODULE_LOADED();
461
462         ast_sorcery_apply_config(ast_sip_get_sorcery(), "res_pjsip_endpoint_identifier_ip");
463         ast_sorcery_apply_default(ast_sip_get_sorcery(), "identify", "config", "pjsip.conf,criteria=type=identify");
464
465         if (ast_sorcery_object_register(ast_sip_get_sorcery(), "identify", ip_identify_alloc, NULL, NULL)) {
466                 return AST_MODULE_LOAD_DECLINE;
467         }
468
469         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "identify", "type", "", OPT_NOOP_T, 0, 0);
470         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "identify", "endpoint", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ip_identify_match, endpoint_name));
471         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);
472         ast_sorcery_load_object(ast_sip_get_sorcery(), "identify");
473
474         ast_sip_register_endpoint_identifier_with_name(&ip_identifier, "ip");
475         ast_sip_register_endpoint_formatter(&endpoint_identify_formatter);
476
477         cli_formatter = ao2_alloc(sizeof(struct ast_sip_cli_formatter_entry), NULL);
478         if (!cli_formatter) {
479                 ast_log(LOG_ERROR, "Unable to allocate memory for cli formatter\n");
480                 return AST_MODULE_LOAD_DECLINE;
481         }
482         cli_formatter->name = "identify";
483         cli_formatter->print_header = cli_print_header;
484         cli_formatter->print_body = cli_print_body;
485         cli_formatter->get_container = cli_get_container;
486         cli_formatter->iterate = cli_iterator;
487         cli_formatter->get_id = ast_sorcery_object_get_id;
488         cli_formatter->retrieve_by_id = cli_retrieve_by_id;
489
490         ast_sip_register_cli_formatter(cli_formatter);
491         ast_cli_register_multiple(cli_identify, ARRAY_LEN(cli_identify));
492
493         return AST_MODULE_LOAD_SUCCESS;
494 }
495
496 static int reload_module(void)
497 {
498         ast_sorcery_reload_object(ast_sip_get_sorcery(), "identify");
499
500         return 0;
501 }
502
503 static int unload_module(void)
504 {
505         ast_cli_unregister_multiple(cli_identify, ARRAY_LEN(cli_identify));
506         ast_sip_unregister_cli_formatter(cli_formatter);
507         ast_sip_unregister_endpoint_formatter(&endpoint_identify_formatter);
508         ast_sip_unregister_endpoint_identifier(&ip_identifier);
509
510         return 0;
511 }
512
513 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP IP endpoint identifier",
514         .support_level = AST_MODULE_SUPPORT_CORE,
515         .load = load_module,
516         .reload = reload_module,
517         .unload = unload_module,
518         .load_pri = AST_MODPRI_CHANNEL_DEPEND - 4,
519 );