BUG/MINOR: tools: fix possible null-deref in env_expand() on out-of-memory

In GH issue #2586 @Bbulatov reported a theoretical null-deref in
env_expand() in case there's no memory anymore to expand an environment
variable. The function should return NULL in this case so that the only
caller (str2sa_range) sees it. In practice it may only happen during
boot thus is harmless but better fix it since it's easy. This can be
backported to all versions where this applies.

(cherry picked from commit ba958fb230d4add678913f18eb520d9d5935c968)
Signed-off-by: Amaury Denoyelle <adenoyelle@haproxy.com>
(cherry picked from commit 43192a0af8f981d50d01d4493bf8e1b124dec5be)
Signed-off-by: Amaury Denoyelle <adenoyelle@haproxy.com>
(cherry picked from commit 91bf1b1fbfd3da81d84bac2f8f07e87451ebcd25)
Signed-off-by: Amaury Denoyelle <adenoyelle@haproxy.com>
(cherry picked from commit 9cb2ca40eb5e98b7a703d2f42f075550b4ccc857)
Signed-off-by: Amaury Denoyelle <adenoyelle@haproxy.com>
(cherry picked from commit ad80d26d2d13b11b47a583355f011b53b44a2223)
Signed-off-by: Amaury Denoyelle <adenoyelle@haproxy.com>
diff --git a/src/tools.c b/src/tools.c
index 1bbdef1..72d2a51 100644
--- a/src/tools.c
+++ b/src/tools.c
@@ -4262,8 +4262,9 @@
  * corresponding value. A variable is identified as a series of alphanumeric
  * characters or underscores following a '$' sign. The <in> string must be
  * free()able. NULL returns NULL. The resulting string might be reallocated if
- * some expansion is made. Variable names may also be enclosed into braces if
- * needed (eg: to concatenate alphanum characters).
+ * some expansion is made (an NULL will be returned on failure). Variable names
+ * may also be enclosed into braces if needed (eg: to concatenate alphanum
+ * characters).
  */
 char *env_expand(char *in)
 {
@@ -4318,6 +4319,9 @@
 		}
 
 		out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
+		if (!out)
+			goto leave;
+
 		if (txt_end > txt_beg) {
 			memcpy(out + out_len, txt_beg, txt_end - txt_beg);
 			out_len += txt_end - txt_beg;
@@ -4332,6 +4336,7 @@
 
 	/* here we know that <out> was allocated and that we don't need <in> anymore */
 	free(in);
+leave:
 	return out;
 }