res_pjsip_exten_state: Presence for digium phones
[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 (exten_state_sub->last_exten_state == info->exten_state &&
338                 exten_state_sub->last_presence_state == info->presence_state) {
339                 return 0;
340         }
341
342         if (!(task_data = alloc_notify_task_data(exten, exten_state_sub, info))) {
343                 return -1;
344         }
345
346         /* safe to push this async since we copy the data from info and
347            add a ref for the device state info */
348         if (ast_sip_push_task(ast_sip_subscription_get_serializer(task_data->exten_state_sub->sip_sub),
349                               notify_task, task_data)) {
350                 ao2_cleanup(task_data);
351                 return -1;
352         }
353         return 0;
354 }
355
356 static void state_changed_destroy(int id, void *data)
357 {
358         struct exten_state_subscription *exten_state_sub = data;
359         ao2_cleanup(exten_state_sub);
360 }
361
362 static struct ast_datastore_info ds_info = { };
363 static const char ds_name[] = "exten state datastore";
364
365 /*!
366  * \internal
367  * \brief Add a datastore for exten exten_state_subscription.
368  *
369  * Adds the exten_state_subscription wrapper object to a datastore so it can be retrieved
370  * later based upon its association with the ast_sip_subscription.
371  */
372 static int add_datastore(struct exten_state_subscription *exten_state_sub)
373 {
374         RAII_VAR(struct ast_datastore *, datastore,
375                  ast_sip_subscription_alloc_datastore(&ds_info, ds_name), ao2_cleanup);
376
377         if (!datastore) {
378                 return -1;
379         }
380
381         datastore->data = exten_state_sub;
382         ast_sip_subscription_add_datastore(exten_state_sub->sip_sub, datastore);
383         ao2_ref(exten_state_sub, +1);
384         return 0;
385 }
386
387 /*!
388  * \internal
389  * \brief Get the exten_state_subscription object associated with the given
390  * ast_sip_subscription in the datastore.
391  */
392 static struct exten_state_subscription *get_exten_state_sub(
393         struct ast_sip_subscription *sub)
394 {
395         RAII_VAR(struct ast_datastore *, datastore,
396                  ast_sip_subscription_get_datastore(sub, ds_name), ao2_cleanup);
397
398         return datastore ? datastore->data : NULL;
399 }
400
401 static void subscription_shutdown(struct ast_sip_subscription *sub)
402 {
403         struct exten_state_subscription *exten_state_sub = get_exten_state_sub(sub);
404
405         if (!exten_state_sub) {
406                 return;
407         }
408
409         ast_extension_state_del(exten_state_sub->id, state_changed);
410         ast_sip_subscription_remove_datastore(exten_state_sub->sip_sub, ds_name);
411         /* remove data store reference */
412         ao2_cleanup(exten_state_sub);
413 }
414
415 static struct ast_sip_subscription *new_subscribe(struct ast_sip_endpoint *endpoint,
416                                                   pjsip_rx_data *rdata)
417 {
418         pjsip_uri *uri = rdata->msg_info.msg->line.req.uri;
419         pjsip_sip_uri *sip_uri = pjsip_uri_get_uri(uri);
420         RAII_VAR(struct exten_state_subscription *, exten_state_sub, NULL, ao2_cleanup);
421
422         if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri)) {
423                 ast_log(LOG_WARNING, "Attempt to SUBSCRIBE to a non-SIP URI\n");
424                 return NULL;
425         }
426
427         if (!(exten_state_sub = exten_state_subscription_alloc(endpoint, AST_SIP_NOTIFIER, rdata))) {
428                 return NULL;
429         }
430
431         ast_copy_string(exten_state_sub->context, endpoint->context, sizeof(exten_state_sub->context));
432         ast_copy_pj_str(exten_state_sub->exten, &sip_uri->user, sizeof(exten_state_sub->exten));
433
434         if ((exten_state_sub->id = ast_extension_state_add_destroy_extended(
435                      exten_state_sub->context, exten_state_sub->exten,
436                      state_changed, state_changed_destroy, exten_state_sub)) < 0) {
437                 ast_log(LOG_WARNING, "Unable to subscribe endpoint '%s' to extension '%s@%s'\n",
438                         ast_sorcery_object_get_id(endpoint), exten_state_sub->exten,
439                         exten_state_sub->context);
440                 pjsip_evsub_terminate(ast_sip_subscription_get_evsub(exten_state_sub->sip_sub), PJ_FALSE);
441                 return NULL;
442         }
443
444         /* bump the ref since ast_extension_state_add holds a reference */
445         ao2_ref(exten_state_sub, +1);
446
447         if (add_datastore(exten_state_sub)) {
448                 ast_log(LOG_WARNING, "Unable to add to subscription datastore.\n");
449                 pjsip_evsub_terminate(ast_sip_subscription_get_evsub(exten_state_sub->sip_sub), PJ_FALSE);
450                 return NULL;
451         }
452
453         if (pjsip_evsub_accept(ast_sip_subscription_get_evsub(exten_state_sub->sip_sub),
454                                rdata, 200, NULL) != PJ_SUCCESS) {
455                 ast_log(LOG_WARNING, "Unable to accept the incoming extension state subscription.\n");
456                 pjsip_evsub_terminate(ast_sip_subscription_get_evsub(exten_state_sub->sip_sub), PJ_FALSE);
457                 return NULL;
458         }
459
460         send_notify(exten_state_sub, NULL, PJSIP_EVSUB_STATE_ACTIVE);
461         return exten_state_sub->sip_sub;
462 }
463
464 static void resubscribe(struct ast_sip_subscription *sub, pjsip_rx_data *rdata,
465                         struct ast_sip_subscription_response_data *response_data)
466 {
467         struct exten_state_subscription *exten_state_sub = get_exten_state_sub(sub);
468
469         if (!exten_state_sub) {
470                 return;
471         }
472
473         send_notify(exten_state_sub, NULL, PJSIP_EVSUB_STATE_ACTIVE);
474 }
475
476 static void subscription_timeout(struct ast_sip_subscription *sub)
477 {
478         struct exten_state_subscription *exten_state_sub = get_exten_state_sub(sub);
479
480         if (!exten_state_sub) {
481                 return;
482         }
483
484         ast_verbose(VERBOSE_PREFIX_3 "Subscription has timed out.\n");
485         send_notify(exten_state_sub, "timeout", PJSIP_EVSUB_STATE_TERMINATED);
486 }
487
488 static void subscription_terminated(struct ast_sip_subscription *sub,
489                                     pjsip_rx_data *rdata)
490 {
491         struct exten_state_subscription *exten_state_sub = get_exten_state_sub(sub);
492
493         if (!exten_state_sub) {
494                 return;
495         }
496
497         ast_verbose(VERBOSE_PREFIX_3 "Subscription has been terminated.\n");
498         send_notify(exten_state_sub, NULL, PJSIP_EVSUB_STATE_TERMINATED);
499 }
500
501 static void to_ami(struct ast_sip_subscription *sub,
502                    struct ast_str **buf)
503 {
504         struct exten_state_subscription *exten_state_sub =
505                 get_exten_state_sub(sub);
506
507         ast_str_append(buf, 0, "SubscriptionType: extension_state\r\n"
508                        "Extension: %s\r\nExtensionStates: %s\r\n",
509                        exten_state_sub->exten, ast_extension_state2str(
510                                exten_state_sub->last_exten_state));
511 }
512
513 static int load_module(void)
514 {
515         if (ast_sip_register_subscription_handler(&presence_handler)) {
516                 ast_log(LOG_WARNING, "Unable to register subscription handler %s\n",
517                         presence_handler.event_name);
518                 return AST_MODULE_LOAD_DECLINE;
519         }
520         return AST_MODULE_LOAD_SUCCESS;
521 }
522
523 static int unload_module(void)
524 {
525         ast_sip_unregister_subscription_handler(&presence_handler);
526         return 0;
527 }
528
529 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Extension State Notifications",
530                 .load = load_module,
531                 .unload = unload_module,
532                 .load_pri = AST_MODPRI_CHANNEL_DEPEND,
533 );