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