Remove global variable that makes dlopen unhappy
[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\n");
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         while ((attendee = AST_LIST_REMOVE_HEAD(&src->attendees, next))) {
757                 AST_LIST_INSERT_TAIL(&dst->attendees, attendee, next);
758         }
759 }
760
761 static int schedule_calendar_event(struct ast_calendar *cal, struct ast_calendar_event *old_event, struct ast_calendar_event *cmp_event)
762 {
763         struct timeval now = ast_tvnow();
764         struct ast_calendar_event *event;
765         time_t alarm_notify_sched = 0, devstate_sched_start, devstate_sched_end;
766         int changed = 0;
767
768         event = cmp_event ? cmp_event : old_event;
769
770         ao2_lock(event);
771         if (!cmp_event || old_event->alarm != event->alarm) {
772                 changed = 1;
773                 if (cal->autoreminder) {
774                         alarm_notify_sched = (event->start - (60 * cal->autoreminder) - now.tv_sec) * 1000;
775                 } else if (event->alarm) {
776                         alarm_notify_sched = (event->alarm - now.tv_sec) * 1000;
777                 }
778
779                 /* For now, send the notification if we missed it, but the meeting hasn't happened yet */
780                 if (event->start >=  now.tv_sec) {
781                         if (alarm_notify_sched <= 0) {
782                                 alarm_notify_sched = 1;
783                         }
784                         ast_mutex_lock(&refreshlock);
785                         AST_SCHED_REPLACE(old_event->notify_sched, sched, alarm_notify_sched, calendar_event_notify, old_event);
786                         ast_mutex_unlock(&refreshlock);
787                         ast_debug(3, "Calendar alarm event notification scheduled to happen in %ld ms\n", (long) alarm_notify_sched);
788                 }
789         }
790
791         if (!cmp_event || old_event->start != event->start) {
792                 changed = 1;
793                 devstate_sched_start = (event->start - now.tv_sec) * 1000;
794
795                 if (devstate_sched_start < 1) {
796                         devstate_sched_start = 1;
797                 }
798
799                 ast_mutex_lock(&refreshlock);
800                 AST_SCHED_REPLACE(old_event->bs_start_sched, sched, devstate_sched_start, calendar_devstate_change, old_event);
801                 ast_mutex_unlock(&refreshlock);
802                 ast_debug(3, "Calendar bs_start event notification scheduled to happen in %ld ms\n", (long) devstate_sched_start);
803         }
804
805         if (!cmp_event || old_event->end != event->end) {
806                 changed = 1;
807                 devstate_sched_end = (event->end - now.tv_sec) * 1000;
808                 ast_mutex_lock(&refreshlock);
809                 AST_SCHED_REPLACE(old_event->bs_end_sched, sched, devstate_sched_end, calendar_devstate_change, old_event);
810                 ast_mutex_unlock(&refreshlock);
811                 ast_debug(3, "Calendar bs_end event notification scheduled to happen in %ld ms\n", (long) devstate_sched_end);
812         }
813
814         if (changed) {
815                 ast_cond_signal(&refresh_condition);
816         }
817
818         ao2_unlock(event);
819
820         return 0;
821 }
822
823 static int merge_events_cb(void *obj, void *arg, int flags)
824 {
825         struct ast_calendar_event *old_event = obj, *new_event;
826         struct ao2_container *new_events = arg;
827
828         /* If we don't find the old_event in new_events, then we can safely delete the old_event */
829         if (!(new_event = find_event(new_events, old_event->uid))) {
830                 old_event = destroy_event(old_event);
831                 return CMP_MATCH;
832         }
833
834         /* We have events to merge.  If any data that will affect a scheduler event has changed,
835          * then we need to replace the scheduler event */
836         schedule_calendar_event(old_event->owner, old_event, new_event);
837
838         /* Since we don't want to mess with cancelling sched events and adding new ones, just
839          * copy the internals of the new_event to the old_event */
840         copy_event_data(old_event, new_event);
841
842         /* Now we can go ahead and unlink the new_event from new_events and unref it so that only completely
843          * new events remain in the container */
844         ao2_unlink(new_events, new_event);
845         new_event = ast_calendar_unref_event(new_event);
846
847         return 0;
848 }
849
850 static int add_new_event_cb(void *obj, void *arg, int flags)
851 {
852         struct ast_calendar_event *new_event = obj;
853         struct ao2_container *events = arg;
854
855         ao2_link(events, new_event);
856         schedule_calendar_event(new_event->owner, new_event, NULL);
857         return CMP_MATCH;
858 }
859
860 void ast_calendar_merge_events(struct ast_calendar *cal, struct ao2_container *new_events)
861 {
862         /* Loop through all events attached to the calendar.  If there is a matching new event
863          * merge its data over and handle any schedule changes that need to be made.  Then remove
864          * the new_event from new_events so that we are left with only new_events that we can add later. */
865         ao2_callback(cal->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, merge_events_cb, new_events);
866
867         /* Now, we should only have completely new events in new_events.  Loop through and add them */
868         ao2_callback(new_events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, add_new_event_cb, cal->events);
869 }
870
871
872 static int load_config(void *data)
873 {
874         struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
875         struct ast_config *tmpcfg;
876
877         if (!(tmpcfg = ast_config_load2("calendar.conf", "calendar", config_flags)) ||
878                 tmpcfg == CONFIG_STATUS_FILEINVALID) {
879                 ast_log(LOG_ERROR, "Unable to load config calendar.conf\n");
880                 return -1;
881         }
882
883         if (tmpcfg == CONFIG_STATUS_FILEUNCHANGED) {
884                 return 0;
885         }
886
887         ast_rwlock_wrlock(&config_lock);
888         if (calendar_config) {
889                 ast_config_destroy(calendar_config);
890         }
891
892         calendar_config = tmpcfg;
893         ast_rwlock_unlock(&config_lock);
894
895         return 0;
896 }
897
898 /*! \brief A dialplan function that can be used to determine the busy status of a calendar */
899 static int calendar_busy_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
900 {
901         struct ast_calendar *cal;
902
903         if (ast_strlen_zero(data)) {
904                 ast_log(LOG_WARNING, "CALENDAR_BUSY requires an argument: CALENDAR_BUSY(<calendar_name>)\n");
905                 return -1;
906         }
907
908         cal = find_calendar(data);
909
910         if (!cal) {
911                 ast_log(LOG_WARNING, "Could not find calendar '%s'\n", data);
912                 return -1;
913         }
914
915         strcpy(buf, calendar_is_busy(cal) ? "1" : "0");
916
917         return 0;
918 }
919
920 static struct ast_custom_function calendar_busy_function = {
921     .name = "CALENDAR_BUSY",
922     .read = calendar_busy_exec,
923 };
924
925 static int add_event_to_list(struct eventlist *events, struct ast_calendar_event *event, time_t start, time_t end)
926 {
927         struct evententry *entry, *iter;
928         int event_startdiff = abs(start - event->start);
929         int event_enddiff = abs(end - event->end);
930         int i = 0;
931
932         if (!(entry = ast_calloc(1, sizeof(*entry)))) {
933                 ast_log(LOG_ERROR, "Unable to allocate memory for event list\n");
934                 return -1;
935         }
936
937         entry->event = event;
938         ao2_ref(event, +1);
939
940         if (start == end) {
941                 AST_LIST_TRAVERSE_SAFE_BEGIN(events, iter, list) {
942                         int startdiff = abs(iter->event->start - start);
943
944                         ast_debug(10, "Comparing %s with startdiff %d to %s with startdiff %d\n", event->summary, event_startdiff, iter->event->summary, startdiff);
945                         ++i;
946                         if (startdiff > event_startdiff) {
947                                 AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
948                                 return i;
949                         }
950                         if (startdiff == event_startdiff) {
951                                 int enddiff = abs(iter->event->end - end);
952
953                                 if (enddiff > event_enddiff) {
954                                         AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
955                                         return i;
956                                 }
957                                 if (event_startdiff == enddiff) {
958                                         if (strcmp(event->uid, iter->event->uid) < 0) {
959                                                 AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
960                                                 return i;
961                                         }
962                                 }
963                         }
964                 }
965                 AST_LIST_TRAVERSE_SAFE_END;
966
967                 AST_LIST_INSERT_TAIL(events, entry, list);
968
969                 return i;
970         }
971
972         AST_LIST_TRAVERSE_SAFE_BEGIN(events, iter, list) {
973                 ++i;
974                 if (iter->event->start > event->start) {
975                         AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
976                         return i;
977                 }
978
979                 if (iter->event->start == event->start) {
980                         if ((iter->event->end - iter->event->start) == (event->end - event->start)) {
981                                 if (strcmp(event->uid, iter->event->uid) < 0) {
982                                         AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
983                                         return i;
984                                 }
985                         }
986                         if ((iter->event->end - iter->event->start) < (event->end - event->start)) {
987                                 AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
988                                 return i;
989                         }
990                 }
991         }
992         AST_LIST_TRAVERSE_SAFE_END;
993
994         AST_LIST_INSERT_TAIL(events, entry, list);
995
996         return i;
997 }
998
999 static void eventlist_destroy(void *data)
1000 {
1001         struct eventlist *events = data;
1002
1003         ao2_ref(events, -1);
1004 }
1005
1006 static void *eventlist_duplicate(void *data)
1007 {
1008         struct eventlist *events = data;
1009
1010         if (!events) {
1011                 return NULL;
1012         }
1013
1014         ao2_ref(events, +1);
1015
1016         return events;
1017 }
1018
1019 static int calendar_query_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1020 {
1021         struct ast_calendar *cal;
1022         struct ao2_iterator i;
1023         struct ast_calendar_event *event;
1024         struct eventlist *events;
1025         time_t start = INT_MIN, end = INT_MAX;
1026         struct ast_datastore *eventlist_datastore;
1027         AST_DECLARE_APP_ARGS(args,
1028                 AST_APP_ARG(calendar);
1029                 AST_APP_ARG(start);
1030                 AST_APP_ARG(end);
1031         );
1032
1033         if (!chan) {
1034                 ast_log(LOG_WARNING, "%s requires a channel to store the data on\n", cmd);
1035                 return -1;
1036         }
1037
1038         AST_STANDARD_APP_ARGS(args, data);
1039
1040         if (ast_strlen_zero(args.calendar)) {
1041                 ast_log(LOG_WARNING, "%s requires a calendar argument\n", cmd);
1042                 return -1;
1043         }
1044
1045         if (!(cal = find_calendar(args.calendar))) {
1046                 ast_log(LOG_WARNING, "Unknown calendar '%s'\n", args.calendar);
1047                 return -1;
1048         }
1049
1050         if (!(events = ao2_alloc(sizeof(*events), eventlist_destructor))) {
1051                 ast_log(LOG_ERROR, "Unable to allocate memory for event list\n");
1052                 cal = unref_calendar(cal);
1053                 return -1;
1054         }
1055
1056         if (!ast_strlen_zero(args.start)) {
1057                 start = atoi(args.start);
1058         }
1059
1060         if (!ast_strlen_zero(args.end)) {
1061                 end = atoi(args.end);
1062         }
1063
1064         i = ao2_iterator_init(cal->events, 0);
1065         while ((event = ao2_iterator_next(&i))) {
1066                 if (!(start > event->end || end < event->start)) {
1067                         ast_debug(10, "%s (%ld - %ld) overlapped with (%ld - %ld)\n", event->summary, (long) event->start, (long) event->end, (long) start, (long) end);
1068                         if (add_event_to_list(events, event, start, end) < 0) {
1069                                 event = ast_calendar_unref_event(event);
1070                                 ao2_iterator_destroy(&i);
1071                                 return -1;
1072                         }
1073                 }
1074
1075                 event = ast_calendar_unref_event(event);
1076         }
1077         ao2_iterator_destroy(&i);
1078
1079         ast_channel_lock(chan);
1080         do {
1081                 generate_random_string(buf, len);
1082         } while (ast_channel_datastore_find(chan, &eventlist_datastore_info, buf));
1083         ast_channel_unlock(chan);
1084
1085         if (!(eventlist_datastore = ast_datastore_alloc(&eventlist_datastore_info, buf))) {
1086                 ast_log(LOG_ERROR, "Could not allocate datastore!\n");
1087                 return -1;
1088         }
1089
1090         eventlist_datastore->inheritance = DATASTORE_INHERIT_FOREVER;
1091         eventlist_datastore->data = events;
1092
1093         ast_channel_lock(chan);
1094         ast_channel_datastore_add(chan, eventlist_datastore);
1095         ast_channel_unlock(chan);
1096
1097         return 0;
1098 }
1099
1100 static struct ast_custom_function calendar_query_function = {
1101     .name = "CALENDAR_QUERY",
1102     .read = calendar_query_exec,
1103 };
1104
1105 static void calendar_join_attendees(struct ast_calendar_event *event, char *buf, size_t len)
1106 {
1107         struct ast_str *tmp;
1108         struct ast_calendar_attendee *attendee;
1109
1110         if (!(tmp = ast_str_create(32))) {
1111                 ast_log(LOG_ERROR, "Could not allocate memory for attendees!\n");
1112                 return;
1113         }
1114
1115         AST_LIST_TRAVERSE(&event->attendees, attendee, next) {
1116                 ast_str_append(&tmp, 0, "%s%s", attendee == AST_LIST_FIRST(&event->attendees) ? "" : ",", attendee->data);
1117         }
1118
1119         ast_copy_string(buf, ast_str_buffer(tmp), len);
1120         ast_free(tmp);
1121 }
1122
1123 static int calendar_query_result_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1124 {
1125         struct ast_datastore *datastore;
1126         struct eventlist *events;
1127         struct evententry *entry;
1128         int row = 1;
1129         AST_DECLARE_APP_ARGS(args,
1130                 AST_APP_ARG(id);
1131                 AST_APP_ARG(field);
1132                 AST_APP_ARG(row);
1133         );
1134
1135         if (!chan) {
1136                 ast_log(LOG_WARNING, "%s requires a channel\n", cmd);
1137                 return -1;
1138         }
1139
1140         AST_STANDARD_APP_ARGS(args, data);
1141
1142         if (ast_strlen_zero(args.id) || ast_strlen_zero(args.field)) {
1143                 ast_log(LOG_WARNING, "%s requires an id and a field", cmd);
1144                 return -1;
1145         }
1146
1147         ast_channel_lock(chan);
1148         if (!(datastore = ast_channel_datastore_find(chan, &eventlist_datastore_info, args.id))) {
1149                 ast_log(LOG_WARNING, "There is no event notification datastore with id '%s' on '%s'!\n", args.id, chan->name);
1150                 ast_channel_unlock(chan);
1151                 return -1;
1152         }
1153         ast_channel_unlock(chan);
1154
1155         if (!(events = datastore->data)) {
1156                 ast_log(LOG_WARNING, "The datastore contains no data!\n");
1157                 return -1;
1158         }
1159
1160         if (!ast_strlen_zero(args.row)) {
1161                 row = atoi(args.row);
1162         }
1163
1164         AST_LIST_TRAVERSE(events, entry, list) {
1165                 if (--row) {
1166                         continue;
1167                 }
1168                 if (!strcasecmp(args.field, "summary")) {
1169                         ast_copy_string(buf, entry->event->summary, len);
1170                 } else if (!strcasecmp(args.field, "description")) {
1171                         ast_copy_string(buf, entry->event->description, len);
1172                 } else if (!strcasecmp(args.field, "organizer")) {
1173                         ast_copy_string(buf, entry->event->organizer, len);
1174                 } else if (!strcasecmp(args.field, "location")) {
1175                         ast_copy_string(buf, entry->event->location, len);
1176                 } else if (!strcasecmp(args.field, "calendar")) {
1177                         ast_copy_string(buf, entry->event->owner->name, len);
1178                 } else if (!strcasecmp(args.field, "uid")) {
1179                         ast_copy_string(buf, entry->event->uid, len);
1180                 } else if (!strcasecmp(args.field, "start")) {
1181                         snprintf(buf, len, "%ld", (long) entry->event->start);
1182                 } else if (!strcasecmp(args.field, "end")) {
1183                         snprintf(buf, len, "%ld", (long) entry->event->end);
1184                 } else if (!strcasecmp(args.field, "busystate")) {
1185                         snprintf(buf, len, "%d", entry->event->busy_state);
1186                 } else if (!strcasecmp(args.field, "attendees")) {
1187                         calendar_join_attendees(entry->event, buf, len);
1188                 } else {
1189                         ast_log(LOG_WARNING, "Unknown field '%s'\n", args.field);
1190                 }
1191                 break;
1192         }
1193
1194         return 0;
1195 }
1196
1197 static struct ast_custom_function calendar_query_result_function = {
1198         .name = "CALENDAR_QUERY_RESULT",
1199         .read = calendar_query_result_exec,
1200 };
1201
1202 static int calendar_write_exec(struct ast_channel *chan, const char *cmd, char *data, const char *value)
1203 {
1204         int i, j, ret = -1;
1205         char *val_dup = NULL;
1206         struct ast_calendar *cal = NULL;
1207         struct ast_calendar_event *event = NULL;
1208         AST_DECLARE_APP_ARGS(fields,
1209                 AST_APP_ARG(field)[10];
1210         );
1211         AST_DECLARE_APP_ARGS(values,
1212                 AST_APP_ARG(value)[10];
1213         );
1214
1215         if (!(val_dup = ast_strdup(value))) {
1216                 ast_log(LOG_ERROR, "Could not allocate memory for values\n");
1217                 return -1;
1218         }
1219
1220         AST_STANDARD_APP_ARGS(fields, data);
1221         AST_STANDARD_APP_ARGS(values, val_dup);
1222
1223         /* XXX Eventually we will support unnamed calendars, so if we don't find one, we parse
1224          * for a calendar type and create it */
1225         if (!(cal = find_calendar(fields.field[0]))) {
1226                 ast_log(LOG_WARNING, "Couldn't find calendar '%s'\n", fields.field[0]);
1227                 goto write_cleanup;
1228         }
1229
1230         if (!(cal->tech->write_event)) {
1231                 ast_log(LOG_WARNING, "Calendar '%s' has no write function!\n", cal->name);
1232                 goto write_cleanup;
1233         }
1234
1235         if (!(event = ast_calendar_event_alloc(cal))) {
1236                 goto write_cleanup;
1237         }
1238
1239         if (ast_strlen_zero(fields.field[0])) {
1240                 ast_log(LOG_WARNING, "CALENDAR_WRITE requires a calendar name!\n");
1241                 goto write_cleanup;
1242         }
1243
1244         if (fields.argc - 1 != values.argc) {
1245                 ast_log(LOG_WARNING, "CALENDAR_WRITE should have the same number of fields (%d) and values (%d)!\n", fields.argc - 1, values.argc);
1246                 goto write_cleanup;
1247         }
1248
1249         event->owner = cal;
1250
1251         for (i = 1, j = 0; i < fields.argc; i++, j++) {
1252                 if (!strcasecmp(fields.field[i], "summary")) {
1253                         ast_string_field_set(event, summary, values.value[j]);
1254                 } else if (!strcasecmp(fields.field[i], "description")) {
1255                         ast_string_field_set(event, description, values.value[j]);
1256                 } else if (!strcasecmp(fields.field[i], "organizer")) {
1257                         ast_string_field_set(event, organizer, values.value[j]);
1258                 } else if (!strcasecmp(fields.field[i], "location")) {
1259                         ast_string_field_set(event, location, values.value[j]);
1260                 } else if (!strcasecmp(fields.field[i], "uid")) {
1261                         ast_string_field_set(event, uid, values.value[j]);
1262                 } else if (!strcasecmp(fields.field[i], "start")) {
1263                         event->start = atoi(values.value[j]);
1264                 } else if (!strcasecmp(fields.field[i], "end")) {
1265                         event->end = atoi(values.value[j]);
1266                 } else if (!strcasecmp(fields.field[i], "busystate")) {
1267                         event->busy_state = atoi(values.value[j]);
1268                 } else {
1269                         ast_log(LOG_WARNING, "Unknown calendar event field '%s'\n", fields.field[i]);
1270                 }
1271         }
1272
1273         if((ret = cal->tech->write_event(event))) {
1274                 ast_log(LOG_WARNING, "Writing event to calendar '%s' failed!\n", cal->name);
1275         }
1276
1277 write_cleanup:
1278         if (cal) {
1279                 cal = unref_calendar(cal);
1280         }
1281         if (event) {
1282                 event = ast_calendar_unref_event(event);
1283         }
1284         if (val_dup) {
1285                 ast_free(val_dup);
1286         }
1287
1288         return ret;
1289 }
1290
1291 static struct ast_custom_function calendar_write_function = {
1292         .name = "CALENDAR_WRITE",
1293         .write = calendar_write_exec,
1294 };
1295
1296 /*! \brief CLI command to list available calendars */
1297 static char *handle_show_calendars(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1298 {
1299 #define FORMAT "%-20.20s %-10.10s %-6.6s\n"
1300         struct ao2_iterator i;
1301         struct ast_calendar *cal;
1302
1303         switch(cmd) {
1304         case CLI_INIT:
1305                 e->command = "calendar show calendars";
1306                 e->usage =
1307                         "Usage: calendar show calendars\n"
1308                         "       Lists all registered calendars.\n";
1309                 return NULL;
1310         case CLI_GENERATE:
1311                 return NULL;
1312         }
1313
1314         ast_cli(a->fd, FORMAT, "Calendar", "Type", "Status");
1315         ast_cli(a->fd, FORMAT, "--------", "----", "------");
1316         i = ao2_iterator_init(calendars, 0);
1317         while ((cal = ao2_iterator_next(&i))) {
1318                 ast_cli(a->fd, FORMAT, cal->name, cal->tech->type, calendar_is_busy(cal) ? "busy" : "free");
1319                 cal = unref_calendar(cal);
1320         }
1321         ao2_iterator_destroy(&i);
1322
1323         return CLI_SUCCESS;
1324 #undef FORMAT
1325 }
1326
1327 static char *epoch_to_string(char *buf, size_t buflen, time_t epoch)
1328 {
1329         struct ast_tm tm;
1330         struct timeval tv = {
1331                 .tv_sec = epoch,
1332         };
1333
1334         if (!epoch) {
1335                 *buf = '\0';
1336                 return buf;
1337         }
1338         ast_localtime(&tv, &tm, NULL);
1339         ast_strftime(buf, buflen, "%F %r", &tm);
1340
1341         return buf;
1342 }
1343
1344 static char *handle_show_calendar(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1345 {
1346 #define FORMAT "%-17.17s : %-20.20s\n"
1347 #define FORMAT2 "%-12.12s: %-40.60s\n"
1348         struct ao2_iterator i;
1349         struct ast_calendar *cal;
1350         struct ast_calendar_event *event;
1351         int which = 0;
1352         char *ret = NULL;
1353
1354         switch(cmd) {
1355         case CLI_INIT:
1356                 e->command = "calendar show calendar";
1357                 e->usage =
1358                         "Usage: calendar show calendar <calendar name>\n"
1359                         "       Displays information about a calendar\n";
1360                 return NULL;
1361
1362         case CLI_GENERATE:
1363                 if (a->pos != 3) {
1364                         return NULL;
1365                 }
1366                 i = ao2_iterator_init(calendars, 0);
1367                 while ((cal = ao2_iterator_next(&i))) {
1368                         if (!strncasecmp(a->word, cal->name, strlen(a->word)) && ++which > a->n) {
1369                                 ret = ast_strdup(cal->name);
1370                                 cal = unref_calendar(cal);
1371                                 break;
1372                         }
1373                         cal = unref_calendar(cal);
1374                 }
1375                 ao2_iterator_destroy(&i);
1376                 return ret;
1377         }
1378
1379         if (a->argc != 4) {
1380                 return CLI_SHOWUSAGE;
1381         }
1382
1383         if (!(cal = find_calendar(a->argv[3]))) {
1384                 return NULL;
1385         }
1386
1387         ast_cli(a->fd, FORMAT, "Name", cal->name);
1388         ast_cli(a->fd, FORMAT, "Notify channel", cal->notify_channel);
1389         ast_cli(a->fd, FORMAT, "Notify context", cal->notify_context);
1390         ast_cli(a->fd, FORMAT, "Notify extension", cal->notify_extension);
1391         ast_cli(a->fd, FORMAT, "Notify application", cal->notify_app);
1392         ast_cli(a->fd, FORMAT, "Notify appdata", cal->notify_appdata);
1393         ast_cli(a->fd, "%-17.17s : %d\n", "Refresh time", cal->refresh);
1394         ast_cli(a->fd, "%-17.17s : %d\n", "Timeframe", cal->timeframe);
1395         ast_cli(a->fd, "%-17.17s : %d\n", "Autoreminder", cal->autoreminder);
1396         ast_cli(a->fd, "%s\n", "Events");
1397         ast_cli(a->fd, "%s\n", "------");
1398
1399         i = ao2_iterator_init(cal->events, 0);
1400         while ((event = ao2_iterator_next(&i))) {
1401                 char buf[100];
1402
1403                 ast_cli(a->fd, FORMAT2, "Summary", event->summary);
1404                 ast_cli(a->fd, FORMAT2, "Description", event->description);
1405                 ast_cli(a->fd, FORMAT2, "Organizer", event->organizer);
1406                 ast_cli(a->fd, FORMAT2, "Location", event->location);
1407                 ast_cli(a->fd, FORMAT2, "UID", event->uid);
1408                 ast_cli(a->fd, FORMAT2, "Start", epoch_to_string(buf, sizeof(buf), event->start));
1409                 ast_cli(a->fd, FORMAT2, "End", epoch_to_string(buf, sizeof(buf), event->end));
1410                 ast_cli(a->fd, FORMAT2, "Alarm", epoch_to_string(buf, sizeof(buf), event->alarm));
1411                 ast_cli(a->fd, "\n");
1412
1413                 event = ast_calendar_unref_event(event);
1414         }
1415         ao2_iterator_destroy(&i);
1416         cal = unref_calendar(cal);
1417         return CLI_SUCCESS;
1418 #undef FORMAT
1419 #undef FORMAT2
1420 }
1421
1422 static char *handle_dump_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1423 {
1424         switch(cmd) {
1425         case CLI_INIT:
1426                 e->command = "calendar dump sched";
1427                 e->usage =
1428                         "Usage: calendar dump sched\n"
1429                         "       Dump the calendar sched context";
1430                 return NULL;
1431
1432         case CLI_GENERATE:
1433                 return NULL;
1434         }
1435
1436         ast_sched_dump(sched);
1437
1438         return CLI_SUCCESS;
1439 }
1440
1441 static struct ast_cli_entry calendar_cli[] = {
1442         AST_CLI_DEFINE(handle_show_calendar, "Display information about a calendar"),
1443         AST_CLI_DEFINE(handle_show_calendars, "Show registered calendars"),
1444         AST_CLI_DEFINE(handle_dump_sched, "Dump calendar sched context"),
1445 };
1446
1447 static int calendar_event_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1448 {
1449         struct ast_datastore *datastore;
1450         struct ast_calendar_event *event;
1451
1452         if (ast_strlen_zero(data)) {
1453                 ast_log(LOG_WARNING, "%s requires an argument\n", cmd);
1454                 return -1;
1455         }
1456
1457         ast_channel_lock(chan);
1458         if (!(datastore = ast_channel_datastore_find(chan, &event_notification_datastore, NULL))) {
1459                 ast_log(LOG_WARNING, "There is no event notification datastore on '%s'!\n", chan->name);
1460                 ast_channel_unlock(chan);
1461                 return -1;
1462         }
1463         ast_channel_unlock(chan);
1464
1465         if (!(event = datastore->data)) {
1466                 ast_log(LOG_WARNING, "The datastore contains no data!\n");
1467                 return -1;
1468         }
1469
1470         if (!strcasecmp(data, "summary")) {
1471                 ast_copy_string(buf, event->summary, len);
1472         } else if (!strcasecmp(data, "description")) {
1473                 ast_copy_string(buf, event->description, len);
1474         } else if (!strcasecmp(data, "organizer")) {
1475                 ast_copy_string(buf, event->organizer, len);
1476         } else if (!strcasecmp(data, "location")) {
1477                 ast_copy_string(buf, event->location, len);
1478         } else if (!strcasecmp(data, "calendar")) {
1479                 ast_copy_string(buf, event->owner->name, len);
1480         } else if (!strcasecmp(data, "uid")) {
1481                 ast_copy_string(buf, event->uid, len);
1482         } else if (!strcasecmp(data, "start")) {
1483                 snprintf(buf, len, "%ld", (long)event->start);
1484         } else if (!strcasecmp(data, "end")) {
1485                 snprintf(buf, len, "%ld", (long)event->end);
1486         } else if (!strcasecmp(data, "busystate")) {
1487                 snprintf(buf, len, "%d", event->busy_state);
1488         } else if (!strcasecmp(data, "attendees")) {
1489                 calendar_join_attendees(event, buf, len);
1490         }
1491
1492
1493         return 0;
1494 }
1495
1496 static struct ast_custom_function calendar_event_function = {
1497         .name = "CALENDAR_EVENT",
1498         .read = calendar_event_read,
1499 };
1500
1501 static int cb_pending_deletion(void *user_data, void *arg, int flags)
1502 {
1503         struct ast_calendar *cal = user_data;
1504
1505         cal->pending_deletion = 1;
1506
1507         return CMP_MATCH;
1508 }
1509
1510 static int cb_rm_pending_deletion(void *user_data, void *arg, int flags)
1511 {
1512         struct ast_calendar *cal = user_data;
1513
1514         return cal->pending_deletion ? CMP_MATCH : 0;
1515 }
1516
1517 static int reload(void)
1518 {
1519         struct ast_calendar_tech *iter;
1520
1521         ast_mutex_lock(&reloadlock);
1522
1523         /* Mark existing calendars for deletion */
1524         ao2_callback(calendars, OBJ_NODATA | OBJ_MULTIPLE, cb_pending_deletion, NULL);
1525         load_config(NULL);
1526
1527         AST_LIST_LOCK(&techs);
1528         AST_LIST_TRAVERSE(&techs, iter, list) {
1529                 if (load_tech_calendars(iter)) {
1530                         ast_log(LOG_WARNING, "Failed to reload %s calendars, module disabled\n", iter->type);
1531                 }
1532         }
1533         AST_LIST_UNLOCK(&techs);
1534
1535         /* Delete calendars that no longer show up in the config */
1536         ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, cb_rm_pending_deletion, NULL);
1537
1538         ast_mutex_unlock(&reloadlock);
1539
1540         return 0;
1541 }
1542
1543 static void *do_refresh(void *data)
1544 {
1545         for (;;) {
1546                 struct timeval now = ast_tvnow();
1547                 struct timespec ts = {0,};
1548                 int res, wait;
1549
1550                 ast_mutex_lock(&refreshlock);
1551
1552                 if ((wait = ast_sched_wait(sched)) < 0) {
1553                         wait = 1000;
1554                 }
1555
1556                 ts.tv_sec = (now.tv_sec + wait / 1000) + 1;
1557                 res = ast_cond_timedwait(&refresh_condition, &refreshlock, &ts);
1558
1559                 ast_mutex_unlock(&refreshlock);
1560
1561                 ast_sched_runq(sched);
1562         }
1563
1564         return NULL;
1565 }
1566
1567 /* If I were to allow unloading it would look something like this */
1568 static int unload_module(void)
1569 {
1570         struct ast_calendar_tech *tech;
1571
1572         ast_devstate_prov_del("calendar");
1573         ast_custom_function_unregister(&calendar_busy_function);
1574         ast_custom_function_unregister(&calendar_event_function);
1575         ast_custom_function_unregister(&calendar_query_function);
1576         ast_custom_function_unregister(&calendar_query_result_function);
1577         ast_custom_function_unregister(&calendar_write_function);
1578         ast_cli_unregister_multiple(calendar_cli, ARRAY_LEN(calendar_cli));
1579
1580         /* Remove all calendars */
1581         ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
1582
1583         AST_LIST_LOCK(&techs);
1584         AST_LIST_TRAVERSE_SAFE_BEGIN(&techs, tech, list) {
1585                 ast_unload_resource(tech->module, 0);
1586         }
1587         AST_LIST_TRAVERSE_SAFE_END;
1588         AST_LIST_UNLOCK(&techs);
1589
1590         return 0;
1591 }
1592
1593 static int load_module(void)
1594 {
1595         if (load_config(NULL)) {
1596                 /* We don't have calendar support enabled */
1597                 return 0;
1598         }
1599
1600         if (!(calendars = ao2_container_alloc(CALENDAR_BUCKETS, calendar_hash_fn, calendar_cmp_fn))) {
1601                 ast_log(LOG_ERROR, "Unable to allocate calendars container!\n");
1602                 return -1;
1603         }
1604
1605         ast_mutex_init(&refreshlock);
1606         ast_cond_init(&refresh_condition, NULL);
1607         ast_mutex_init(&reloadlock);
1608
1609         if (!(sched = sched_context_create())) {
1610                 ast_log(LOG_ERROR, "Unable to create sched context\n");
1611                 return -1;
1612         }
1613
1614         if (ast_pthread_create_background(&refresh_thread, NULL, do_refresh, NULL) < 0) {
1615                 ast_log(LOG_ERROR, "Unable to start refresh thread--notifications disabled!\n");
1616         }
1617
1618         ast_custom_function_register(&calendar_busy_function);
1619         ast_custom_function_register(&calendar_event_function);
1620         ast_custom_function_register(&calendar_query_function);
1621         ast_custom_function_register(&calendar_query_result_function);
1622         ast_custom_function_register(&calendar_write_function);
1623         ast_cli_register_multiple(calendar_cli, ARRAY_LEN(calendar_cli));
1624
1625         ast_devstate_prov_add("Calendar", calendarstate);
1626
1627         /* Since other modules depend on this, disable unloading */
1628         ast_module_ref(ast_module_info->self);
1629
1630         return 0;
1631 }
1632 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Asterisk Calendar integration",
1633                 .load = load_module,
1634                 .unload = unload_module,
1635                 .reload = reload,
1636         );