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