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