From 64a764c33eee75f9b8cdd827b6961034542499eb Mon Sep 17 00:00:00 2001
From: Naveen Albert <asterisk@phreaknet.org>
Date: Wed, 23 Mar 2022 11:05:28 +0000
Subject: [PATCH] res_calendar: Prevent assertion if event ends in past.

res_calendar will trigger an assertion currently
if the ending time is calculated to be in the past.
Unlike the reminder and start times, however, there
is currently no check to catch non-positive times
and set them to 1. As a result, if we get a negative
value by happenstance, this can cause a crash.

To prevent the assertion from begin triggered, we now
use the same logic as the reminder and start events
to catch this issue before it can cause a problem.

ASTERISK-29981 #close

Change-Id: Idfb3204d195f350d2575fb4bc72a54a597d6e93c
---
 res/res_calendar.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/res/res_calendar.c b/res/res_calendar.c
index ba0079679f..98f9169347 100644
--- a/res/res_calendar.c
+++ b/res/res_calendar.c
@@ -998,10 +998,15 @@ static int schedule_calendar_event(struct ast_calendar *cal, struct ast_calendar
 	if (!cmp_event || old_event->end != event->end) {
 		changed = 1;
 		devstate_sched_end = (event->end - now.tv_sec) * 1000;
-		ast_mutex_lock(&refreshlock);
-		AST_SCHED_REPLACE(old_event->bs_end_sched, sched, devstate_sched_end, calendar_devstate_change, old_event);
-		ast_mutex_unlock(&refreshlock);
-		ast_debug(3, "Calendar bs_end event notification scheduled to happen in %ld ms\n", (long) devstate_sched_end);
+
+		if (devstate_sched_end <= 0) { /* if we let this slip by, Asterisk will assert */
+			ast_log(LOG_WARNING, "Whoops! Event end notification scheduled in the past: %ld ms\n", (long) devstate_sched_end);
+		} else {
+			ast_mutex_lock(&refreshlock);
+			AST_SCHED_REPLACE(old_event->bs_end_sched, sched, devstate_sched_end, calendar_devstate_change, old_event);
+			ast_mutex_unlock(&refreshlock);
+			ast_debug(3, "Calendar bs_end event notification scheduled to happen in %ld ms\n", (long) devstate_sched_end);
+		}
 	}
 
 	if (changed) {
-- 
GitLab