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