From 4bdf24a689b52364a58cb7587b572a80515422b8 Mon Sep 17 00:00:00 2001
From: sungtae kim <sungtae@messagebird.com>
Date: Sun, 3 Mar 2019 16:20:24 +0100
Subject: [PATCH] res/res_rtp_asterisk.c: Fixing possible divide by zero

Currently, when the Asterisk calculates rtp statistics, it uses
sample_count as a unsigned integer parameter. This would be fine
for most of cases, but in case of large enough number of sample_count,
this might be causing the divide by zero error.

ASTERISK-28321

Change-Id: If7e0629abaceddd2166eb012456c53033ea26249
---
 res/res_rtp_asterisk.c | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)

diff --git a/res/res_rtp_asterisk.c b/res/res_rtp_asterisk.c
index c5d557ec1e..909d82a816 100644
--- a/res/res_rtp_asterisk.c
+++ b/res/res_rtp_asterisk.c
@@ -2755,6 +2755,14 @@ static double normdev_compute(double normdev, double sample, unsigned int sample
 	normdev = normdev * sample_count + sample;
 	sample_count++;
 
+	/*
+	 It's possible the sample_count hits the maximum value and back to 0.
+	 Set to 1 to prevent the divide by zero crash if the sample_count is 0.
+	 */
+	if (sample_count == 0) {
+		sample_count = 1;
+	}
+
 	return normdev / sample_count;
 }
 
@@ -2771,6 +2779,14 @@ static double stddev_compute(double stddev, double sample, double normdev, doubl
 	stddev = sample_count * stddev;
 	sample_count++;
 
+	/*
+	 It's possible the sample_count hits the maximum value and back to 0.
+	 Set to 1 to prevent the divide by zero crash if the sample_count is 0.
+	 */
+	if (sample_count == 0) {
+		sample_count = 1;
+	}
+
 	return stddev +
 		( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
 		( SQUARE(sample - normdev_curent) / sample_count );
-- 
GitLab