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