From 1c5285658dbe680eb9fcfcb6ec5dd5fbec09a8ff Mon Sep 17 00:00:00 2001
From: Sergei Turchanov <turchanov@farpost.com>
Date: Fri, 30 Aug 2019 12:54:38 +1000
Subject: [PATCH] Fix locale saving when using setlocale

Fix implemented by b74175e236c34beeb930c95bb25300c92a205cd3 is incorrect.
"setlocale" doesn't return previous locale like "uselocale" does.
Restored the original method from the commit
c397fb230f70cfa1dc8f3d387f4df8ebec6c1a63 to save locale.
---
 src/funcs.c   | 7 ++++++-
 src/readcdf.c | 9 +++++++--
 2 files changed, 13 insertions(+), 3 deletions(-)

diff --git a/src/funcs.c b/src/funcs.c
index 069e4d04..5a8aea61 100644
--- a/src/funcs.c
+++ b/src/funcs.c
@@ -556,7 +556,11 @@ file_regcomp(file_regex_t *rx, const char *pat, int flags)
 	rx->old_lc_ctype = uselocale(rx->c_lc_ctype);
 	assert(rx->old_lc_ctype != NULL);
 #else
-	rx->old_lc_ctype = setlocale(LC_CTYPE, "C");
+	rx->old_lc_ctype = setlocale(LC_CTYPE, NULL);
+	assert(rx->old_lc_ctype != NULL);
+	rx->old_lc_ctype = strdup(rx->old_lc_ctype);
+	assert(rx->old_lc_ctype != NULL);
+	(void)setlocale(LC_CTYPE, "C");
 #endif
 	rx->pat = pat;
 
@@ -583,6 +587,7 @@ file_regfree(file_regex_t *rx)
 	freelocale(rx->c_lc_ctype);
 #else
 	(void)setlocale(LC_CTYPE, rx->old_lc_ctype);
+	free(rx->old_lc_ctype);
 #endif
 }
 
diff --git a/src/readcdf.c b/src/readcdf.c
index e6ea8e47..4520eff8 100644
--- a/src/readcdf.c
+++ b/src/readcdf.c
@@ -120,7 +120,11 @@ cdf_app_to_mime(const char *vbuf, const struct nv *nv)
 	old_lc_ctype = uselocale(c_lc_ctype);
 	assert(old_lc_ctype != NULL);
 #else
-	char *old_lc_ctype = setlocale(LC_CTYPE, "C");
+	char *old_lc_ctype = setlocale(LC_CTYPE, NULL);
+	assert(old_lc_ctype != NULL);
+	old_lc_ctype = strdup(old_lc_ctype);
+	assert(old_lc_ctype != NULL);
+	(void)setlocale(LC_CTYPE, "C");
 #endif
 	for (i = 0; nv[i].pattern != NULL; i++)
 		if (strcasestr(vbuf, nv[i].pattern) != NULL) {
@@ -134,7 +138,8 @@ cdf_app_to_mime(const char *vbuf, const struct nv *nv)
 	(void)uselocale(old_lc_ctype);
 	freelocale(c_lc_ctype);
 #else
-	setlocale(LC_CTYPE, old_lc_ctype);
+	(void)setlocale(LC_CTYPE, old_lc_ctype);
+	free(old_lc_ctype);
 #endif
 	return rv;
 }
-- 
2.17.1

