res_pjsip_pubsub: Solidify lifetime and ownership of objects.
[asterisk/asterisk.git] / res / res_pjsip_pubsub.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Mark Michelson <mmichelson@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18 /*!
19  * \brief Opaque structure representing an RFC 3265 SIP subscription
20  */
21
22 /*** MODULEINFO
23         <depend>pjproject</depend>
24         <depend>res_pjsip</depend>
25         <support_level>core</support_level>
26  ***/
27
28 #include "asterisk.h"
29
30 #include <pjsip.h>
31 #include <pjsip_simple.h>
32 #include <pjlib.h>
33
34 #include "asterisk/res_pjsip_pubsub.h"
35 #include "asterisk/module.h"
36 #include "asterisk/linkedlists.h"
37 #include "asterisk/astobj2.h"
38 #include "asterisk/datastore.h"
39 #include "asterisk/uuid.h"
40 #include "asterisk/taskprocessor.h"
41 #include "asterisk/sched.h"
42 #include "asterisk/res_pjsip.h"
43 #include "asterisk/callerid.h"
44 #include "asterisk/manager.h"
45 #include "asterisk/test.h"
46 #include "res_pjsip/include/res_pjsip_private.h"
47 #include "asterisk/res_pjsip_presence_xml.h"
48
49 /*** DOCUMENTATION
50         <manager name="PJSIPShowSubscriptionsInbound" language="en_US">
51                 <synopsis>
52                         Lists subscriptions.
53                 </synopsis>
54                 <syntax />
55                 <description>
56                         <para>
57                         Provides a listing of all inbound subscriptions.  An event <literal>InboundSubscriptionDetail</literal>
58                         is issued for each subscription object.  Once all detail events are completed an
59                         <literal>InboundSubscriptionDetailComplete</literal> event is issued.
60                         </para>
61                 </description>
62         </manager>
63         <manager name="PJSIPShowSubscriptionsOutbound" language="en_US">
64                 <synopsis>
65                         Lists subscriptions.
66                 </synopsis>
67                 <syntax />
68                 <description>
69                         <para>
70                         Provides a listing of all outbound subscriptions.  An event <literal>OutboundSubscriptionDetail</literal>
71                         is issued for each subscription object.  Once all detail events are completed an
72                         <literal>OutboundSubscriptionDetailComplete</literal> event is issued.
73                         </para>
74                 </description>
75         </manager>
76         <manager name="PJSIPShowResourceLists" language="en_US">
77                 <synopsis>
78                         Displays settings for configured resource lists.
79                 </synopsis>
80                 <syntax />
81                 <description>
82                         <para>
83                         Provides a listing of all resource lists.  An event <literal>ResourceListDetail</literal>
84                         is issued for each resource list object.  Once all detail events are completed a
85                         <literal>ResourceListDetailComplete</literal> event is issued.
86                         </para>
87                 </description>
88         </manager>
89
90         <configInfo name="res_pjsip_pubsub" language="en_US">
91                 <synopsis>Module that implements publish and subscribe support.</synopsis>
92                 <configFile name="pjsip.conf">
93                         <configObject name="subscription_persistence">
94                                 <synopsis>Persists SIP subscriptions so they survive restarts.</synopsis>
95                                 <configOption name="packet">
96                                         <synopsis>Entire SIP SUBSCRIBE packet that created the subscription</synopsis>
97                                 </configOption>
98                                 <configOption name="src_name">
99                                         <synopsis>The source address of the subscription</synopsis>
100                                 </configOption>
101                                 <configOption name="src_port">
102                                         <synopsis>The source port of the subscription</synopsis>
103                                 </configOption>
104                                 <configOption name="transport_key">
105                                         <synopsis>The type of transport the subscription was received on</synopsis>
106                                 </configOption>
107                                 <configOption name="local_name">
108                                         <synopsis>The local address the subscription was received on</synopsis>
109                                 </configOption>
110                                 <configOption name="local_port">
111                                         <synopsis>The local port the subscription was received on</synopsis>
112                                 </configOption>
113                                 <configOption name="cseq">
114                                         <synopsis>The sequence number of the next NOTIFY to be sent</synopsis>
115                                 </configOption>
116                                 <configOption name="tag">
117                                         <synopsis>The local tag of the dialog for the subscription</synopsis>
118                                 </configOption>
119                                 <configOption name="endpoint">
120                                         <synopsis>The name of the endpoint that subscribed</synopsis>
121                                 </configOption>
122                                 <configOption name="expires">
123                                         <synopsis>The time at which the subscription expires</synopsis>
124                                 </configOption>
125                         </configObject>
126                         <configObject name="resource_list">
127                                 <synopsis>Resource list configuration parameters.</synopsis>
128                                 <description>
129                                         <para>This configuration object allows for RFC 4662 resource list subscriptions
130                                         to be specified. This can be useful to decrease the amount of subscription traffic
131                                         that a server has to process.</para>
132                                         <note>
133                                                 <para>Current limitations limit the size of SIP NOTIFY requests that Asterisk sends
134                                                 to 64000 bytes. If your resource list notifications are larger than this maximum, you
135                                                 will need to make adjustments.</para>
136                                         </note>
137                                 </description>
138                                 <configOption name="type">
139                                         <synopsis>Must be of type 'resource_list'</synopsis>
140                                 </configOption>
141                                 <configOption name="event">
142                                         <synopsis>The SIP event package that the list resource belong to.</synopsis>
143                                         <description><para>
144                                                 The SIP event package describes the types of resources that Asterisk reports
145                                                 the state of.
146                                         </para>
147                                                 <enumlist>
148                                                         <enum name="presence"><para>
149                                                                 Device state and presence reporting.
150                                                         </para></enum>
151                                                         <enum name="dialog"><para>
152                                                                 This is identical to <replaceable>presence</replaceable>.
153                                                         </para></enum>
154                                                         <enum name="message-summary"><para>
155                                                                 Message-waiting indication (MWI) reporting.
156                                                         </para></enum>
157                                                 </enumlist>
158                                         </description>
159                                 </configOption>
160                                 <configOption name="list_item">
161                                         <synopsis>The name of a resource to report state on</synopsis>
162                                         <description>
163                                                 <para>In general Asterisk looks up list items in the following way:</para>
164                                                 <para>1. Check if the list item refers to another configured resource list.</para>
165                                                 <para>2. Pass the name of the resource off to event-package-specific handlers
166                                                    to find the specified resource.</para>
167                                                 <para>The second part means that the way the list item is specified depends
168                                                 on what type of list this is. For instance, if you have the <replaceable>event</replaceable>
169                                                 set to <literal>presence</literal>, then list items should be in the form of
170                                                 dialplan_extension@dialplan_context. For <literal>message-summary</literal> mailbox
171                                                 names should be listed.</para>
172                                         </description>
173                                 </configOption>
174                                 <configOption name="full_state" default="no">
175                                         <synopsis>Indicates if the entire list's state should be sent out.</synopsis>
176                                         <description>
177                                                 <para>If this option is enabled, and a resource changes state, then Asterisk will construct
178                                                 a notification that contains the state of all resources in the list. If the option is
179                                                 disabled, Asterisk will construct a notification that only contains the states of
180                                                 resources that have changed.</para>
181                                                 <note>
182                                                         <para>Even with this option disabled, there are certain situations where Asterisk is forced
183                                                         to send a notification with the states of all resources in the list. When a subscriber
184                                                         renews or terminates its subscription to the list, Asterisk MUST send a full state
185                                                         notification.</para>
186                                                 </note>
187                                         </description>
188                                 </configOption>
189                                 <configOption name="notification_batch_interval" default="0">
190                                         <synopsis>Time Asterisk should wait, in milliseconds, before sending notifications.</synopsis>
191                                         <description>
192                                                 <para>When a resource's state changes, it may be desired to wait a certain amount before Asterisk
193                                                 sends a notification to subscribers. This allows for other state changes to accumulate, so that
194                                                 Asterisk can communicate multiple state changes in a single notification instead of rapidly sending
195                                                 many notifications.</para>
196                                         </description>
197                                 </configOption>
198                         </configObject>
199                         <configObject name="inbound-publication">
200                                 <synopsis>The configuration for inbound publications</synopsis>
201                                 <configOption name="endpoint" default="">
202                                         <synopsis>Optional name of an endpoint that is only allowed to publish to this resource</synopsis>
203                                 </configOption>
204                                 <configOption name="type">
205                                         <synopsis>Must be of type 'inbound-publication'.</synopsis>
206                                 </configOption>
207                         </configObject>
208                 </configFile>
209         </configInfo>
210  ***/
211
212 static pj_bool_t pubsub_on_rx_request(pjsip_rx_data *rdata);
213
214 static struct pjsip_module pubsub_module = {
215         .name = { "PubSub Module", 13 },
216         .priority = PJSIP_MOD_PRIORITY_APPLICATION,
217         .on_rx_request = pubsub_on_rx_request,
218 };
219
220 #define MOD_DATA_PERSISTENCE "sub_persistence"
221 #define MOD_DATA_MSG "sub_msg"
222
223 static const pj_str_t str_event_name = { "Event", 5 };
224
225 /*! \brief Scheduler used for automatically expiring publications */
226 static struct ast_sched_context *sched;
227
228 /*! \brief Number of buckets for publications (on a per handler) */
229 #define PUBLICATIONS_BUCKETS 37
230
231 /*! \brief Default expiration time for PUBLISH if one is not specified */
232 #define DEFAULT_PUBLISH_EXPIRES 3600
233
234 /*! \brief Number of buckets for subscription datastore */
235 #define DATASTORE_BUCKETS 53
236
237 /*! \brief Default expiration for subscriptions */
238 #define DEFAULT_EXPIRES 3600
239
240 /*! \brief Defined method for PUBLISH */
241 const pjsip_method pjsip_publish_method =
242 {
243         PJSIP_OTHER_METHOD,
244         { "PUBLISH", 7 }
245 };
246
247 /*!
248  * \brief The types of PUBLISH messages defined in RFC 3903
249  */
250 enum sip_publish_type {
251         /*!
252          * \brief Unknown
253          *
254          * \details
255          * This actually is not defined in RFC 3903. We use this as a constant
256          * to indicate that an incoming PUBLISH does not fit into any of the
257          * other categories and is thus invalid.
258          */
259         SIP_PUBLISH_UNKNOWN,
260
261         /*!
262          * \brief Initial
263          *
264          * \details
265          * The first PUBLISH sent. This will contain a non-zero Expires header
266          * as well as a body that indicates the current state of the endpoint
267          * that has sent the message. The initial PUBLISH is the only type
268          * of PUBLISH to not contain a Sip-If-Match header in it.
269          */
270         SIP_PUBLISH_INITIAL,
271
272         /*!
273          * \brief Refresh
274          *
275          * \details
276          * Used to keep a published state from expiring. This will contain a
277          * non-zero Expires header but no body since its purpose is not to
278          * update state.
279          */
280         SIP_PUBLISH_REFRESH,
281
282         /*!
283          * \brief Modify
284          *
285          * \details
286          * Used to change state from its previous value. This will contain
287          * a body updating the published state. May or may not contain an
288          * Expires header.
289          */
290         SIP_PUBLISH_MODIFY,
291
292         /*!
293          * \brief Remove
294          *
295          * \details
296          * Used to remove published state from an ESC. This will contain
297          * an Expires header set to 0 and likely no body.
298          */
299         SIP_PUBLISH_REMOVE,
300 };
301
302 /*!
303  * \brief A vector of strings commonly used throughout this module
304  */
305 AST_VECTOR(resources, const char *);
306
307 /*!
308  * \brief Resource list configuration item
309  */
310 struct resource_list {
311         SORCERY_OBJECT(details);
312         /*! SIP event package the list uses. */
313         char event[32];
314         /*! Strings representing resources in the list. */
315         struct resources items;
316         /*! Indicates if Asterisk sends full or partial state on notifications. */
317         unsigned int full_state;
318         /*! Time, in milliseconds Asterisk waits before sending a batched notification.*/
319         unsigned int notification_batch_interval;
320 };
321
322 /*!
323  * Used to create new entity IDs by ESCs.
324  */
325 static int esc_etag_counter;
326
327 /*!
328  * \brief Structure representing a SIP publication
329  */
330 struct ast_sip_publication {
331         /*! Publication datastores set up by handlers */
332         struct ao2_container *datastores;
333         /*! \brief Entity tag for the publication */
334         int entity_tag;
335         /*! \brief Handler for this publication */
336         struct ast_sip_publish_handler *handler;
337         /*! \brief The endpoint with which the subscription is communicating */
338         struct ast_sip_endpoint *endpoint;
339         /*! \brief Expiration time of the publication */
340         int expires;
341         /*! \brief Scheduled item for expiration of publication */
342         int sched_id;
343         /*! \brief The resource the publication is to */
344         char *resource;
345         /*! \brief The name of the event type configuration */
346         char *event_configuration_name;
347         /*! \brief Data containing the above */
348         char data[0];
349 };
350
351
352 /*!
353  * \brief Structure used for persisting an inbound subscription
354  */
355 struct subscription_persistence {
356         /*! Sorcery object details */
357         SORCERY_OBJECT(details);
358         /*! The name of the endpoint involved in the subscrption */
359         char *endpoint;
360         /*! SIP message that creates the subscription */
361         char packet[PJSIP_MAX_PKT_LEN];
362         /*! Source address of the message */
363         char src_name[PJ_INET6_ADDRSTRLEN];
364         /*! Source port of the message */
365         int src_port;
366         /*! Local transport key type */
367         char transport_key[32];
368         /*! Local transport address */
369         char local_name[PJ_INET6_ADDRSTRLEN];
370         /*! Local transport port */
371         int local_port;
372         /*! Next CSeq to use for message */
373         unsigned int cseq;
374         /*! Local tag of the dialog */
375         char *tag;
376         /*! When this subscription expires */
377         struct timeval expires;
378 };
379
380 /*!
381  * \brief A tree of SIP subscriptions
382  *
383  * Because of the ability to subscribe to resource lists, a SIP
384  * subscription can result in a tree of subscriptions being created.
385  * This structure represents the information relevant to the subscription
386  * as a whole, to include the underlying PJSIP structure for the
387  * subscription.
388  */
389 struct sip_subscription_tree {
390         /*! The endpoint with which the subscription is communicating */
391         struct ast_sip_endpoint *endpoint;
392         /*! Serializer on which to place operations for this subscription */
393         struct ast_taskprocessor *serializer;
394         /*! The role for this subscription */
395         enum ast_sip_subscription_role role;
396         /*! Persistence information */
397         struct subscription_persistence *persistence;
398         /*! The underlying PJSIP event subscription structure */
399         pjsip_evsub *evsub;
400         /*! The underlying PJSIP dialog */
401         pjsip_dialog *dlg;
402         /*! Interval to use for batching notifications */
403         unsigned int notification_batch_interval;
404         /*! Scheduler ID for batched notification */
405         int notify_sched_id;
406         /*! Indicator if scheduled batched notification should be sent */
407         unsigned int send_scheduled_notify;
408         /*! The root of the subscription tree */
409         struct ast_sip_subscription *root;
410         /*! Is this subscription to a list? */
411         int is_list;
412         /*! Next item in the list */
413         AST_LIST_ENTRY(sip_subscription_tree) next;
414         /*! Indicates that a NOTIFY is currently being sent on the SIP subscription */
415         int last_notify;
416 };
417
418 /*!
419  * \brief Structure representing a "virtual" SIP subscription.
420  *
421  * This structure serves a dual purpose. Structurally, it is
422  * the constructed tree of subscriptions based on the resources
423  * being subscribed to. API-wise, this serves as the handle that
424  * subscription handlers use in order to interact with the pubsub API.
425  */
426 struct ast_sip_subscription {
427         /*! Subscription datastores set up by handlers */
428         struct ao2_container *datastores;
429         /*! The handler for this subscription */
430         const struct ast_sip_subscription_handler *handler;
431         /*! Pointer to the base of the tree */
432         struct sip_subscription_tree *tree;
433         /*! Body generaator for NOTIFYs */
434         struct ast_sip_pubsub_body_generator *body_generator;
435         /*! Vector of child subscriptions */
436         AST_VECTOR(, struct ast_sip_subscription *) children;
437         /*! Saved NOTIFY body text for this subscription */
438         struct ast_str *body_text;
439         /*! Indicator that the body text has changed since the last notification */
440         int body_changed;
441         /*! The current state of the subscription */
442         pjsip_evsub_state subscription_state;
443         /*! For lists, the current version to place in the RLMI body */
444         unsigned int version;
445         /*! For lists, indicates if full state should always be communicated. */
446         unsigned int full_state;
447         /*! URI associated with the subscription */
448         pjsip_sip_uri *uri;
449         /*! Name of resource being subscribed to */
450         char resource[0];
451 };
452
453 /*!
454  * \brief Structure representing a publication resource
455  */
456 struct ast_sip_publication_resource {
457         /*! \brief Sorcery object details */
458         SORCERY_OBJECT(details);
459         /*! \brief Optional name of an endpoint that is only allowed to publish to this resource */
460         char *endpoint;
461         /*! \brief Mapping for event types to configuration */
462         struct ast_variable *events;
463 };
464
465 static const char *sip_subscription_roles_map[] = {
466         [AST_SIP_SUBSCRIBER] = "Subscriber",
467         [AST_SIP_NOTIFIER] = "Notifier"
468 };
469
470 AST_RWLIST_HEAD_STATIC(subscriptions, sip_subscription_tree);
471
472 AST_RWLIST_HEAD_STATIC(body_generators, ast_sip_pubsub_body_generator);
473 AST_RWLIST_HEAD_STATIC(body_supplements, ast_sip_pubsub_body_supplement);
474
475 static void pubsub_on_evsub_state(pjsip_evsub *sub, pjsip_event *event);
476 static void pubsub_on_rx_refresh(pjsip_evsub *sub, pjsip_rx_data *rdata,
477                 int *p_st_code, pj_str_t **p_st_text, pjsip_hdr *res_hdr, pjsip_msg_body **p_body);
478 static void pubsub_on_rx_notify(pjsip_evsub *sub, pjsip_rx_data *rdata, int *p_st_code,
479                 pj_str_t **p_st_text, pjsip_hdr *res_hdr, pjsip_msg_body **p_body);
480 static void pubsub_on_client_refresh(pjsip_evsub *sub);
481 static void pubsub_on_server_timeout(pjsip_evsub *sub);
482  
483 static pjsip_evsub_user pubsub_cb = {
484         .on_evsub_state = pubsub_on_evsub_state,
485         .on_rx_refresh = pubsub_on_rx_refresh,
486         .on_rx_notify = pubsub_on_rx_notify,
487         .on_client_refresh = pubsub_on_client_refresh,
488         .on_server_timeout = pubsub_on_server_timeout,
489 };
490
491 /*! \brief Destructor for publication resource */
492 static void publication_resource_destroy(void *obj)
493 {
494         struct ast_sip_publication_resource *resource = obj;
495
496         ast_free(resource->endpoint);
497         ast_variables_destroy(resource->events);
498 }
499
500 /*! \brief Allocator for publication resource */
501 static void *publication_resource_alloc(const char *name)
502 {
503         return ast_sorcery_generic_alloc(sizeof(struct ast_sip_publication_resource), publication_resource_destroy);
504 }
505
506 /*! \brief Destructor for subscription persistence */
507 static void subscription_persistence_destroy(void *obj)
508 {
509         struct subscription_persistence *persistence = obj;
510
511         ast_free(persistence->endpoint);
512         ast_free(persistence->tag);
513 }
514
515 /*! \brief Allocator for subscription persistence */
516 static void *subscription_persistence_alloc(const char *name)
517 {
518         return ast_sorcery_generic_alloc(sizeof(struct subscription_persistence), subscription_persistence_destroy);
519 }
520
521 /*! \brief Function which creates initial persistence information of a subscription in sorcery */
522 static struct subscription_persistence *subscription_persistence_create(struct sip_subscription_tree *sub_tree)
523 {
524         char tag[PJ_GUID_STRING_LENGTH + 1];
525
526         /* The id of this persistence object doesn't matter as we keep it on the subscription and don't need to
527          * look it up by id at all.
528          */
529         struct subscription_persistence *persistence = ast_sorcery_alloc(ast_sip_get_sorcery(),
530                 "subscription_persistence", NULL);
531
532         pjsip_dialog *dlg = sub_tree->dlg;
533
534         if (!persistence) {
535                 return NULL;
536         }
537
538         persistence->endpoint = ast_strdup(ast_sorcery_object_get_id(sub_tree->endpoint));
539         ast_copy_pj_str(tag, &dlg->local.info->tag, sizeof(tag));
540         persistence->tag = ast_strdup(tag);
541
542         ast_sorcery_create(ast_sip_get_sorcery(), persistence);
543         return persistence;
544 }
545
546 /*! \brief Function which updates persistence information of a subscription in sorcery */
547 static void subscription_persistence_update(struct sip_subscription_tree *sub_tree,
548         pjsip_rx_data *rdata)
549 {
550         pjsip_dialog *dlg;
551
552         if (!sub_tree->persistence) {
553                 return;
554         }
555
556         dlg = sub_tree->dlg;
557         sub_tree->persistence->cseq = dlg->local.cseq;
558
559         if (rdata) {
560                 int expires;
561                 pjsip_expires_hdr *expires_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL);
562
563                 expires = expires_hdr ? expires_hdr->ivalue : DEFAULT_PUBLISH_EXPIRES;
564                 sub_tree->persistence->expires = ast_tvadd(ast_tvnow(), ast_samp2tv(expires, 1));
565
566                 /* When receiving a packet on an streaming transport, it's possible to receive more than one SIP
567                  * message at a time into the rdata->pkt_info.packet buffer. However, the rdata->msg_info.msg_buf
568                  * will always point to the proper SIP message that is to be processed. When updating subscription
569                  * persistence that is pulled from persistent storage, though, the rdata->pkt_info.packet will
570                  * only ever have a single SIP message on it, and so we base persistence on that.
571                  */
572                 if (rdata->msg_info.msg_buf) {
573                         ast_copy_string(sub_tree->persistence->packet, rdata->msg_info.msg_buf,
574                                         MIN(sizeof(sub_tree->persistence->packet), rdata->msg_info.len));
575                 } else {
576                         ast_copy_string(sub_tree->persistence->packet, rdata->pkt_info.packet,
577                                         sizeof(sub_tree->persistence->packet));
578                 }
579                 ast_copy_string(sub_tree->persistence->src_name, rdata->pkt_info.src_name,
580                                 sizeof(sub_tree->persistence->src_name));
581                 sub_tree->persistence->src_port = rdata->pkt_info.src_port;
582                 ast_copy_string(sub_tree->persistence->transport_key, rdata->tp_info.transport->type_name,
583                         sizeof(sub_tree->persistence->transport_key));
584                 ast_copy_pj_str(sub_tree->persistence->local_name, &rdata->tp_info.transport->local_name.host,
585                         sizeof(sub_tree->persistence->local_name));
586                 sub_tree->persistence->local_port = rdata->tp_info.transport->local_name.port;
587         }
588
589         ast_sorcery_update(ast_sip_get_sorcery(), sub_tree->persistence);
590 }
591
592 /*! \brief Function which removes persistence of a subscription from sorcery */
593 static void subscription_persistence_remove(struct sip_subscription_tree *sub_tree)
594 {
595         if (!sub_tree->persistence) {
596                 return;
597         }
598
599         ast_sorcery_delete(ast_sip_get_sorcery(), sub_tree->persistence);
600         ao2_ref(sub_tree->persistence, -1);
601 }
602
603
604 static struct ast_sip_subscription_handler *find_sub_handler_for_event_name(const char *event_name);
605 static struct ast_sip_pubsub_body_generator *find_body_generator(char accept[AST_SIP_MAX_ACCEPT][64],
606                 size_t num_accept, const char *body_type);
607
608 /*! \brief Retrieve a handler using the Event header of an rdata message */
609 static struct ast_sip_subscription_handler *subscription_get_handler_from_rdata(pjsip_rx_data *rdata)
610 {
611         pjsip_event_hdr *event_header;
612         char event[32];
613         struct ast_sip_subscription_handler *handler;
614
615         event_header = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_event_name, rdata->msg_info.msg->hdr.next);
616         if (!event_header) {
617                 ast_log(LOG_WARNING, "Incoming SUBSCRIBE request with no Event header\n");
618                 return NULL;
619         }
620         ast_copy_pj_str(event, &event_header->event_type, sizeof(event));
621
622         handler = find_sub_handler_for_event_name(event);
623         if (!handler) {
624                 ast_log(LOG_WARNING, "No registered subscribe handler for event %s\n", event);
625         }
626
627         return handler;
628 }
629
630 /*!
631  * \brief Accept headers that are exceptions to the rule
632  *
633  * Typically, when a SUBSCRIBE arrives, we attempt to find a
634  * body generator that matches one of the Accept headers in
635  * the request. When subscribing to a single resource, this works
636  * great. However, when subscribing to a list, things work
637  * differently. Most Accept header values are fine, but there
638  * are a couple that are endemic to resource lists that need
639  * to be ignored when searching for a body generator to use
640  * for the individual resources of the subscription.
641  */
642 const char *accept_exceptions[] =  {
643         "multipart/related",
644         "application/rlmi+xml",
645 };
646
647 /*!
648  * \brief Is the Accept header from the SUBSCRIBE in the list of exceptions?
649  *
650  * \retval 1 This Accept header value is an exception to the rule.
651  * \retval 0 This Accept header is not an exception to the rule.
652  */
653 static int exceptional_accept(const pj_str_t *accept)
654 {
655         int i;
656
657         for (i = 0; i < ARRAY_LEN(accept_exceptions); ++i) {
658                 if (!pj_strcmp2(accept, accept_exceptions[i])) {
659                         return 1;
660                 }
661         }
662
663         return 0;
664 }
665
666 /*! \brief Retrieve a body generator using the Accept header of an rdata message */
667 static struct ast_sip_pubsub_body_generator *subscription_get_generator_from_rdata(pjsip_rx_data *rdata,
668         const struct ast_sip_subscription_handler *handler)
669 {
670         pjsip_accept_hdr *accept_header = (pjsip_accept_hdr *) &rdata->msg_info.msg->hdr;
671         char accept[AST_SIP_MAX_ACCEPT][64];
672         size_t num_accept_headers = 0;
673
674         while ((accept_header = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_ACCEPT, accept_header->next))) {
675                 int i;
676
677                 for (i = 0; i < accept_header->count; ++i) {
678                         if (!exceptional_accept(&accept_header->values[i])) {
679                                 ast_copy_pj_str(accept[num_accept_headers], &accept_header->values[i], sizeof(accept[num_accept_headers]));
680                                 ++num_accept_headers;
681                         }
682                 }
683         }
684
685         if (num_accept_headers == 0) {
686                 /* If a SUBSCRIBE contains no Accept headers, then we must assume that
687                  * the default accept type for the event package is to be used.
688                  */
689                 ast_copy_string(accept[0], handler->notifier->default_accept, sizeof(accept[0]));
690                 num_accept_headers = 1;
691         }
692
693         return find_body_generator(accept, num_accept_headers, handler->body_type);
694 }
695
696 /*! \brief Check if the rdata has a Supported header containing 'eventlist'
697  *
698  *  \retval 1 rdata has an eventlist containing supported header
699  *  \retval 0 rdata doesn't have an eventlist containing supported header
700  */
701 static int ast_sip_pubsub_has_eventlist_support(pjsip_rx_data *rdata)
702 {
703         pjsip_supported_hdr *supported_header = (pjsip_supported_hdr *) &rdata->msg_info.msg->hdr;
704
705         while ((supported_header = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_SUPPORTED, supported_header->next))) {
706                 int i;
707
708                 for (i = 0; i < supported_header->count; i++) {
709                         if (!pj_stricmp2(&supported_header->values[i], "eventlist")) {
710                                 return 1;
711                         }
712                 }
713         }
714
715         return 0;
716 }
717
718 struct resource_tree;
719
720 /*!
721  * \brief A node for a resource tree.
722  */
723 struct tree_node {
724         AST_VECTOR(, struct tree_node *) children;
725         unsigned int full_state;
726         char resource[0];
727 };
728
729 /*!
730  * \brief Helper function for retrieving a resource list for a given event.
731  *
732  * This will retrieve a resource list that corresponds to the resource and event provided.
733  *
734  * \param resource The name of the resource list to retrieve
735  * \param event The expected event name on the resource list
736  */
737 static struct resource_list *retrieve_resource_list(const char *resource, const char *event)
738 {
739         struct resource_list *list;
740
741         list = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "resource_list", resource);
742         if (!list) {
743                 return NULL;
744         }
745
746         if (strcmp(list->event, event)) {
747                 ast_log(LOG_WARNING, "Found resource list %s, but its event type (%s) does not match SUBSCRIBE's (%s)\n",
748                                 resource, list->event, event);
749                 ao2_cleanup(list);
750                 return NULL;
751         }
752
753         return list;
754 }
755
756 /*!
757  * \brief Allocate a tree node
758  *
759  * In addition to allocating and initializing the tree node, the node is also added
760  * to the vector of visited resources. See \ref build_resource_tree for more information
761  * on the visited resources.
762  *
763  * \param resource The name of the resource for this tree node.
764  * \param visited The vector of resources that have been visited.
765  * \param if allocating a list, indicate whether full state is requested in notifications.
766  * \retval NULL Allocation failure.
767  * \retval non-NULL The newly-allocated tree_node
768  */
769 static struct tree_node *tree_node_alloc(const char *resource, struct resources *visited, unsigned int full_state)
770 {
771         struct tree_node *node;
772
773         node = ast_calloc(1, sizeof(*node) + strlen(resource) + 1);
774         if (!node) {
775                 return NULL;
776         }
777
778         strcpy(node->resource, resource);
779         if (AST_VECTOR_INIT(&node->children, 4)) {
780                 ast_free(node);
781                 return NULL;
782         }
783         node->full_state = full_state;
784
785         if (visited) {
786                 AST_VECTOR_APPEND(visited, resource);
787         }
788         return node;
789 }
790
791 /*!
792  * \brief Destructor for a tree node
793  *
794  * This function calls recursively in order to destroy
795  * all nodes lower in the tree from the given node in
796  * addition to the node itself.
797  *
798  * \param node The node to destroy.
799  */
800 static void tree_node_destroy(struct tree_node *node)
801 {
802         int i;
803         if (!node) {
804                 return;
805         }
806
807         for (i = 0; i < AST_VECTOR_SIZE(&node->children); ++i) {
808                 tree_node_destroy(AST_VECTOR_GET(&node->children, i));
809         }
810         AST_VECTOR_FREE(&node->children);
811         ast_free(node);
812 }
813
814 /*!
815  * \brief Determine if this resource has been visited already
816  *
817  * See \ref build_resource_tree for more information
818  *
819  * \param resource The resource currently being visited
820  * \param visited The resources that have previously been visited
821  */
822 static int have_visited(const char *resource, struct resources *visited)
823 {
824         int i;
825
826         for (i = 0; i < AST_VECTOR_SIZE(visited); ++i) {
827                 if (!strcmp(resource, AST_VECTOR_GET(visited, i))) {
828                         return 1;
829                 }
830         }
831
832         return 0;
833 }
834
835 /*!
836  * \brief Build child nodes for a given parent.
837  *
838  * This iterates through the items on a resource list and creates tree nodes for each one. The
839  * tree nodes created are children of the supplied parent node. If an item in the resource
840  * list is itself a list, then this function is called recursively to provide children for
841  * the the new node.
842  *
843  * If an item in a resource list is not a list, then the supplied subscription handler is
844  * called into as if a new SUBSCRIBE for the list item were presented. The handler's response
845  * is used to determine if the node can be added to the tree or not.
846  *
847  * If a parent node ends up having no child nodes added under it, then the parent node is
848  * pruned from the tree.
849  *
850  * \param endpoint The endpoint that sent the inbound SUBSCRIBE.
851  * \param handler The subscription handler for leaf nodes in the tree.
852  * \param list The configured resource list from which the child node is being built.
853  * \param parent The parent node for these children.
854  * \param visited The resources that have already been visited.
855  */
856 static void build_node_children(struct ast_sip_endpoint *endpoint, const struct ast_sip_subscription_handler *handler,
857                 struct resource_list *list, struct tree_node *parent, struct resources *visited)
858 {
859         int i;
860
861         for (i = 0; i < AST_VECTOR_SIZE(&list->items); ++i) {
862                 struct tree_node *current;
863                 struct resource_list *child_list;
864                 const char *resource = AST_VECTOR_GET(&list->items, i);
865
866                 if (have_visited(resource, visited)) {
867                         ast_debug(1, "Already visited resource %s. Avoiding duplicate resource or potential loop.\n", resource);
868                         continue;
869                 }
870
871                 child_list = retrieve_resource_list(resource, list->event);
872                 if (!child_list) {
873                         int resp = handler->notifier->new_subscribe(endpoint, resource);
874                         if (PJSIP_IS_STATUS_IN_CLASS(resp, 200)) {
875                                 current = tree_node_alloc(resource, visited, 0);
876                                 if (!current) {
877                                         ast_debug(1, "Subscription to leaf resource %s was successful, but encountered"
878                                                         "allocation error afterwards\n", resource);
879                                         continue;
880                                 }
881                                 ast_debug(1, "Subscription to leaf resource %s resulted in success. Adding to parent %s\n",
882                                                 resource, parent->resource);
883                                 AST_VECTOR_APPEND(&parent->children, current);
884                         } else {
885                                 ast_debug(1, "Subscription to leaf resource %s resulted in error response %d\n",
886                                                 resource, resp);
887                         }
888                 } else {
889                         ast_debug(1, "Resource %s (child of %s) is a list\n", resource, parent->resource);
890                         current = tree_node_alloc(resource, visited, child_list->full_state);
891                         if (!current) {
892                                 ast_debug(1, "Cannot build children of resource %s due to allocation failure\n", resource);
893                                 continue;
894                         }
895                         build_node_children(endpoint, handler, child_list, current, visited);
896                         if (AST_VECTOR_SIZE(&current->children) > 0) {
897                                 ast_debug(1, "List %s had no successful children.\n", resource);
898                                 AST_VECTOR_APPEND(&parent->children, current);
899                         } else {
900                                 ast_debug(1, "List %s had successful children. Adding to parent %s\n",
901                                                 resource, parent->resource);
902                                 tree_node_destroy(current);
903                         }
904                         ao2_cleanup(child_list);
905                 }
906         }
907 }
908
909 /*!
910  * \brief A resource tree
911  *
912  * When an inbound SUBSCRIBE arrives, the resource being subscribed to may
913  * be a resource list. If this is the case, the resource list may contain resources
914  * that are themselves lists. The structure needed to hold the resources is
915  * a tree.
916  *
917  * Upon receipt of the SUBSCRIBE, the tree is built by determining if subscriptions
918  * to the individual resources in the tree would be successful or not. Any successful
919  * subscriptions result in a node in the tree being created. Any unsuccessful subscriptions
920  * result in no node being created.
921  *
922  * This tree can be seen as a bare-bones analog of the tree of ast_sip_subscriptions that
923  * will end up being created to actually carry out the duties of a SIP SUBSCRIBE dialog.
924  */
925 struct resource_tree {
926         struct tree_node *root;
927         unsigned int notification_batch_interval;
928 };
929
930 /*!
931  * \brief Destroy a resource tree.
932  *
933  * This function makes no assumptions about how the tree itself was
934  * allocated and does not attempt to free the tree itself. Callers
935  * of this function are responsible for freeing the tree.
936  *
937  * \param tree The tree to destroy.
938  */
939 static void resource_tree_destroy(struct resource_tree *tree)
940 {
941         if (tree) {
942                 tree_node_destroy(tree->root);
943         }
944 }
945
946 /*!
947  * \brief Build a resource tree
948  *
949  * This function builds a resource tree based on the requested resource in a SUBSCRIBE request.
950  *
951  * This function also creates a container that has all resources that have been visited during
952  * creation of the tree, whether those resources resulted in a tree node being created or not.
953  * Keeping this container of visited resources allows for misconfigurations such as loops in
954  * the tree or duplicated resources to be detected.
955  *
956  * \param endpoint The endpoint that sent the SUBSCRIBE request.
957  * \param handler The subscription handler for leaf nodes in the tree.
958  * \param resource The resource requested in the SUBSCRIBE request.
959  * \param tree The tree that is to be built.
960  * \param has_eventlist_support
961  *
962  * \retval 200-299 Successfully subscribed to at least one resource.
963  * \retval 300-699 Failure to subscribe to requested resource.
964  */
965 static int build_resource_tree(struct ast_sip_endpoint *endpoint, const struct ast_sip_subscription_handler *handler,
966                 const char *resource, struct resource_tree *tree, int has_eventlist_support)
967 {
968         RAII_VAR(struct resource_list *, list, NULL, ao2_cleanup);
969         struct resources visited;
970
971         if (!has_eventlist_support || !(list = retrieve_resource_list(resource, handler->event_name))) {
972                 ast_debug(1, "Subscription to resource %s is not to a list\n", resource);
973                 tree->root = tree_node_alloc(resource, NULL, 0);
974                 if (!tree->root) {
975                         return 500;
976                 }
977                 return handler->notifier->new_subscribe(endpoint, resource);
978         }
979
980         ast_debug(1, "Subscription to resource %s is a list\n", resource);
981         if (AST_VECTOR_INIT(&visited, AST_VECTOR_SIZE(&list->items))) {
982                 return 500;
983         }
984
985         tree->root = tree_node_alloc(resource, &visited, list->full_state);
986         if (!tree->root) {
987                 AST_VECTOR_FREE(&visited);
988                 return 500;
989         }
990
991         tree->notification_batch_interval = list->notification_batch_interval;
992
993         build_node_children(endpoint, handler, list, tree->root, &visited);
994         AST_VECTOR_FREE(&visited);
995
996         if (AST_VECTOR_SIZE(&tree->root->children) > 0) {
997                 return 200;
998         } else {
999                 return 500;
1000         }
1001 }
1002
1003 static int datastore_hash(const void *obj, int flags)
1004 {
1005         const struct ast_datastore *datastore = obj;
1006         const char *uid = flags & OBJ_KEY ? obj : datastore->uid;
1007
1008         ast_assert(uid != NULL);
1009
1010         return ast_str_hash(uid);
1011 }
1012
1013 static int datastore_cmp(void *obj, void *arg, int flags)
1014 {
1015         const struct ast_datastore *datastore1 = obj;
1016         const struct ast_datastore *datastore2 = arg;
1017         const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;
1018
1019         ast_assert(datastore1->uid != NULL);
1020         ast_assert(uid2 != NULL);
1021
1022         return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;
1023 }
1024
1025 static int subscription_remove_serializer(void *obj)
1026 {
1027         struct sip_subscription_tree *sub_tree = obj;
1028
1029         /* This is why we keep the dialog on the subscription. When the subscription
1030          * is destroyed, there is no guarantee that the underlying dialog is ready
1031          * to be destroyed. Furthermore, there's no guarantee in the opposite direction
1032          * either. The dialog could be destroyed before our subscription is. We fix
1033          * this problem by keeping a reference to the dialog until it is time to
1034          * destroy the subscription. We need to have the dialog available when the
1035          * subscription is destroyed so that we can guarantee that our attempt to
1036          * remove the serializer will be successful.
1037          */
1038         ast_sip_dialog_set_serializer(sub_tree->dlg, NULL);
1039         ast_sip_dialog_set_endpoint(sub_tree->dlg, NULL);
1040         pjsip_dlg_dec_session(sub_tree->dlg, &pubsub_module);
1041
1042         return 0;
1043 }
1044
1045 static void add_subscription(struct sip_subscription_tree *obj)
1046 {
1047         SCOPED_LOCK(lock, &subscriptions, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
1048         AST_RWLIST_INSERT_TAIL(&subscriptions, obj, next);
1049 }
1050
1051 static void remove_subscription(struct sip_subscription_tree *obj)
1052 {
1053         struct sip_subscription_tree *i;
1054         SCOPED_LOCK(lock, &subscriptions, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
1055         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&subscriptions, i, next) {
1056                 if (i == obj) {
1057                         AST_RWLIST_REMOVE_CURRENT(next);
1058                         if (i->root) {
1059                                 ast_debug(1, "Removing subscription to resource %s from list of subscriptions\n",
1060                                                 ast_sip_subscription_get_resource_name(i->root));
1061                         }
1062                         break;
1063                 }
1064         }
1065         AST_RWLIST_TRAVERSE_SAFE_END;
1066 }
1067
1068 static void destroy_subscription(struct ast_sip_subscription *sub)
1069 {
1070         ast_debug(3, "Destroying SIP subscription to resource %s\n", sub->resource);
1071         ast_free(sub->body_text);
1072
1073         AST_VECTOR_FREE(&sub->children);
1074         ao2_cleanup(sub->datastores);
1075         ast_free(sub);
1076 }
1077
1078 static void destroy_subscriptions(struct ast_sip_subscription *root)
1079 {
1080         int i;
1081
1082         for (i = 0; i < AST_VECTOR_SIZE(&root->children); ++i) {
1083                 struct ast_sip_subscription *child;
1084
1085                 child = AST_VECTOR_GET(&root->children, i);
1086                 destroy_subscriptions(child);
1087         }
1088
1089         destroy_subscription(root);
1090 }
1091
1092 static struct ast_sip_subscription *allocate_subscription(const struct ast_sip_subscription_handler *handler,
1093                 const char *resource, struct sip_subscription_tree *tree)
1094 {
1095         struct ast_sip_subscription *sub;
1096         pjsip_sip_uri *contact_uri;
1097
1098         sub = ast_calloc(1, sizeof(*sub) + strlen(resource) + 1);
1099         if (!sub) {
1100                 return NULL;
1101         }
1102         strcpy(sub->resource, resource); /* Safe */
1103
1104         sub->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);
1105         if (!sub->datastores) {
1106                 destroy_subscription(sub);
1107                 return NULL;
1108         }
1109
1110         sub->body_text = ast_str_create(128);
1111         if (!sub->body_text) {
1112                 destroy_subscription(sub);
1113                 return NULL;
1114         }
1115
1116         sub->uri = pjsip_sip_uri_create(tree->dlg->pool, PJ_FALSE);
1117         contact_uri = pjsip_uri_get_uri(tree->dlg->local.contact->uri);
1118         pjsip_sip_uri_assign(tree->dlg->pool, sub->uri, contact_uri);
1119         pj_strdup2(tree->dlg->pool, &sub->uri->user, resource);
1120
1121         sub->handler = handler;
1122         sub->subscription_state = PJSIP_EVSUB_STATE_ACTIVE;
1123         sub->tree = ao2_bump(tree);
1124
1125         return sub;
1126 }
1127
1128 /*!
1129  * \brief Create a tree of virtual subscriptions based on a resource tree node.
1130  *
1131  * \param handler The handler to supply to leaf subscriptions.
1132  * \param resource The requested resource for this subscription.
1133  * \param generator Body generator to use for leaf subscriptions.
1134  * \param tree The root of the subscription tree.
1135  * \param current The tree node that corresponds to the subscription being created.
1136  */
1137 static struct ast_sip_subscription *create_virtual_subscriptions(const struct ast_sip_subscription_handler *handler,
1138                 const char *resource, struct ast_sip_pubsub_body_generator *generator,
1139                 struct sip_subscription_tree *tree, struct tree_node *current)
1140 {
1141         int i;
1142         struct ast_sip_subscription *sub;
1143
1144         sub = allocate_subscription(handler, resource, tree);
1145         if (!sub) {
1146                 return NULL;
1147         }
1148
1149         sub->full_state = current->full_state;
1150         sub->body_generator = generator;
1151         AST_VECTOR_INIT(&sub->children, AST_VECTOR_SIZE(&current->children));
1152
1153         for (i = 0; i < AST_VECTOR_SIZE(&current->children); ++i) {
1154                 struct ast_sip_subscription *child;
1155                 struct tree_node *child_node = AST_VECTOR_GET(&current->children, i);
1156
1157                 child = create_virtual_subscriptions(handler, child_node->resource, generator,
1158                                 tree, child_node);
1159
1160                 if (!child) {
1161                         ast_debug(1, "Child subscription to resource %s could not be created\n",
1162                                         child_node->resource);
1163                         continue;
1164                 }
1165
1166                 if (AST_VECTOR_APPEND(&sub->children, child)) {
1167                         ast_debug(1, "Child subscription to resource %s could not be appended\n",
1168                                         child_node->resource);
1169                 }
1170         }
1171
1172         return sub;
1173 }
1174
1175 static void shutdown_subscriptions(struct ast_sip_subscription *sub)
1176 {
1177         int i;
1178
1179         if (!sub) {
1180                 return;
1181         }
1182
1183         if (AST_VECTOR_SIZE(&sub->children) > 0) {
1184                 for (i = 0; i < AST_VECTOR_SIZE(&sub->children); ++i) {
1185                         shutdown_subscriptions(AST_VECTOR_GET(&sub->children, i));
1186                 }
1187                 return;
1188         }
1189
1190         /* We notify subscription shutdown only on the tree leaves. */
1191         if (sub->handler->subscription_shutdown) {
1192                 sub->handler->subscription_shutdown(sub);
1193         }
1194 }
1195
1196 static void subscription_tree_destructor(void *obj)
1197 {
1198         struct sip_subscription_tree *sub_tree = obj;
1199
1200         ast_debug(3, "Destroying subscription tree %p\n", sub_tree);
1201
1202         remove_subscription(sub_tree);
1203
1204         subscription_persistence_remove(sub_tree);
1205         ao2_cleanup(sub_tree->endpoint);
1206
1207         if (sub_tree->dlg) {
1208                 ast_sip_push_task_synchronous(NULL, subscription_remove_serializer, sub_tree);
1209         }
1210         destroy_subscriptions(sub_tree->root);
1211
1212         ast_taskprocessor_unreference(sub_tree->serializer);
1213         ast_module_unref(ast_module_info->self);
1214 }
1215
1216 void ast_sip_subscription_destroy(struct ast_sip_subscription *sub)
1217 {
1218         ast_debug(3, "Removing subscription %p reference to subscription tree %p\n", sub, sub->tree);
1219         ao2_cleanup(sub->tree);
1220 }
1221
1222 static void subscription_setup_dialog(struct sip_subscription_tree *sub_tree, pjsip_dialog *dlg)
1223 {
1224         /* We keep a reference to the dialog until our subscription is destroyed. See
1225          * the subscription_destructor for more details
1226          */
1227         pjsip_dlg_inc_session(dlg, &pubsub_module);
1228         sub_tree->dlg = dlg;
1229         ast_sip_dialog_set_serializer(dlg, sub_tree->serializer);
1230         ast_sip_dialog_set_endpoint(dlg, sub_tree->endpoint);
1231         pjsip_evsub_set_mod_data(sub_tree->evsub, pubsub_module.id, sub_tree);
1232 }
1233
1234 static struct sip_subscription_tree *allocate_subscription_tree(struct ast_sip_endpoint *endpoint)
1235 {
1236         struct sip_subscription_tree *sub_tree;
1237
1238         sub_tree = ao2_alloc(sizeof *sub_tree, subscription_tree_destructor);
1239         if (!sub_tree) {
1240                 return NULL;
1241         }
1242
1243         ast_module_ref(ast_module_info->self);
1244
1245         sub_tree->serializer = ast_sip_create_serializer();
1246         if (!sub_tree->serializer) {
1247                 ao2_ref(sub_tree, -1);
1248                 return NULL;
1249         }
1250
1251         sub_tree->endpoint = ao2_bump(endpoint);
1252         sub_tree->notify_sched_id = -1;
1253
1254         add_subscription(sub_tree);
1255         return sub_tree;
1256 }
1257
1258 /*!
1259  * \brief Create a subscription tree based on a resource tree.
1260  *
1261  * Using the previously-determined valid resources in the provided resource tree,
1262  * a corresponding tree of ast_sip_subscriptions are created. The root of the
1263  * subscription tree is a real subscription, and the rest in the tree are
1264  * virtual subscriptions.
1265  *
1266  * \param handler The handler to use for leaf subscriptions
1267  * \param endpoint The endpoint that sent the SUBSCRIBE request
1268  * \param rdata The SUBSCRIBE content
1269  * \param resource The requested resource in the SUBSCRIBE request
1270  * \param generator The body generator to use in leaf subscriptions
1271  * \param tree The resource tree on which the subscription tree is based
1272  * \param dlg_status[out] The result of attempting to create a dialog.
1273  *
1274  * \retval NULL Could not create the subscription tree
1275  * \retval non-NULL The root of the created subscription tree
1276  */
1277
1278 static struct sip_subscription_tree *create_subscription_tree(const struct ast_sip_subscription_handler *handler,
1279                 struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata, const char *resource,
1280                 struct ast_sip_pubsub_body_generator *generator, struct resource_tree *tree,
1281                 pj_status_t *dlg_status)
1282 {
1283         struct sip_subscription_tree *sub_tree;
1284         pjsip_dialog *dlg;
1285         struct subscription_persistence *persistence;
1286
1287         sub_tree = allocate_subscription_tree(endpoint);
1288         if (!sub_tree) {
1289                 *dlg_status = PJ_ENOMEM;
1290                 return NULL;
1291         }
1292         sub_tree->role = AST_SIP_NOTIFIER;
1293
1294         dlg = ast_sip_create_dialog_uas(endpoint, rdata, dlg_status);
1295         if (!dlg) {
1296                 if (*dlg_status != PJ_EEXISTS) {
1297                         ast_log(LOG_WARNING, "Unable to create dialog for SIP subscription\n");
1298                 }
1299                 ao2_ref(sub_tree, -1);
1300                 return NULL;
1301         }
1302
1303         persistence = ast_sip_mod_data_get(rdata->endpt_info.mod_data,
1304                         pubsub_module.id, MOD_DATA_PERSISTENCE);
1305         if (persistence) {
1306                 /* Update the created dialog with the persisted information */
1307                 pjsip_ua_unregister_dlg(pjsip_ua_instance(), dlg);
1308                 pj_strdup2(dlg->pool, &dlg->local.info->tag, persistence->tag);
1309                 dlg->local.tag_hval = pj_hash_calc_tolower(0, NULL, &dlg->local.info->tag);
1310                 pjsip_ua_register_dlg(pjsip_ua_instance(), dlg);
1311                 dlg->local.cseq = persistence->cseq;
1312                 dlg->remote.cseq = persistence->cseq;
1313         }
1314
1315         pjsip_evsub_create_uas(dlg, &pubsub_cb, rdata, 0, &sub_tree->evsub);
1316         subscription_setup_dialog(sub_tree, dlg);
1317
1318         ast_sip_mod_data_set(dlg->pool, dlg->mod_data, pubsub_module.id, MOD_DATA_MSG,
1319                         pjsip_msg_clone(dlg->pool, rdata->msg_info.msg));
1320
1321         sub_tree->notification_batch_interval = tree->notification_batch_interval;
1322
1323         sub_tree->root = create_virtual_subscriptions(handler, resource, generator, sub_tree, tree->root);
1324         if (AST_VECTOR_SIZE(&sub_tree->root->children) > 0) {
1325                 sub_tree->is_list = 1;
1326         }
1327
1328         return sub_tree;
1329 }
1330
1331 static int initial_notify_task(void *obj);
1332 static int send_notify(struct sip_subscription_tree *sub_tree, unsigned int force_full_state);
1333
1334 /*! \brief Callback function to perform the actual recreation of a subscription */
1335 static int subscription_persistence_recreate(void *obj, void *arg, int flags)
1336 {
1337         struct subscription_persistence *persistence = obj;
1338         pj_pool_t *pool = arg;
1339         pjsip_rx_data rdata = { { 0, }, };
1340         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
1341         struct sip_subscription_tree *sub_tree;
1342         struct ast_sip_pubsub_body_generator *generator;
1343         int resp;
1344         char *resource;
1345         size_t resource_size;
1346         pjsip_sip_uri *request_uri;
1347         struct resource_tree tree;
1348         pjsip_expires_hdr *expires_header;
1349         struct ast_sip_subscription_handler *handler;
1350
1351         /* If this subscription has already expired remove it */
1352         if (ast_tvdiff_ms(persistence->expires, ast_tvnow()) <= 0) {
1353                 ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
1354                 return 0;
1355         }
1356
1357         endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", persistence->endpoint);
1358         if (!endpoint) {
1359                 ast_log(LOG_WARNING, "A subscription for '%s' could not be recreated as the endpoint was not found\n",
1360                         persistence->endpoint);
1361                 ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
1362                 return 0;
1363         }
1364
1365         pj_pool_reset(pool);
1366         rdata.tp_info.pool = pool;
1367
1368         if (ast_sip_create_rdata(&rdata, persistence->packet, persistence->src_name, persistence->src_port,
1369                 persistence->transport_key, persistence->local_name, persistence->local_port)) {
1370                 ast_log(LOG_WARNING, "A subscription for '%s' could not be recreated as the message could not be parsed\n",
1371                         persistence->endpoint);
1372                 ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
1373                 return 0;
1374         }
1375
1376         if (rdata.msg_info.msg->type != PJSIP_REQUEST_MSG) {
1377                 ast_log(LOG_NOTICE, "Endpoint %s persisted a SIP response instead of a subscribe request. Unable to reload subscription.\n",
1378                                 ast_sorcery_object_get_id(endpoint));
1379                 ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
1380                 return 0;
1381         }
1382
1383         request_uri = pjsip_uri_get_uri(rdata.msg_info.msg->line.req.uri);
1384         resource_size = pj_strlen(&request_uri->user) + 1;
1385         resource = ast_alloca(resource_size);
1386         ast_copy_pj_str(resource, &request_uri->user, resource_size);
1387
1388         /* Update the expiration header with the new expiration */
1389         expires_header = pjsip_msg_find_hdr(rdata.msg_info.msg, PJSIP_H_EXPIRES, rdata.msg_info.msg->hdr.next);
1390         if (!expires_header) {
1391                 expires_header = pjsip_expires_hdr_create(pool, 0);
1392                 if (!expires_header) {
1393                         ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
1394                         return 0;
1395                 }
1396                 pjsip_msg_add_hdr(rdata.msg_info.msg, (pjsip_hdr*)expires_header);
1397         }
1398         expires_header->ivalue = (ast_tvdiff_ms(persistence->expires, ast_tvnow()) / 1000);
1399
1400         handler = subscription_get_handler_from_rdata(&rdata);
1401         if (!handler || !handler->notifier) {
1402                 ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
1403                 return 0;
1404         }
1405
1406         generator = subscription_get_generator_from_rdata(&rdata, handler);
1407         if (!generator) {
1408                 ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
1409                 return 0;
1410         }
1411
1412         ast_sip_mod_data_set(rdata.tp_info.pool, rdata.endpt_info.mod_data,
1413                         pubsub_module.id, MOD_DATA_PERSISTENCE, persistence);
1414
1415         memset(&tree, 0, sizeof(tree));
1416         resp = build_resource_tree(endpoint, handler, resource, &tree,
1417                 ast_sip_pubsub_has_eventlist_support(&rdata));
1418         if (PJSIP_IS_STATUS_IN_CLASS(resp, 200)) {
1419                 pj_status_t dlg_status;
1420
1421                 sub_tree = create_subscription_tree(handler, endpoint, &rdata, resource, generator, &tree, &dlg_status);
1422                 if (!sub_tree) {
1423                         ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
1424                         ast_log(LOG_WARNING, "Failed to re-create subscription for %s\n", persistence->endpoint);
1425                         return 0;
1426                 }
1427                 sub_tree->persistence = ao2_bump(persistence);
1428                 subscription_persistence_update(sub_tree, &rdata);
1429                 if (ast_sip_push_task(sub_tree->serializer, initial_notify_task, ao2_bump(sub_tree))) {
1430                         pjsip_evsub_terminate(sub_tree->evsub, PJ_TRUE);
1431                         ao2_ref(sub_tree, -1);
1432                 }
1433         } else {
1434                 ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
1435         }
1436         resource_tree_destroy(&tree);
1437
1438         return 0;
1439 }
1440
1441 /*! \brief Function which loads and recreates persisted subscriptions upon startup when the system is fully booted */
1442 static int subscription_persistence_load(void *data)
1443 {
1444         struct ao2_container *persisted_subscriptions = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(),
1445                 "subscription_persistence", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
1446         pj_pool_t *pool;
1447
1448         pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "rtd%p", PJSIP_POOL_RDATA_LEN,
1449                 PJSIP_POOL_RDATA_INC);
1450         if (!pool) {
1451                 ast_log(LOG_WARNING, "Could not create a memory pool for recreating SIP subscriptions\n");
1452                 return 0;
1453         }
1454
1455         ao2_callback(persisted_subscriptions, OBJ_NODATA, subscription_persistence_recreate, pool);
1456
1457         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
1458
1459         ao2_ref(persisted_subscriptions, -1);
1460         return 0;
1461 }
1462
1463 /*! \brief Event callback which fires subscription persistence recreation when the system is fully booted */
1464 static void subscription_persistence_event_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
1465 {
1466         struct ast_json_payload *payload;
1467         const char *type;
1468
1469         if (stasis_message_type(message) != ast_manager_get_generic_type()) {
1470                 return;
1471         }
1472
1473         payload = stasis_message_data(message);
1474         type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
1475
1476         /* This subscription only responds to the FullyBooted event so that all modules have been loaded when we
1477          * recreate SIP subscriptions.
1478          */
1479         if (strcmp(type, "FullyBooted")) {
1480                 return;
1481         }
1482
1483         /* This has to be here so the subscription is recreated when the body generator is available */
1484         ast_sip_push_task(NULL, subscription_persistence_load, NULL);
1485
1486         /* Once the system is fully booted we don't care anymore */
1487         stasis_unsubscribe(sub);
1488 }
1489
1490 typedef int (*on_subscription_t)(struct sip_subscription_tree *sub, void *arg);
1491
1492 static int for_each_subscription(on_subscription_t on_subscription, void *arg)
1493 {
1494         int num = 0;
1495         struct sip_subscription_tree *i;
1496         SCOPED_LOCK(lock, &subscriptions, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
1497
1498         if (!on_subscription) {
1499                 return num;
1500         }
1501
1502         AST_RWLIST_TRAVERSE(&subscriptions, i, next) {
1503                 if (on_subscription(i, arg)) {
1504                         break;
1505                 }
1506                 ++num;
1507         }
1508         return num;
1509 }
1510
1511 static void sip_subscription_to_ami(struct sip_subscription_tree *sub_tree,
1512                                     struct ast_str **buf)
1513 {
1514         char str[256];
1515         struct ast_sip_endpoint_id_configuration *id = &sub_tree->endpoint->id;
1516
1517         ast_str_append(buf, 0, "Role: %s\r\n",
1518                        sip_subscription_roles_map[sub_tree->role]);
1519         ast_str_append(buf, 0, "Endpoint: %s\r\n",
1520                        ast_sorcery_object_get_id(sub_tree->endpoint));
1521
1522         ast_copy_pj_str(str, &sub_tree->dlg->call_id->id, sizeof(str));
1523         ast_str_append(buf, 0, "Callid: %s\r\n", str);
1524
1525         ast_str_append(buf, 0, "State: %s\r\n", pjsip_evsub_get_state_name(sub_tree->evsub));
1526
1527         ast_callerid_merge(str, sizeof(str),
1528                            S_COR(id->self.name.valid, id->self.name.str, NULL),
1529                            S_COR(id->self.number.valid, id->self.number.str, NULL),
1530                            "Unknown");
1531
1532         ast_str_append(buf, 0, "Callerid: %s\r\n", str);
1533
1534         /* XXX This needs to be done recursively for lists */
1535         if (sub_tree->root->handler->to_ami) {
1536                 sub_tree->root->handler->to_ami(sub_tree->root, buf);
1537         }
1538 }
1539
1540
1541 void *ast_sip_subscription_get_header(const struct ast_sip_subscription *sub, const char *header)
1542 {
1543         pjsip_dialog *dlg = sub->tree->dlg;
1544         pjsip_msg *msg = ast_sip_mod_data_get(dlg->mod_data, pubsub_module.id, MOD_DATA_MSG);
1545         pj_str_t name;
1546
1547         pj_cstr(&name, header);
1548
1549         return pjsip_msg_find_hdr_by_name(msg, &name, NULL);
1550 }
1551
1552 /* XXX This function is not used. */
1553 struct ast_sip_subscription *ast_sip_create_subscription(const struct ast_sip_subscription_handler *handler,
1554                 struct ast_sip_endpoint *endpoint, const char *resource)
1555 {
1556         struct ast_sip_subscription *sub;
1557         pjsip_dialog *dlg;
1558         struct ast_sip_contact *contact;
1559         pj_str_t event;
1560         pjsip_tx_data *tdata;
1561         pjsip_evsub *evsub;
1562         struct sip_subscription_tree *sub_tree = NULL;
1563
1564         sub_tree = allocate_subscription_tree(endpoint);
1565         if (!sub_tree) {
1566                 return NULL;
1567         }
1568
1569         sub = allocate_subscription(handler, resource, sub_tree);
1570         if (!sub) {
1571                 ao2_cleanup(sub_tree);
1572                 return NULL;
1573         }
1574
1575         contact = ast_sip_location_retrieve_contact_from_aor_list(endpoint->aors);
1576         if (!contact || ast_strlen_zero(contact->uri)) {
1577                 ast_log(LOG_WARNING, "No contacts configured for endpoint %s. Unable to create SIP subsription\n",
1578                                 ast_sorcery_object_get_id(endpoint));
1579                 ao2_ref(sub_tree, -1);
1580                 ao2_cleanup(contact);
1581                 return NULL;
1582         }
1583
1584         dlg = ast_sip_create_dialog_uac(endpoint, contact->uri, NULL);
1585         ao2_cleanup(contact);
1586         if (!dlg) {
1587                 ast_log(LOG_WARNING, "Unable to create dialog for SIP subscription\n");
1588                 ao2_ref(sub_tree, -1);
1589                 return NULL;
1590         }
1591
1592         pj_cstr(&event, handler->event_name);
1593         pjsip_evsub_create_uac(dlg, &pubsub_cb, &event, 0, &sub_tree->evsub);
1594         subscription_setup_dialog(sub_tree, dlg);
1595
1596         evsub = sub_tree->evsub;
1597
1598         if (pjsip_evsub_initiate(evsub, NULL, -1, &tdata) == PJ_SUCCESS) {
1599                 pjsip_evsub_send_request(evsub, tdata);
1600         } else {
1601                 /* pjsip_evsub_terminate will result in pubsub_on_evsub_state,
1602                  * being called and terminating the subscription. Therefore, we don't
1603                  * need to decrease the reference count of sub here.
1604                  */
1605                 pjsip_evsub_terminate(evsub, PJ_TRUE);
1606                 ao2_ref(sub_tree, -1);
1607                 return NULL;
1608         }
1609
1610         return sub;
1611 }
1612
1613 struct ast_sip_endpoint *ast_sip_subscription_get_endpoint(struct ast_sip_subscription *sub)
1614 {
1615         ast_assert(sub->tree->endpoint != NULL);
1616         return ao2_bump(sub->tree->endpoint);
1617 }
1618
1619 struct ast_taskprocessor *ast_sip_subscription_get_serializer(struct ast_sip_subscription *sub)
1620 {
1621         ast_assert(sub->tree->serializer != NULL);
1622         return sub->tree->serializer;
1623 }
1624
1625 /*!
1626  * \brief Pre-allocate a buffer for the transmission
1627  *
1628  * Typically, we let PJSIP do this step for us when we send a request. PJSIP's buffer
1629  * allocation algorithm is to allocate a buffer of PJSIP_MAX_PKT_LEN bytes and attempt
1630  * to write the packet to the allocated buffer. If the buffer is too small to hold the
1631  * packet, then we get told the message is too long to be sent.
1632  *
1633  * When dealing with SIP NOTIFY, especially with RLS, it is possible to exceed
1634  * PJSIP_MAX_PKT_LEN. Rather than accepting the limitation imposed on us by default,
1635  * we instead take the strategy of pre-allocating the buffer, testing for ourselves
1636  * if the message will fit, and resizing the buffer as required.
1637  *
1638  * RFC 3261 says that a SIP UDP request can be up to 65535 bytes long. We're capping
1639  * it at 64000 for a couple of reasons:
1640  * 1) Allocating more than 64K at a time is hard to justify
1641  * 2) If the message goes through proxies, those proxies will want to add Via and
1642  *    Record-Route headers, making the message even larger. Giving some space for
1643  *    those headers is a nice thing to do.
1644  *
1645  * RFC 3261 does not place an upper limit on the size of TCP requests, but we are
1646  * going to impose the same 64K limit as a memory savings.
1647  *
1648  * \param tdata The tdata onto which to allocate a buffer
1649  * \retval 0 Success
1650  * \retval -1 The message is too large
1651  */
1652 static int allocate_tdata_buffer(pjsip_tx_data *tdata)
1653 {
1654         int buf_size;
1655         int size = -1;
1656         char *buf;
1657
1658         for (buf_size = PJSIP_MAX_PKT_LEN; size == -1 && buf_size < 64000; buf_size *= 2) {
1659                 buf = pj_pool_alloc(tdata->pool, buf_size);
1660                 size = pjsip_msg_print(tdata->msg, buf, buf_size);
1661         }
1662
1663         if (size == -1) {
1664                 return -1;
1665         }
1666
1667         tdata->buf.start = buf;
1668         tdata->buf.cur = tdata->buf.start;
1669         tdata->buf.end = tdata->buf.start + buf_size;
1670
1671         return 0;
1672 }
1673
1674 static int sip_subscription_send_request(struct sip_subscription_tree *sub_tree, pjsip_tx_data *tdata)
1675 {
1676 #ifdef TEST_FRAMEWORK
1677         struct ast_sip_endpoint *endpoint = sub_tree->endpoint;
1678 #endif
1679         pjsip_evsub *evsub = sub_tree->evsub;
1680         int res;
1681
1682         if (allocate_tdata_buffer(tdata)) {
1683                 ast_log(LOG_ERROR, "SIP request %s is too large to send.\n", tdata->info);
1684                 return -1;
1685         }
1686
1687         res = pjsip_evsub_send_request(evsub, tdata) == PJ_SUCCESS ? 0 : -1;
1688         subscription_persistence_update(sub_tree, NULL);
1689
1690         ast_test_suite_event_notify("SUBSCRIPTION_STATE_SET",
1691                 "StateText: %s\r\n"
1692                 "Endpoint: %s\r\n",
1693                 pjsip_evsub_get_state_name(evsub),
1694                 ast_sorcery_object_get_id(endpoint));
1695
1696         return res;
1697 }
1698
1699 /*!
1700  * \brief Add a resource XML element to an RLMI body
1701  *
1702  * Each resource element represents a subscribed resource in the list. This function currently
1703  * will unconditionally add an instance element to each created resource element. Instance
1704  * elements refer to later parts in the multipart body.
1705  *
1706  * \param pool PJLIB allocation pool
1707  * \param cid Content-ID header of the resource
1708  * \param resource_name Name of the resource
1709  * \param resource_uri URI of the resource
1710  * \param state State of the subscribed resource
1711  */
1712 static void add_rlmi_resource(pj_pool_t *pool, pj_xml_node *rlmi, const pjsip_generic_string_hdr *cid,
1713                 const char *resource_name, const pjsip_sip_uri *resource_uri, pjsip_evsub_state state)
1714 {
1715         static pj_str_t cid_name = { "cid", 3 };
1716         pj_xml_node *resource;
1717         pj_xml_node *name;
1718         pj_xml_node *instance;
1719         pj_xml_attr *cid_attr;
1720         char id[6];
1721         char uri[PJSIP_MAX_URL_SIZE];
1722
1723         /* This creates a string representing the Content-ID without the enclosing < > */
1724         const pj_str_t cid_stripped = {
1725                 .ptr = cid->hvalue.ptr + 1,
1726                 .slen = cid->hvalue.slen - 2,
1727         };
1728
1729         resource = ast_sip_presence_xml_create_node(pool, rlmi, "resource");
1730         name = ast_sip_presence_xml_create_node(pool, resource, "name");
1731         instance = ast_sip_presence_xml_create_node(pool, resource, "instance");
1732
1733         pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, resource_uri, uri, sizeof(uri));
1734         ast_sip_presence_xml_create_attr(pool, resource, "uri", uri);
1735
1736         pj_strdup2(pool, &name->content, resource_name);
1737
1738         ast_generate_random_string(id, sizeof(id));
1739
1740         ast_sip_presence_xml_create_attr(pool, instance, "id", id);
1741         ast_sip_presence_xml_create_attr(pool, instance, "state",
1742                         state == PJSIP_EVSUB_STATE_TERMINATED ? "terminated" : "active");
1743
1744         /* Use the PJLIB-util XML library directly here since we are using a
1745          * pj_str_t
1746          */
1747
1748         cid_attr = pj_xml_attr_new(pool, &cid_name, &cid_stripped);
1749         pj_xml_add_attr(instance, cid_attr);
1750 }
1751
1752 /*!
1753  * \brief A multipart body part and meta-information
1754  *
1755  * When creating a multipart body part, the end result (the
1756  * pjsip_multipart_part) is hard to inspect without undoing
1757  * a lot of what was done to create it. Therefore, we use this
1758  * structure to store meta-information about the body part.
1759  *
1760  * The main consumer of this is the creator of the RLMI body
1761  * part of a multipart resource list body.
1762  */
1763 struct body_part {
1764         /*! Content-ID header for the body part */
1765         pjsip_generic_string_hdr *cid;
1766         /*! Subscribed resource represented in the body part */
1767         const char *resource;
1768         /*! URI for the subscribed body part */
1769         pjsip_sip_uri *uri;
1770         /*! Subscription state of the resource represented in the body part */
1771         pjsip_evsub_state state;
1772         /*! The actual body part that will be present in the multipart body */
1773         pjsip_multipart_part *part;
1774 };
1775
1776 /*!
1777  * \brief Type declaration for container of body part structures
1778  */
1779 AST_VECTOR(body_part_list, struct body_part *);
1780
1781 /*!
1782  * \brief Create a Content-ID header
1783  *
1784  * Content-ID headers are required by RFC2387 for multipart/related
1785  * bodies. They serve as identifiers for each part of the multipart body.
1786  *
1787  * \param pool PJLIB allocation pool
1788  * \param sub Subscription to a resource
1789  */
1790 static pjsip_generic_string_hdr *generate_content_id_hdr(pj_pool_t *pool,
1791                 const struct ast_sip_subscription *sub)
1792 {
1793         static const pj_str_t cid_name = { "Content-ID", 10 };
1794         pjsip_generic_string_hdr *cid;
1795         char id[6];
1796         size_t alloc_size;
1797         pj_str_t cid_value;
1798
1799         /* '<' + '@' + '>' = 3. pj_str_t does not require a null-terminator */
1800         alloc_size = sizeof(id) + pj_strlen(&sub->uri->host) + 3;
1801         cid_value.ptr = pj_pool_alloc(pool, alloc_size);
1802         cid_value.slen = sprintf(cid_value.ptr, "<%s@%.*s>",
1803                         ast_generate_random_string(id, sizeof(id)),
1804                         (int) pj_strlen(&sub->uri->host), pj_strbuf(&sub->uri->host));
1805         cid = pjsip_generic_string_hdr_create(pool, &cid_name, &cid_value);
1806
1807         return cid;
1808 }
1809
1810 static int rlmi_print_body(struct pjsip_msg_body *msg_body, char *buf, pj_size_t size)
1811 {
1812         int num_printed;
1813         pj_xml_node *rlmi = msg_body->data;
1814
1815         num_printed = pj_xml_print(rlmi, buf, size, PJ_TRUE);
1816         if (num_printed <= AST_PJSIP_XML_PROLOG_LEN) {
1817                 return -1;
1818         }
1819
1820         return num_printed;
1821 }
1822
1823 static void *rlmi_clone_data(pj_pool_t *pool, const void *data, unsigned len)
1824 {
1825         const pj_xml_node *rlmi = data;
1826
1827         return pj_xml_clone(pool, rlmi);
1828 }
1829
1830 /*!
1831  * \brief Create an RLMI body part for a multipart resource list body
1832  *
1833  * RLMI (Resource list meta information) is a special body type that lists
1834  * the subscribed resources and tells subscribers the number of subscribed
1835  * resources and what other body parts are in the multipart body. The
1836  * RLMI body also has a version number that a subscriber can use to ensure
1837  * that the locally-stored state corresponds to server state.
1838  *
1839  * \param pool The allocation pool
1840  * \param sub The subscription representing the subscribed resource list
1841  * \param body_parts A container of body parts that RLMI will refer to
1842  * \param full_state Indicates whether this is a full or partial state notification
1843  * \return The multipart part representing the RLMI body
1844  */
1845 static pjsip_multipart_part *build_rlmi_body(pj_pool_t *pool, struct ast_sip_subscription *sub,
1846                 struct body_part_list *body_parts, unsigned int full_state)
1847 {
1848         static const pj_str_t rlmi_type = { "application", 11 };
1849         static const pj_str_t rlmi_subtype = { "rlmi+xml", 8 };
1850         pj_xml_node *rlmi;
1851         pj_xml_node *name;
1852         pjsip_multipart_part *rlmi_part;
1853         char version_str[32];
1854         char uri[PJSIP_MAX_URL_SIZE];
1855         pjsip_generic_string_hdr *cid;
1856         int i;
1857
1858         rlmi = ast_sip_presence_xml_create_node(pool, NULL, "list");
1859         ast_sip_presence_xml_create_attr(pool, rlmi, "xmlns", "urn:ietf:params:xml:ns:rlmi");
1860
1861         ast_sip_subscription_get_local_uri(sub, uri, sizeof(uri));
1862         ast_sip_presence_xml_create_attr(pool, rlmi, "uri", uri);
1863
1864         snprintf(version_str, sizeof(version_str), "%u", sub->version++);
1865         ast_sip_presence_xml_create_attr(pool, rlmi, "version", version_str);
1866         ast_sip_presence_xml_create_attr(pool, rlmi, "fullState", full_state ? "true" : "false");
1867
1868         name = ast_sip_presence_xml_create_node(pool, rlmi, "name");
1869         pj_strdup2(pool, &name->content, ast_sip_subscription_get_resource_name(sub));
1870
1871         for (i = 0; i < AST_VECTOR_SIZE(body_parts); ++i) {
1872                 const struct body_part *part = AST_VECTOR_GET(body_parts, i);
1873
1874                 add_rlmi_resource(pool, rlmi, part->cid, part->resource, part->uri, part->state);
1875         }
1876
1877         rlmi_part = pjsip_multipart_create_part(pool);
1878
1879         rlmi_part->body = PJ_POOL_ZALLOC_T(pool, pjsip_msg_body);
1880         pj_strdup(pool, &rlmi_part->body->content_type.type, &rlmi_type);
1881         pj_strdup(pool, &rlmi_part->body->content_type.subtype, &rlmi_subtype);
1882         pj_list_init(&rlmi_part->body->content_type.param);
1883
1884         rlmi_part->body->data = pj_xml_clone(pool, rlmi);
1885         rlmi_part->body->clone_data = rlmi_clone_data;
1886         rlmi_part->body->print_body = rlmi_print_body;
1887
1888         cid = generate_content_id_hdr(pool, sub);
1889         pj_list_insert_before(&rlmi_part->hdr, cid);
1890
1891         return rlmi_part;
1892 }
1893
1894 static pjsip_msg_body *generate_notify_body(pj_pool_t *pool, struct ast_sip_subscription *root,
1895                 unsigned int force_full_state);
1896
1897 /*!
1898  * \brief Destroy a list of body parts
1899  *
1900  * \param parts The container of parts to destroy
1901  */
1902 static void free_body_parts(struct body_part_list *parts)
1903 {
1904         int i;
1905
1906         for (i = 0; i < AST_VECTOR_SIZE(parts); ++i) {
1907                 struct body_part *part = AST_VECTOR_GET(parts, i);
1908                 ast_free(part);
1909         }
1910
1911         AST_VECTOR_FREE(parts);
1912 }
1913
1914 /*!
1915  * \brief Allocate and initialize a body part structure
1916  *
1917  * \param pool PJLIB allocation pool
1918  * \param sub Subscription representing a subscribed resource
1919  */
1920 static struct body_part *allocate_body_part(pj_pool_t *pool, const struct ast_sip_subscription *sub)
1921 {
1922         struct body_part *bp;
1923
1924         bp = ast_calloc(1, sizeof(*bp));
1925         if (!bp) {
1926                 return NULL;
1927         }
1928
1929         bp->cid = generate_content_id_hdr(pool, sub);
1930         bp->resource = sub->resource;
1931         bp->state = sub->subscription_state;
1932         bp->uri = sub->uri;
1933
1934         return bp;
1935 }
1936
1937 /*!
1938  * \brief Create a multipart body part for a subscribed resource
1939  *
1940  * \param pool PJLIB allocation pool
1941  * \param sub The subscription representing a subscribed resource
1942  * \param parts A vector of parts to append the created part to.
1943  * \param use_full_state Unused locally, but may be passed to other functions
1944  */
1945 static void build_body_part(pj_pool_t *pool, struct ast_sip_subscription *sub,
1946                 struct body_part_list *parts, unsigned int use_full_state)
1947 {
1948         struct body_part *bp;
1949         pjsip_msg_body *body;
1950
1951         bp = allocate_body_part(pool, sub);
1952         if (!bp) {
1953                 return;
1954         }
1955
1956         body = generate_notify_body(pool, sub, use_full_state);
1957         if (!body) {
1958                 /* Partial state was requested and the resource has not changed state */
1959                 ast_free(bp);
1960                 return;
1961         }
1962
1963         bp->part = pjsip_multipart_create_part(pool);
1964         bp->part->body = body;
1965         pj_list_insert_before(&bp->part->hdr, bp->cid);
1966
1967         AST_VECTOR_APPEND(parts, bp);
1968 }
1969
1970 /*!
1971  * \brief Create and initialize the PJSIP multipart body structure for a resource list subscription
1972  *
1973  * \param pool
1974  * \return The multipart message body
1975  */
1976 static pjsip_msg_body *create_multipart_body(pj_pool_t *pool)
1977 {
1978         pjsip_media_type media_type;
1979         pjsip_param *media_type_param;
1980         char boundary[6];
1981         pj_str_t pj_boundary;
1982
1983         pjsip_media_type_init2(&media_type, "multipart", "related");
1984
1985         media_type_param = pj_pool_alloc(pool, sizeof(*media_type_param));
1986         pj_list_init(media_type_param);
1987
1988         pj_strdup2(pool, &media_type_param->name, "type");
1989         pj_strdup2(pool, &media_type_param->value, "\"application/rlmi+xml\"");
1990
1991         pj_list_insert_before(&media_type.param, media_type_param);
1992
1993         pj_cstr(&pj_boundary, ast_generate_random_string(boundary, sizeof(boundary)));
1994         return pjsip_multipart_create(pool, &media_type, &pj_boundary);
1995 }
1996
1997 /*!
1998  * \brief Create a resource list body for NOTIFY requests
1999  *
2000  * Resource list bodies are multipart/related bodies. The first part of the multipart body
2001  * is an RLMI body that describes the rest of the parts to come. The other parts of the body
2002  * convey state of individual subscribed resources.
2003  *
2004  * \param pool PJLIB allocation pool
2005  * \param sub Subscription details from which to generate body
2006  * \param force_full_state If true, ignore resource list settings and send a full state notification
2007  * \return The generated multipart/related body
2008  */
2009 static pjsip_msg_body *generate_list_body(pj_pool_t *pool, struct ast_sip_subscription *sub,
2010                 unsigned int force_full_state)
2011 {
2012         int i;
2013         pjsip_multipart_part *rlmi_part;
2014         pjsip_msg_body *multipart;
2015         struct body_part_list body_parts;
2016         unsigned int use_full_state = force_full_state ? 1 : sub->full_state;
2017
2018         if (AST_VECTOR_INIT(&body_parts, AST_VECTOR_SIZE(&sub->children))) {
2019                 return NULL;
2020         }
2021
2022         for (i = 0; i < AST_VECTOR_SIZE(&sub->children); ++i) {
2023                 build_body_part(pool, AST_VECTOR_GET(&sub->children, i), &body_parts, use_full_state);
2024         }
2025
2026         /* This can happen if issuing partial state and no children of the list have changed state */
2027         if (AST_VECTOR_SIZE(&body_parts) == 0) {
2028                 return NULL;
2029         }
2030
2031         multipart = create_multipart_body(pool);
2032
2033         rlmi_part = build_rlmi_body(pool, sub, &body_parts, use_full_state);
2034         if (!rlmi_part) {
2035                 return NULL;
2036         }
2037         pjsip_multipart_add_part(pool, multipart, rlmi_part);
2038
2039         for (i = 0; i < AST_VECTOR_SIZE(&body_parts); ++i) {
2040                 pjsip_multipart_add_part(pool, multipart, AST_VECTOR_GET(&body_parts, i)->part);
2041         }
2042
2043         free_body_parts(&body_parts);
2044         return multipart;
2045 }
2046
2047 /*!
2048  * \brief Create the body for a NOTIFY request.
2049  *
2050  * \param pool The pool used for allocations
2051  * \param root The root of the subscription tree
2052  * \param force_full_state If true, ignore resource list settings and send a full state notification
2053  */
2054 static pjsip_msg_body *generate_notify_body(pj_pool_t *pool, struct ast_sip_subscription *root,
2055                 unsigned int force_full_state)
2056 {
2057         pjsip_msg_body *body;
2058
2059         if (AST_VECTOR_SIZE(&root->children) == 0) {
2060                 if (force_full_state || root->body_changed) {
2061                         /* Not a list. We've already generated the body and saved it on the subscription.
2062                          * Use that directly.
2063                          */
2064                         pj_str_t type;
2065                         pj_str_t subtype;
2066                         pj_str_t text;
2067
2068                         pj_cstr(&type, ast_sip_subscription_get_body_type(root));
2069                         pj_cstr(&subtype, ast_sip_subscription_get_body_subtype(root));
2070                         pj_cstr(&text, ast_str_buffer(root->body_text));
2071
2072                         body = pjsip_msg_body_create(pool, &type, &subtype, &text);
2073                         root->body_changed = 0;
2074                 } else {
2075                         body = NULL;
2076                 }
2077         } else {
2078                 body = generate_list_body(pool, root, force_full_state);
2079         }
2080
2081         return body;
2082 }
2083
2084 /*!
2085  * \brief Shortcut method to create a Require: eventlist header
2086  */
2087 static pjsip_require_hdr *create_require_eventlist(pj_pool_t *pool)
2088 {
2089         pjsip_require_hdr *require;
2090
2091         require = pjsip_require_hdr_create(pool);
2092         pj_strdup2(pool, &require->values[0], "eventlist");
2093         require->count = 1;
2094
2095         return require;
2096 }
2097
2098 /*!
2099  * \brief Send a NOTIFY request to a subscriber
2100  *
2101  * \pre sub_tree->dlg is locked
2102  *
2103  * \param sub_tree The subscription tree representing the subscription
2104  * \param force_full_state If true, ignore resource list settings and send full resource list state.
2105  * \retval 0 Success
2106  * \retval non-zero Failure
2107  */
2108 static int send_notify(struct sip_subscription_tree *sub_tree, unsigned int force_full_state)
2109 {
2110         pjsip_evsub *evsub = sub_tree->evsub;
2111         pjsip_tx_data *tdata;
2112
2113         if (ast_shutdown_final()
2114                 && sub_tree->root->subscription_state == PJSIP_EVSUB_STATE_TERMINATED
2115                 && sub_tree->persistence) {
2116                 return 0;
2117         }
2118
2119         if (pjsip_evsub_notify(evsub, sub_tree->root->subscription_state,
2120                                 NULL, NULL, &tdata) != PJ_SUCCESS) {
2121                 return -1;
2122         }
2123
2124         tdata->msg->body = generate_notify_body(tdata->pool, sub_tree->root, force_full_state);
2125         if (!tdata->msg->body) {
2126                 pjsip_tx_data_dec_ref(tdata);
2127                 return -1;
2128         }
2129
2130         if (sub_tree->is_list) {
2131                 pjsip_require_hdr *require = create_require_eventlist(tdata->pool);
2132                 pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *) require);
2133         }
2134
2135         if (sub_tree->root->subscription_state == PJSIP_EVSUB_STATE_TERMINATED) {
2136                 sub_tree->last_notify = 1;
2137         }
2138         if (sip_subscription_send_request(sub_tree, tdata)) {
2139                 return -1;
2140         }
2141
2142         sub_tree->send_scheduled_notify = 0;
2143
2144         return 0;
2145 }
2146
2147 static int serialized_send_notify(void *userdata)
2148 {
2149         struct sip_subscription_tree *sub_tree = userdata;
2150
2151         pjsip_dlg_inc_lock(sub_tree->dlg);
2152         /* It's possible that between when the notification was scheduled
2153          * and now, that a new SUBSCRIBE arrived, requiring full state to be
2154          * sent out in an immediate NOTIFY. If that has happened, we need to
2155          * bail out here instead of sending the batched NOTIFY.
2156          */
2157         if (!sub_tree->send_scheduled_notify) {
2158                 pjsip_dlg_dec_lock(sub_tree->dlg);
2159                 ao2_cleanup(sub_tree);
2160                 return 0;
2161         }
2162
2163         send_notify(sub_tree, 0);
2164         ast_test_suite_event_notify("SUBSCRIPTION_STATE_CHANGED",
2165                         "Resource: %s",
2166                         sub_tree->root->resource);
2167         sub_tree->notify_sched_id = -1;
2168         pjsip_dlg_dec_lock(sub_tree->dlg);
2169         ao2_cleanup(sub_tree);
2170         return 0;
2171 }
2172
2173 static int sched_cb(const void *data)
2174 {
2175         struct sip_subscription_tree *sub_tree = (struct sip_subscription_tree *) data;
2176
2177         /* We don't need to bump the refcount of sub_tree since we bumped it when scheduling this task */
2178         ast_sip_push_task(sub_tree->serializer, serialized_send_notify, sub_tree);
2179         return 0;
2180 }
2181
2182 static int schedule_notification(struct sip_subscription_tree *sub_tree)
2183 {
2184         /* There's already a notification scheduled */
2185         if (sub_tree->notify_sched_id > -1) {
2186                 return 0;
2187         }
2188
2189         sub_tree->notify_sched_id = ast_sched_add(sched, sub_tree->notification_batch_interval, sched_cb, ao2_bump(sub_tree));
2190         if (sub_tree->notify_sched_id < 0) {
2191                 return -1;
2192         }
2193
2194         sub_tree->send_scheduled_notify = 1;
2195         return 0;
2196 }
2197
2198 int ast_sip_subscription_notify(struct ast_sip_subscription *sub, struct ast_sip_body_data *notify_data,
2199                 int terminate)
2200 {
2201         int res;
2202
2203         pjsip_dlg_inc_lock(sub->tree->dlg);
2204
2205         if (!sub->tree->evsub) {
2206                 pjsip_dlg_dec_lock(sub->tree->dlg);
2207                 return 0;
2208         }
2209
2210         if (ast_sip_pubsub_generate_body_content(ast_sip_subscription_get_body_type(sub),
2211                                 ast_sip_subscription_get_body_subtype(sub), notify_data, &sub->body_text)) {
2212                 pjsip_dlg_dec_lock(sub->tree->dlg);
2213                 return -1;
2214         }
2215
2216         sub->body_changed = 1;
2217         if (terminate) {
2218                 sub->subscription_state = PJSIP_EVSUB_STATE_TERMINATED;
2219         }
2220
2221         if (sub->tree->notification_batch_interval) {
2222                 res = schedule_notification(sub->tree);
2223         } else {
2224                 /* See the note in pubsub_on_rx_refresh() for why sub->tree is refbumped here */
2225                 ao2_ref(sub->tree, +1);
2226                 res = send_notify(sub->tree, 0);
2227                 ast_test_suite_event_notify(terminate ? "SUBSCRIPTION_TERMINATED" : "SUBSCRIPTION_STATE_CHANGED",
2228                                 "Resource: %s",
2229                                 sub->tree->root->resource);
2230                 ao2_ref(sub->tree, -1);
2231         }
2232
2233         pjsip_dlg_dec_lock(sub->tree->dlg);
2234         return res;
2235 }
2236
2237 void ast_sip_subscription_get_local_uri(struct ast_sip_subscription *sub, char *buf, size_t size)
2238 {
2239         pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, sub->uri, buf, size);
2240 }
2241
2242 void ast_sip_subscription_get_remote_uri(struct ast_sip_subscription *sub, char *buf, size_t size)
2243 {
2244         pjsip_dialog *dlg = sub->tree->dlg;
2245         ast_copy_pj_str(buf, &dlg->remote.info_str, size);
2246 }
2247
2248 const char *ast_sip_subscription_get_resource_name(struct ast_sip_subscription *sub)
2249 {
2250         return sub->resource;
2251 }
2252
2253 int ast_sip_subscription_is_terminated(const struct ast_sip_subscription *sub)
2254 {
2255         return sub->subscription_state == PJSIP_EVSUB_STATE_TERMINATED ? 1 : 0;
2256 }
2257
2258 static int sip_subscription_accept(struct sip_subscription_tree *sub_tree, pjsip_rx_data *rdata, int response)
2259 {
2260         pjsip_hdr res_hdr;
2261
2262         /* If this is a persistence recreation the subscription has already been accepted */
2263         if (ast_sip_mod_data_get(rdata->endpt_info.mod_data, pubsub_module.id, MOD_DATA_PERSISTENCE)) {
2264                 return 0;
2265         }
2266
2267         pj_list_init(&res_hdr);
2268         if (sub_tree->is_list) {
2269                 /* If subscribing to a list, our response has to have a Require: eventlist header in it */
2270                 pj_list_insert_before(&res_hdr, create_require_eventlist(rdata->tp_info.pool));
2271         }
2272
2273         return pjsip_evsub_accept(sub_tree->evsub, rdata, response, &res_hdr) == PJ_SUCCESS ? 0 : -1;
2274 }
2275
2276 static void subscription_datastore_destroy(void *obj)
2277 {
2278         struct ast_datastore *datastore = obj;
2279
2280         /* Using the destroy function (if present) destroy the data */
2281         if (datastore->info->destroy != NULL && datastore->data != NULL) {
2282                 datastore->info->destroy(datastore->data);
2283                 datastore->data = NULL;
2284         }
2285
2286         ast_free((void *) datastore->uid);
2287         datastore->uid = NULL;
2288 }
2289
2290 struct ast_datastore *ast_sip_subscription_alloc_datastore(const struct ast_datastore_info *info, const char *uid)
2291 {
2292         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
2293         char uuid_buf[AST_UUID_STR_LEN];
2294         const char *uid_ptr = uid;
2295
2296         if (!info) {
2297                 return NULL;
2298         }
2299
2300         datastore = ao2_alloc(sizeof(*datastore), subscription_datastore_destroy);
2301         if (!datastore) {
2302                 return NULL;
2303         }
2304
2305         datastore->info = info;
2306         if (ast_strlen_zero(uid)) {
2307                 /* They didn't provide an ID so we'll provide one ourself */
2308                 uid_ptr = ast_uuid_generate_str(uuid_buf, sizeof(uuid_buf));
2309         }
2310
2311         datastore->uid = ast_strdup(uid_ptr);
2312         if (!datastore->uid) {
2313                 return NULL;
2314         }
2315
2316         ao2_ref(datastore, +1);
2317         return datastore;
2318 }
2319
2320 int ast_sip_subscription_add_datastore(struct ast_sip_subscription *subscription, struct ast_datastore *datastore)
2321 {
2322         ast_assert(datastore != NULL);
2323         ast_assert(datastore->info != NULL);
2324         ast_assert(!ast_strlen_zero(datastore->uid));
2325
2326         if (!ao2_link(subscription->datastores, datastore)) {
2327                 return -1;
2328         }
2329         return 0;
2330 }
2331
2332 struct ast_datastore *ast_sip_subscription_get_datastore(struct ast_sip_subscription *subscription, const char *name)
2333 {
2334         return ao2_find(subscription->datastores, name, OBJ_KEY);
2335 }
2336
2337 void ast_sip_subscription_remove_datastore(struct ast_sip_subscription *subscription, const char *name)
2338 {
2339         ao2_find(subscription->datastores, name, OBJ_SEARCH_KEY | OBJ_UNLINK | OBJ_NODATA);
2340 }
2341
2342 int ast_sip_publication_add_datastore(struct ast_sip_publication *publication, struct ast_datastore *datastore)
2343 {
2344         ast_assert(datastore != NULL);
2345         ast_assert(datastore->info != NULL);
2346         ast_assert(!ast_strlen_zero(datastore->uid));
2347
2348         if (!ao2_link(publication->datastores, datastore)) {
2349                 return -1;
2350         }
2351         return 0;
2352 }
2353
2354 struct ast_datastore *ast_sip_publication_get_datastore(struct ast_sip_publication *publication, const char *name)
2355 {
2356         return ao2_find(publication->datastores, name, OBJ_KEY);
2357 }
2358
2359 void ast_sip_publication_remove_datastore(struct ast_sip_publication *publication, const char *name)
2360 {
2361         ao2_callback(publication->datastores, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, NULL, (void *) name);
2362 }
2363
2364 AST_RWLIST_HEAD_STATIC(publish_handlers, ast_sip_publish_handler);
2365
2366 static int publication_hash_fn(const void *obj, const int flags)
2367 {
2368         const struct ast_sip_publication *publication = obj;
2369         const int *entity_tag = obj;
2370
2371         return flags & OBJ_KEY ? *entity_tag : publication->entity_tag;
2372 }
2373
2374 static int publication_cmp_fn(void *obj, void *arg, int flags)
2375 {
2376         const struct ast_sip_publication *publication1 = obj;
2377         const struct ast_sip_publication *publication2 = arg;
2378         const int *entity_tag = arg;
2379
2380         return (publication1->entity_tag == (flags & OBJ_KEY ? *entity_tag : publication2->entity_tag) ?
2381                 CMP_MATCH | CMP_STOP : 0);
2382 }
2383
2384 static void publish_add_handler(struct ast_sip_publish_handler *handler)
2385 {
2386         SCOPED_LOCK(lock, &publish_handlers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
2387         AST_RWLIST_INSERT_TAIL(&publish_handlers, handler, next);
2388 }
2389
2390 int ast_sip_register_publish_handler(struct ast_sip_publish_handler *handler)
2391 {
2392         if (ast_strlen_zero(handler->event_name)) {
2393                 ast_log(LOG_ERROR, "No event package specified for publish handler. Cannot register\n");
2394                 return -1;
2395         }
2396
2397         if (!(handler->publications = ao2_container_alloc(PUBLICATIONS_BUCKETS,
2398                 publication_hash_fn, publication_cmp_fn))) {
2399                 ast_log(LOG_ERROR, "Could not allocate publications container for event '%s'\n",
2400                         handler->event_name);
2401                 return -1;
2402         }
2403
2404         publish_add_handler(handler);
2405
2406         ast_module_ref(ast_module_info->self);
2407
2408         return 0;
2409 }
2410
2411 void ast_sip_unregister_publish_handler(struct ast_sip_publish_handler *handler)
2412 {
2413         struct ast_sip_publish_handler *iter;
2414         SCOPED_LOCK(lock, &publish_handlers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
2415         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&publish_handlers, iter, next) {
2416                 if (handler == iter) {
2417                         AST_RWLIST_REMOVE_CURRENT(next);
2418                         ao2_cleanup(handler->publications);
2419                         ast_module_unref(ast_module_info->self);
2420                         break;
2421                 }
2422         }
2423         AST_RWLIST_TRAVERSE_SAFE_END;
2424 }
2425
2426 AST_RWLIST_HEAD_STATIC(subscription_handlers, ast_sip_subscription_handler);
2427
2428 static void sub_add_handler(struct ast_sip_subscription_handler *handler)
2429 {
2430         SCOPED_LOCK(lock, &subscription_handlers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
2431         AST_RWLIST_INSERT_TAIL(&subscription_handlers, handler, next);
2432         ast_module_ref(ast_module_info->self);
2433 }
2434
2435 static struct ast_sip_subscription_handler *find_sub_handler_for_event_name(const char *event_name)
2436 {
2437         struct ast_sip_subscription_handler *iter;
2438         SCOPED_LOCK(lock, &subscription_handlers, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
2439
2440         AST_RWLIST_TRAVERSE(&subscription_handlers, iter, next) {
2441                 if (!strcmp(iter->event_name, event_name)) {
2442                         break;
2443                 }
2444         }
2445         return iter;
2446 }
2447
2448 int ast_sip_register_subscription_handler(struct ast_sip_subscription_handler *handler)
2449 {
2450         pj_str_t event;
2451         pj_str_t accept[AST_SIP_MAX_ACCEPT] = { {0, }, };
2452         struct ast_sip_subscription_handler *existing;
2453         int i = 0;
2454
2455         if (ast_strlen_zero(handler->event_name)) {
2456                 ast_log(LOG_ERROR, "No event package specified for subscription handler. Cannot register\n");
2457                 return -1;
2458         }
2459
2460         existing = find_sub_handler_for_event_name(handler->event_name);
2461         if (existing) {
2462                 ast_log(LOG_ERROR, "Unable to register subscription handler for event %s."
2463                                 "A handler is already registered\n", handler->event_name);
2464                 return -1;
2465         }
2466
2467         for (i = 0; i < AST_SIP_MAX_ACCEPT && !ast_strlen_zero(handler->accept[i]); ++i) {
2468                 pj_cstr(&accept[i], handler->accept[i]);
2469         }
2470
2471         pj_cstr(&event, handler->event_name);
2472
2473         pjsip_evsub_register_pkg(&pubsub_module, &event, DEFAULT_EXPIRES, i, accept);
2474
2475         sub_add_handler(handler);
2476
2477         return 0;
2478 }
2479
2480 void ast_sip_unregister_subscription_handler(struct ast_sip_subscription_handler *handler)
2481 {
2482         struct ast_sip_subscription_handler *iter;
2483         SCOPED_LOCK(lock, &subscription_handlers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
2484         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&subscription_handlers, iter, next) {
2485                 if (handler == iter) {
2486                         AST_RWLIST_REMOVE_CURRENT(next);
2487                         ast_module_unref(ast_module_info->self);
2488                         break;
2489                 }
2490         }
2491         AST_RWLIST_TRAVERSE_SAFE_END;
2492 }
2493
2494 static struct ast_sip_pubsub_body_generator *find_body_generator_type_subtype(const char *content_type,
2495                 const char *content_subtype)
2496 {
2497         struct ast_sip_pubsub_body_generator *iter;
2498         SCOPED_LOCK(lock, &body_generators, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
2499
2500         AST_LIST_TRAVERSE(&body_generators, iter, list) {
2501                 if (!strcmp(iter->type, content_type) &&
2502                                 !strcmp(iter->subtype, content_subtype)) {
2503                         break;
2504                 }
2505         };
2506
2507         return iter;
2508 }
2509
2510 static struct ast_sip_pubsub_body_generator *find_body_generator_accept(const char *accept)
2511 {
2512         char *accept_copy = ast_strdupa(accept);
2513         char *subtype = accept_copy;
2514         char *type = strsep(&subtype, "/");
2515
2516         if (ast_strlen_zero(type) || ast_strlen_zero(subtype)) {
2517                 return NULL;
2518         }
2519
2520         return find_body_generator_type_subtype(type, subtype);
2521 }
2522
2523 static struct ast_sip_pubsub_body_generator *find_body_generator(char accept[AST_SIP_MAX_ACCEPT][64],
2524                 size_t num_accept, const char *body_type)
2525 {
2526         int i;
2527         struct ast_sip_pubsub_body_generator *generator = NULL;
2528
2529         for (i = 0; i < num_accept; ++i) {
2530                 generator = find_body_generator_accept(accept[i]);
2531                 if (generator) {
2532                         ast_debug(3, "Body generator %p found for accept type %s\n", generator, accept[i]);
2533                         if (strcmp(generator->body_type, body_type)) {
2534                                 ast_log(LOG_WARNING, "Body generator '%s/%s'(%p) does not accept the type of data this event generates\n",
2535                                                 generator->type, generator->subtype, generator);
2536                                 generator = NULL;
2537                                 continue;
2538                         }
2539                         break;
2540                 } else {
2541                         ast_debug(3, "No body generator found for accept type %s\n", accept[i]);
2542                 }
2543         }
2544
2545         return generator;
2546 }
2547
2548 static int generate_initial_notify(struct ast_sip_subscription *sub)
2549 {
2550         void *notify_data;
2551         int res;
2552         struct ast_sip_body_data data = {
2553                 .body_type = sub->handler->body_type,
2554         };
2555
2556         if (AST_VECTOR_SIZE(&sub->children) > 0) {
2557                 int i;
2558
2559                 for (i = 0; i < AST_VECTOR_SIZE(&sub->children); ++i) {
2560                         if (generate_initial_notify(AST_VECTOR_GET(&sub->children, i))) {
2561                                 return -1;
2562                         }
2563                 }
2564
2565                 return 0;
2566         }
2567
2568         /* We notify subscription establishment only on the tree leaves. */
2569         if (sub->handler->notifier->subscription_established(sub)) {
2570                 return -1;
2571         }
2572
2573         notify_data = sub->handler->notifier->get_notify_data(sub);
2574         if (!notify_data) {
2575                 return -1;
2576         }
2577
2578         data.body_data = notify_data;
2579
2580         res = ast_sip_pubsub_generate_body_content(ast_sip_subscription_get_body_type(sub),
2581                         ast_sip_subscription_get_body_subtype(sub), &data, &sub->body_text);
2582
2583         ao2_cleanup(notify_data);
2584
2585         return res;
2586 }
2587
2588 static int initial_notify_task(void * obj)
2589 {
2590         struct sip_subscription_tree *sub_tree;
2591
2592         sub_tree = obj;
2593         if (generate_initial_notify(sub_tree->root)) {
2594                 pjsip_evsub_terminate(sub_tree->evsub, PJ_TRUE);
2595         } else {
2596                 send_notify(sub_tree, 1);
2597                 ast_test_suite_event_notify("SUBSCRIPTION_ESTABLISHED",
2598                         "Resource: %s",
2599                         sub_tree->root->resource);
2600         }
2601
2602         ao2_ref(sub_tree, -1);
2603         return 0;
2604 }
2605
2606 static pj_bool_t pubsub_on_rx_subscribe_request(pjsip_rx_data *rdata)
2607 {
2608         pjsip_expires_hdr *expires_header;
2609         struct ast_sip_subscription_handler *handler;
2610         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
2611         struct sip_subscription_tree *sub_tree;
2612         struct ast_sip_pubsub_body_generator *generator;
2613         char *resource;
2614         pjsip_uri *request_uri;
2615         pjsip_sip_uri *request_uri_sip;
2616         size_t resource_size;
2617         int resp;
2618         struct resource_tree tree;
2619         pj_status_t dlg_status;
2620
2621         endpoint = ast_pjsip_rdata_get_endpoint(rdata);
2622         ast_assert(endpoint != NULL);
2623
2624         if (!endpoint->subscription.allow) {
2625                 ast_log(LOG_WARNING, "Subscriptions not permitted for endpoint %s.\n", ast_sorcery_object_get_id(endpoint));
2626                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 603, NULL, NULL, NULL);
2627                 return PJ_TRUE;
2628         }
2629
2630         request_uri = rdata->msg_info.msg->line.req.uri;
2631
2632         if (!PJSIP_URI_SCHEME_IS_SIP(request_uri) && !PJSIP_URI_SCHEME_IS_SIPS(request_uri)) {
2633                 char uri_str[PJSIP_MAX_URL_SIZE];
2634
2635                 pjsip_uri_print(PJSIP_URI_IN_REQ_URI, request_uri, uri_str, sizeof(uri_str));
2636                 ast_log(LOG_WARNING, "Request URI '%s' is not a sip: or sips: URI.\n", uri_str);
2637                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 416, NULL, NULL, NULL);
2638                 return PJ_TRUE;
2639         }
2640
2641         request_uri_sip = pjsip_uri_get_uri(request_uri);
2642         resource_size = pj_strlen(&request_uri_sip->user) + 1;
2643         resource = ast_alloca(resource_size);
2644         ast_copy_pj_str(resource, &request_uri_sip->user, resource_size);
2645
2646         expires_header = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, rdata->msg_info.msg->hdr.next);
2647
2648         if (expires_header) {
2649                 if (expires_header->ivalue == 0) {
2650                         ast_log(LOG_WARNING, "Subscription request from endpoint %s rejected. Expiration of 0 is invalid\n",
2651                                 ast_sorcery_object_get_id(endpoint));
2652                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 400, NULL, NULL, NULL);
2653                                 return PJ_TRUE;
2654                 }
2655                 if (expires_header->ivalue < endpoint->subscription.minexpiry) {
2656                         ast_log(LOG_WARNING, "Subscription expiration %d is too brief for endpoint %s. Minimum is %u\n",
2657                                 expires_header->ivalue, ast_sorcery_object_get_id(endpoint), endpoint->subscription.minexpiry);
2658                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 423, NULL, NULL, NULL);
2659                         return PJ_TRUE;
2660                 }
2661         }
2662
2663         handler = subscription_get_handler_from_rdata(rdata);
2664         if (!handler) {
2665                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 489, NULL, NULL, NULL);
2666                 return PJ_TRUE;
2667         }
2668
2669         generator = subscription_get_generator_from_rdata(rdata, handler);
2670         if (!generator) {
2671                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 489, NULL, NULL, NULL);
2672                 return PJ_TRUE;
2673         }
2674
2675         memset(&tree, 0, sizeof(tree));
2676         resp = build_resource_tree(endpoint, handler, resource, &tree,
2677                 ast_sip_pubsub_has_eventlist_support(rdata));
2678         if (!PJSIP_IS_STATUS_IN_CLASS(resp, 200)) {
2679                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, resp, NULL, NULL, NULL);
2680                 resource_tree_destroy(&tree);
2681                 return PJ_TRUE;
2682         }
2683
2684         sub_tree = create_subscription_tree(handler, endpoint, rdata, resource, generator, &tree, &dlg_status);
2685         if (!sub_tree) {
2686                 if (dlg_status != PJ_EEXISTS) {
2687                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2688                 }
2689         } else {
2690                 sub_tree->persistence = subscription_persistence_create(sub_tree);
2691                 subscription_persistence_update(sub_tree, rdata);
2692                 sip_subscription_accept(sub_tree, rdata, resp);
2693                 if (ast_sip_push_task(sub_tree->serializer, initial_notify_task, ao2_bump(sub_tree))) {
2694                         pjsip_evsub_terminate(sub_tree->evsub, PJ_TRUE);
2695                         ao2_ref(sub_tree, -1);
2696                 }
2697         }
2698
2699         resource_tree_destroy(&tree);
2700         return PJ_TRUE;
2701 }
2702
2703 static struct ast_sip_publish_handler *find_pub_handler(const char *event)
2704 {
2705         struct ast_sip_publish_handler *iter = NULL;
2706         SCOPED_LOCK(lock, &publish_handlers, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
2707
2708         AST_RWLIST_TRAVERSE(&publish_handlers, iter, next) {
2709                 if (strcmp(event, iter->event_name)) {
2710                         ast_debug(3, "Event %s does not match %s\n", event, iter->event_name);
2711                         continue;
2712                 }
2713                 ast_debug(3, "Event name match: %s = %s\n", event, iter->event_name);
2714                 break;
2715         }
2716
2717         return iter;
2718 }
2719
2720 static enum sip_publish_type determine_sip_publish_type(pjsip_rx_data *rdata,
2721         pjsip_generic_string_hdr *etag_hdr, int *expires, int *entity_id)
2722 {
2723         pjsip_expires_hdr *expires_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL);
2724
2725         if (etag_hdr) {
2726                 char etag[pj_strlen(&etag_hdr->hvalue) + 1];
2727
2728                 ast_copy_pj_str(etag, &etag_hdr->hvalue, sizeof(etag));
2729
2730                 if (sscanf(etag, "%30d", entity_id) != 1) {
2731                         return SIP_PUBLISH_UNKNOWN;
2732                 }
2733         }
2734
2735         *expires = expires_hdr ? expires_hdr->ivalue : DEFAULT_PUBLISH_EXPIRES;
2736
2737         if (!(*expires)) {
2738                 return SIP_PUBLISH_REMOVE;
2739         } else if (!etag_hdr && rdata->msg_info.msg->body) {
2740                 return SIP_PUBLISH_INITIAL;
2741         } else if (etag_hdr && !rdata->msg_info.msg->body) {
2742                 return SIP_PUBLISH_REFRESH;
2743         } else if (etag_hdr && rdata->msg_info.msg->body) {
2744                 return SIP_PUBLISH_MODIFY;
2745         }
2746
2747         return SIP_PUBLISH_UNKNOWN;
2748 }
2749
2750 /*! \brief Internal destructor for publications */
2751 static void publication_destroy_fn(void *obj)
2752 {
2753         struct ast_sip_publication *publication = obj;
2754
2755         ast_debug(3, "Destroying SIP publication\n");
2756
2757         ao2_cleanup(publication->datastores);
2758         ao2_cleanup(publication->endpoint);
2759 }
2760
2761 static struct ast_sip_publication *sip_create_publication(struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata,
2762         const char *resource, const char *event_configuration_name)
2763 {
2764         struct ast_sip_publication *publication;
2765         pjsip_expires_hdr *expires_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL);
2766         size_t resource_len = strlen(resource) + 1, event_configuration_name_len = strlen(event_configuration_name) + 1;
2767         char *dst;
2768
2769         ast_assert(endpoint != NULL);
2770
2771         if (!(publication = ao2_alloc(sizeof(*publication) + resource_len + event_configuration_name_len, publication_destroy_fn))) {
2772                 return NULL;
2773         }
2774
2775         if (!(publication->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp))) {
2776                 ao2_ref(publication, -1);
2777                 return NULL;
2778         }
2779
2780         publication->entity_tag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
2781         ao2_ref(endpoint, +1);
2782         publication->endpoint = endpoint;
2783         publication->expires = expires_hdr ? expires_hdr->ivalue : DEFAULT_PUBLISH_EXPIRES;
2784         publication->sched_id = -1;
2785         dst = publication->data;
2786         publication->resource = strcpy(dst, resource);
2787         dst += resource_len;
2788         publication->event_configuration_name = strcpy(dst, event_configuration_name);
2789
2790         return publication;
2791 }
2792
2793 static int sip_publication_respond(struct ast_sip_publication *pub, int status_code,
2794                 pjsip_rx_data *rdata)
2795 {
2796         pj_status_t status;
2797         pjsip_tx_data *tdata;
2798         pjsip_transaction *tsx;
2799
2800         if (pjsip_endpt_create_response(ast_sip_get_pjsip_endpoint(), rdata, status_code, NULL, &tdata) != PJ_SUCCESS) {
2801                 return -1;
2802         }
2803
2804         if (PJSIP_IS_STATUS_IN_CLASS(status_code, 200)) {
2805                 RAII_VAR(char *, entity_tag, NULL, ast_free_ptr);
2806                 RAII_VAR(char *, expires, NULL, ast_free_ptr);
2807
2808                 if ((ast_asprintf(&entity_tag, "%d", pub->entity_tag) < 0) ||
2809                         (ast_asprintf(&expires, "%d", pub->expires) < 0)) {
2810                         pjsip_tx_data_dec_ref(tdata);
2811                         return -1;
2812                 }
2813
2814                 ast_sip_add_header(tdata, "SIP-ETag", entity_tag);
2815                 ast_sip_add_header(tdata, "Expires", expires);
2816         }
2817
2818         if ((status = pjsip_tsx_create_uas(&pubsub_module, rdata, &tsx)) != PJ_SUCCESS) {
2819                 return -1;
2820         }
2821
2822         pjsip_tsx_recv_msg(tsx, rdata);
2823
2824         if (pjsip_tsx_send_msg(tsx, tdata) != PJ_SUCCESS) {
2825                 return -1;
2826         }
2827
2828         return 0;
2829 }
2830
2831 static struct ast_sip_publication *publish_request_initial(struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata,
2832         struct ast_sip_publish_handler *handler)
2833 {
2834         struct ast_sip_publication *publication;
2835         char *resource_name;
2836         size_t resource_size;
2837         RAII_VAR(struct ast_sip_publication_resource *, resource, NULL, ao2_cleanup);
2838         struct ast_variable *event_configuration_name = NULL;
2839         pjsip_uri *request_uri;
2840         pjsip_sip_uri *request_uri_sip;
2841         int resp;
2842
2843         request_uri = rdata->msg_info.msg->line.req.uri;
2844
2845         if (!PJSIP_URI_SCHEME_IS_SIP(request_uri) && !PJSIP_URI_SCHEME_IS_SIPS(request_uri)) {
2846                 char uri_str[PJSIP_MAX_URL_SIZE];
2847
2848                 pjsip_uri_print(PJSIP_URI_IN_REQ_URI, request_uri, uri_str, sizeof(uri_str));
2849                 ast_log(LOG_WARNING, "Request URI '%s' is not a sip: or sips: URI.\n", uri_str);
2850                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 416, NULL, NULL, NULL);
2851                 return NULL;
2852         }
2853
2854         request_uri_sip = pjsip_uri_get_uri(request_uri);
2855         resource_size = pj_strlen(&request_uri_sip->user) + 1;
2856         resource_name = ast_alloca(resource_size);
2857         ast_copy_pj_str(resource_name, &request_uri_sip->user, resource_size);
2858
2859         resource = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "inbound-publication", resource_name);
2860         if (!resource) {
2861                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 404, NULL, NULL, NULL);
2862                 return NULL;
2863         }
2864
2865         if (!ast_strlen_zero(resource->endpoint) && strcmp(resource->endpoint, ast_sorcery_object_get_id(endpoint))) {
2866                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
2867                 return NULL;
2868         }
2869
2870         for (event_configuration_name = resource->events; event_configuration_name; event_configuration_name = event_configuration_name->next) {
2871                 if (!strcmp(event_configuration_name->name, handler->event_name)) {
2872                         break;
2873                 }
2874         }
2875
2876         if (!event_configuration_name) {
2877                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 404, NULL, NULL, NULL);
2878                 return NULL;
2879         }
2880
2881         resp = handler->new_publication(endpoint, resource_name, event_configuration_name->value);
2882
2883         if (!PJSIP_IS_STATUS_IN_CLASS(resp, 200)) {
2884                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, resp, NULL, NULL, NULL);
2885                 return NULL;
2886         }
2887
2888         publication = sip_create_publication(endpoint, rdata, S_OR(resource_name, ""), event_configuration_name->value);
2889
2890         if (!publication) {
2891                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 503, NULL, NULL, NULL);
2892                 return NULL;
2893         }
2894
2895         publication->handler = handler;
2896         if (publication->handler->publication_state_change(publication, rdata->msg_info.msg->body,
2897                         AST_SIP_PUBLISH_STATE_INITIALIZED)) {
2898                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2899                 ao2_cleanup(publication);
2900                 return NULL;
2901         }
2902
2903         sip_publication_respond(publication, resp, rdata);
2904
2905         return publication;
2906 }
2907
2908 static int publish_expire_callback(void *data)
2909 {
2910         RAII_VAR(struct ast_sip_publication *, publication, data, ao2_cleanup);
2911
2912         if (publication->handler->publish_expire) {
2913                 publication->handler->publish_expire(publication);
2914         }
2915
2916         return 0;
2917 }
2918
2919 static int publish_expire(const void *data)
2920 {
2921         struct ast_sip_publication *publication = (struct ast_sip_publication*)data;
2922
2923         ao2_unlink(publication->handler->publications, publication);
2924         publication->sched_id = -1;
2925
2926         if (ast_sip_push_task(NULL, publish_expire_callback, publication)) {
2927                 ao2_cleanup(publication);
2928         }
2929
2930         return 0;
2931 }
2932
2933 static pj_bool_t pubsub_on_rx_publish_request(pjsip_rx_data *rdata)
2934 {
2935         pjsip_event_hdr *event_header;
2936         struct ast_sip_publish_handler *handler;
2937         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
2938         char event[32];
2939         static const pj_str_t str_sip_if_match = { "SIP-If-Match", 12 };
2940         pjsip_generic_string_hdr *etag_hdr = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_sip_if_match, NULL);
2941         enum sip_publish_type publish_type;
2942         RAII_VAR(struct ast_sip_publication *, publication, NULL, ao2_cleanup);
2943         int expires = 0, entity_id, response = 0;
2944
2945         endpoint = ast_pjsip_rdata_get_endpoint(rdata);
2946         ast_assert(endpoint != NULL);
2947
2948         event_header = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_event_name, rdata->msg_info.msg->hdr.next);
2949         if (!event_header) {
2950                 ast_log(LOG_WARNING, "Incoming PUBLISH request with no Event header\n");
2951                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 489, NULL, NULL, NULL);
2952                 return PJ_TRUE;
2953         }
2954         ast_copy_pj_str(event, &event_header->event_type, sizeof(event));
2955
2956         handler = find_pub_handler(event);
2957         if (!handler) {
2958                 ast_log(LOG_WARNING, "No registered publish handler for event %s\n", event);
2959                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 489, NULL, NULL, NULL);
2960                 return PJ_TRUE;
2961         }
2962
2963         publish_type = determine_sip_publish_type(rdata, etag_hdr, &expires, &entity_id);
2964
2965         /* If this is not an initial publish ensure that a publication is present */
2966         if ((publish_type != SIP_PUBLISH_INITIAL) && (publish_type != SIP_PUBLISH_UNKNOWN)) {
2967                 if (!(publication = ao2_find(handler->publications, &entity_id, OBJ_KEY | OBJ_UNLINK))) {
2968                         static const pj_str_t str_conditional_request_failed = { "Conditional Request Failed", 26 };
2969
2970                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 412, &str_conditional_request_failed,
2971                                 NULL, NULL);
2972                         return PJ_TRUE;
2973                 }
2974
2975                 /* Per the RFC every response has to have a new entity tag */
2976                 publication->entity_tag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
2977
2978                 /* Update the expires here so that the created responses will contain the correct value */
2979                 publication->expires = expires;
2980         }
2981
2982         switch (publish_type) {
2983                 case SIP_PUBLISH_INITIAL:
2984                         publication = publish_request_initial(endpoint, rdata, handler);
2985                         break;
2986                 case SIP_PUBLISH_REFRESH:
2987                 case SIP_PUBLISH_MODIFY:
2988                         if (handler->publication_state_change(publication, rdata->msg_info.msg->body,
2989                                                 AST_SIP_PUBLISH_STATE_ACTIVE)) {
2990                                 /* If an error occurs we want to terminate the publication */
2991                                 expires = 0;
2992                         }
2993                         response = 200;
2994                         break;
2995                 case SIP_PUBLISH_REMOVE:
2996                         handler->publication_state_change(publication, rdata->msg_info.msg->body,
2997                                         AST_SIP_PUBLISH_STATE_TERMINATED);
2998                         response = 200;
2999                         break;
3000                 case SIP_PUBLISH_UNKNOWN:
3001                 default:
3002                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 400, NULL, NULL, NULL);
3003                         break;
3004         }
3005
3006         if (publication) {
3007                 if (expires) {
3008                         ao2_link(handler->publications, publication);
3009
3010                         AST_SCHED_REPLACE_UNREF(publication->sched_id, sched, expires * 1000, publish_expire, publication,
3011                                                 ao2_ref(publication, -1), ao2_ref(publication, -1), ao2_ref(publication, +1));
3012                 } else {
3013                         AST_SCHED_DEL_UNREF(sched, publication->sched_id, ao2_ref(publication, -1));
3014                 }
3015         }
3016
3017         if (response) {
3018                 sip_publication_respond(publication, response, rdata);
3019         }
3020
3021         return PJ_TRUE;
3022 }
3023
3024 struct ast_sip_endpoint *ast_sip_publication_get_endpoint(struct ast_sip_publication *pub)
3025 {
3026         return pub->endpoint;
3027 }
3028
3029 const char *ast_sip_publication_get_resource(const struct ast_sip_publication *pub)
3030 {
3031         return pub->resource;
3032 }
3033
3034 const char *ast_sip_publication_get_event_configuration(const struct ast_sip_publication *pub)
3035 {
3036         return pub->event_configuration_name;
3037 }
3038
3039 int ast_sip_pubsub_register_body_generator(struct ast_sip_pubsub_body_generator *generator)
3040 {
3041         struct ast_sip_pubsub_body_generator *existing;
3042         pj_str_t accept;
3043         pj_size_t accept_len;
3044
3045         existing = find_body_generator_type_subtype(generator->type, generator->subtype);
3046         if (existing) {
3047                 ast_log(LOG_WARNING, "Cannot register body generator of %s/%s."
3048                                 "One is already registered.\n", generator->type, generator->subtype);
3049                 return -1;
3050         }
3051
3052         AST_RWLIST_WRLOCK(&body_generators);
3053         AST_LIST_INSERT_HEAD(&body_generators, generator, list);
3054         AST_RWLIST_UNLOCK(&body_generators);
3055
3056         /* Lengths of type and subtype plus a slash. */
3057         accept_len = strlen(generator->type) + strlen(generator->subtype) + 1;
3058
3059         /* Add room for null terminator that sprintf() will set. */
3060         pj_strset(&accept, ast_alloca(accept_len + 1), accept_len);
3061         sprintf((char *) pj_strbuf(&accept), "%s/%s", generator->type, generator->subtype);/* Safe */
3062
3063         pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), &pubsub_module,
3064                         PJSIP_H_ACCEPT, NULL, 1, &accept);
3065
3066         return 0;
3067 }
3068
3069 void ast_sip_pubsub_unregister_body_generator(struct ast_sip_pubsub_body_generator *generator)
3070 {
3071         struct ast_sip_pubsub_body_generator *iter;
3072         SCOPED_LOCK(lock, &body_generators, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
3073
3074         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&body_generators, iter, list) {
3075                 if (iter == generator) {
3076                         AST_LIST_REMOVE_CURRENT(list);
3077                         break;
3078                 }
3079         }
3080         AST_RWLIST_TRAVERSE_SAFE_END;
3081 }
3082
3083 int ast_sip_pubsub_register_body_supplement(struct ast_sip_pubsub_body_supplement *supplement)
3084 {
3085         AST_RWLIST_WRLOCK(&body_supplements);
3086         AST_RWLIST_INSERT_TAIL(&body_supplements, supplement, list);
3087         AST_RWLIST_UNLOCK(&body_supplements);
3088
3089         return 0;
3090 }
3091
3092 void ast_sip_pubsub_unregister_body_supplement(struct ast_sip_pubsub_body_supplement *supplement)
3093 {
3094         struct ast_sip_pubsub_body_supplement *iter;
3095         SCOPED_LOCK(lock, &body_supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
3096
3097         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&body_supplements, iter, list) {
3098                 if (iter == supplement) {
3099                         AST_LIST_REMOVE_CURRENT(list);
3100                         break;
3101                 }
3102         }
3103         AST_RWLIST_TRAVERSE_SAFE_END;
3104 }
3105
3106 const char *ast_sip_subscription_get_body_type(struct ast_sip_subscription *sub)
3107 {
3108         return sub->body_generator->type;
3109 }
3110
3111 const char *ast_sip_subscription_get_body_subtype(struct ast_sip_subscription *sub)
3112 {
3113         return sub->body_generator->subtype;
3114 }
3115
3116 int ast_sip_pubsub_generate_body_content(const char *type, const char *subtype,
3117                 struct ast_sip_body_data *data, struct ast_str **str)
3118 {
3119         struct ast_sip_pubsub_body_supplement *supplement;
3120         struct ast_sip_pubsub_body_generator *generator;
3121         int res = 0;
3122         void *body;
3123
3124         generator = find_body_generator_type_subtype(type, subtype);
3125         if (!generator) {
3126                 ast_log(LOG_WARNING, "Unable to find a body generator for %s/%s\n",
3127                                 type, subtype);
3128                 return -1;
3129         }
3130
3131         if (strcmp(data->body_type, generator->body_type)) {
3132                 ast_log(LOG_WARNING, "Body generator does not accept the type of data provided\n");
3133                 return -1;
3134         }
3135
3136         body = generator->allocate_body(data->body_data);
3137         if (!body) {
3138                 ast_log(LOG_WARNING, "Unable to allocate a NOTIFY body of type %s/%s\n",
3139                                 type, subtype);
3140                 return -1;
3141         }
3142
3143         if (generator->generate_body_content(body, data->body_data)) {
3144                 res = -1;
3145                 goto end;
3146         }
3147
3148         AST_RWLIST_RDLOCK(&body_supplements);
3149         AST_RWLIST_TRAVERSE(&body_supplements, supplement, list) {
3150                 if (!strcmp(generator->type, supplement->type) &&
3151                                 !strcmp(generator->subtype, supplement->subtype)) {
3152                         res = supplement->supplement_body(body, data->body_data);
3153                         if (res) {
3154                                 break;
3155                         }
3156                 }
3157         }
3158         AST_RWLIST_UNLOCK(&body_supplements);
3159
3160         if (!res) {
3161                 generator->to_string(body, str);
3162         }
3163
3164 end:
3165         if (generator->destroy_body) {
3166                 generator->destroy_body(body);
3167         }
3168
3169         return res;
3170 }
3171
3172 static pj_bool_t pubsub_on_rx_request(pjsip_rx_data *rdata)
3173 {
3174         if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, pjsip_get_subscribe_method())) {
3175                 return pubsub_on_rx_subscribe_request(rdata);
3176         } else if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_publish_method)) {
3177                 return pubsub_on_rx_publish_request(rdata);
3178         }
3179
3180         return PJ_FALSE;
3181 }
3182
3183 static void set_state_terminated(struct ast_sip_subscription *sub)
3184 {
3185         int i;
3186
3187         sub->subscription_state = PJSIP_EVSUB_STATE_TERMINATED;
3188         for (i = 0; i < AST_VECTOR_SIZE(&sub->children); ++i) {
3189                 set_state_terminated(AST_VECTOR_GET(&sub->children, i));
3190         }
3191 }
3192
3193 /* XXX This function and serialized_pubsub_on_rx_refresh are nearly identical */
3194 static int serialized_pubsub_on_server_timeout(void *userdata)
3195 {
3196         struct sip_subscription_tree *sub_tree = userdata;
3197
3198         pjsip_dlg_inc_lock(sub_tree->dlg);
3199         if (!sub_tree->evsub) {
3200                 pjsip_dlg_dec_lock(sub_tree->dlg);
3201                 return 0;
3202         }
3203         set_state_terminated(sub_tree->root);
3204         send_notify(sub_tree, 1);
3205         ast_test_suite_event_notify("SUBSCRIPTION_TERMINATED",
3206                         "Resource: %s",
3207                         sub_tree->root->resource);
3208
3209         pjsip_dlg_dec_lock(sub_tree->dlg);
3210         ao2_cleanup(sub_tree);
3211         return 0;
3212 }
3213
3214 /*!
3215  * \brief PJSIP callback when underlying SIP subscription changes state
3216  *
3217  * This callback is a bit of a mess, because it's not always called when
3218  * you might expect it to be, and it can be called multiple times for the
3219  * same state.
3220  *
3221  * For instance, this function is not called at all when an incoming SUBSCRIBE
3222  * arrives to refresh a subscription. That makes sense in a way, since the
3223  * subscription state has not made a change; it was active and remains active.
3224  *
3225  * However, if an incoming SUBSCRIBE arrives to end a subscription, then this
3226  * will be called into once upon receiving the SUBSCRIBE (after the call to
3227  * pubsub_on_rx_refresh) and again when sending a NOTIFY to end the subscription.
3228  * In both cases, the apparent state of the subscription is "terminated".
3229  *
3230  * However, the double-terminated state changes don't happen in all cases. For
3231  * instance, if a subscription expires, then the only time this callback is
3232  * called is when we send the NOTIFY to end the subscription.
3233  *
3234  * As far as state changes are concerned, we only ever care about transitions
3235  * to the "terminated" state. The action we take here is dependent on the
3236  * conditions behind why the state change to "terminated" occurred. If the
3237  * state change has occurred because we are sending a NOTIFY to end the
3238  * subscription, we consider this to be the final hurrah of the subscription
3239  * and take measures to start shutting things down. If the state change to
3240  * terminated occurs for a different reason (e.g. transaction timeout,
3241  * incoming SUBSCRIBE to end the subscription), then we push a task to
3242  * send out a NOTIFY. When that NOTIFY is sent, this callback will be
3243  * called again and we will actually shut down the subscription. The
3244  * subscription tree's last_notify field let's us know if this is being
3245  * called as a result of a terminating NOTIFY or not.
3246  *
3247  * There is no guarantee that this function will be called from a serializer
3248  * thread since it can be called due to a transaction timeout. Therefore
3249  * synchronization primitives are necessary to ensure that no operations
3250  * step on each others' toes. The dialog lock is always held when this
3251  * callback is called, so we ensure that relevant structures that may
3252  * be touched in this function are always protected by the dialog lock
3253  * elsewhere as well. The dialog lock in particular protects
3254  *
3255  * \li The subscription tree's last_notify field
3256  * \li The subscription tree's evsub pointer
3257  */
3258 static void pubsub_on_evsub_state(pjsip_evsub *evsub, pjsip_event *event)
3259 {
3260         struct sip_subscription_tree *sub_tree;
3261
3262         ast_debug(3, "on_evsub_state called with state %s\n", pjsip_evsub_get_state_name(evsub));
3263
3264         if (pjsip_evsub_get_state(evsub) != PJSIP_EVSUB_STATE_TERMINATED) {
3265                 return;
3266         }
3267
3268         sub_tree = pjsip_evsub_get_mod_data(evsub, pubsub_module.id);
3269         if (!sub_tree) {
3270                 return;
3271         }
3272
3273         if (!sub_tree->last_notify) {
3274                 if (ast_sip_push_task(sub_tree->serializer, serialized_pubsub_on_server_timeout, ao2_bump(sub_tree))) {
3275                         ast_log(LOG_ERROR, "Failed to push task to send final NOTIFY.\n");
3276                         ao2_ref(sub_tree, -1);
3277                 } else {
3278                         return;
3279                 }
3280         }
3281
3282         pjsip_evsub_set_mod_data(evsub, pubsub_module.id, NULL);
3283         sub_tree->evsub = NULL;
3284         shutdown_subscriptions(sub_tree->root);
3285         /* Remove evsub's reference to the sub_tree */
3286         ao2_ref(sub_tree, -1);
3287 }
3288
3289 static int serialized_pubsub_on_rx_refresh(void *userdata)
3290 {
3291         struct sip_subscription_tree *sub_tree = userdata;
3292
3293         pjsip_dlg_inc_lock(sub_tree->dlg);
3294         if (!sub_tree->evsub) {
3295                 pjsip_dlg_dec_lock(sub_tree->dlg);
3296                 return 0;
3297         }
3298
3299         if (pjsip_evsub_get_state(sub_tree->evsub) == PJSIP_EVSUB_STATE_TERMINATED) {
3300                 set_state_terminated(sub_tree->root);
3301         }
3302
3303         send_notify(sub_tree, 1);
3304
3305         ast_test_suite_event_notify(sub_tree->root->subscription_state == PJSIP_EVSUB_STATE_TERMINATED ?
3306                         "SUBSCRIPTION_TERMINATED" : "SUBSCRIPTION_REFRESHED",
3307                         "Resource: %s", sub_tree->root->resource);
3308
3309         pjsip_dlg_dec_lock(sub_tree->dlg);
3310         ao2_cleanup(sub_tree);
3311         return 0;
3312 }
3313
3314 /*!
3315  * \brief Called whenever an in-dialog SUBSCRIBE is received
3316  *
3317  * This includes both SUBSCRIBE requests that actually refresh the subscription
3318  * as well as SUBSCRIBE requests that end the subscription.
3319  *
3320  * In the case where the SUBSCRIBE is actually refreshing the subscription we
3321  * push a task to send an appropriate NOTIFY request. In the case where the
3322  * SUBSCRIBE is ending the subscription, we let the pubsub_on_evsub_state
3323  * callback take care of sending the terminal NOTIFY request instead.
3324  */
3325 static void pubsub_on_rx_refresh(pjsip_evsub *evsub, pjsip_rx_data *rdata,
3326                 int *p_st_code, pj_str_t **p_st_text, pjsip_hdr *res_hdr, pjsip_msg_body **p_body)
3327 {
3328         struct sip_subscription_tree *sub_tree;
3329
3330         sub_tree = pjsip_evsub_get_mod_data(evsub, pubsub_module.id);
3331         if (!sub_tree) {
3332                 return;
3333         }
3334
3335         /* PJSIP will set the evsub's state to terminated before calling into this function
3336          * if the Expires value of the incoming SUBSCRIBE is 0.
3337          */
3338         if (pjsip_evsub_get_state(sub_tree->evsub) != PJSIP_EVSUB_STATE_TERMINATED) {
3339                 if (ast_sip_push_task(sub_tree->serializer, serialized_pubsub_on_rx_refresh, ao2_bump(sub_tree))) {
3340                         /* If we can't push the NOTIFY refreshing task...we'll just go with it. */
3341                         ao2_ref(sub_tree, -1);
3342                 }
3343         }
3344
3345         if (sub_tree->is_list) {
3346                 pj_list_insert_before(res_hdr, create_require_eventlist(rdata->tp_info.pool));
3347         }
3348 }
3349
3350 static void pubsub_on_rx_notify(pjsip_evsub *evsub, pjsip_rx_data *rdata, int *p_st_code,
3351                 pj_str_t **p_st_text, pjsip_hdr *res_hdr, pjsip_msg_body **p_body)
3352 {
3353         struct ast_sip_subscription *sub = pjsip_evsub_get_mod_data(evsub, pubsub_module.id);
3354
3355         if (!sub) {
3356                 return;
3357         }
3358
3359         sub->handler->subscriber->state_change(sub, rdata->msg_info.msg->body,
3360                         pjsip_evsub_get_state(evsub));
3361 }
3362
3363 static int serialized_pubsub_on_client_refresh(void *userdata)
3364 {
3365         struct sip_subscription_tree *sub_tree = userdata;
3366         pjsip_tx_data *tdata;
3367
3368         if (pjsip_evsub_initiate(sub_tree->evsub, NULL, -1, &tdata) == PJ_SUCCESS) {
3369                 pjsip_evsub_send_request(sub_tree->evsub, tdata);
3370         } else {
3371                 pjsip_evsub_terminate(sub_tree->evsub, PJ_TRUE);
3372         }
3373         ao2_cleanup(sub_tree);
3374         return 0;
3375 }
3376
3377 static void pubsub_on_client_refresh(pjsip_evsub *evsub)
3378 {
3379         struct sip_subscription_tree *sub_tree = pjsip_evsub_get_mod_data(evsub, pubsub_module.id);
3380
3381         ao2_ref(sub_tree, +1);
3382         ast_sip_push_task(sub_tree->serializer, serialized_pubsub_on_client_refresh, sub_tree);
3383 }
3384
3385 static void pubsub_on_server_timeout(pjsip_evsub *evsub)
3386 {
3387
3388         struct sip_subscription_tree *sub_tree = pjsip_evsub_get_mod_data(evsub, pubsub_module.id);
3389         if (!sub_tree) {
3390                 /* PJSIP does not terminate the server timeout timer when a SUBSCRIBE
3391                  * with Expires: 0 arrives to end a subscription, nor does it terminate
3392                  * this timer when we send a NOTIFY request in response to receiving such
3393                  * a SUBSCRIBE. PJSIP does not stop the server timeout timer until the
3394                  * NOTIFY transaction has finished (either through receiving a response
3395                  * or through a transaction timeout).
3396                  *
3397                  * Therefore, it is possible that we can be told that a server timeout
3398                  * occurred after we already thought that the subscription had been
3399                  * terminated. In such a case, we will have already removed the sub_tree
3400                  * from the evsub's mod_data array.
3401                  */
3402         return;
3403         }
3404
3405         ao2_ref(sub_tree, +1);
3406         ast_sip_push_task(sub_tree->serializer, serialized_pubsub_on_server_timeout, sub_tree);
3407 }
3408
3409 static int ami_subscription_detail(struct sip_subscription_tree *sub_tree,
3410                                    struct ast_sip_ami *ami,
3411                                    const char *event)
3412 {
3413         struct ast_str *buf;
3414
3415         buf = ast_sip_create_ami_event(event, ami);
3416         if (!buf) {
3417                 return -1;
3418         }
3419
3420         sip_subscription_to_ami(sub_tree, &buf);
3421         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
3422         ast_free(buf);
3423         return 0;
3424 }
3425
3426 static int ami_subscription_detail_inbound(struct sip_subscription_tree *sub_tree, void *arg)
3427 {
3428         return sub_tree->role == AST_SIP_NOTIFIER ? ami_subscription_detail(
3429                 sub_tree, arg, "InboundSubscriptionDetail") : 0;
3430 }
3431
3432 static int ami_subscription_detail_outbound(struct sip_subscription_tree *sub_tree, void *arg)
3433 {
3434         return sub_tree->role == AST_SIP_SUBSCRIBER ? ami_subscription_detail(
3435                 sub_tree, arg, "OutboundSubscriptionDetail") : 0;
3436 }
3437
3438 static int ami_show_subscriptions_inbound(struct mansession *s, const struct message *m)
3439 {
3440         struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"), };
3441         int num;
3442
3443         astman_send_listack(s, m, "Following are Events for each inbound Subscription",
3444                 "start");
3445
3446         num = for_each_subscription(ami_subscription_detail_inbound, &ami);
3447
3448         astman_send_list_complete_start(s, m, "InboundSubscriptionDetailComplete", num);
3449         astman_send_list_complete_end(s);
3450         return 0;
3451 }
3452
3453 static int ami_show_subscriptions_outbound(struct mansession *s, const struct message *m)
3454 {
3455         struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"), };
3456         int num;
3457
3458         astman_send_listack(s, m, "Following are Events for each outbound Subscription",
3459                 "start");
3460
3461         num = for_each_subscription(ami_subscription_detail_outbound, &ami);
3462
3463         astman_send_list_complete_start(s, m, "OutboundSubscriptionDetailComplete", num);
3464         astman_send_list_complete_end(s);
3465         return 0;
3466 }
3467
3468 static int format_ami_resource_lists(void *obj, void *arg, int flags)
3469 {
3470         struct resource_list *list = obj;
3471         struct ast_sip_ami *ami = arg;
3472         struct ast_str *buf;
3473
3474         buf = ast_sip_create_ami_event("ResourceListDetail", ami);
3475         if (!buf) {
3476                 return CMP_STOP;
3477         }
3478
3479         if (ast_sip_sorcery_object_to_ami(list, &buf)) {
3480                 ast_free(buf);
3481                 return CMP_STOP;
3482         }
3483         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
3484
3485         ast_free(buf);
3486         return 0;
3487 }
3488
3489 static int ami_show_resource_lists(struct mansession *s, const struct message *m)
3490 {
3491         struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"), };
3492         int num;
3493         struct ao2_container *lists;
3494
3495         lists = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "resource_list",
3496                         AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
3497
3498         if (!lists || !(num = ao2_container_count(lists))) {
3499                 astman_send_error(s, m, "No resource lists found\n");
3500                 return 0;
3501         }
3502
3503         astman_send_listack(s, m, "A listing of resource lists follows, presented as ResourceListDetail events",
3504                 "start");
3505
3506         ao2_callback(lists, OBJ_NODATA, format_ami_resource_lists, &ami);
3507
3508         astman_send_list_complete_start(s, m, "ResourceListDetailComplete", num);
3509         astman_send_list_complete_end(s);
3510         return 0;
3511 }
3512
3513 #define AMI_SHOW_SUBSCRIPTIONS_INBOUND "PJSIPShowSubscriptionsInbound"
3514 #define AMI_SHOW_SUBSCRIPTIONS_OUTBOUND "PJSIPShowSubscriptionsOutbound"
3515
3516 static int persistence_endpoint_str2struct(const struct aco_option *opt, struct ast_variable *var, void *obj)
3517 {
3518         struct subscription_persistence *persistence = obj;
3519
3520         persistence->endpoint = ast_strdup(var->value);
3521         return 0;
3522 }
3523
3524 static int persistence_endpoint_struct2str(const void *obj, const intptr_t *args, char **buf)
3525 {
3526         const struct subscription_persistence *persistence = obj;
3527
3528         *buf = ast_strdup(persistence->endpoint);
3529         return 0;
3530 }
3531
3532 static int persistence_tag_str2struct(const struct aco_option *opt, struct ast_variable *var, void *obj)
3533 {
3534         struct subscription_persistence *persistence = obj;
3535
3536         persistence->tag = ast_strdup(var->value);
3537         return 0;
3538 }
3539
3540 static int persistence_tag_struct2str(const void *obj, const intptr_t *args, char **buf)
3541 {
3542         const struct subscription_persistence *persistence = obj;
3543
3544         *buf = ast_strdup(persistence->tag);
3545         return 0;
3546 }
3547
3548 static int persistence_expires_str2struct(const struct aco_option *opt, struct ast_variable *var, void *obj)
3549 {
3550         struct subscription_persistence *persistence = obj;
3551         return ast_get_timeval(var->value, &persistence->expires, ast_tv(0, 0), NULL);
3552 }
3553
3554 static int persistence_expires_struct2str(const void *obj, const intptr_t *args, char **buf)
3555 {
3556         const struct subscription_persistence *persistence = obj;
3557         return (ast_asprintf(buf, "%ld", persistence->expires.tv_sec) < 0) ? -1 : 0;
3558 }
3559
3560 #define RESOURCE_LIST_INIT_SIZE 4
3561
3562 static void resource_list_destructor(void *obj)
3563 {
3564         struct resource_list *list = obj;
3565         int i;
3566
3567         for (i = 0; i < AST_VECTOR_SIZE(&list->items); ++i) {
3568                 ast_free((char *) AST_VECTOR_GET(&list->items, i));
3569         }
3570
3571         AST_VECTOR_FREE(&list->items);
3572 }
3573
3574 static void *resource_list_alloc(const char *name)
3575 {
3576         struct resource_list *list;
3577
3578         list = ast_sorcery_generic_alloc(sizeof(*list), resource_list_destructor);
3579         if (!list) {
3580                 return NULL;
3581         }
3582
3583         if (AST_VECTOR_INIT(&list->items, RESOURCE_LIST_INIT_SIZE)) {
3584                 ao2_cleanup(list);
3585                 return NULL;
3586         }
3587
3588         return list;
3589 }
3590
3591 static int item_in_vector(const struct resource_list *list, const char *item)
3592 {
3593         int i;
3594
3595         for (i = 0; i < AST_VECTOR_SIZE(&list->items); ++i) {
3596                 if (!strcmp(item, AST_VECTOR_GET(&list->items, i))) {
3597                         return 1;
3598                 }
3599         }
3600
3601         return 0;
3602 }
3603
3604 static int list_item_handler(const struct aco_option *opt,
3605                 struct ast_variable *var, void *obj)
3606 {
3607         struct resource_list *list = obj;
3608         char *items = ast_strdupa(var->value);
3609         char *item;
3610
3611         while ((item = strsep(&items, ","))) {
3612                 if (item_in_vector(list, item)) {
3613                         ast_log(LOG_WARNING, "Ignoring duplicated list item '%s'\n", item);
3614                         continue;
3615                 }
3616                 if (AST_VECTOR_APPEND(&list->items, ast_strdup(item))) {
3617                         return -1;
3618                 }
3619         }
3620
3621         return 0;
3622 }
3623
3624 static int list_item_to_str(const void *obj, const intptr_t *args, char **buf)
3625 {
3626         const struct resource_list *list = obj;
3627         int i;
3628         struct ast_str *str = ast_str_create(32);
3629
3630         for (i = 0; i < AST_VECTOR_SIZE(&list->items); ++i) {
3631                 ast_str_append(&str, 0, "%s,", AST_VECTOR_GET(&list->items, i));
3632         }
3633
3634         /* Chop off trailing comma */
3635         ast_str_truncate(str, -1);
3636         *buf = ast_strdup(ast_str_buffer(str));
3637         ast_free(str);
3638         return 0;
3639 }
3640
3641 static int resource_list_apply_handler(const struct ast_sorcery *sorcery, void *obj)
3642 {
3643         struct resource_list *list = obj;
3644
3645         if (ast_strlen_zero(list->event)) {
3646                 ast_log(LOG_WARNING, "Resource list '%s' has no event set\n",
3647                                 ast_sorcery_object_get_id(list));
3648                 return -1;
3649         }
3650
3651         if (AST_VECTOR_SIZE(&list->items) == 0) {
3652                 ast_log(LOG_WARNING, "Resource list '%s' has no list items\n",
3653                                 ast_sorcery_object_get_id(list));
3654                 return -1;
3655         }
3656
3657         return 0;
3658 }
3659
3660 static int apply_list_configuration(struct ast_sorcery *sorcery)
3661 {
3662         ast_sorcery_apply_default(sorcery, "resource_list", "config",
3663                         "pjsip.conf,criteria=type=resource_list");
3664         if (ast_sorcery_object_register(sorcery, "resource_list", resource_list_alloc,
3665                                 NULL, resource_list_apply_handler)) {
3666                 return -1;
3667         }
3668
3669         ast_sorcery_object_field_register(sorcery, "resource_list", "type", "",
3670                         OPT_NOOP_T, 0, 0);
3671         ast_sorcery_object_field_register(sorcery, "resource_list", "event", "",
3672                         OPT_CHAR_ARRAY_T, 1, CHARFLDSET(struct resource_list, event));
3673         ast_sorcery_object_field_register(sorcery, "resource_list", "full_state", "no",
3674                         OPT_BOOL_T, 1, FLDSET(struct resource_list, full_state));
3675         ast_sorcery_object_field_register(sorcery, "resource_list", "notification_batch_interval",
3676                         "0", OPT_UINT_T, 0, FLDSET(struct resource_list, notification_batch_interval));
3677         ast_sorcery_object_field_register_custom(sorcery, "resource_list", "list_item",
3678                         "", list_item_handler, list_item_to_str, NULL, 0, 0);
3679
3680         ast_sorcery_reload_object(sorcery, "resource_list");
3681
3682         return 0;
3683 }
3684
3685 #ifdef TEST_FRAMEWORK
3686
3687 /*!
3688  * \brief "bad" resources
3689  *
3690  * These are resources that the test handler will reject subscriptions to.
3691  */
3692 const char *bad_resources[] = {
3693         "coconut",
3694         "cilantro",
3695         "olive",
3696         "cheese",
3697 };
3698
3699 /*!
3700  * \brief new_subscribe callback for unit tests
3701  *
3702  * Will give a 200 OK response to any resource except the "bad" ones.
3703  */
3704 static int test_new_subscribe(struct ast_sip_endpoint *endpoint, const char *resource)
3705 {
3706         int i;
3707
3708         for (i = 0; i < ARRAY_LEN(bad_resources); ++i) {
3709                 if (!strcmp(resource, bad_resources[i])) {
3710                         return 400;
3711                 }
3712         }
3713
3714         return 200;
3715 }
3716
3717 /*!
3718  * \brief Subscription notifier for unit tests.
3719  *
3720  * Since unit tests are only concerned with building a resource tree,
3721  * only the new_subscribe callback needs to be defined.
3722  */
3723 struct ast_sip_notifier test_notifier = {
3724         .new_subscribe = test_new_subscribe,
3725 };
3726
3727 /*!
3728  * \brief Subscription handler for unit tests.
3729  */
3730 struct ast_sip_subscription_handler test_handler = {
3731         .event_name = "test",
3732         .notifier = &test_notifier,
3733 };
3734
3735 /*!
3736  * \brief Set properties on an allocated resource list
3737  *
3738  * \param list The list to set details on.
3739  * \param event The list's event.
3740  * \param resources Array of resources to add to the list.
3741  * \param num_resources Number of resources in the array.
3742  * \retval 0 Success
3743  * \retval non-zero Failure
3744  */
3745 static int populate_list(struct resource_list *list, const char *event, const char **resources, size_t num_resources)
3746 {
3747         int i;
3748
3749         ast_copy_string(list->event, event, sizeof(list->event));
3750
3751         for (i = 0; i < num_resources; ++i) {
3752                 if (AST_VECTOR_APPEND(&list->items, ast_strdup(resources[i]))) {
3753                         return -1;
3754                 }
3755         }
3756         return 0;
3757 }
3758
3759 /*!
3760  * \brief RAII callback to destroy a resource list
3761  */
3762 static void cleanup_resource_list(struct resource_list *list)
3763 {
3764         if (!list) {
3765                 return;
3766         }
3767
3768         ast_sorcery_delete(ast_sip_get_sorcery(), list);
3769         ao2_cleanup(list);
3770 }
3771
3772 /*!
3773  * \brief allocate a resource list, store it in sorcery, and set its details
3774  *
3775  * \param test The unit test. Used for logging status messages.
3776  * \param list_name The name of the list to create.
3777  * \param event The event the list services
3778  * \param resources Array of resources to apply to the list
3779  * \param num_resources The number of resources in the array
3780  * \retval NULL Failed to allocate or populate list
3781  * \retval non-NULL The created list
3782  */
3783 static struct resource_list *create_resource_list(struct ast_test *test,
3784                 const char *list_name, const char *event, const char **resources, size_t num_resources)