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