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