Merge "chan_pjsip: Relock correct channel during "fax" redirect."
[asterisk/asterisk.git] / res / res_calendar.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2008 - 2009, Digium, Inc.
5  *
6  * Terry Wilson <twilson@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 /*! \file
20  * \brief Calendaring API
21  *
22  * \todo Support responding to a meeting invite
23  * \todo Support writing attendees
24  */
25
26 /*! \li \ref res_calendar.c uses the configuration file \ref calendar.conf
27  * \addtogroup configuration_file Configuration Files
28  */
29
30 /*!
31  * \page calendar.conf calendar.conf
32  * \verbinclude calendar.conf.sample
33  */
34
35 /*** MODULEINFO
36         <support_level>extended</support_level>
37  ***/
38
39 #include "asterisk.h"
40
41 #include "asterisk/_private.h"
42 #include "asterisk/channel.h"
43 #include "asterisk/calendar.h"
44 #include "asterisk/utils.h"
45 #include "asterisk/astobj2.h"
46 #include "asterisk/module.h"
47 #include "asterisk/config.h"
48 #include "asterisk/channel.h"
49 #include "asterisk/devicestate.h"
50 #include "asterisk/linkedlists.h"
51 #include "asterisk/sched.h"
52 #include "asterisk/dial.h"
53 #include "asterisk/cli.h"
54 #include "asterisk/pbx.h"
55 #include "asterisk/app.h"
56 #include "asterisk/format_cache.h"
57
58 /*** DOCUMENTATION
59         <function name="CALENDAR_BUSY" language="en_US">
60                 <synopsis>
61                         Determine if the calendar is marked busy at this time.
62                 </synopsis>
63                 <syntax>
64                         <parameter name="calendar" required="true" />
65                 </syntax>
66                 <description>
67                         <para>Check the specified calendar's current busy status.</para>
68                 </description>
69                 <see-also>
70                         <ref type="function">CALENDAR_EVENT</ref>
71                         <ref type="function">CALENDAR_QUERY</ref>
72                         <ref type="function">CALENDAR_QUERY_RESULT</ref>
73                         <ref type="function">CALENDAR_WRITE</ref>
74                 </see-also>
75         </function>
76         <function name="CALENDAR_EVENT" language="en_US">
77                 <synopsis>
78                         Get calendar event notification data from a notification call.
79                 </synopsis>
80                 <syntax>
81                         <parameter name="field" required="true">
82                                 <enumlist>
83                                         <enum name="summary"><para>The VEVENT SUMMARY property or Exchange event 'subject'</para></enum>
84                                         <enum name="description"><para>The text description of the event</para></enum>
85                                         <enum name="organizer"><para>The organizer of the event</para></enum>
86                                         <enum name="location"><para>The location of the eventt</para></enum>
87                                         <enum name="categories"><para>The categories of the event</para></enum>
88                                         <enum name="priority"><para>The priority of the event</para></enum>
89                                         <enum name="calendar"><para>The name of the calendar associated with the event</para></enum>
90                                         <enum name="uid"><para>The unique identifier for this event</para></enum>
91                                         <enum name="start"><para>The start time of the event</para></enum>
92                                         <enum name="end"><para>The end time of the event</para></enum>
93                                         <enum name="busystate"><para>The busy state of the event 0=FREE, 1=TENTATIVE, 2=BUSY</para></enum>
94                                 </enumlist>
95                         </parameter>
96                 </syntax>
97                 <description>
98                         <para>Whenever a calendar event notification call is made, the event data
99                         may be accessed with this function.</para>
100                 </description>
101                 <see-also>
102                         <ref type="function">CALENDAR_BUSY</ref>
103                         <ref type="function">CALENDAR_QUERY</ref>
104                         <ref type="function">CALENDAR_QUERY_RESULT</ref>
105                         <ref type="function">CALENDAR_WRITE</ref>
106                 </see-also>
107         </function>
108         <function name="CALENDAR_QUERY" language="en_US">
109                 <synopsis>Query a calendar server and store the data on a channel
110                 </synopsis>
111                 <syntax>
112                         <parameter name="calendar" required="true">
113                                 <para>The calendar that should be queried</para>
114                         </parameter>
115                         <parameter name="start" required="false">
116                                 <para>The start time of the query (in seconds since epoch)</para>
117                         </parameter>
118                         <parameter name="end" required="false">
119                                 <para>The end time of the query (in seconds since epoch)</para>
120                         </parameter>
121                 </syntax>
122                 <description>
123                         <para>Get a list of events in the currently accessible timeframe of the <replaceable>calendar</replaceable>
124                         The function returns the id for accessing the result with CALENDAR_QUERY_RESULT()</para>
125                 </description>
126                 <see-also>
127                         <ref type="function">CALENDAR_BUSY</ref>
128                         <ref type="function">CALENDAR_EVENT</ref>
129                         <ref type="function">CALENDAR_QUERY_RESULT</ref>
130                         <ref type="function">CALENDAR_WRITE</ref>
131                 </see-also>
132         </function>
133         <function name="CALENDAR_QUERY_RESULT" language="en_US">
134                 <synopsis>
135                         Retrieve data from a previously run CALENDAR_QUERY() call
136                 </synopsis>
137                 <syntax>
138                         <parameter name="id" required="true">
139                                 <para>The query ID returned by <literal>CALENDAR_QUERY</literal></para>
140                         </parameter>
141                         <parameter name="field" required="true">
142                                 <enumlist>
143                                         <enum name="getnum"><para>number of events occurring during time range</para></enum>
144                                         <enum name="summary"><para>A summary of the event</para></enum>
145                                         <enum name="description"><para>The full event description</para></enum>
146                                         <enum name="organizer"><para>The event organizer</para></enum>
147                                         <enum name="location"><para>The event location</para></enum>
148                                         <enum name="categories"><para>The categories of the event</para></enum>
149                                         <enum name="priority"><para>The priority of the event</para></enum>
150                                         <enum name="calendar"><para>The name of the calendar associted with the event</para></enum>
151                                         <enum name="uid"><para>The unique identifier for the event</para></enum>
152                                         <enum name="start"><para>The start time of the event (in seconds since epoch)</para></enum>
153                                         <enum name="end"><para>The end time of the event (in seconds since epoch)</para></enum>
154                                         <enum name="busystate"><para>The busy status of the event 0=FREE, 1=TENTATIVE, 2=BUSY</para></enum>
155                                 </enumlist>
156                         </parameter>
157                         <parameter name="entry" required="false" default="1">
158                                 <para>Return data from a specific event returned by the query</para>
159                         </parameter>
160                 </syntax>
161                 <description>
162                         <para>After running CALENDAR_QUERY and getting a result <replaceable>id</replaceable>, calling
163                         <literal>CALENDAR_QUERY</literal> with that <replaceable>id</replaceable> and a <replaceable>field</replaceable>
164                         will return the data for that field. If multiple events matched the query, and <replaceable>entry</replaceable>
165                         is provided, information from that event will be returned.</para>
166                 </description>
167                 <see-also>
168                         <ref type="function">CALENDAR_BUSY</ref>
169                         <ref type="function">CALENDAR_EVENT</ref>
170                         <ref type="function">CALENDAR_QUERY</ref>
171                         <ref type="function">CALENDAR_WRITE</ref>
172                 </see-also>
173         </function>
174         <function name="CALENDAR_WRITE" language="en_US">
175                 <synopsis>Write an event to a calendar</synopsis>
176                 <syntax>
177                         <parameter name="calendar" required="true">
178                                 <para>The calendar to write to</para>
179                         </parameter>
180                         <parameter name="field" multiple="true" required="true">
181                                 <enumlist>
182                                         <enum name="summary"><para>A summary of the event</para></enum>
183                                         <enum name="description"><para>The full event description</para></enum>
184                                         <enum name="organizer"><para>The event organizer</para></enum>
185                                         <enum name="location"><para>The event location</para></enum>
186                                         <enum name="categories"><para>The categories of the event</para></enum>
187                                         <enum name="priority"><para>The priority of the event</para></enum>
188                                         <enum name="uid"><para>The unique identifier for the event</para></enum>
189                                         <enum name="start"><para>The start time of the event (in seconds since epoch)</para></enum>
190                                         <enum name="end"><para>The end time of the event (in seconds since epoch)</para></enum>
191                                         <enum name="busystate"><para>The busy status of the event 0=FREE, 1=TENTATIVE, 2=BUSY</para></enum>
192                                 </enumlist>
193                         </parameter>
194                 </syntax>
195                 <description>
196                         <para>Example: CALENDAR_WRITE(calendar,field1,field2,field3)=val1,val2,val3</para>
197                         <para>The field and value arguments can easily be set/passed using the HASHKEYS() and HASH() functions</para>
198                         <variablelist>
199                                 <variable name="CALENDAR_SUCCESS">
200                                         <para>The status of the write operation to the calendar</para>
201                                         <value name="1" >
202                                                 The event was successfully written to the calendar.
203                                         </value>
204                                         <value name="0" >
205                                                 The event was not written to the calendar due to network issues, permissions, etc.
206                                         </value>
207                                 </variable>
208                         </variablelist>
209
210                 </description>
211                 <see-also>
212                         <ref type="function">CALENDAR_BUSY</ref>
213                         <ref type="function">CALENDAR_EVENT</ref>
214                         <ref type="function">CALENDAR_QUERY</ref>
215                         <ref type="function">CALENDAR_QUERY_RESULT</ref>
216                 </see-also>
217         </function>
218
219 ***/
220 #define CALENDAR_BUCKETS 19
221
222 static struct ao2_container *calendars;
223 static struct ast_sched_context *sched;
224 static pthread_t refresh_thread = AST_PTHREADT_NULL;
225 static ast_mutex_t refreshlock;
226 static ast_cond_t refresh_condition;
227 static ast_mutex_t reloadlock;
228 static int module_unloading;
229
230 static void event_notification_destroy(void *data);
231 static void *event_notification_duplicate(void *data);
232 static void eventlist_destroy(void *data);
233 static void *eventlist_duplicate(void *data);
234
235 static const struct ast_datastore_info event_notification_datastore = {
236         .type = "EventNotification",
237         .destroy = event_notification_destroy,
238         .duplicate = event_notification_duplicate,
239 };
240
241 static const struct ast_datastore_info eventlist_datastore_info = {
242         .type = "CalendarEventList",
243         .destroy = eventlist_destroy,
244         .duplicate = eventlist_duplicate,
245 };
246
247 struct evententry {
248         struct ast_calendar_event *event;
249         AST_LIST_ENTRY(evententry) list;
250 };
251
252 static AST_LIST_HEAD_STATIC(techs, ast_calendar_tech);
253 AST_LIST_HEAD_NOLOCK(eventlist, evententry); /* define the type */
254
255 static struct ast_config *calendar_config;
256 AST_RWLOCK_DEFINE_STATIC(config_lock);
257
258 const struct ast_config *ast_calendar_config_acquire(void)
259 {
260         ast_rwlock_rdlock(&config_lock);
261
262         if (!calendar_config) {
263                 ast_rwlock_unlock(&config_lock);
264                 return NULL;
265         }
266
267         return calendar_config;
268 }
269
270 void ast_calendar_config_release(void)
271 {
272         ast_rwlock_unlock(&config_lock);
273 }
274
275 static struct ast_calendar *unref_calendar(struct ast_calendar *cal)
276 {
277         ao2_ref(cal, -1);
278         return NULL;
279 }
280
281 static int calendar_hash_fn(const void *obj, const int flags)
282 {
283         const struct ast_calendar *cal = obj;
284         return ast_str_case_hash(cal->name);
285 }
286
287 static int calendar_cmp_fn(void *obj, void *arg, int flags)
288 {
289         const struct ast_calendar *one = obj, *two = arg;
290         return !strcasecmp(one->name, two->name) ? CMP_MATCH | CMP_STOP: 0;
291 }
292
293 static struct ast_calendar *find_calendar(const char *name)
294 {
295         struct ast_calendar tmp = {
296                 .name = name,
297         };
298         return ao2_find(calendars, &tmp, OBJ_POINTER);
299 }
300
301 static int event_hash_fn(const void *obj, const int flags)
302 {
303         const struct ast_calendar_event *event = obj;
304         return ast_str_hash(event->uid);
305 }
306
307 static int event_cmp_fn(void *obj, void *arg, int flags)
308 {
309         const struct ast_calendar_event *one = obj, *two = arg;
310         return !strcmp(one->uid, two->uid) ? CMP_MATCH | CMP_STOP : 0;
311 }
312
313 static struct ast_calendar_event *find_event(struct ao2_container *events, const char *uid)
314 {
315         struct ast_calendar_event tmp = {
316                 .uid = uid,
317         };
318         return ao2_find(events, &tmp, OBJ_POINTER);
319 }
320
321 struct ast_calendar_event *ast_calendar_unref_event(struct ast_calendar_event *event)
322 {
323         ao2_ref(event, -1);
324         return NULL;
325 }
326
327 static void calendar_destructor(void *obj)
328 {
329         struct ast_calendar *cal = obj;
330
331         ast_debug(3, "Destroying calendar %s\n", cal->name);
332
333         ao2_lock(cal);
334         cal->unloading = 1;
335         ast_cond_signal(&cal->unload);
336         pthread_join(cal->thread, NULL);
337         if (cal->tech_pvt) {
338                 cal->tech_pvt = cal->tech->unref_calendar(cal->tech_pvt);
339         }
340         ast_calendar_clear_events(cal);
341         ast_string_field_free_memory(cal);
342         ast_variables_destroy(cal->vars);
343         ao2_ref(cal->events, -1);
344         ao2_unlock(cal);
345 }
346
347 static void eventlist_destructor(void *obj)
348 {
349         struct eventlist *events = obj;
350         struct evententry *entry;
351
352         while ((entry = AST_LIST_REMOVE_HEAD(events, list))) {
353                 ao2_ref(entry->event, -1);
354                 ast_free(entry);
355         }
356 }
357
358 static int calendar_busy_callback(void *obj, void *arg, int flags)
359 {
360         struct ast_calendar_event *event = obj;
361         int *is_busy = arg;
362         struct timeval tv = ast_tvnow();
363
364         if (tv.tv_sec >= event->start && tv.tv_sec <= event->end && event->busy_state > AST_CALENDAR_BS_FREE) {
365                 *is_busy = 1;
366                 return CMP_STOP;
367         }
368
369         return 0;
370 }
371
372 static int calendar_is_busy(struct ast_calendar *cal)
373 {
374         int is_busy = 0;
375
376         ao2_callback(cal->events, OBJ_NODATA, calendar_busy_callback, &is_busy);
377
378         return is_busy;
379 }
380
381 static enum ast_device_state calendarstate(const char *data)
382 {
383         enum ast_device_state state;
384         struct ast_calendar *cal;
385
386         if (ast_strlen_zero(data) || (!(cal = find_calendar(data)))) {
387                 return AST_DEVICE_INVALID;
388         }
389
390         if (cal->tech->is_busy) {
391                 state = cal->tech->is_busy(cal) ? AST_DEVICE_INUSE : AST_DEVICE_NOT_INUSE;
392         } else {
393                 state = calendar_is_busy(cal) ? AST_DEVICE_INUSE : AST_DEVICE_NOT_INUSE;
394         }
395
396         cal = unref_calendar(cal);
397         return state;
398 }
399
400 static struct ast_calendar *build_calendar(struct ast_config *cfg, const char *cat, const struct ast_calendar_tech *tech)
401 {
402         struct ast_calendar *cal;
403         struct ast_variable *v, *last = NULL;
404         int new_calendar = 0;
405
406         cal = find_calendar(cat);
407         if (cal && cal->fetch_again_at_reload) {
408                 /** Create new calendar, old will be removed during reload */
409                 cal = unref_calendar(cal);
410         }
411         if (!cal) {
412                 new_calendar = 1;
413                 if (!(cal = ao2_alloc(sizeof(*cal), calendar_destructor))) {
414                         ast_log(LOG_ERROR, "Could not allocate calendar structure. Stopping.\n");
415                         return NULL;
416                 }
417
418                 cal->events = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
419                         CALENDAR_BUCKETS, event_hash_fn, NULL, event_cmp_fn);
420                 if (!cal->events) {
421                         ast_log(LOG_ERROR, "Could not allocate events container for %s\n", cat);
422                         cal = unref_calendar(cal);
423                         return NULL;
424                 }
425
426                 if (ast_string_field_init(cal, 32)) {
427                         ast_log(LOG_ERROR, "Couldn't create string fields for %s\n", cat);
428                         cal = unref_calendar(cal);
429                         return NULL;
430                 }
431         } else {
432                 cal->pending_deletion = 0;
433         }
434
435         ast_string_field_set(cal, name, cat);
436         cal->tech = tech;
437
438         cal->refresh = 3600;
439         cal->timeframe = 60;
440         cal->notify_waittime = 30000;
441         cal->fetch_again_at_reload = 0;
442
443         for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
444                 if (!strcasecmp(v->name, "autoreminder")) {
445                         cal->autoreminder = atoi(v->value);
446                 } else if (!strcasecmp(v->name, "channel")) {
447                         ast_string_field_set(cal, notify_channel, v->value);
448                 } else if (!strcasecmp(v->name, "context")) {
449                         ast_string_field_set(cal, notify_context, v->value);
450                 } else if (!strcasecmp(v->name, "extension")) {
451                         ast_string_field_set(cal, notify_extension, v->value);
452                 } else if (!strcasecmp(v->name, "waittime")) {
453                         int i = atoi(v->value);
454                         if (i > 0) {
455                                 cal->notify_waittime = 1000 * i;
456                         }
457                 } else if (!strcasecmp(v->name, "app")) {
458                         ast_string_field_set(cal, notify_app, v->value);
459                 } else if (!strcasecmp(v->name, "appdata")) {
460                         ast_string_field_set(cal, notify_appdata, v->value);
461                 } else if (!strcasecmp(v->name, "refresh")) {
462                         cal->refresh = atoi(v->value);
463                 } else if (!strcasecmp(v->name, "fetch_again_at_reload")) {
464                         cal->fetch_again_at_reload = ast_true(v->value);
465                 } else if (!strcasecmp(v->name, "timeframe")) {
466                         cal->timeframe = atoi(v->value);
467                 } else if (!strcasecmp(v->name, "setvar")) {
468                         char *name, *value;
469                         struct ast_variable *var;
470
471                         if ((name = (value = ast_strdup(v->value)))) {
472                                 strsep(&value, "=");
473                                 if (value) {
474                                         if ((var = ast_variable_new(ast_strip(name), ast_strip(value), ""))) {
475                                                 if (last) {
476                                                         last->next = var;
477                                                 } else {
478                                                         cal->vars = var;
479                                                 }
480                                                 last = var;
481                                         }
482                                 } else {
483                                         ast_log(LOG_WARNING, "Malformed argument. Should be '%s: variable=value'\n", v->name);
484                                 }
485                                 ast_free(name);
486                         }
487                 }
488         }
489
490         if (cal->autoreminder && ast_strlen_zero(cal->notify_channel)) {
491                 ast_log(LOG_WARNING,
492                                 "You have set 'autoreminder' but not 'channel' for calendar '%s.' "
493                                 "Notifications will not occur.\n",
494                                 cal->name);
495         }
496
497         if (new_calendar) {
498                 cal->thread = AST_PTHREADT_NULL;
499                 ast_cond_init(&cal->unload, NULL);
500                 ao2_link(calendars, cal);
501                 if (ast_pthread_create(&cal->thread, NULL, cal->tech->load_calendar, cal)) {
502                         /* If we start failing to create threads, go ahead and return NULL
503                          * and the tech module will be unregistered
504                          */
505                         ao2_unlink(calendars, cal);
506                         cal = unref_calendar(cal);
507                 }
508         }
509
510         return cal;
511 }
512
513 static int load_tech_calendars(struct ast_calendar_tech *tech)
514 {
515         struct ast_calendar *cal;
516         const char *cat = NULL;
517         const char *val;
518
519         if (!calendar_config) {
520                 ast_log(LOG_WARNING, "Calendar support disabled, not loading %s calendar module\n", tech->type);
521                 return -1;
522         }
523
524         ast_rwlock_wrlock(&config_lock);
525         while ((cat = ast_category_browse(calendar_config, cat))) {
526                 if (!strcasecmp(cat, "general")) {
527                         continue;
528                 }
529
530                 if (!(val = ast_variable_retrieve(calendar_config, cat, "type")) || strcasecmp(val, tech->type)) {
531                         continue;
532                 }
533
534                 /* A serious error occurred loading calendars from this tech and it should be disabled */
535                 if (!(cal = build_calendar(calendar_config, cat, tech))) {
536                         ast_calendar_unregister(tech);
537                         ast_rwlock_unlock(&config_lock);
538                         return -1;
539                 }
540
541                 cal = unref_calendar(cal);
542         }
543
544         ast_rwlock_unlock(&config_lock);
545
546         return 0;
547 }
548
549 int ast_calendar_register(struct ast_calendar_tech *tech)
550 {
551         struct ast_calendar_tech *iter;
552
553         if (!calendar_config) {
554                 ast_log(LOG_WARNING, "Calendar support disabled, not loading %s calendar module\n", tech->type);
555                 return -1;
556         }
557
558         AST_LIST_LOCK(&techs);
559         AST_LIST_TRAVERSE(&techs, iter, list) {
560                 if(!strcasecmp(tech->type, iter->type)) {
561                         ast_log(LOG_WARNING, "Already have a handler for calendar type '%s'\n", tech->type);
562                         AST_LIST_UNLOCK(&techs);
563                         return -1;
564                 }
565         }
566         AST_LIST_INSERT_HEAD(&techs, tech, list);
567         tech->user = ast_module_user_add(NULL);
568         AST_LIST_UNLOCK(&techs);
569
570         ast_verb(2, "Registered calendar type '%s' (%s)\n", tech->type, tech->description);
571
572         return load_tech_calendars(tech);
573 }
574
575 static int match_caltech_cb(void *user_data, void *arg, int flags)
576 {
577         struct ast_calendar *cal = user_data;
578         struct ast_calendar_tech *tech = arg;
579
580         if (cal->tech == tech) {
581                 return CMP_MATCH;
582         }
583
584         return 0;
585 }
586
587 void ast_calendar_unregister(struct ast_calendar_tech *tech)
588 {
589         struct ast_calendar_tech *iter;
590
591         AST_LIST_LOCK(&techs);
592         AST_LIST_TRAVERSE_SAFE_BEGIN(&techs, iter, list) {
593                 if (iter != tech) {
594                         continue;
595                 }
596
597                 ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, match_caltech_cb, tech);
598
599                 AST_LIST_REMOVE_CURRENT(list);
600                 ast_module_user_remove(iter->user);
601                 ast_verb(2, "Unregistered calendar type '%s'\n", tech->type);
602                 break;
603         }
604         AST_LIST_TRAVERSE_SAFE_END;
605         AST_LIST_UNLOCK(&techs);
606
607 }
608
609 static void calendar_event_destructor(void *obj)
610 {
611         struct ast_calendar_event *event = obj;
612         struct ast_calendar_attendee *attendee;
613
614         ast_debug(3, "Destroying event for calendar '%s'\n", event->owner->name);
615         ast_string_field_free_memory(event);
616         while ((attendee = AST_LIST_REMOVE_HEAD(&event->attendees, next))) {
617                 if (attendee->data) {
618                         ast_free(attendee->data);
619                 }
620                 ast_free(attendee);
621         }
622 }
623
624 /* This is only called from ao2_callbacks that are going to unref the event for us,
625  * so we don't unref the event here.  */
626 static struct ast_calendar_event *destroy_event(struct ast_calendar_event *event)
627 {
628         if (event->notify_sched > -1 && ast_sched_del(sched, event->notify_sched)) {
629                 ast_debug(3, "Notification running, can't delete sched entry\n");
630         }
631         if (event->bs_start_sched > -1 && ast_sched_del(sched, event->bs_start_sched)) {
632                 ast_debug(3, "Devicestate update (start) running, can't delete sched entry\n");
633         }
634         if (event->bs_end_sched > -1 && ast_sched_del(sched, event->bs_end_sched)) {
635                 ast_debug(3, "Devicestate update (end) running, can't delete sched entry\n");
636         }
637
638         /* If an event is being deleted and we've fired an event changing the status at the beginning,
639          * but haven't hit the end event yet, go ahead and set the devicestate to the current busy status */
640         if (event->bs_start_sched < 0 && event->bs_end_sched >= 0) {
641                 if (!calendar_is_busy(event->owner)) {
642                         ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Calendar:%s", event->owner->name);
643                 } else {
644                         ast_devstate_changed(AST_DEVICE_BUSY, AST_DEVSTATE_CACHABLE, "Calendar:%s", event->owner->name);
645                 }
646         }
647
648         return NULL;
649 }
650
651 static int clear_events_cb(void *user_data, void *arg, int flags)
652 {
653         struct ast_calendar_event *event = user_data;
654
655         event = destroy_event(event);
656
657         return CMP_MATCH;
658 }
659
660 void ast_calendar_clear_events(struct ast_calendar *cal)
661 {
662         ast_debug(3, "Clearing all events for calendar %s\n", cal->name);
663
664         ao2_callback(cal->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, clear_events_cb, NULL);
665 }
666
667 struct ast_calendar_event *ast_calendar_event_alloc(struct ast_calendar *cal)
668 {
669         struct ast_calendar_event *event;
670         if (!(event = ao2_alloc(sizeof(*event), calendar_event_destructor))) {
671                 return NULL;
672         }
673
674         if (ast_string_field_init(event, 32)) {
675                 event = ast_calendar_unref_event(event);
676                 return NULL;
677         }
678
679         event->owner = cal;
680         event->notify_sched = -1;
681         event->bs_start_sched = -1;
682         event->bs_end_sched = -1;
683
684         AST_LIST_HEAD_INIT_NOLOCK(&event->attendees);
685
686         return event;
687 }
688
689 struct ao2_container *ast_calendar_event_container_alloc(void)
690 {
691         return ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, CALENDAR_BUCKETS,
692                 event_hash_fn, NULL, event_cmp_fn);
693 }
694
695 static void event_notification_destroy(void *data)
696 {
697         struct ast_calendar_event *event = data;
698
699         event = ast_calendar_unref_event(event);
700
701 }
702
703 static void *event_notification_duplicate(void *data)
704 {
705         struct ast_calendar_event *event = data;
706
707         if (!event) {
708                 return NULL;
709         }
710
711         ao2_ref(event, +1);
712
713         return event;
714 }
715
716 /*! \brief Generate 32 byte random string (stolen from chan_sip.c)*/
717 static char *generate_random_string(char *buf, size_t size)
718 {
719         unsigned long val[4];
720         int x;
721
722         for (x = 0; x < 4; x++) {
723                 val[x] = ast_random();
724         }
725         snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
726
727         return buf;
728 }
729
730 static int null_chan_write(struct ast_channel *chan, struct ast_frame *frame)
731 {
732         return 0;
733 }
734
735 static const struct ast_channel_tech null_tech = {
736         .type = "NULL",
737         .description = "Null channel (should not see this)",
738                 .write = null_chan_write,
739 };
740
741 static void *do_notify(void *data)
742 {
743         struct ast_calendar_event *event = data;
744         struct ast_dial *dial = NULL;
745         struct ast_str *apptext = NULL, *tmpstr = NULL;
746         struct ast_datastore *datastore;
747         enum ast_dial_result res;
748         struct ast_channel *chan = NULL;
749         struct ast_variable *itervar;
750         char *tech, *dest;
751         char buf[33];
752         struct ast_format_cap *caps;
753
754         tech = ast_strdupa(event->owner->notify_channel);
755
756         if ((dest = strchr(tech, '/'))) {
757                 *dest = '\0';
758                 dest++;
759         } else {
760                 ast_log(LOG_WARNING, "Channel should be in form Tech/Dest (was '%s')\n", tech);
761                 goto notify_cleanup;
762         }
763
764         if (!(dial = ast_dial_create())) {
765                 ast_log(LOG_ERROR, "Could not create dial structure\n");
766                 goto notify_cleanup;
767         }
768
769         if (ast_dial_append(dial, tech, dest, NULL) < 0) {
770                 ast_log(LOG_ERROR, "Could not append channel\n");
771                 goto notify_cleanup;
772         }
773
774         ast_dial_set_global_timeout(dial, event->owner->notify_waittime);
775         generate_random_string(buf, sizeof(buf));
776
777         if (!(chan = ast_channel_alloc(1, AST_STATE_DOWN, 0, 0, 0, 0, 0, NULL, NULL, 0, "Calendar/%s-%s", event->owner->name, buf))) {
778                 ast_log(LOG_ERROR, "Could not allocate notification channel\n");
779                 goto notify_cleanup;
780         }
781
782         ast_channel_tech_set(chan, &null_tech);
783         ast_channel_set_writeformat(chan, ast_format_slin);
784         ast_channel_set_readformat(chan, ast_format_slin);
785         ast_channel_set_rawwriteformat(chan, ast_format_slin);
786         ast_channel_set_rawreadformat(chan, ast_format_slin);
787
788         caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
789         if (!caps) {
790                 ast_log(LOG_ERROR, "Could not allocate capabilities, notification not being sent!\n");
791                 goto notify_cleanup;
792         }
793         ast_format_cap_append(caps, ast_format_slin, 0);
794         ast_channel_nativeformats_set(chan, caps);
795         ao2_ref(caps, -1);
796
797         ast_channel_unlock(chan);
798
799         if (!(datastore = ast_datastore_alloc(&event_notification_datastore, NULL))) {
800                 ast_log(LOG_ERROR, "Could not allocate datastore, notification not being sent!\n");
801                 goto notify_cleanup;
802         }
803
804         datastore->data = event;
805         datastore->inheritance = DATASTORE_INHERIT_FOREVER;
806
807         ao2_ref(event, +1);
808
809         ast_channel_lock(chan);
810         res = ast_channel_datastore_add(chan, datastore);
811         ast_channel_unlock(chan);
812
813         if (!(tmpstr = ast_str_create(32))) {
814                 goto notify_cleanup;
815         }
816
817         for (itervar = event->owner->vars; itervar; itervar = itervar->next) {
818                 ast_str_substitute_variables(&tmpstr, 0, chan, itervar->value);
819                 pbx_builtin_setvar_helper(chan, itervar->name, ast_str_buffer(tmpstr));
820         }
821
822         if (!(apptext = ast_str_create(32))) {
823                 goto notify_cleanup;
824         }
825
826         if (!ast_strlen_zero(event->owner->notify_app)) {
827                 ast_str_set(&apptext, 0, "%s,%s", event->owner->notify_app, event->owner->notify_appdata);
828                 ast_dial_option_global_enable(dial, AST_DIAL_OPTION_ANSWER_EXEC, ast_str_buffer(apptext));
829         } else {
830         }
831
832         ast_verb(3, "Dialing %s for notification on calendar %s\n", event->owner->notify_channel, event->owner->name);
833         res = ast_dial_run(dial, chan, 0);
834
835         if (res != AST_DIAL_RESULT_ANSWERED) {
836                 ast_verb(3, "Notification call for %s was not completed\n", event->owner->name);
837         } else {
838                 struct ast_channel *answered;
839
840                 answered = ast_dial_answered_steal(dial);
841                 if (ast_strlen_zero(event->owner->notify_app)) {
842                         ast_channel_context_set(answered, event->owner->notify_context);
843                         ast_channel_exten_set(answered, event->owner->notify_extension);
844                         ast_channel_priority_set(answered, 1);
845                         ast_pbx_run(answered);
846                 }
847         }
848
849 notify_cleanup:
850         if (apptext) {
851                 ast_free(apptext);
852         }
853         if (tmpstr) {
854                 ast_free(tmpstr);
855         }
856         if (dial) {
857                 ast_dial_destroy(dial);
858         }
859         if (chan) {
860                 ast_channel_release(chan);
861         }
862
863         event = ast_calendar_unref_event(event);
864
865         return NULL;
866 }
867
868 static int calendar_event_notify(const void *data)
869 {
870         struct ast_calendar_event *event = (void *)data;
871         int res = -1;
872         pthread_t notify_thread = AST_PTHREADT_NULL;
873
874         if (!(event && event->owner)) {
875                 ast_log(LOG_ERROR, "Extremely low-cal...in fact cal is NULL!\n");
876                 return res;
877         }
878
879         ao2_ref(event, +1);
880         event->notify_sched = -1;
881
882         if (ast_pthread_create_background(&notify_thread, NULL, do_notify, event) < 0) {
883                 ast_log(LOG_ERROR, "Could not create notification thread\n");
884                 return res;
885         }
886
887         res = 0;
888
889         return res;
890 }
891
892 static int calendar_devstate_change(const void *data)
893 {
894         struct ast_calendar_event *event = (struct ast_calendar_event *)data;
895         struct timeval now = ast_tvnow();
896         int is_end_event;
897
898         if (!event) {
899                 ast_log(LOG_WARNING, "Event was NULL!\n");
900                 return 0;
901         }
902
903         ao2_ref(event, +1);
904
905         is_end_event = event->end <= now.tv_sec;
906
907         if (is_end_event) {
908                 event->bs_end_sched = -1;
909         } else {
910                 event->bs_start_sched = -1;
911         }
912
913         /* We can have overlapping events, so ignore the event->busy_state and check busy state
914          * based on all events in the calendar */
915         if (!calendar_is_busy(event->owner)) {
916                 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Calendar:%s", event->owner->name);
917         } else {
918                 ast_devstate_changed(AST_DEVICE_BUSY, AST_DEVSTATE_CACHABLE, "Calendar:%s", event->owner->name);
919         }
920
921         event = ast_calendar_unref_event(event);
922
923         return 0;
924 }
925
926 static void copy_event_data(struct ast_calendar_event *dst, struct ast_calendar_event *src)
927 {
928         struct ast_calendar_attendee *attendee;
929
930         ast_string_field_set(dst, summary, src->summary);
931         ast_string_field_set(dst, description, src->description);
932         ast_string_field_set(dst, organizer, src->organizer);
933         ast_string_field_set(dst, location, src->location);
934         ast_string_field_set(dst, uid, src->uid);
935         ast_string_field_set(dst, categories, src->categories);
936         dst->priority = src->priority;
937         dst->owner = src->owner;
938         dst->start = src->start;
939         dst->end = src->end;
940         dst->alarm = src->alarm;
941         dst->busy_state = src->busy_state;
942
943         /* Delete any existing attendees */
944         while ((attendee = AST_LIST_REMOVE_HEAD(&dst->attendees, next))) {
945                 ast_free(attendee);
946         }
947
948         /* Copy over the new attendees */
949         while ((attendee = AST_LIST_REMOVE_HEAD(&src->attendees, next))) {
950                 AST_LIST_INSERT_TAIL(&dst->attendees, attendee, next);
951         }
952 }
953
954 static int schedule_calendar_event(struct ast_calendar *cal, struct ast_calendar_event *old_event, struct ast_calendar_event *cmp_event)
955 {
956         struct timeval now = ast_tvnow();
957         struct ast_calendar_event *event;
958         time_t alarm_notify_sched = 0, devstate_sched_start, devstate_sched_end;
959         int changed = 0;
960
961         event = cmp_event ? cmp_event : old_event;
962
963         ao2_lock(event);
964         if (!ast_strlen_zero(cal->notify_channel) && (!cmp_event || old_event->alarm != event->alarm)) {
965                 changed = 1;
966                 if (cal->autoreminder) {
967                         alarm_notify_sched = (event->start - (60 * cal->autoreminder) - now.tv_sec) * 1000;
968                 } else if (event->alarm) {
969                         alarm_notify_sched = (event->alarm - now.tv_sec) * 1000;
970                 }
971
972                 /* For now, send the notification if we missed it, but the meeting hasn't happened yet */
973                 if (event->start >= now.tv_sec) {
974                         if (alarm_notify_sched <= 0) {
975                                 alarm_notify_sched = 1;
976                         }
977                         ast_mutex_lock(&refreshlock);
978                         AST_SCHED_REPLACE(old_event->notify_sched, sched, alarm_notify_sched, calendar_event_notify, old_event);
979                         ast_mutex_unlock(&refreshlock);
980                         ast_debug(3, "Calendar alarm event notification scheduled to happen in %ld ms\n", (long) alarm_notify_sched);
981                 }
982         }
983
984         if (!cmp_event || old_event->start != event->start) {
985                 changed = 1;
986                 devstate_sched_start = (event->start - now.tv_sec) * 1000;
987
988                 if (devstate_sched_start < 1) {
989                         devstate_sched_start = 1;
990                 }
991
992                 ast_mutex_lock(&refreshlock);
993                 AST_SCHED_REPLACE(old_event->bs_start_sched, sched, devstate_sched_start, calendar_devstate_change, old_event);
994                 ast_mutex_unlock(&refreshlock);
995                 ast_debug(3, "Calendar bs_start event notification scheduled to happen in %ld ms\n", (long) devstate_sched_start);
996         }
997
998         if (!cmp_event || old_event->end != event->end) {
999                 changed = 1;
1000                 devstate_sched_end = (event->end - now.tv_sec) * 1000;
1001                 ast_mutex_lock(&refreshlock);
1002                 AST_SCHED_REPLACE(old_event->bs_end_sched, sched, devstate_sched_end, calendar_devstate_change, old_event);
1003                 ast_mutex_unlock(&refreshlock);
1004                 ast_debug(3, "Calendar bs_end event notification scheduled to happen in %ld ms\n", (long) devstate_sched_end);
1005         }
1006
1007         if (changed) {
1008                 ast_cond_signal(&refresh_condition);
1009         }
1010
1011         ao2_unlock(event);
1012
1013         return 0;
1014 }
1015
1016 static int merge_events_cb(void *obj, void *arg, int flags)
1017 {
1018         struct ast_calendar_event *old_event = obj, *new_event;
1019         struct ao2_container *new_events = arg;
1020
1021         /* If we don't find the old_event in new_events, then we can safely delete the old_event */
1022         if (!(new_event = find_event(new_events, old_event->uid))) {
1023                 old_event = destroy_event(old_event);
1024                 return CMP_MATCH;
1025         }
1026
1027         /* We have events to merge.  If any data that will affect a scheduler event has changed,
1028          * then we need to replace the scheduler event */
1029         schedule_calendar_event(old_event->owner, old_event, new_event);
1030
1031         /* Since we don't want to mess with cancelling sched events and adding new ones, just
1032          * copy the internals of the new_event to the old_event */
1033         copy_event_data(old_event, new_event);
1034
1035         /* Now we can go ahead and unlink the new_event from new_events and unref it so that only completely
1036          * new events remain in the container */
1037         ao2_unlink(new_events, new_event);
1038         new_event = ast_calendar_unref_event(new_event);
1039
1040         return 0;
1041 }
1042
1043 static int add_new_event_cb(void *obj, void *arg, int flags)
1044 {
1045         struct ast_calendar_event *new_event = obj;
1046         struct ao2_container *events = arg;
1047
1048         ao2_link(events, new_event);
1049         schedule_calendar_event(new_event->owner, new_event, NULL);
1050         return CMP_MATCH;
1051 }
1052
1053 void ast_calendar_merge_events(struct ast_calendar *cal, struct ao2_container *new_events)
1054 {
1055         /* Loop through all events attached to the calendar.  If there is a matching new event
1056          * merge its data over and handle any schedule changes that need to be made.  Then remove
1057          * the new_event from new_events so that we are left with only new_events that we can add later. */
1058         ao2_callback(cal->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, merge_events_cb, new_events);
1059
1060         /* Now, we should only have completely new events in new_events.  Loop through and add them */
1061         ao2_callback(new_events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, add_new_event_cb, cal->events);
1062 }
1063
1064
1065 static int load_config(int reload)
1066 {
1067         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1068         struct ast_config *tmpcfg;
1069
1070         if (!(tmpcfg = ast_config_load2("calendar.conf", "calendar", config_flags)) ||
1071                 tmpcfg == CONFIG_STATUS_FILEINVALID) {
1072                 ast_log(LOG_ERROR, "Unable to load config calendar.conf\n");
1073                 return -1;
1074         }
1075
1076         if (tmpcfg == CONFIG_STATUS_FILEUNCHANGED) {
1077                 return 0;
1078         }
1079
1080         ast_rwlock_wrlock(&config_lock);
1081         if (calendar_config) {
1082                 ast_config_destroy(calendar_config);
1083         }
1084
1085         calendar_config = tmpcfg;
1086         ast_rwlock_unlock(&config_lock);
1087
1088         return 0;
1089 }
1090
1091 /*! \brief A dialplan function that can be used to determine the busy status of a calendar */
1092 static int calendar_busy_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1093 {
1094         struct ast_calendar *cal;
1095
1096         if (ast_strlen_zero(data)) {
1097                 ast_log(LOG_WARNING, "CALENDAR_BUSY requires an argument: CALENDAR_BUSY(<calendar_name>)\n");
1098                 return -1;
1099         }
1100
1101         cal = find_calendar(data);
1102
1103         if (!cal) {
1104                 ast_log(LOG_WARNING, "Could not find calendar '%s'\n", data);
1105                 return -1;
1106         }
1107
1108         strcpy(buf, calendar_is_busy(cal) ? "1" : "0");
1109         cal = unref_calendar(cal);
1110
1111         return 0;
1112 }
1113
1114 static struct ast_custom_function calendar_busy_function = {
1115     .name = "CALENDAR_BUSY",
1116     .read = calendar_busy_exec,
1117 };
1118
1119 static int add_event_to_list(struct eventlist *events, struct ast_calendar_event *event, time_t start, time_t end)
1120 {
1121         struct evententry *entry, *iter;
1122         long event_startdiff = labs(start - event->start);
1123         long event_enddiff = labs(end - event->end);
1124         int i = 0;
1125
1126         if (!(entry = ast_calloc(1, sizeof(*entry)))) {
1127                 ast_log(LOG_ERROR, "Unable to allocate memory for event list\n");
1128                 return -1;
1129         }
1130
1131         entry->event = event;
1132         ao2_ref(event, +1);
1133
1134         if (start == end) {
1135                 AST_LIST_TRAVERSE_SAFE_BEGIN(events, iter, list) {
1136                         long startdiff = labs(iter->event->start - start);
1137
1138                         ast_debug(10, "Comparing %s with startdiff %ld to %s with startdiff %ld\n", event->summary, event_startdiff, iter->event->summary, startdiff);
1139                         ++i;
1140                         if (startdiff > event_startdiff) {
1141                                 AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
1142                                 return i;
1143                         }
1144                         if (startdiff == event_startdiff) {
1145                                 long enddiff = labs(iter->event->end - end);
1146
1147                                 if (enddiff > event_enddiff) {
1148                                         AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
1149                                         return i;
1150                                 }
1151                                 if (event_startdiff == enddiff) {
1152                                         if (strcmp(event->uid, iter->event->uid) < 0) {
1153                                                 AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
1154                                                 return i;
1155                                         }
1156                                 }
1157                         }
1158                 }
1159                 AST_LIST_TRAVERSE_SAFE_END;
1160
1161                 AST_LIST_INSERT_TAIL(events, entry, list);
1162
1163                 return i;
1164         }
1165
1166         AST_LIST_TRAVERSE_SAFE_BEGIN(events, iter, list) {
1167                 ++i;
1168                 if (iter->event->start > event->start) {
1169                         AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
1170                         return i;
1171                 }
1172
1173                 if (iter->event->start == event->start) {
1174                         if ((iter->event->end - iter->event->start) == (event->end - event->start)) {
1175                                 if (strcmp(event->uid, iter->event->uid) < 0) {
1176                                         AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
1177                                         return i;
1178                                 }
1179                         }
1180                         if ((iter->event->end - iter->event->start) < (event->end - event->start)) {
1181                                 AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
1182                                 return i;
1183                         }
1184                 }
1185         }
1186         AST_LIST_TRAVERSE_SAFE_END;
1187
1188         AST_LIST_INSERT_TAIL(events, entry, list);
1189
1190         return i;
1191 }
1192
1193 static void eventlist_destroy(void *data)
1194 {
1195         struct eventlist *events = data;
1196
1197         ao2_ref(events, -1);
1198 }
1199
1200 static void *eventlist_duplicate(void *data)
1201 {
1202         struct eventlist *events = data;
1203
1204         if (!events) {
1205                 return NULL;
1206         }
1207
1208         ao2_ref(events, +1);
1209
1210         return events;
1211 }
1212
1213 static int calendar_query_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1214 {
1215         struct ast_calendar *cal;
1216         struct ao2_iterator i;
1217         struct ast_calendar_event *event;
1218         struct eventlist *events;
1219         time_t start = INT_MIN, end = INT_MAX;
1220         struct ast_datastore *eventlist_datastore;
1221         AST_DECLARE_APP_ARGS(args,
1222                 AST_APP_ARG(calendar);
1223                 AST_APP_ARG(start);
1224                 AST_APP_ARG(end);
1225         );
1226
1227         if (!chan) {
1228                 ast_log(LOG_WARNING, "%s requires a channel to store the data on\n", cmd);
1229                 return -1;
1230         }
1231
1232         AST_STANDARD_APP_ARGS(args, data);
1233
1234         if (ast_strlen_zero(args.calendar)) {
1235                 ast_log(LOG_WARNING, "%s requires a calendar argument\n", cmd);
1236                 return -1;
1237         }
1238
1239         if (!(cal = find_calendar(args.calendar))) {
1240                 ast_log(LOG_WARNING, "Unknown calendar '%s'\n", args.calendar);
1241                 return -1;
1242         }
1243
1244         if (!(events = ao2_alloc(sizeof(*events), eventlist_destructor))) {
1245                 ast_log(LOG_ERROR, "Unable to allocate memory for event list\n");
1246                 cal = unref_calendar(cal);
1247                 return -1;
1248         }
1249
1250         if (!ast_strlen_zero(args.start)) {
1251                 start = atoi(args.start);
1252         }
1253
1254         if (!ast_strlen_zero(args.end)) {
1255                 end = atoi(args.end);
1256         }
1257
1258         i = ao2_iterator_init(cal->events, 0);
1259         while ((event = ao2_iterator_next(&i))) {
1260                 if (!(start > event->end || end < event->start)) {
1261                         ast_debug(10, "%s (%ld - %ld) overlapped with (%ld - %ld)\n", event->summary, (long) event->start, (long) event->end, (long) start, (long) end);
1262                         if (add_event_to_list(events, event, start, end) < 0) {
1263                                 event = ast_calendar_unref_event(event);
1264                                 cal = unref_calendar(cal);
1265                                 ao2_ref(events, -1);
1266                                 ao2_iterator_destroy(&i);
1267                                 return -1;
1268                         }
1269                 }
1270
1271                 event = ast_calendar_unref_event(event);
1272         }
1273         ao2_iterator_destroy(&i);
1274
1275         ast_channel_lock(chan);
1276         do {
1277                 generate_random_string(buf, len);
1278         } while (ast_channel_datastore_find(chan, &eventlist_datastore_info, buf));
1279         ast_channel_unlock(chan);
1280
1281         if (!(eventlist_datastore = ast_datastore_alloc(&eventlist_datastore_info, buf))) {
1282                 ast_log(LOG_ERROR, "Could not allocate datastore!\n");
1283                 cal = unref_calendar(cal);
1284                 ao2_ref(events, -1);
1285                 return -1;
1286         }
1287
1288         eventlist_datastore->inheritance = DATASTORE_INHERIT_FOREVER;
1289         eventlist_datastore->data = events;
1290
1291         ast_channel_lock(chan);
1292         ast_channel_datastore_add(chan, eventlist_datastore);
1293         ast_channel_unlock(chan);
1294
1295         cal = unref_calendar(cal);
1296         return 0;
1297 }
1298
1299 static struct ast_custom_function calendar_query_function = {
1300     .name = "CALENDAR_QUERY",
1301     .read = calendar_query_exec,
1302 };
1303
1304 static void calendar_join_attendees(struct ast_calendar_event *event, char *buf, size_t len)
1305 {
1306         struct ast_str *tmp;
1307         struct ast_calendar_attendee *attendee;
1308
1309         if (!(tmp = ast_str_create(32))) {
1310                 ast_log(LOG_ERROR, "Could not allocate memory for attendees!\n");
1311                 return;
1312         }
1313
1314         AST_LIST_TRAVERSE(&event->attendees, attendee, next) {
1315                 ast_str_append(&tmp, 0, "%s%s", attendee == AST_LIST_FIRST(&event->attendees) ? "" : ",", attendee->data);
1316         }
1317
1318         ast_copy_string(buf, ast_str_buffer(tmp), len);
1319         ast_free(tmp);
1320 }
1321
1322 static int calendar_query_result_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1323 {
1324         struct ast_datastore *datastore;
1325         struct eventlist *events;
1326         struct evententry *entry;
1327         int row = 1;
1328         size_t listlen = 0;
1329         AST_DECLARE_APP_ARGS(args,
1330                 AST_APP_ARG(id);
1331                 AST_APP_ARG(field);
1332                 AST_APP_ARG(row);
1333         );
1334
1335         if (!chan) {
1336                 ast_log(LOG_WARNING, "%s requires a channel\n", cmd);
1337                 return -1;
1338         }
1339
1340         AST_STANDARD_APP_ARGS(args, data);
1341
1342         if (ast_strlen_zero(args.id) || ast_strlen_zero(args.field)) {
1343                 ast_log(LOG_WARNING, "%s requires an id and a field", cmd);
1344                 return -1;
1345         }
1346
1347         ast_channel_lock(chan);
1348         if (!(datastore = ast_channel_datastore_find(chan, &eventlist_datastore_info, args.id))) {
1349                 ast_log(LOG_WARNING, "There is no event notification datastore with id '%s' on '%s'!\n", args.id, ast_channel_name(chan));
1350                 ast_channel_unlock(chan);
1351                 return -1;
1352         }
1353         ast_channel_unlock(chan);
1354
1355         if (!(events = datastore->data)) {
1356                 ast_log(LOG_WARNING, "The datastore contains no data!\n");
1357                 return -1;
1358         }
1359
1360         if (!ast_strlen_zero(args.row)) {
1361                 row = atoi(args.row);
1362         }
1363
1364         AST_LIST_TRAVERSE(events, entry, list) {
1365                 listlen++;
1366         }
1367
1368         if (!strcasecmp(args.field, "getnum")) {
1369                 snprintf(buf, len, "%zu", listlen);
1370                 return 0;
1371         }
1372
1373         AST_LIST_TRAVERSE(events, entry, list) {
1374                 if (--row) {
1375                         continue;
1376                 }
1377                 if (!strcasecmp(args.field, "summary")) {
1378                         ast_copy_string(buf, entry->event->summary, len);
1379                 } else if (!strcasecmp(args.field, "description")) {
1380                         ast_copy_string(buf, entry->event->description, len);
1381                 } else if (!strcasecmp(args.field, "organizer")) {
1382                         ast_copy_string(buf, entry->event->organizer, len);
1383                 } else if (!strcasecmp(args.field, "location")) {
1384                         ast_copy_string(buf, entry->event->location, len);
1385                 } else if (!strcasecmp(args.field, "categories")) {
1386                         ast_copy_string(buf, entry->event->categories, len);
1387                 } else if (!strcasecmp(args.field, "priority")) {
1388                         snprintf(buf, len, "%d", entry->event->priority);
1389                 } else if (!strcasecmp(args.field, "calendar")) {
1390                         ast_copy_string(buf, entry->event->owner->name, len);
1391                 } else if (!strcasecmp(args.field, "uid")) {
1392                         ast_copy_string(buf, entry->event->uid, len);
1393                 } else if (!strcasecmp(args.field, "start")) {
1394                         snprintf(buf, len, "%ld", (long) entry->event->start);
1395                 } else if (!strcasecmp(args.field, "end")) {
1396                         snprintf(buf, len, "%ld", (long) entry->event->end);
1397                 } else if (!strcasecmp(args.field, "busystate")) {
1398                         snprintf(buf, len, "%u", entry->event->busy_state);
1399                 } else if (!strcasecmp(args.field, "attendees")) {
1400                         calendar_join_attendees(entry->event, buf, len);
1401                 } else {
1402                         ast_log(LOG_WARNING, "Unknown field '%s'\n", args.field);
1403                 }
1404                 break;
1405         }
1406
1407         return 0;
1408 }
1409
1410 static struct ast_custom_function calendar_query_result_function = {
1411         .name = "CALENDAR_QUERY_RESULT",
1412         .read = calendar_query_result_exec,
1413 };
1414
1415 static int calendar_write_exec(struct ast_channel *chan, const char *cmd, char *data, const char *value)
1416 {
1417         int i, j, ret = -1;
1418         char *val_dup = NULL;
1419         struct ast_calendar *cal = NULL;
1420         struct ast_calendar_event *event = NULL;
1421         struct timeval tv = ast_tvnow();
1422         AST_DECLARE_APP_ARGS(fields,
1423                 AST_APP_ARG(field)[10];
1424         );
1425         AST_DECLARE_APP_ARGS(values,
1426                 AST_APP_ARG(value)[10];
1427         );
1428
1429         if (!(val_dup = ast_strdup(value))) {
1430                 ast_log(LOG_ERROR, "Could not allocate memory for values\n");
1431                 goto write_cleanup;
1432         }
1433
1434         AST_STANDARD_APP_ARGS(fields, data);
1435         AST_STANDARD_APP_ARGS(values, val_dup);
1436
1437         /* XXX Eventually we will support unnamed calendars, so if we don't find one, we parse
1438          * for a calendar type and create it */
1439         if (!(cal = find_calendar(fields.field[0]))) {
1440                 ast_log(LOG_WARNING, "Couldn't find calendar '%s'\n", fields.field[0]);
1441                 goto write_cleanup;
1442         }
1443
1444         if (!(cal->tech->write_event)) {
1445                 ast_log(LOG_WARNING, "Calendar '%s' has no write function!\n", cal->name);
1446                 goto write_cleanup;
1447         }
1448
1449         if (!(event = ast_calendar_event_alloc(cal))) {
1450                 goto write_cleanup;
1451         }
1452
1453         if (ast_strlen_zero(fields.field[0])) {
1454                 ast_log(LOG_WARNING, "CALENDAR_WRITE requires a calendar name!\n");
1455                 goto write_cleanup;
1456         }
1457
1458         if (fields.argc - 1 != values.argc) {
1459                 ast_log(LOG_WARNING, "CALENDAR_WRITE should have the same number of fields (%u) and values (%u)!\n", fields.argc - 1, values.argc);
1460                 goto write_cleanup;
1461         }
1462
1463         event->owner = cal;
1464
1465         for (i = 1, j = 0; i < fields.argc; i++, j++) {
1466                 if (!strcasecmp(fields.field[i], "summary")) {
1467                         ast_string_field_set(event, summary, values.value[j]);
1468                 } else if (!strcasecmp(fields.field[i], "description")) {
1469                         ast_string_field_set(event, description, values.value[j]);
1470                 } else if (!strcasecmp(fields.field[i], "organizer")) {
1471                         ast_string_field_set(event, organizer, values.value[j]);
1472                 } else if (!strcasecmp(fields.field[i], "location")) {
1473                         ast_string_field_set(event, location, values.value[j]);
1474                 } else if (!strcasecmp(fields.field[i], "categories")) {
1475                         ast_string_field_set(event, categories, values.value[j]);
1476                 } else if (!strcasecmp(fields.field[i], "priority")) {
1477                         event->priority = atoi(values.value[j]);
1478                 } else if (!strcasecmp(fields.field[i], "uid")) {
1479                         ast_string_field_set(event, uid, values.value[j]);
1480                 } else if (!strcasecmp(fields.field[i], "start")) {
1481                         event->start = atoi(values.value[j]);
1482                 } else if (!strcasecmp(fields.field[i], "end")) {
1483                         event->end = atoi(values.value[j]);
1484                 } else if (!strcasecmp(fields.field[i], "busystate")) {
1485                         event->busy_state = atoi(values.value[j]);
1486                 } else {
1487                         ast_log(LOG_WARNING, "Unknown calendar event field '%s'\n", fields.field[i]);
1488                 }
1489         }
1490
1491         if (!event->start) {
1492                 event->start = tv.tv_sec;
1493         }
1494
1495         if (!event->end) {
1496                 event->end = tv.tv_sec;
1497         }
1498
1499         if((ret = cal->tech->write_event(event))) {
1500                 ast_log(LOG_WARNING, "Writing event to calendar '%s' failed!\n", cal->name);
1501         }
1502
1503 write_cleanup:
1504         if (ret) {
1505                 pbx_builtin_setvar_helper(chan, "CALENDAR_SUCCESS", "0");
1506         } else {
1507                 pbx_builtin_setvar_helper(chan, "CALENDAR_SUCCESS", "1");
1508         }
1509         if (cal) {
1510                 cal = unref_calendar(cal);
1511         }
1512         if (event) {
1513                 event = ast_calendar_unref_event(event);
1514         }
1515         if (val_dup) {
1516                 ast_free(val_dup);
1517         }
1518
1519         return ret;
1520 }
1521
1522 static struct ast_custom_function calendar_write_function = {
1523         .name = "CALENDAR_WRITE",
1524         .write = calendar_write_exec,
1525 };
1526
1527 /*! \brief CLI command to list available calendars */
1528 static char *handle_show_calendars(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1529 {
1530 #define FORMAT "%-20.20s %-10.10s %-6.6s\n"
1531         struct ao2_iterator i;
1532         struct ast_calendar *cal;
1533
1534         switch(cmd) {
1535         case CLI_INIT:
1536                 e->command = "calendar show calendars";
1537                 e->usage =
1538                         "Usage: calendar show calendars\n"
1539                         "       Lists all registered calendars.\n";
1540                 return NULL;
1541         case CLI_GENERATE:
1542                 return NULL;
1543         }
1544
1545         ast_cli(a->fd, FORMAT, "Calendar", "Type", "Status");
1546         ast_cli(a->fd, FORMAT, "--------", "----", "------");
1547         i = ao2_iterator_init(calendars, 0);
1548         while ((cal = ao2_iterator_next(&i))) {
1549                 ast_cli(a->fd, FORMAT, cal->name, cal->tech->type, calendar_is_busy(cal) ? "busy" : "free");
1550                 cal = unref_calendar(cal);
1551         }
1552         ao2_iterator_destroy(&i);
1553
1554         return CLI_SUCCESS;
1555 #undef FORMAT
1556 }
1557
1558 /*! \brief CLI command to list of all calendars types currently loaded on the backend */
1559 static char *handle_show_calendars_types(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1560 {
1561 #define FORMAT "%-10.10s %-30.30s\n"
1562         struct ast_calendar_tech *iter;
1563
1564
1565         switch(cmd) {
1566         case CLI_INIT:
1567                 e->command = "calendar show types";
1568                 e->usage =
1569                         "Usage: calendar show types\n"
1570                         "       Lists all registered calendars types.\n";
1571                 return NULL;
1572         case CLI_GENERATE:
1573                 return NULL;
1574         }
1575
1576         ast_cli(a->fd, FORMAT, "Type", "Description");
1577         AST_LIST_LOCK(&techs);
1578         AST_LIST_TRAVERSE(&techs, iter, list) {
1579                 ast_cli(a->fd, FORMAT, iter->type, iter->description);
1580         }
1581         AST_LIST_UNLOCK(&techs);
1582
1583         return CLI_SUCCESS;
1584 #undef FORMAT
1585 }
1586
1587 static char *epoch_to_string(char *buf, size_t buflen, time_t epoch)
1588 {
1589         struct ast_tm tm;
1590         struct timeval tv = {
1591                 .tv_sec = epoch,
1592         };
1593
1594         if (!epoch) {
1595                 *buf = '\0';
1596                 return buf;
1597         }
1598         ast_localtime(&tv, &tm, NULL);
1599         ast_strftime(buf, buflen, "%F %r %z", &tm);
1600
1601         return buf;
1602 }
1603
1604 static char *handle_show_calendar(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1605 {
1606 #define FORMAT  "%-18.18s : %-20.20s\n"
1607 #define FORMAT2 "%-12.12s: %-40.60s\n"
1608         struct ao2_iterator i;
1609         struct ast_calendar *cal;
1610         struct ast_calendar_event *event;
1611         int which = 0;
1612         char *ret = NULL;
1613
1614         switch(cmd) {
1615         case CLI_INIT:
1616                 e->command = "calendar show calendar";
1617                 e->usage =
1618                         "Usage: calendar show calendar <calendar name>\n"
1619                         "       Displays information about a calendar\n";
1620                 return NULL;
1621
1622         case CLI_GENERATE:
1623                 if (a->pos != 3) {
1624                         return NULL;
1625                 }
1626                 i = ao2_iterator_init(calendars, 0);
1627                 while ((cal = ao2_iterator_next(&i))) {
1628                         if (!strncasecmp(a->word, cal->name, strlen(a->word)) && ++which > a->n) {
1629                                 ret = ast_strdup(cal->name);
1630                                 cal = unref_calendar(cal);
1631                                 break;
1632                         }
1633                         cal = unref_calendar(cal);
1634                 }
1635                 ao2_iterator_destroy(&i);
1636                 return ret;
1637         }
1638
1639         if (a->argc != 4) {
1640                 return CLI_SHOWUSAGE;
1641         }
1642
1643         if (!(cal = find_calendar(a->argv[3]))) {
1644                 return NULL;
1645         }
1646
1647         ast_cli(a->fd, FORMAT, "Name", cal->name);
1648         ast_cli(a->fd, FORMAT, "Notify channel", cal->notify_channel);
1649         ast_cli(a->fd, FORMAT, "Notify context", cal->notify_context);
1650         ast_cli(a->fd, FORMAT, "Notify extension", cal->notify_extension);
1651         ast_cli(a->fd, FORMAT, "Notify application", cal->notify_app);
1652         ast_cli(a->fd, FORMAT, "Notify appdata", cal->notify_appdata);
1653         ast_cli(a->fd, "%-17.17s : %d\n", "Refresh time", cal->refresh);
1654         ast_cli(a->fd, "%-17.17s : %d\n", "Timeframe", cal->timeframe);
1655
1656         if (cal->autoreminder) {
1657                 ast_cli(a->fd, "%-17.17s : %d minutes before event\n", "Autoreminder", cal->autoreminder);
1658         } else {
1659                 ast_cli(a->fd, "%-17.17s : None\n", "Autoreminder");
1660         }
1661
1662         ast_cli(a->fd, "%s\n", "Events");
1663         ast_cli(a->fd, "%s\n", "------");
1664
1665         i = ao2_iterator_init(cal->events, 0);
1666         while ((event = ao2_iterator_next(&i))) {
1667                 char buf[100];
1668
1669                 ast_cli(a->fd, FORMAT2, "Summary", event->summary);
1670                 ast_cli(a->fd, FORMAT2, "Description", event->description);
1671                 ast_cli(a->fd, FORMAT2, "Organizer", event->organizer);
1672                 ast_cli(a->fd, FORMAT2, "Location", event->location);
1673                 ast_cli(a->fd, FORMAT2, "Categories", event->categories);
1674                 ast_cli(a->fd, "%-12.12s: %d\n", "Priority", event->priority);
1675                 ast_cli(a->fd, FORMAT2, "UID", event->uid);
1676                 ast_cli(a->fd, FORMAT2, "Start", epoch_to_string(buf, sizeof(buf), event->start));
1677                 ast_cli(a->fd, FORMAT2, "End", epoch_to_string(buf, sizeof(buf), event->end));
1678                 ast_cli(a->fd, FORMAT2, "Alarm", epoch_to_string(buf, sizeof(buf), event->alarm));
1679                 ast_cli(a->fd, "\n");
1680
1681                 event = ast_calendar_unref_event(event);
1682         }
1683         ao2_iterator_destroy(&i);
1684         cal = unref_calendar(cal);
1685         return CLI_SUCCESS;
1686 #undef FORMAT
1687 #undef FORMAT2
1688 }
1689
1690 static char *handle_dump_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1691 {
1692         switch(cmd) {
1693         case CLI_INIT:
1694                 e->command = "calendar dump sched";
1695                 e->usage =
1696                         "Usage: calendar dump sched\n"
1697                         "       Dump the calendar sched context";
1698                 return NULL;
1699
1700         case CLI_GENERATE:
1701                 return NULL;
1702         }
1703
1704         ast_sched_dump(sched);
1705
1706         return CLI_SUCCESS;
1707 }
1708
1709 static struct ast_cli_entry calendar_cli[] = {
1710         AST_CLI_DEFINE(handle_show_calendar, "Display information about a calendar"),
1711         AST_CLI_DEFINE(handle_show_calendars, "Show registered calendars"),
1712         AST_CLI_DEFINE(handle_dump_sched, "Dump calendar sched context"),
1713         AST_CLI_DEFINE(handle_show_calendars_types, "Show all calendar types loaded"),
1714 };
1715
1716 static int calendar_event_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1717 {
1718         struct ast_datastore *datastore;
1719         struct ast_calendar_event *event;
1720
1721         if (!chan) {
1722                 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
1723                 return -1;
1724         }
1725
1726         if (ast_strlen_zero(data)) {
1727                 ast_log(LOG_WARNING, "%s requires an argument\n", cmd);
1728                 return -1;
1729         }
1730
1731         ast_channel_lock(chan);
1732         if (!(datastore = ast_channel_datastore_find(chan, &event_notification_datastore, NULL))) {
1733                 ast_log(LOG_WARNING, "There is no event notification datastore on '%s'!\n", ast_channel_name(chan));
1734                 ast_channel_unlock(chan);
1735                 return -1;
1736         }
1737         ast_channel_unlock(chan);
1738
1739         if (!(event = datastore->data)) {
1740                 ast_log(LOG_WARNING, "The datastore contains no data!\n");
1741                 return -1;
1742         }
1743
1744         if (!strcasecmp(data, "summary")) {
1745                 ast_copy_string(buf, event->summary, len);
1746         } else if (!strcasecmp(data, "description")) {
1747                 ast_copy_string(buf, event->description, len);
1748         } else if (!strcasecmp(data, "organizer")) {
1749                 ast_copy_string(buf, event->organizer, len);
1750         } else if (!strcasecmp(data, "location")) {
1751                 ast_copy_string(buf, event->location, len);
1752         } else if (!strcasecmp(data, "categories")) {
1753                 ast_copy_string(buf, event->categories, len);
1754         } else if (!strcasecmp(data, "priority")) {
1755                 snprintf(buf, len, "%d", event->priority);
1756         } else if (!strcasecmp(data, "calendar")) {
1757                 ast_copy_string(buf, event->owner->name, len);
1758         } else if (!strcasecmp(data, "uid")) {
1759                 ast_copy_string(buf, event->uid, len);
1760         } else if (!strcasecmp(data, "start")) {
1761                 snprintf(buf, len, "%ld", (long)event->start);
1762         } else if (!strcasecmp(data, "end")) {
1763                 snprintf(buf, len, "%ld", (long)event->end);
1764         } else if (!strcasecmp(data, "busystate")) {
1765                 snprintf(buf, len, "%u", event->busy_state);
1766         } else if (!strcasecmp(data, "attendees")) {
1767                 calendar_join_attendees(event, buf, len);
1768         }
1769
1770
1771         return 0;
1772 }
1773
1774 static struct ast_custom_function calendar_event_function = {
1775         .name = "CALENDAR_EVENT",
1776         .read = calendar_event_read,
1777 };
1778
1779 static int cb_pending_deletion(void *user_data, void *arg, int flags)
1780 {
1781         struct ast_calendar *cal = user_data;
1782
1783         cal->pending_deletion = 1;
1784
1785         return CMP_MATCH;
1786 }
1787
1788 static int cb_rm_pending_deletion(void *user_data, void *arg, int flags)
1789 {
1790         struct ast_calendar *cal = user_data;
1791
1792         return cal->pending_deletion ? CMP_MATCH : 0;
1793 }
1794
1795 static int reload(void)
1796 {
1797         struct ast_calendar_tech *iter;
1798
1799         ast_mutex_lock(&reloadlock);
1800
1801         /* Mark existing calendars for deletion */
1802         ao2_callback(calendars, OBJ_NODATA | OBJ_MULTIPLE, cb_pending_deletion, NULL);
1803         load_config(1);
1804
1805         AST_LIST_LOCK(&techs);
1806         AST_LIST_TRAVERSE(&techs, iter, list) {
1807                 if (load_tech_calendars(iter)) {
1808                         ast_log(LOG_WARNING, "Failed to reload %s calendars, module disabled\n", iter->type);
1809                 }
1810         }
1811         AST_LIST_UNLOCK(&techs);
1812
1813         /* Delete calendars that no longer show up in the config */
1814         ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, cb_rm_pending_deletion, NULL);
1815
1816         ast_mutex_unlock(&reloadlock);
1817
1818         return 0;
1819 }
1820
1821 static void *do_refresh(void *data)
1822 {
1823         for (;;) {
1824                 struct timeval now = ast_tvnow();
1825                 struct timespec ts = {0,};
1826                 int wait;
1827
1828                 ast_mutex_lock(&refreshlock);
1829
1830                 while (!module_unloading) {
1831                         if ((wait = ast_sched_wait(sched)) < 0) {
1832                                 wait = 1000;
1833                         }
1834
1835                         ts.tv_sec = (now.tv_sec + wait / 1000) + 1;
1836                         if (ast_cond_timedwait(&refresh_condition, &refreshlock, &ts) == ETIMEDOUT) {
1837                                 break;
1838                         }
1839                 }
1840                 ast_mutex_unlock(&refreshlock);
1841
1842                 if (module_unloading) {
1843                         break;
1844                 }
1845                 ast_sched_runq(sched);
1846         }
1847
1848         return NULL;
1849 }
1850
1851 /* If I were to allow unloading it would look something like this */
1852 static int unload_module(void)
1853 {
1854         struct ast_calendar_tech *tech;
1855
1856         ast_devstate_prov_del("calendar");
1857         ast_custom_function_unregister(&calendar_busy_function);
1858         ast_custom_function_unregister(&calendar_event_function);
1859         ast_custom_function_unregister(&calendar_query_function);
1860         ast_custom_function_unregister(&calendar_query_result_function);
1861         ast_custom_function_unregister(&calendar_write_function);
1862         ast_cli_unregister_multiple(calendar_cli, ARRAY_LEN(calendar_cli));
1863
1864         /* Remove all calendars */
1865         ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
1866         ao2_cleanup(calendars);
1867         calendars = NULL;
1868
1869         ast_mutex_lock(&refreshlock);
1870         module_unloading = 1;
1871         ast_cond_signal(&refresh_condition);
1872         ast_mutex_unlock(&refreshlock);
1873         pthread_join(refresh_thread, NULL);
1874
1875         ast_sched_context_destroy(sched);
1876
1877         AST_LIST_LOCK(&techs);
1878         AST_LIST_TRAVERSE_SAFE_BEGIN(&techs, tech, list) {
1879                 ast_unload_resource(tech->module, 0);
1880         }
1881         AST_LIST_TRAVERSE_SAFE_END;
1882         AST_LIST_UNLOCK(&techs);
1883
1884         ast_config_destroy(calendar_config);
1885         calendar_config = NULL;
1886
1887         return 0;
1888 }
1889
1890 /*!
1891  * \brief Load the module
1892  *
1893  * Module loading including tests for configuration or dependencies.
1894  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1895  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1896  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
1897  * configuration file or other non-critical problem return
1898  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1899  */
1900 static int load_module(void)
1901 {
1902         calendars = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, CALENDAR_BUCKETS,
1903                 calendar_hash_fn, NULL, calendar_cmp_fn);
1904         if (!calendars) {
1905                 ast_log(LOG_ERROR, "Unable to allocate calendars container!\n");
1906                 return AST_MODULE_LOAD_DECLINE;
1907         }
1908
1909         if (load_config(0)) {
1910                 /* We don't have calendar support enabled */
1911                 return AST_MODULE_LOAD_DECLINE;
1912         }
1913
1914         ast_mutex_init(&refreshlock);
1915         ast_cond_init(&refresh_condition, NULL);
1916         ast_mutex_init(&reloadlock);
1917
1918         if (!(sched = ast_sched_context_create())) {
1919                 ast_log(LOG_ERROR, "Unable to create sched context\n");
1920                 ast_config_destroy(calendar_config);
1921                 calendar_config = NULL;
1922                 return AST_MODULE_LOAD_DECLINE;
1923         }
1924
1925         if (ast_pthread_create_background(&refresh_thread, NULL, do_refresh, NULL) < 0) {
1926                 ast_log(LOG_ERROR, "Unable to start refresh thread--notifications disabled!\n");
1927         }
1928
1929         ast_custom_function_register(&calendar_busy_function);
1930         ast_custom_function_register(&calendar_event_function);
1931         ast_custom_function_register(&calendar_query_function);
1932         ast_custom_function_register(&calendar_query_result_function);
1933         ast_custom_function_register(&calendar_write_function);
1934         ast_cli_register_multiple(calendar_cli, ARRAY_LEN(calendar_cli));
1935
1936         ast_devstate_prov_add("Calendar", calendarstate);
1937
1938         return AST_MODULE_LOAD_SUCCESS;
1939 }
1940 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Asterisk Calendar integration",
1941         .support_level = AST_MODULE_SUPPORT_EXTENDED,
1942         .load = load_module,
1943         .unload = unload_module,
1944         .reload = reload,
1945         .load_pri = AST_MODPRI_DEVSTATE_PROVIDER,
1946 );