loader: Add dependency fields to module structures.
[asterisk/asterisk.git] / res / res_pjsip_publish_asterisk.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2014, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@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_outbound_publish</depend>
23         <depend>res_pjsip_pubsub</depend>
24         <support_level>core</support_level>
25  ***/
26
27 #include "asterisk.h"
28
29 #include <regex.h>
30
31 #include <pjsip.h>
32 #include <pjsip_simple.h>
33
34 #include "asterisk/res_pjsip.h"
35 #include "asterisk/res_pjsip_outbound_publish.h"
36 #include "asterisk/res_pjsip_pubsub.h"
37 #include "asterisk/module.h"
38 #include "asterisk/logger.h"
39 #include "asterisk/app.h"
40
41 /*** DOCUMENTATION
42         <configInfo name="res_pjsip_publish_asterisk" language="en_US">
43                 <synopsis>SIP resource for inbound and outbound Asterisk event publications</synopsis>
44                 <description><para>
45                         <emphasis>Inbound and outbound Asterisk event publication</emphasis>
46                         </para>
47                         <para>This module allows <literal>res_pjsip</literal> to send and receive Asterisk event publications.</para>
48                 </description>
49                 <configFile name="pjsip.conf">
50                         <configObject name="asterisk-publication">
51                                 <synopsis>The configuration for inbound Asterisk event publication</synopsis>
52                                 <description><para>
53                                         Publish is <emphasis>COMPLETELY</emphasis> separate from the rest of
54                                         <literal>pjsip.conf</literal>.
55                                 </para></description>
56                                 <configOption name="devicestate_publish">
57                                         <synopsis>Optional name of a publish item that can be used to publish a request for full device state information.</synopsis>
58                                 </configOption>
59                                 <configOption name="mailboxstate_publish">
60                                         <synopsis>Optional name of a publish item that can be used to publish a request for full mailbox state information.</synopsis>
61                                 </configOption>
62                                 <configOption name="device_state" default="no">
63                                         <synopsis>Whether we should permit incoming device state events.</synopsis>
64                                 </configOption>
65                                 <configOption name="device_state_filter">
66                                         <synopsis>Optional regular expression used to filter what devices we accept events for.</synopsis>
67                                 </configOption>
68                                 <configOption name="mailbox_state" default="no">
69                                         <synopsis>Whether we should permit incoming mailbox state events.</synopsis>
70                                 </configOption>
71                                 <configOption name="mailbox_state_filter">
72                                         <synopsis>Optional regular expression used to filter what mailboxes we accept events for.</synopsis>
73                                 </configOption>
74                                 <configOption name="type">
75                                         <synopsis>Must be of type 'asterisk-publication'.</synopsis>
76                                 </configOption>
77                         </configObject>
78                 </configFile>
79         </configInfo>
80  ***/
81
82 /*! \brief Structure which contains Asterisk device state publisher state information */
83 struct asterisk_devicestate_publisher_state {
84         /*! \brief The publish client to send PUBLISH messages on */
85         struct ast_sip_outbound_publish_client *client;
86         /*! \brief Device state subscription */
87         struct stasis_subscription *device_state_subscription;
88         /*! \brief Regex used for filtering outbound device state */
89         regex_t device_state_regex;
90         /*! \brief Device state should be filtered */
91         unsigned int device_state_filter;
92 };
93
94 /*! \brief Structure which contains Asterisk mailbox publisher state information */
95 struct asterisk_mwi_publisher_state {
96         /*! \brief The publish client to send PUBLISH messages on */
97         struct ast_sip_outbound_publish_client *client;
98         /*! \brief Mailbox state subscription */
99         struct stasis_subscription *mailbox_state_subscription;
100         /*! \brief Regex used for filtering outbound mailbox state */
101         regex_t mailbox_state_regex;
102         /*! \brief Mailbox state should be filtered */
103         unsigned int mailbox_state_filter;
104 };
105
106 /*! \brief Structure which contains Asterisk publication information */
107 struct asterisk_publication_config {
108         /*! \brief Sorcery object details */
109         SORCERY_OBJECT(details);
110         /*! \brief Stringfields */
111         AST_DECLARE_STRING_FIELDS(
112                 /*! \brief Optional name of a device state publish item, used to request the remote side update us */
113                 AST_STRING_FIELD(devicestate_publish);
114                 /*! \brief Optional name of a mailbox state publish item, used to request the remote side update us */
115                 AST_STRING_FIELD(mailboxstate_publish);
116         );
117         /*! \brief Accept inbound device state events */
118         unsigned int device_state;
119         /*! \brief Regex used for filtering inbound device state */
120         regex_t device_state_regex;
121         /*! \brief Device state should be filtered */
122         unsigned int device_state_filter;
123         /*! \brief Accept inbound mailbox state events */
124         unsigned int mailbox_state;
125         /*! \brief Regex used for filtering inbound mailbox state */
126         regex_t mailbox_state_regex;
127         /*! \brief Mailbox state should be filtered */
128         unsigned int mailbox_state_filter;
129 };
130
131 /*! \brief Destroy callback for Asterisk devicestate publisher state information from datastore */
132 static void asterisk_devicestate_publisher_state_destroy(void *obj)
133 {
134         struct asterisk_devicestate_publisher_state *publisher_state = obj;
135
136         ao2_cleanup(publisher_state->client);
137
138         if (publisher_state->device_state_filter) {
139                 regfree(&publisher_state->device_state_regex);
140         }
141 }
142
143 /*! \brief Datastore for attaching devicestate publisher state information */
144 static const struct ast_datastore_info asterisk_devicestate_publisher_state_datastore = {
145         .type = "asterisk-devicestate-publisher",
146         .destroy = asterisk_devicestate_publisher_state_destroy,
147 };
148
149 /*! \brief Destroy callback for Asterisk mwi publisher state information from datastore */
150 static void asterisk_mwi_publisher_state_destroy(void *obj)
151 {
152         struct asterisk_mwi_publisher_state *publisher_state = obj;
153
154         ao2_cleanup(publisher_state->client);
155
156         if (publisher_state->mailbox_state_filter) {
157                 regfree(&publisher_state->mailbox_state_regex);
158         }
159 }
160
161 /*! \brief Datastore for attaching devicestate publisher state information */
162 static const struct ast_datastore_info asterisk_mwi_publisher_state_datastore = {
163         .type = "asterisk-mwi-publisher",
164         .destroy = asterisk_mwi_publisher_state_destroy,
165 };
166
167 /*!
168  * \brief Callback function for device state events
169  * \param ast_event
170  * \param data void pointer to ast_client structure
171  * \return void
172  */
173 static void asterisk_publisher_devstate_cb(void *data, struct stasis_subscription *sub, struct stasis_message *msg)
174 {
175         struct ast_datastore *datastore = data;
176         struct asterisk_devicestate_publisher_state *publisher_state = datastore->data;
177         struct ast_device_state_message *dev_state;
178         char eid_str[20];
179         struct ast_json *json;
180         char *text;
181         struct ast_sip_body body = {
182                 .type = "application",
183                 .subtype = "json",
184         };
185
186         if (!stasis_subscription_is_subscribed(sub) || ast_device_state_message_type() != stasis_message_type(msg)) {
187                 return;
188         }
189
190         dev_state = stasis_message_data(msg);
191         if (!dev_state->eid || ast_eid_cmp(&ast_eid_default, dev_state->eid)) {
192                 /* If the event is aggregate or didn't originate from this server, don't send it out. */
193                 return;
194         }
195
196         if (publisher_state->device_state_filter && regexec(&publisher_state->device_state_regex, dev_state->device, 0, NULL, 0)) {
197                 /* Outgoing device state has been filtered and the device name does not match */
198                 return;
199         }
200
201         ast_eid_to_str(eid_str, sizeof(eid_str), &ast_eid_default);
202         json = ast_json_pack(
203                 "{ s: s, s: s, s: s, s: i, s:s }",
204                 "type", "devicestate",
205                 "device", dev_state->device,
206                 "state", ast_devstate_str(dev_state->state),
207                 "cachable", dev_state->cachable,
208                 "eid", eid_str);
209         if (!json) {
210                 return;
211         }
212
213         text = ast_json_dump_string(json);
214         if (!text) {
215                 ast_json_unref(json);
216                 return;
217         }
218         body.body_text = text;
219
220         ast_sip_publish_client_send(publisher_state->client, &body);
221
222         ast_json_free(text);
223         ast_json_unref(json);
224 }
225
226 /*!
227  * \brief Callback function for mailbox state events
228  * \param ast_event
229  * \param data void pointer to ast_client structure
230  * \return void
231  */
232 static void asterisk_publisher_mwistate_cb(void *data, struct stasis_subscription *sub, struct stasis_message *msg)
233 {
234         struct ast_datastore *datastore = data;
235         struct asterisk_mwi_publisher_state *publisher_state = datastore->data;
236         struct ast_mwi_state *mwi_state;
237         char eid_str[20];
238         struct ast_json *json;
239         char *text;
240         struct ast_sip_body body = {
241                 .type = "application",
242                 .subtype = "json",
243         };
244
245         if (!stasis_subscription_is_subscribed(sub) || ast_mwi_state_type() != stasis_message_type(msg)) {
246                 return;
247         }
248
249         mwi_state = stasis_message_data(msg);
250         if (ast_eid_cmp(&ast_eid_default, &mwi_state->eid)) {
251                 /* If the event is aggregate or didn't originate from this server, don't send it out. */
252                 return;
253         }
254
255         if (publisher_state->mailbox_state_filter && regexec(&publisher_state->mailbox_state_regex, mwi_state->uniqueid, 0, NULL, 0)) {
256                 /* Outgoing mailbox state has been filtered and the uniqueid does not match */
257                 return;
258         }
259
260         ast_eid_to_str(eid_str, sizeof(eid_str), &ast_eid_default);
261         json = ast_json_pack(
262                 "{ s: s, s: s, s: i, s: i, s:s }",
263                 "type", "mailboxstate",
264                 "uniqueid", mwi_state->uniqueid,
265                 "old", mwi_state->old_msgs,
266                 "new", mwi_state->new_msgs,
267                 "eid", eid_str);
268         if (!json) {
269                 return;
270         }
271
272         text = ast_json_dump_string(json);
273         if (!text) {
274                 ast_json_unref(json);
275                 return;
276         }
277         body.body_text = text;
278
279         ast_sip_publish_client_send(publisher_state->client, &body);
280
281         ast_json_free(text);
282         ast_json_unref(json);
283 }
284
285 static int cached_devstate_cb(void *obj, void *arg, int flags)
286 {
287         struct stasis_message *msg = obj;
288         struct ast_datastore *datastore = arg;
289         struct asterisk_devicestate_publisher_state *publisher_state = datastore->data;
290
291         asterisk_publisher_devstate_cb(arg, publisher_state->device_state_subscription, msg);
292
293         return 0;
294 }
295
296 static int cached_mwistate_cb(void *obj, void *arg, int flags)
297 {
298         struct stasis_message *msg = obj;
299         struct ast_datastore *datastore = arg;
300         struct asterisk_mwi_publisher_state *publisher_state = datastore->data;
301
302         asterisk_publisher_mwistate_cb(arg, publisher_state->mailbox_state_subscription, msg);
303
304         return 0;
305 }
306
307 static int build_regex(regex_t *regex, const char *text)
308 {
309         int res;
310
311         if ((res = regcomp(regex, text, REG_EXTENDED | REG_ICASE | REG_NOSUB))) {
312                 size_t len = regerror(res, regex, NULL, 0);
313                 char buf[len];
314                 regerror(res, regex, buf, len);
315                 ast_log(LOG_ERROR, "Could not compile regex '%s': %s\n", text, buf);
316                 return -1;
317         }
318
319         return 0;
320 }
321
322 static int asterisk_start_devicestate_publishing(struct ast_sip_outbound_publish *configuration,
323         struct ast_sip_outbound_publish_client *client)
324 {
325         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
326         struct asterisk_devicestate_publisher_state *publisher_state;
327         const char *value;
328         struct ao2_container *cached;
329
330         datastore = ast_sip_publish_client_alloc_datastore(&asterisk_devicestate_publisher_state_datastore,
331                 "asterisk-devicestate-publisher");
332         if (!datastore) {
333                 return -1;
334         }
335
336         publisher_state = ast_calloc(1, sizeof(struct asterisk_devicestate_publisher_state));
337         if (!publisher_state) {
338                 return -1;
339         }
340         datastore->data = publisher_state;
341
342         value = ast_sorcery_object_get_extended(configuration, "device_state_filter");
343         if (!ast_strlen_zero(value)) {
344                 if (build_regex(&publisher_state->device_state_regex, value)) {
345                         return -1;
346                 }
347                 publisher_state->device_state_filter = 1;
348         }
349
350         publisher_state->client = ao2_bump(client);
351
352         if (ast_sip_publish_client_add_datastore(client, datastore)) {
353                 return -1;
354         }
355
356         publisher_state->device_state_subscription = stasis_subscribe(ast_device_state_topic_all(),
357                 asterisk_publisher_devstate_cb, ao2_bump(datastore));
358         if (!publisher_state->device_state_subscription) {
359                 ast_sip_publish_client_remove_datastore(client, "asterisk-devicestate-publisher");
360                 ao2_ref(datastore, -1);
361                 return -1;
362         }
363
364         cached = stasis_cache_dump(ast_device_state_cache(), NULL);
365         ao2_callback(cached, OBJ_NODATA, cached_devstate_cb, datastore);
366         ao2_ref(cached, -1);
367
368         return 0;
369 }
370
371 static int asterisk_stop_devicestate_publishing(struct ast_sip_outbound_publish_client *client)
372 {
373         RAII_VAR(struct ast_datastore *, datastore, ast_sip_publish_client_get_datastore(client, "asterisk-devicestate-publisher"),
374                 ao2_cleanup);
375         struct asterisk_devicestate_publisher_state *publisher_state;
376
377         if (!datastore) {
378                 return 0;
379         }
380
381         publisher_state = datastore->data;
382         if (publisher_state->device_state_subscription) {
383                 stasis_unsubscribe_and_join(publisher_state->device_state_subscription);
384                 ao2_ref(datastore, -1);
385         }
386
387         ast_sip_publish_client_remove_datastore(client, "asterisk-devicestate-publisher");
388
389         return 0;
390 }
391
392 struct ast_sip_event_publisher_handler asterisk_devicestate_publisher_handler = {
393         .event_name = "asterisk-devicestate",
394         .start_publishing = asterisk_start_devicestate_publishing,
395         .stop_publishing = asterisk_stop_devicestate_publishing,
396 };
397
398 static int asterisk_start_mwi_publishing(struct ast_sip_outbound_publish *configuration,
399         struct ast_sip_outbound_publish_client *client)
400 {
401         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
402         struct asterisk_mwi_publisher_state *publisher_state;
403         const char *value;
404         struct ao2_container *cached;
405
406         datastore = ast_sip_publish_client_alloc_datastore(&asterisk_mwi_publisher_state_datastore, "asterisk-mwi-publisher");
407         if (!datastore) {
408                 return -1;
409         }
410
411         publisher_state = ast_calloc(1, sizeof(struct asterisk_mwi_publisher_state));
412         if (!publisher_state) {
413                 return -1;
414         }
415         datastore->data = publisher_state;
416
417         value = ast_sorcery_object_get_extended(configuration, "mailbox_state_filter");
418         if (!ast_strlen_zero(value)) {
419                 if (build_regex(&publisher_state->mailbox_state_regex, value)) {
420                         return -1;
421                 }
422                 publisher_state->mailbox_state_filter = 1;
423         }
424
425         publisher_state->client = ao2_bump(client);
426
427         if (ast_sip_publish_client_add_datastore(client, datastore)) {
428                 return -1;
429         }
430
431         publisher_state->mailbox_state_subscription = stasis_subscribe(ast_mwi_topic_all(),
432                 asterisk_publisher_mwistate_cb, ao2_bump(datastore));
433         if (!publisher_state->mailbox_state_subscription) {
434                 ast_sip_publish_client_remove_datastore(client, "asterisk-mwi-publisher");
435                 ao2_ref(datastore, -1);
436                 return -1;
437         }
438
439         cached = stasis_cache_dump(ast_mwi_state_cache(), NULL);
440         ao2_callback(cached, OBJ_NODATA, cached_mwistate_cb, datastore);
441         ao2_ref(cached, -1);
442
443         return 0;
444 }
445
446 static int asterisk_stop_mwi_publishing(struct ast_sip_outbound_publish_client *client)
447 {
448         RAII_VAR(struct ast_datastore *, datastore, ast_sip_publish_client_get_datastore(client, "asterisk-mwi-publisher"),
449                 ao2_cleanup);
450         struct asterisk_mwi_publisher_state *publisher_state;
451
452         if (!datastore) {
453                 return 0;
454         }
455
456         publisher_state = datastore->data;
457         if (publisher_state->mailbox_state_subscription) {
458                 stasis_unsubscribe_and_join(publisher_state->mailbox_state_subscription);
459                 ao2_ref(datastore, -1);
460         }
461
462         ast_sip_publish_client_remove_datastore(client, "asterisk-mwi-publisher");
463
464         return 0;
465 }
466
467 struct ast_sip_event_publisher_handler asterisk_mwi_publisher_handler = {
468         .event_name = "asterisk-mwi",
469         .start_publishing = asterisk_start_mwi_publishing,
470         .stop_publishing = asterisk_stop_mwi_publishing,
471 };
472
473 static int asterisk_publication_new(struct ast_sip_endpoint *endpoint, const char *resource, const char *event_configuration)
474 {
475         RAII_VAR(struct asterisk_publication_config *, config, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "asterisk-publication",
476                 event_configuration), ao2_cleanup);
477
478         /* If no inbound Asterisk publication configuration exists reject the PUBLISH */
479         if (!config) {
480                 return 404;
481         }
482
483         return 200;
484 }
485
486 static int asterisk_publication_devicestate(struct ast_sip_publication *pub, struct asterisk_publication_config *config,
487         struct ast_eid *pubsub_eid, struct ast_json *json)
488 {
489         const char *device = ast_json_string_get(ast_json_object_get(json, "device"));
490         const char *state = ast_json_string_get(ast_json_object_get(json, "state"));
491         int cachable = ast_json_integer_get(ast_json_object_get(json, "cachable"));
492
493         if (!config->device_state) {
494                 ast_debug(2, "Received device state event for resource '%s' but it is not configured to accept them\n",
495                         ast_sorcery_object_get_id(config));
496                 return 0;
497         }
498
499         if (ast_strlen_zero(device) || ast_strlen_zero(state)) {
500                 ast_debug(1, "Received incomplete device state event for resource '%s'\n",
501                         ast_sorcery_object_get_id(config));
502                 return -1;
503         }
504
505         if (config->device_state_filter && regexec(&config->device_state_regex, device, 0, NULL, 0)) {
506                 ast_debug(2, "Received device state on resource '%s' for device '%s' but it has been filtered out\n",
507                         ast_sorcery_object_get_id(config), device);
508                 return 0;
509         }
510
511         ast_publish_device_state_full(device, ast_devstate_val(state),
512                 cachable == AST_DEVSTATE_CACHABLE ? AST_DEVSTATE_CACHABLE : AST_DEVSTATE_NOT_CACHABLE,
513                 pubsub_eid);
514
515         return 0;
516 }
517
518 static int asterisk_publication_mailboxstate(struct ast_sip_publication *pub, struct asterisk_publication_config *config,
519         struct ast_eid *pubsub_eid, struct ast_json *json)
520 {
521         const char *uniqueid = ast_json_string_get(ast_json_object_get(json, "uniqueid"));
522         int old_msgs = ast_json_integer_get(ast_json_object_get(json, "old"));
523         int new_msgs = ast_json_integer_get(ast_json_object_get(json, "new"));
524         char *item_id;
525         const char *mailbox;
526
527         if (!config->mailbox_state) {
528                 ast_debug(2, "Received mailbox state event for resource '%s' but it is not configured to accept them\n",
529                         ast_sorcery_object_get_id(config));
530                 return 0;
531         }
532
533         if (ast_strlen_zero(uniqueid)) {
534                 ast_debug(1, "Received incomplete mailbox state event for resource '%s'\n",
535                         ast_sorcery_object_get_id(config));
536                 return -1;
537         }
538
539         if (config->mailbox_state_filter && regexec(&config->mailbox_state_regex, uniqueid, 0, NULL, 0)) {
540                 ast_debug(2, "Received mailbox state on resource '%s' for uniqueid '%s' but it has been filtered out\n",
541                         ast_sorcery_object_get_id(config), uniqueid);
542                 return 0;
543         }
544
545         item_id = ast_strdupa(uniqueid);
546         mailbox = strsep(&item_id, "@");
547
548         ast_publish_mwi_state_full(mailbox, item_id, new_msgs, old_msgs, NULL, pubsub_eid);
549
550         return 0;
551 }
552
553 static int asterisk_publication_devicestate_refresh(struct ast_sip_publication *pub,
554         struct asterisk_publication_config *config, struct ast_eid *pubsub_eid, struct ast_json *json)
555 {
556         struct ast_sip_outbound_publish_client *client;
557         struct ast_datastore *datastore;
558         struct ao2_container *cached;
559
560         if (ast_strlen_zero(config->devicestate_publish)) {
561                 return 0;
562         }
563
564         client = ast_sip_publish_client_get(config->devicestate_publish);
565         if (!client) {
566                 ast_log(LOG_ERROR, "Received refresh request for devicestate on publication '%s' but publish '%s' is not available\n",
567                         ast_sorcery_object_get_id(config), config->devicestate_publish);
568                 return 0;
569         }
570
571         datastore = ast_sip_publish_client_get_datastore(client, "asterisk-devicestate-publisher");
572         if (!datastore) {
573                 ao2_ref(client, -1);
574                 return 0;
575         }
576
577         cached = stasis_cache_dump(ast_device_state_cache(), NULL);
578         if (cached) {
579                 ao2_callback(cached, OBJ_NODATA, cached_devstate_cb, datastore);
580                 ao2_ref(cached, -1);
581         }
582         ao2_ref(client, -1);
583         ao2_ref(datastore, -1);
584
585         return 0;
586 }
587
588 static int asterisk_publication_devicestate_state_change(struct ast_sip_publication *pub, pjsip_msg_body *body,
589                         enum ast_sip_publish_state state)
590 {
591         RAII_VAR(struct asterisk_publication_config *, config, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "asterisk-publication",
592                 ast_sip_publication_get_event_configuration(pub)), ao2_cleanup);
593         RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
594         const char *eid, *type;
595         struct ast_eid pubsub_eid;
596         int res = -1;
597
598         /* If no configuration exists for this publication it has most likely been removed, so drop this immediately */
599         if (!config) {
600                 return -1;
601         }
602
603         /* If no body exists this is a refresh and can be ignored */
604         if (!body) {
605                 return 0;
606         }
607
608         /* We only accept JSON for content */
609         if (!ast_sip_is_content_type(&body->content_type, "application", "json")) {
610                 ast_debug(2, "Received unsupported content type for Asterisk event on resource '%s'\n",
611                         ast_sorcery_object_get_id(config));
612                 return -1;
613         }
614
615         json = ast_json_load_buf(body->data, body->len, NULL);
616         if (!json) {
617                 ast_debug(1, "Received unparseable JSON event for resource '%s'\n",
618                         ast_sorcery_object_get_id(config));
619                 return -1;
620         }
621
622         eid = ast_json_string_get(ast_json_object_get(json, "eid"));
623         if (!eid) {
624                 ast_debug(1, "Received event without eid for resource '%s'\n",
625                         ast_sorcery_object_get_id(config));
626                 return -1;
627         }
628         ast_str_to_eid(&pubsub_eid, eid);
629
630         type = ast_json_string_get(ast_json_object_get(json, "type"));
631         if (!type) {
632                 ast_debug(1, "Received event without type for resource '%s'\n",
633                         ast_sorcery_object_get_id(config));
634                 return -1;
635         } else if (!strcmp(type, "devicestate")) {
636                 res = asterisk_publication_devicestate(pub, config, &pubsub_eid, json);
637         } else if (!strcmp(type, "refresh")) {
638                 res = asterisk_publication_devicestate_refresh(pub, config, &pubsub_eid, json);
639         }
640
641         return res;
642 }
643
644 static int asterisk_publication_mwi_refresh(struct ast_sip_publication *pub,
645         struct asterisk_publication_config *config, struct ast_eid *pubsub_eid, struct ast_json *json)
646 {
647         struct ast_sip_outbound_publish_client *client;
648         struct ast_datastore *datastore;
649         struct ao2_container *cached;
650
651         if (ast_strlen_zero(config->mailboxstate_publish)) {
652                 return 0;
653         }
654
655         client = ast_sip_publish_client_get(config->mailboxstate_publish);
656         if (!client) {
657                 ast_log(LOG_ERROR, "Received refresh request for mwi state on publication '%s' but publish '%s' is not available\n",
658                         ast_sorcery_object_get_id(config), config->mailboxstate_publish);
659                 return 0;
660         }
661
662         datastore = ast_sip_publish_client_get_datastore(client, "asterisk-mwi-publisher");
663         if (!datastore) {
664                 ao2_ref(client, -1);
665                 return 0;
666         }
667
668         cached = stasis_cache_dump(ast_mwi_state_cache(), NULL);
669         if (cached) {
670                 ao2_callback(cached, OBJ_NODATA, cached_mwistate_cb, datastore);
671                 ao2_ref(cached, -1);
672         }
673         ao2_ref(client, -1);
674         ao2_ref(datastore, -1);
675
676         return 0;
677 }
678
679 static int asterisk_publication_mwi_state_change(struct ast_sip_publication *pub, pjsip_msg_body *body,
680                         enum ast_sip_publish_state state)
681 {
682         RAII_VAR(struct asterisk_publication_config *, config, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "asterisk-publication",
683                 ast_sip_publication_get_event_configuration(pub)), ao2_cleanup);
684         RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
685         const char *eid, *type;
686         struct ast_eid pubsub_eid;
687         int res = -1;
688
689         /* If no configuration exists for this publication it has most likely been removed, so drop this immediately */
690         if (!config) {
691                 return -1;
692         }
693
694         /* If no body exists this is a refresh and can be ignored */
695         if (!body) {
696                 return 0;
697         }
698
699         /* We only accept JSON for content */
700         if (!ast_sip_is_content_type(&body->content_type, "application", "json")) {
701                 ast_debug(2, "Received unsupported content type for Asterisk event on resource '%s'\n",
702                         ast_sorcery_object_get_id(config));
703                 return -1;
704         }
705
706         json = ast_json_load_buf(body->data, body->len, NULL);
707         if (!json) {
708                 ast_debug(1, "Received unparseable JSON event for resource '%s'\n",
709                         ast_sorcery_object_get_id(config));
710                 return -1;
711         }
712
713         eid = ast_json_string_get(ast_json_object_get(json, "eid"));
714         if (!eid) {
715                 ast_debug(1, "Received event without eid for resource '%s'\n",
716                         ast_sorcery_object_get_id(config));
717                 return -1;
718         }
719         ast_str_to_eid(&pubsub_eid, eid);
720
721         type = ast_json_string_get(ast_json_object_get(json, "type"));
722         if (!type) {
723                 ast_debug(1, "Received event without type for resource '%s'\n",
724                         ast_sorcery_object_get_id(config));
725                 return -1;
726         } else if (!strcmp(type, "mailboxstate")) {
727                 res = asterisk_publication_mailboxstate(pub, config, &pubsub_eid, json);
728         } else if (!strcmp(type, "refresh")) {
729                 res = asterisk_publication_mwi_refresh(pub, config, &pubsub_eid, json);
730         }
731
732         return res;
733 }
734
735 static int send_refresh_cb(void *obj, void *arg, int flags)
736 {
737         struct asterisk_publication_config *config = obj;
738         struct ast_sip_outbound_publish_client *client;
739
740         if (!ast_strlen_zero(config->devicestate_publish)) {
741                 client = ast_sip_publish_client_get(config->devicestate_publish);
742                 if (client) {
743                         ast_sip_publish_client_send(client, arg);
744                         ao2_ref(client, -1);
745                 }
746         }
747
748         if (!ast_strlen_zero(config->mailboxstate_publish)) {
749                 client = ast_sip_publish_client_get(config->mailboxstate_publish);
750                 if (client) {
751                         ast_sip_publish_client_send(client, arg);
752                         ao2_ref(client, -1);
753                 }
754         }
755
756         return 0;
757 }
758
759 /*! \brief Internal function to send refresh requests to all publications */
760 static void asterisk_publication_send_refresh(void)
761 {
762         struct ao2_container *publications = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "asterisk-publication", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
763         char eid_str[20];
764         struct ast_json *json;
765         char *text;
766         struct ast_sip_body body = {
767                 .type = "application",
768                 .subtype = "json",
769         };
770
771         if (!publications) {
772                 return;
773         }
774
775         ast_eid_to_str(eid_str, sizeof(eid_str), &ast_eid_default);
776         json = ast_json_pack(
777                 "{ s: s, s: s }",
778                 "type", "refresh",
779                 "eid", eid_str);
780         if (!json) {
781                 ao2_ref(publications, -1);
782                 return;
783         }
784
785         text = ast_json_dump_string(json);
786         if (!text) {
787                 ast_json_unref(json);
788                 ao2_ref(publications, -1);
789                 return;
790         }
791         body.body_text = text;
792
793         ao2_callback(publications, OBJ_NODATA, send_refresh_cb, &body);
794
795         ast_json_free(text);
796         ast_json_unref(json);
797         ao2_ref(publications, -1);
798 }
799
800 struct ast_sip_publish_handler asterisk_devicestate_publication_handler = {
801         .event_name = "asterisk-devicestate",
802         .new_publication = asterisk_publication_new,
803         .publication_state_change = asterisk_publication_devicestate_state_change,
804 };
805
806 struct ast_sip_publish_handler asterisk_mwi_publication_handler = {
807         .event_name = "asterisk-mwi",
808         .new_publication = asterisk_publication_new,
809         .publication_state_change = asterisk_publication_mwi_state_change,
810 };
811
812 /*! \brief Destructor function for Asterisk publication configuration */
813 static void asterisk_publication_config_destroy(void *obj)
814 {
815         struct asterisk_publication_config *config = obj;
816
817         ast_string_field_free_memory(config);
818 }
819
820 /*! \brief Allocator function for Asterisk publication configuration */
821 static void *asterisk_publication_config_alloc(const char *name)
822 {
823         struct asterisk_publication_config *config = ast_sorcery_generic_alloc(sizeof(*config),
824                 asterisk_publication_config_destroy);
825
826         if (!config || ast_string_field_init(config, 256)) {
827                 ao2_cleanup(config);
828                 return NULL;
829         }
830
831         return config;
832 }
833
834 static int regex_filter_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
835 {
836         struct asterisk_publication_config *config = obj;
837         int res = -1;
838
839         if (ast_strlen_zero(var->value)) {
840                 return 0;
841         }
842
843         if (!strcmp(var->name, "device_state_filter")) {
844                 if (!(res = build_regex(&config->device_state_regex, var->value))) {
845                         config->device_state_filter = 1;
846                 }
847         } else if (!strcmp(var->name, "mailbox_state_filter")) {
848                 if (!(res = build_regex(&config->mailbox_state_regex, var->value))) {
849                         config->mailbox_state_filter = 1;
850                 }
851         }
852
853         return res;
854 }
855
856 static int load_module(void)
857 {
858         CHECK_PJSIP_PUBSUB_MODULE_LOADED();
859
860         if (ast_eid_is_empty(&ast_eid_default)) {
861                 ast_log(LOG_ERROR, "Entity ID is not set.\n");
862                 return AST_MODULE_LOAD_DECLINE;
863         }
864
865         ast_sorcery_apply_config(ast_sip_get_sorcery(), "res_pjsip_publish_asterisk");
866         ast_sorcery_apply_default(ast_sip_get_sorcery(), "asterisk-publication", "config", "pjsip.conf,criteria=type=asterisk-publication");
867
868         if (ast_sorcery_object_register(ast_sip_get_sorcery(), "asterisk-publication", asterisk_publication_config_alloc, NULL, NULL)) {
869                 ast_log(LOG_ERROR, "Unable to register 'asterisk-publication' type with sorcery\n");
870                 return AST_MODULE_LOAD_DECLINE;
871         }
872
873         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "asterisk-publication", "type", "", OPT_NOOP_T, 0, 0);
874         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "asterisk-publication", "devicestate_publish", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct asterisk_publication_config, devicestate_publish));
875         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "asterisk-publication", "mailboxstate_publish", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct asterisk_publication_config, mailboxstate_publish));
876         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "asterisk-publication", "device_state", "no", OPT_BOOL_T, 1, FLDSET(struct asterisk_publication_config, device_state));
877         ast_sorcery_object_field_register_custom(ast_sip_get_sorcery(), "asterisk-publication", "device_state_filter", "", regex_filter_handler, NULL, NULL, 0, 0);
878         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "asterisk-publication", "mailbox_state", "no", OPT_BOOL_T, 1, FLDSET(struct asterisk_publication_config, mailbox_state));
879         ast_sorcery_object_field_register_custom(ast_sip_get_sorcery(), "asterisk-publication", "mailbox_state_filter", "", regex_filter_handler, NULL, NULL, 0, 0);
880         ast_sorcery_reload_object(ast_sip_get_sorcery(), "asterisk-publication");
881
882         if (ast_sip_register_publish_handler(&asterisk_devicestate_publication_handler)) {
883                 ast_log(LOG_WARNING, "Unable to register event publication handler %s\n",
884                         asterisk_devicestate_publication_handler.event_name);
885                 return AST_MODULE_LOAD_DECLINE;
886         }
887         if (ast_sip_register_publish_handler(&asterisk_mwi_publication_handler)) {
888                 ast_log(LOG_WARNING, "Unable to register event publication handler %s\n",
889                         asterisk_mwi_publication_handler.event_name);
890                 ast_sip_unregister_publish_handler(&asterisk_devicestate_publication_handler);
891                 return AST_MODULE_LOAD_DECLINE;
892         }
893         if (ast_sip_register_event_publisher_handler(&asterisk_devicestate_publisher_handler)) {
894                 ast_log(LOG_WARNING, "Unable to register event publisher handler %s\n",
895                         asterisk_devicestate_publisher_handler.event_name);
896                 ast_sip_unregister_publish_handler(&asterisk_devicestate_publication_handler);
897                 ast_sip_unregister_publish_handler(&asterisk_mwi_publication_handler);
898                 return AST_MODULE_LOAD_DECLINE;
899         }
900         if (ast_sip_register_event_publisher_handler(&asterisk_mwi_publisher_handler)) {
901                 ast_log(LOG_WARNING, "Unable to register event publisher handler %s\n",
902                         asterisk_mwi_publisher_handler.event_name);
903                 ast_sip_unregister_event_publisher_handler(&asterisk_mwi_publisher_handler);
904                 ast_sip_unregister_publish_handler(&asterisk_devicestate_publication_handler);
905                 ast_sip_unregister_publish_handler(&asterisk_mwi_publication_handler);
906                 return AST_MODULE_LOAD_DECLINE;
907         }
908
909         asterisk_publication_send_refresh();
910
911         return AST_MODULE_LOAD_SUCCESS;
912 }
913
914 static int reload_module(void)
915 {
916         ast_sorcery_reload_object(ast_sip_get_sorcery(), "asterisk-publication");
917         asterisk_publication_send_refresh();
918         return 0;
919 }
920
921 static int unload_module(void)
922 {
923         ast_sip_unregister_publish_handler(&asterisk_devicestate_publication_handler);
924         ast_sip_unregister_publish_handler(&asterisk_mwi_publication_handler);
925         ast_sip_unregister_event_publisher_handler(&asterisk_devicestate_publisher_handler);
926         ast_sip_unregister_event_publisher_handler(&asterisk_mwi_publisher_handler);
927         ast_sorcery_object_unregister(ast_sip_get_sorcery(), "asterisk-publication");
928         return 0;
929 }
930
931 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Asterisk Event PUBLISH Support",
932         .support_level = AST_MODULE_SUPPORT_CORE,
933         .load = load_module,
934         .reload = reload_module,
935         .unload = unload_module,
936         .load_pri = AST_MODPRI_CHANNEL_DEPEND + 5,
937         .requires = "res_pjsip,res_pjsip_outbound_publish,res_pjsip_pubsub",
938 );