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