5d938c03ed320a4b2798152c811f3f4fc1c81f81
[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         int num_addrs = 0, error = 0, i;
161         struct ast_sockaddr *addrs;
162
163         num_addrs = ast_sockaddr_resolve(&addrs, var->value, PARSE_PORT_FORBID, AST_AF_UNSPEC);
164         if (!num_addrs) {
165                 ast_log(LOG_ERROR, "Address '%s' provided on ip endpoint identifier '%s' did not resolve to any address\n",
166                         var->value, ast_sorcery_object_get_id(obj));
167                 return -1;
168         }
169
170         for (i = 0; i < num_addrs; ++i) {
171                 /* We deny what we actually want to match because there is an implicit permit all rule for ACLs */
172                 identify->matches = ast_append_ha("d", ast_sockaddr_stringify_addr(&addrs[i]), identify->matches, &error);
173
174                 if (!identify->matches || error) {
175                         ast_log(LOG_ERROR, "Failed to add address '%s' to ip endpoint identifier '%s'\n",
176                                 ast_sockaddr_stringify_addr(&addrs[i]), ast_sorcery_object_get_id(obj));
177                         error = -1;
178                         break;
179                 }
180         }
181
182         ast_free(addrs);
183
184         return error;
185 }
186
187
188 static int match_to_str(const void *obj, const intptr_t *args, char **buf)
189 {
190         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
191         const struct ip_identify_match *identify = obj;
192
193         ast_ha_join(identify->matches, &str);
194         *buf = ast_strdup(ast_str_buffer(str));
195         return 0;
196 }
197
198 static int match_to_var_list(const void *obj, struct ast_variable **fields)
199 {
200         char str[MAX_OBJECT_FIELD];
201         const struct ip_identify_match *identify = obj;
202         struct ast_variable *head = NULL;
203         struct ast_ha *ha = identify->matches;
204
205         for (; ha; ha = ha->next) {
206                 const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&ha->addr));
207                 snprintf(str, MAX_OBJECT_FIELD, "%s%s/%s", ha->sense == AST_SENSE_ALLOW ? "!" : "",
208                         addr, ast_sockaddr_stringify_addr(&ha->netmask));
209
210                 ast_variable_list_append(&head, ast_variable_new("match", str, ""));
211
212         }
213
214         if (head) {
215                 *fields = head;
216         }
217
218         return 0;
219 }
220
221 static int sip_identify_to_ami(const struct ip_identify_match *identify,
222                                struct ast_str **buf)
223 {
224         return ast_sip_sorcery_object_to_ami(identify, buf);
225 }
226
227 static int find_identify_by_endpoint(void *obj, void *arg, int flags)
228 {
229         struct ip_identify_match *identify = obj;
230         const char *endpoint_name = arg;
231
232         return strcmp(identify->endpoint_name, endpoint_name) ? 0 : CMP_MATCH;
233 }
234
235 static int format_ami_endpoint_identify(const struct ast_sip_endpoint *endpoint,
236                                         struct ast_sip_ami *ami)
237 {
238         RAII_VAR(struct ao2_container *, identifies, NULL, ao2_cleanup);
239         RAII_VAR(struct ip_identify_match *, identify, NULL, ao2_cleanup);
240         RAII_VAR(struct ast_str *, buf, NULL, ast_free);
241
242         identifies = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "identify",
243                 AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
244         if (!identifies) {
245                 return -1;
246         }
247
248         identify = ao2_callback(identifies, 0, find_identify_by_endpoint,
249                 (void *) ast_sorcery_object_get_id(endpoint));
250         if (!identify) {
251                 return 1;
252         }
253
254         if (!(buf = ast_sip_create_ami_event("IdentifyDetail", ami))) {
255                 return -1;
256         }
257
258         if (sip_identify_to_ami(identify, &buf)) {
259                 return -1;
260         }
261
262         ast_str_append(&buf, 0, "EndpointName: %s\r\n",
263                 ast_sorcery_object_get_id(endpoint));
264
265         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
266         ami->count++;
267
268         return 0;
269 }
270
271 struct ast_sip_endpoint_formatter endpoint_identify_formatter = {
272         .format_ami = format_ami_endpoint_identify
273 };
274
275 static int cli_populate_container(void *obj, void *arg, int flags)
276 {
277         ao2_link(arg, obj);
278
279         return 0;
280 }
281
282 static int cli_iterator(void *container, ao2_callback_fn callback, void *args)
283 {
284         const struct ast_sip_endpoint *endpoint = container;
285         struct ao2_container *identifies;
286
287         struct ast_variable fields = {
288                 .name = "endpoint",
289                 .value = ast_sorcery_object_get_id(endpoint),
290                 .next = NULL,
291         };
292
293         identifies = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "identify",
294                 AST_RETRIEVE_FLAG_MULTIPLE, &fields);
295         if (!identifies) {
296                 return -1;
297         }
298
299         ao2_callback(identifies, OBJ_NODATA, callback, args);
300
301         return 0;
302 }
303
304 static int cli_endpoint_gather_identifies(void *obj, void *arg, int flags)
305 {
306         struct ast_sip_endpoint *endpoint = obj;
307         struct ao2_container *container = arg;
308
309         cli_iterator(endpoint, cli_populate_container, container);
310
311         return 0;
312 }
313
314 static struct ao2_container *cli_get_container(void)
315 {
316         RAII_VAR(struct ao2_container *, parent_container, NULL, ao2_cleanup);
317         RAII_VAR(struct ao2_container *, s_parent_container, NULL, ao2_cleanup);
318         struct ao2_container *child_container;
319
320         parent_container =  ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "endpoint",
321                 AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
322         if (!parent_container) {
323                 return NULL;
324         }
325
326         s_parent_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
327                 ast_sorcery_object_id_sort, ast_sorcery_object_id_compare);
328         if (!s_parent_container) {
329                 return NULL;
330         }
331
332         if (ao2_container_dup(s_parent_container, parent_container, 0)) {
333                 return NULL;
334         }
335
336         child_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
337                 ast_sorcery_object_id_sort, ast_sorcery_object_id_compare);
338         if (!child_container) {
339                 return NULL;
340         }
341
342         ao2_callback(s_parent_container, OBJ_NODATA, cli_endpoint_gather_identifies, child_container);
343
344         return child_container;
345 }
346
347 static void *cli_retrieve_by_id(const char *id)
348 {
349         return ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "identify", id);
350 }
351
352 static int cli_print_header(void *obj, void *arg, int flags)
353 {
354         struct ast_sip_cli_context *context = arg;
355         int indent = CLI_INDENT_TO_SPACES(context->indent_level);
356         int filler = CLI_MAX_WIDTH - indent - 14;
357
358         ast_assert(context->output_buffer != NULL);
359
360         ast_str_append(&context->output_buffer, 0,
361                 "%*s:  <MatchList%*.*s>\n",
362                 indent, "Identify", filler, filler, CLI_HEADER_FILLER);
363
364         return 0;
365 }
366
367 static int cli_print_body(void *obj, void *arg, int flags)
368 {
369         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
370         struct ip_identify_match *ident = obj;
371         struct ast_sip_cli_context *context = arg;
372
373         ast_assert(context->output_buffer != NULL);
374
375         ast_str_append(&context->output_buffer, 0, "%*s:  ",
376                 CLI_INDENT_TO_SPACES(context->indent_level), "Identify");
377         ast_ha_join_cidr(ident->matches, &str);
378         ast_str_append(&context->output_buffer, 0, "%s\n", ast_str_buffer(str));
379
380         return 0;
381 }
382
383 static struct ast_sip_cli_formatter_entry *cli_formatter;
384
385 static int load_module(void)
386 {
387         ast_sorcery_apply_config(ast_sip_get_sorcery(), "res_pjsip_endpoint_identifier_ip");
388         ast_sorcery_apply_default(ast_sip_get_sorcery(), "identify", "config", "pjsip.conf,criteria=type=identify");
389
390         if (ast_sorcery_object_register(ast_sip_get_sorcery(), "identify", ip_identify_alloc, NULL, NULL)) {
391                 return AST_MODULE_LOAD_DECLINE;
392         }
393
394         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "identify", "type", "", OPT_NOOP_T, 0, 0);
395         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "identify", "endpoint", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ip_identify_match, endpoint_name));
396         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);
397         ast_sorcery_reload_object(ast_sip_get_sorcery(), "identify");
398
399         ast_sip_register_endpoint_identifier(&ip_identifier);
400         ast_sip_register_endpoint_formatter(&endpoint_identify_formatter);
401
402         cli_formatter = ao2_alloc(sizeof(struct ast_sip_cli_formatter_entry), NULL);
403         if (!cli_formatter) {
404                 ast_log(LOG_ERROR, "Unable to allocate memory for cli formatter\n");
405                 return -1;
406         }
407         cli_formatter->name = "identify";
408         cli_formatter->print_header = cli_print_header;
409         cli_formatter->print_body = cli_print_body;
410         cli_formatter->get_container = cli_get_container;
411         cli_formatter->iterate = cli_iterator;
412         cli_formatter->get_id = ast_sorcery_object_get_id;
413         cli_formatter->retrieve_by_id = cli_retrieve_by_id;
414
415         ast_sip_register_cli_formatter(cli_formatter);
416
417         return AST_MODULE_LOAD_SUCCESS;
418 }
419
420 static int reload_module(void)
421 {
422         ast_sorcery_reload_object(ast_sip_get_sorcery(), "identify");
423
424         return 0;
425 }
426
427 static int unload_module(void)
428 {
429         ast_sip_unregister_cli_formatter(cli_formatter);
430         ast_sip_unregister_endpoint_formatter(&endpoint_identify_formatter);
431         ast_sip_unregister_endpoint_identifier(&ip_identifier);
432
433         return 0;
434 }
435
436 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP IP endpoint identifier",
437                 .support_level = AST_MODULE_SUPPORT_CORE,
438                 .load = load_module,
439                 .reload = reload_module,
440                 .unload = unload_module,
441                 .load_pri = AST_MODPRI_APP_DEPEND,
442                );