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