f4bfef772e093eeeee85aaffa3bb73d512dd548c
[asterisk/asterisk.git] / res / res_pjsip_exten_state.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Kevin Harwell <kharwell@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         <depend>res_pjsip_pubsub</depend>
23         <support_level>core</support_level>
24  ***/
25
26 #include "asterisk.h"
27
28 #include <pjsip.h>
29 #include <pjsip_simple.h>
30 #include <pjlib.h>
31
32 #include "asterisk/res_pjsip.h"
33 #include "asterisk/res_pjsip_pubsub.h"
34 #include "asterisk/res_pjsip_body_generator_types.h"
35 #include "asterisk/module.h"
36 #include "asterisk/logger.h"
37 #include "asterisk/astobj2.h"
38 #include "asterisk/sorcery.h"
39 #include "asterisk/app.h"
40
41 #define BODY_SIZE 1024
42 #define EVENT_TYPE_SIZE 50
43
44 /*!
45  * \brief A subscription for extension state
46  *
47  * This structure acts as the owner for the underlying SIP subscription. It
48  * also keeps a pointer to an associated "provider" so when a state changes
49  * a notify data creator is quickly accessible.
50  */
51 struct exten_state_subscription {
52         /*! Watcher id when registering for extension state changes */
53         int id;
54         /*! The SIP subscription */
55         struct ast_sip_subscription *sip_sub;
56         /*! Context in which subscription looks for updates */
57         char context[AST_MAX_CONTEXT];
58         /*! Extension within the context to receive updates from */
59         char exten[AST_MAX_EXTENSION];
60         /*! The subscription's user agent */
61         char *user_agent;
62         /*! The last known extension state */
63         enum ast_extension_states last_exten_state;
64         /*! The last known presence state */
65         enum ast_presence_state last_presence_state;
66 };
67
68 #define DEFAULT_PRESENCE_BODY "application/pidf+xml"
69
70 static void subscription_shutdown(struct ast_sip_subscription *sub);
71 static struct ast_sip_subscription *new_subscribe(struct ast_sip_endpoint *endpoint,
72                                                   pjsip_rx_data *rdata);
73 static void resubscribe(struct ast_sip_subscription *sub, pjsip_rx_data *rdata,
74                         struct ast_sip_subscription_response_data *response_data);
75 static void subscription_timeout(struct ast_sip_subscription *sub);
76 static void subscription_terminated(struct ast_sip_subscription *sub,
77                                     pjsip_rx_data *rdata);
78 static void to_ami(struct ast_sip_subscription *sub,
79                    struct ast_str **buf);
80
81 struct ast_sip_subscription_handler presence_handler = {
82         .event_name = "presence",
83         .accept = { DEFAULT_PRESENCE_BODY, },
84         .default_accept = DEFAULT_PRESENCE_BODY,
85         .subscription_shutdown = subscription_shutdown,
86         .new_subscribe = new_subscribe,
87         .resubscribe = resubscribe,
88         .subscription_timeout = subscription_timeout,
89         .subscription_terminated = subscription_terminated,
90         .to_ami = to_ami,
91 };
92
93 static void exten_state_subscription_destructor(void *obj)
94 {
95         struct exten_state_subscription *sub = obj;
96
97         ast_free(sub->user_agent);
98         ao2_cleanup(sub->sip_sub);
99 }
100
101 static char *get_user_agent(pjsip_rx_data *rdata)
102 {
103         static const pj_str_t USER_AGENT = { "User-Agent", 10 };
104
105         size_t size;
106         char *user_agent = NULL;
107         pjsip_user_agent_hdr *user_agent_hdr = pjsip_msg_find_hdr_by_name(
108                 rdata->msg_info.msg, &USER_AGENT, NULL);
109
110         if (!user_agent_hdr) {
111                 return NULL;
112         }
113
114         size = pj_strlen(&user_agent_hdr->hvalue) + 1;
115         user_agent = ast_malloc(size);
116         ast_copy_pj_str(user_agent, &user_agent_hdr->hvalue, size);
117         return ast_str_to_lower(user_agent);
118 }
119
120 /*!
121  * \internal
122  * \brief Initialize the last extension state to something outside
123  * its usual states.
124  */
125 #define INITIAL_LAST_EXTEN_STATE -3
126
127 /*!
128  * \internal
129  * \brief Allocates an exten_state_subscription object.
130  *
131  * Creates the underlying SIP subscription for the given request. First makes
132  * sure that there are registered handler and provider objects available.
133  */
134 static struct exten_state_subscription *exten_state_subscription_alloc(
135         struct ast_sip_endpoint *endpoint, enum ast_sip_subscription_role role, pjsip_rx_data *rdata)
136 {
137         RAII_VAR(struct exten_state_subscription *, exten_state_sub,
138                  ao2_alloc(sizeof(*exten_state_sub), exten_state_subscription_destructor), ao2_cleanup);
139
140         if (!exten_state_sub) {
141                 return NULL;
142         }
143
144         if (!(exten_state_sub->sip_sub = ast_sip_create_subscription(
145                       &presence_handler, role, endpoint, rdata))) {
146                 ast_log(LOG_WARNING, "Unable to create SIP subscription for endpoint %s\n",
147                         ast_sorcery_object_get_id(endpoint));
148                 return NULL;
149         }
150
151         exten_state_sub->last_exten_state = INITIAL_LAST_EXTEN_STATE;
152         exten_state_sub->last_presence_state = AST_PRESENCE_NOT_SET;
153         exten_state_sub->user_agent = get_user_agent(rdata);
154         ao2_ref(exten_state_sub, +1);
155         return exten_state_sub;
156 }
157
158 /*!
159  * \internal
160  * \brief Create and send a NOTIFY request to the subscriber.
161  */
162 static void create_send_notify(struct exten_state_subscription *exten_state_sub, const char *reason,
163                                pjsip_evsub_state evsub_state, struct ast_sip_exten_state_data *exten_state_data)
164 {
165         RAII_VAR(struct ast_str *, body_text, ast_str_create(BODY_SIZE), ast_free_ptr);
166         pj_str_t reason_str;
167         const pj_str_t *reason_str_ptr = NULL;
168         pjsip_tx_data *tdata;
169         struct ast_sip_body body;
170
171         body.type = ast_sip_subscription_get_body_type(exten_state_sub->sip_sub);
172         body.subtype = ast_sip_subscription_get_body_subtype(exten_state_sub->sip_sub);
173
174         if (ast_sip_pubsub_generate_body_content(body.type, body.subtype,
175                                 exten_state_data, &body_text)) {
176                 ast_log(LOG_ERROR, "Unable to create body on NOTIFY request\n");
177                 return;
178         }
179
180         body.body_text = ast_str_buffer(body_text);
181
182         if (reason) {
183                 pj_cstr(&reason_str, reason);
184                 reason_str_ptr = &reason_str;
185         }
186
187         if (pjsip_evsub_notify(ast_sip_subscription_get_evsub(exten_state_sub->sip_sub),
188                               evsub_state, NULL, reason_str_ptr, &tdata) != PJ_SUCCESS) {
189                 ast_log(LOG_WARNING, "Unable to create NOTIFY request\n");
190                 return;
191         }
192
193         if (ast_sip_add_body(tdata, &body)) {
194                 ast_log(LOG_WARNING, "Unable to add body to NOTIFY request\n");
195                 pjsip_tx_data_dec_ref(tdata);
196                 return;
197         }
198
199         if (ast_sip_subscription_send_request(exten_state_sub->sip_sub, tdata) != PJ_SUCCESS) {
200                 ast_log(LOG_WARNING, "Unable to send NOTIFY request\n");
201         }
202 }
203
204 /*!
205  * \internal
206  * \brief Get device state information and send notification to the subscriber.
207  */
208 static void send_notify(struct exten_state_subscription *exten_state_sub, const char *reason,
209         pjsip_evsub_state evsub_state)
210 {
211         RAII_VAR(struct ao2_container*, info, NULL, ao2_cleanup);
212         char *subtype = NULL, *message = NULL;
213         pjsip_dialog *dlg;
214         struct ast_sip_exten_state_data exten_state_data = {
215                 .exten = exten_state_sub->exten,
216                 .presence_state = ast_hint_presence_state(NULL, exten_state_sub->context,
217                                                           exten_state_sub->exten, &subtype, &message),
218                 .presence_subtype = subtype,
219                 .presence_message = message,
220                 .user_agent = exten_state_sub->user_agent
221         };
222
223         dlg = ast_sip_subscription_get_dlg(exten_state_sub->sip_sub);
224         ast_copy_pj_str(exten_state_data.local, &dlg->local.info_str,
225                         sizeof(exten_state_data.local));
226         ast_copy_pj_str(exten_state_data.remote, &dlg->remote.info_str,
227                         sizeof(exten_state_data.remote));
228
229         if ((exten_state_data.exten_state = ast_extension_state_extended(
230                      NULL, exten_state_sub->context, exten_state_sub->exten, &info)) < 0) {
231
232                 ast_log(LOG_WARNING, "Unable to get device hint/info for extension %s\n",
233                         exten_state_sub->exten);
234                 return;
235         }
236
237         exten_state_data.pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(),
238                         "exten_state", 1024, 1024);
239
240         exten_state_data.device_state_info = info;
241         create_send_notify(exten_state_sub, reason, evsub_state, &exten_state_data);
242         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), exten_state_data.pool);
243 }
244
245 struct notify_task_data {
246         struct ast_sip_exten_state_data exten_state_data;
247         struct exten_state_subscription *exten_state_sub;
248         pjsip_evsub_state evsub_state;
249 };
250
251 static void notify_task_data_destructor(void *obj)
252 {
253         struct notify_task_data *task_data = obj;
254
255         ao2_ref(task_data->exten_state_sub, -1);
256         ao2_cleanup(task_data->exten_state_data.device_state_info);
257         ast_free(task_data->exten_state_data.presence_subtype);
258         ast_free(task_data->exten_state_data.presence_message);
259         ast_free(task_data->exten_state_data.user_agent);
260 }
261
262 static struct notify_task_data *alloc_notify_task_data(char *exten, struct exten_state_subscription *exten_state_sub,
263                                                        struct ast_state_cb_info *info)
264 {
265         struct notify_task_data *task_data =
266                 ao2_alloc(sizeof(*task_data), notify_task_data_destructor);
267         struct pjsip_dialog *dlg;
268
269         if (!task_data) {
270                 ast_log(LOG_WARNING, "Unable to create notify task data\n");
271                 return NULL;
272         }
273
274         task_data->evsub_state = PJSIP_EVSUB_STATE_ACTIVE;
275         task_data->exten_state_sub = exten_state_sub;
276         task_data->exten_state_sub->last_exten_state = info->exten_state;
277         task_data->exten_state_sub->last_presence_state = info->presence_state;
278         ao2_ref(task_data->exten_state_sub, +1);
279
280         task_data->exten_state_data.exten = exten_state_sub->exten;
281         task_data->exten_state_data.exten_state = info->exten_state;
282         task_data->exten_state_data.presence_state = info->presence_state;
283         task_data->exten_state_data.presence_subtype = ast_strdup(info->presence_subtype);
284         task_data->exten_state_data.presence_message = ast_strdup(info->presence_message);
285         task_data->exten_state_data.user_agent = ast_strdup(exten_state_sub->user_agent);
286         task_data->exten_state_data.device_state_info = info->device_state_info;
287
288         if (task_data->exten_state_data.device_state_info) {
289                 ao2_ref(task_data->exten_state_data.device_state_info, +1);
290         }
291
292         dlg = ast_sip_subscription_get_dlg(exten_state_sub->sip_sub);
293         ast_copy_pj_str(task_data->exten_state_data.local, &dlg->local.info_str,
294                         sizeof(task_data->exten_state_data.local));
295         ast_copy_pj_str(task_data->exten_state_data.remote, &dlg->remote.info_str,
296                         sizeof(task_data->exten_state_data.remote));
297
298         if ((info->exten_state == AST_EXTENSION_DEACTIVATED) ||
299             (info->exten_state == AST_EXTENSION_REMOVED)) {
300                 task_data->evsub_state = PJSIP_EVSUB_STATE_TERMINATED;
301                 ast_log(LOG_WARNING, "Watcher for hint %s %s\n", exten, info->exten_state
302                          == AST_EXTENSION_REMOVED ? "removed" : "deactivated");
303         }
304
305         return task_data;
306 }
307
308 static int notify_task(void *obj)
309 {
310         RAII_VAR(struct notify_task_data *, task_data, obj, ao2_cleanup);
311
312         /* Pool allocation has to happen here so that we allocate within a PJLIB thread */
313         task_data->exten_state_data.pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(),
314                         "exten_state", 1024, 1024);
315
316         create_send_notify(task_data->exten_state_sub, task_data->evsub_state ==
317                            PJSIP_EVSUB_STATE_TERMINATED ? "noresource" : NULL,
318                            task_data->evsub_state, &task_data->exten_state_data);
319
320         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(),
321                         task_data->exten_state_data.pool);
322         return 0;
323 }
324
325 /*!
326  * \internal
327  * \brief Callback for exten/device state changes.
328  *
329  * Upon state change, send the appropriate notification to the subscriber.
330  */
331 static int state_changed(char *context, char *exten,
332                          struct ast_state_cb_info *info, void *data)
333 {
334         struct notify_task_data *task_data;
335         struct exten_state_subscription *exten_state_sub = data;
336
337         if (!(task_data = alloc_notify_task_data(exten, exten_state_sub, info))) {
338                 return -1;
339         }
340
341         /* safe to push this async since we copy the data from info and
342            add a ref for the device state info */
343         if (ast_sip_push_task(ast_sip_subscription_get_serializer(task_data->exten_state_sub->sip_sub),
344                               notify_task, task_data)) {
345                 ao2_cleanup(task_data);
346                 return -1;
347         }
348         return 0;
349 }
350
351 static void state_changed_destroy(int id, void *data)
352 {
353         struct exten_state_subscription *exten_state_sub = data;
354         ao2_cleanup(exten_state_sub);
355 }
356
357 static struct ast_datastore_info ds_info = { };
358 static const char ds_name[] = "exten state datastore";
359
360 /*!
361  * \internal
362  * \brief Add a datastore for exten exten_state_subscription.
363  *
364  * Adds the exten_state_subscription wrapper object to a datastore so it can be retrieved
365  * later based upon its association with the ast_sip_subscription.
366  */
367 static int add_datastore(struct exten_state_subscription *exten_state_sub)
368 {
369         RAII_VAR(struct ast_datastore *, datastore,
370                  ast_sip_subscription_alloc_datastore(&ds_info, ds_name), ao2_cleanup);
371
372         if (!datastore) {
373                 return -1;
374         }
375
376         datastore->data = exten_state_sub;
377         ast_sip_subscription_add_datastore(exten_state_sub->sip_sub, datastore);
378         ao2_ref(exten_state_sub, +1);
379         return 0;
380 }
381
382 /*!
383  * \internal
384  * \brief Get the exten_state_subscription object associated with the given
385  * ast_sip_subscription in the datastore.
386  */
387 static struct exten_state_subscription *get_exten_state_sub(
388         struct ast_sip_subscription *sub)
389 {
390         RAII_VAR(struct ast_datastore *, datastore,
391                  ast_sip_subscription_get_datastore(sub, ds_name), ao2_cleanup);
392
393         return datastore ? datastore->data : NULL;
394 }
395
396 static void subscription_shutdown(struct ast_sip_subscription *sub)
397 {
398         struct exten_state_subscription *exten_state_sub = get_exten_state_sub(sub);
399
400         if (!exten_state_sub) {
401                 return;
402         }
403
404         ast_extension_state_del(exten_state_sub->id, state_changed);
405         ast_sip_subscription_remove_datastore(exten_state_sub->sip_sub, ds_name);
406         /* remove data store reference */
407         ao2_cleanup(exten_state_sub);
408 }
409
410 static struct ast_sip_subscription *new_subscribe(struct ast_sip_endpoint *endpoint,
411                                                   pjsip_rx_data *rdata)
412 {
413         pjsip_uri *uri = rdata->msg_info.msg->line.req.uri;
414         pjsip_sip_uri *sip_uri = pjsip_uri_get_uri(uri);
415         RAII_VAR(struct exten_state_subscription *, exten_state_sub, NULL, ao2_cleanup);
416
417         if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri)) {
418                 ast_log(LOG_WARNING, "Attempt to SUBSCRIBE to a non-SIP URI\n");
419                 return NULL;
420         }
421
422         if (!(exten_state_sub = exten_state_subscription_alloc(endpoint, AST_SIP_NOTIFIER, rdata))) {
423                 return NULL;
424         }
425
426         ast_copy_string(exten_state_sub->context, endpoint->context, sizeof(exten_state_sub->context));
427         ast_copy_pj_str(exten_state_sub->exten, &sip_uri->user, sizeof(exten_state_sub->exten));
428
429         if ((exten_state_sub->id = ast_extension_state_add_destroy_extended(
430                      exten_state_sub->context, exten_state_sub->exten,
431                      state_changed, state_changed_destroy, exten_state_sub)) < 0) {
432                 ast_log(LOG_WARNING, "Unable to subscribe endpoint '%s' to extension '%s@%s'\n",
433                         ast_sorcery_object_get_id(endpoint), exten_state_sub->exten,
434                         exten_state_sub->context);
435                 pjsip_evsub_terminate(ast_sip_subscription_get_evsub(exten_state_sub->sip_sub), PJ_FALSE);
436                 return NULL;
437         }
438
439         /* bump the ref since ast_extension_state_add holds a reference */
440         ao2_ref(exten_state_sub, +1);
441
442         if (add_datastore(exten_state_sub)) {
443                 ast_log(LOG_WARNING, "Unable to add to subscription datastore.\n");
444                 pjsip_evsub_terminate(ast_sip_subscription_get_evsub(exten_state_sub->sip_sub), PJ_FALSE);
445                 return NULL;
446         }
447
448         if (ast_sip_subscription_accept(exten_state_sub->sip_sub, rdata, 200)) {
449                 ast_log(LOG_WARNING, "Unable to accept the incoming extension state subscription.\n");
450                 pjsip_evsub_terminate(ast_sip_subscription_get_evsub(exten_state_sub->sip_sub), PJ_FALSE);
451                 return NULL;
452         }
453
454         send_notify(exten_state_sub, NULL, PJSIP_EVSUB_STATE_ACTIVE);
455         return exten_state_sub->sip_sub;
456 }
457
458 static void resubscribe(struct ast_sip_subscription *sub, pjsip_rx_data *rdata,
459                         struct ast_sip_subscription_response_data *response_data)
460 {
461         struct exten_state_subscription *exten_state_sub = get_exten_state_sub(sub);
462
463         if (!exten_state_sub) {
464                 return;
465         }
466
467         send_notify(exten_state_sub, NULL, PJSIP_EVSUB_STATE_ACTIVE);
468 }
469
470 static void subscription_timeout(struct ast_sip_subscription *sub)
471 {
472         struct exten_state_subscription *exten_state_sub = get_exten_state_sub(sub);
473
474         if (!exten_state_sub) {
475                 return;
476         }
477
478         ast_verbose(VERBOSE_PREFIX_3 "Subscription has timed out.\n");
479         send_notify(exten_state_sub, "timeout", PJSIP_EVSUB_STATE_TERMINATED);
480 }
481
482 static void subscription_terminated(struct ast_sip_subscription *sub,
483                                     pjsip_rx_data *rdata)
484 {
485         struct exten_state_subscription *exten_state_sub = get_exten_state_sub(sub);
486
487         if (!exten_state_sub) {
488                 return;
489         }
490
491         ast_verbose(VERBOSE_PREFIX_3 "Subscription has been terminated.\n");
492         send_notify(exten_state_sub, NULL, PJSIP_EVSUB_STATE_TERMINATED);
493 }
494
495 static void to_ami(struct ast_sip_subscription *sub,
496                    struct ast_str **buf)
497 {
498         struct exten_state_subscription *exten_state_sub =
499                 get_exten_state_sub(sub);
500
501         ast_str_append(buf, 0, "SubscriptionType: extension_state\r\n"
502                        "Extension: %s\r\nExtensionStates: %s\r\n",
503                        exten_state_sub->exten, ast_extension_state2str(
504                                exten_state_sub->last_exten_state));
505 }
506
507 static int load_module(void)
508 {
509         if (ast_sip_register_subscription_handler(&presence_handler)) {
510                 ast_log(LOG_WARNING, "Unable to register subscription handler %s\n",
511                         presence_handler.event_name);
512                 return AST_MODULE_LOAD_DECLINE;
513         }
514         return AST_MODULE_LOAD_SUCCESS;
515 }
516
517 static int unload_module(void)
518 {
519         ast_sip_unregister_subscription_handler(&presence_handler);
520         return 0;
521 }
522
523 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Extension State Notifications",
524                 .load = load_module,
525                 .unload = unload_module,
526                 .load_pri = AST_MODPRI_CHANNEL_DEPEND,
527 );