92b3f8
From 8c8c86d008da636d208ddeb8ac9cf9c06c4164a3 Mon Sep 17 00:00:00 2001
92b3f8
From: Willy Tarreau <w@1wt.eu>
92b3f8
Date: Thu, 3 Nov 2016 20:31:40 +0100
92b3f8
Subject: [PATCH] BUG/MEDIUM: systemd-wrapper: return correct exit codes
92b3f8
92b3f8
Gabriele Cerami reported the the exit codes of the systemd-wrapper are
92b3f8
wrong. In short, it directly returns the output of the wait syscall's
92b3f8
status, which is a composite value made of error code an signal numbers.
92b3f8
In general it contains the signal number on the lower bits and the error
92b3f8
code on the higher bits, but exit() truncates it to the lowest 8 bits,
92b3f8
causing config validations to incorrectly report a success. Example :
92b3f8
92b3f8
  $ ./haproxy-systemd-wrapper -c -f /dev/null
92b3f8
  <7>haproxy-systemd-wrapper: executing /tmp/haproxy -c -f /dev/null -Ds
92b3f8
  Configuration file has no error but will not start (no listener) => exit(2).
92b3f8
  <5>haproxy-systemd-wrapper: exit, haproxy RC=512
92b3f8
  $ echo $?
92b3f8
  0
92b3f8
92b3f8
If the process is killed however, the signal number is directly reported
92b3f8
in the exit code.
92b3f8
92b3f8
Let's fix all this to ensure that the exit code matches what the shell does,
92b3f8
which means that codes 0..127 are for exit codes, codes 128..254 for signals,
92b3f8
and code 255 for unknown exit code. Now the return code is correct :
92b3f8
92b3f8
  $ ./haproxy-systemd-wrapper -c -f /dev/null
92b3f8
  <7>haproxy-systemd-wrapper: executing /tmp/haproxy -c -f /dev/null -Ds
92b3f8
  Configuration file has no error but will not start (no listener) => exit(2).
92b3f8
  <5>haproxy-systemd-wrapper: exit, haproxy RC=2
92b3f8
  $ echo $?
92b3f8
  2
92b3f8
92b3f8
  $ ./haproxy-systemd-wrapper -f /tmp/cfg.conf
92b3f8
  <7>haproxy-systemd-wrapper: executing /tmp/haproxy -f /dev/null -Ds
92b3f8
  ^C
92b3f8
  <5>haproxy-systemd-wrapper: exit, haproxy RC=130
92b3f8
  $ echo $?
92b3f8
  130
92b3f8
92b3f8
This fix must be backported to 1.6 and 1.5.
92b3f8
---
92b3f8
 src/haproxy-systemd-wrapper.c | 10 ++++++++++
92b3f8
 1 file changed, 10 insertions(+)
92b3f8
92b3f8
diff --git a/src/haproxy-systemd-wrapper.c b/src/haproxy-systemd-wrapper.c
92b3f8
index 4e4d039..86520ca 100644
92b3f8
--- a/src/haproxy-systemd-wrapper.c
92b3f8
+++ b/src/haproxy-systemd-wrapper.c
92b3f8
@@ -215,6 +215,16 @@ int main(int argc, char **argv)
92b3f8
 		}
92b3f8
 	}
92b3f8
 
92b3f8
+	/* return either exit code or signal+128 */
92b3f8
+	if (WIFEXITED(status))
92b3f8
+		status = WEXITSTATUS(status);
92b3f8
+	else if (WIFSIGNALED(status))
92b3f8
+		status = 128 + WTERMSIG(status);
92b3f8
+	else if (WIFSTOPPED(status))
92b3f8
+		status = 128 + WSTOPSIG(status);
92b3f8
+	else
92b3f8
+		status = 255;
92b3f8
+
92b3f8
 	fprintf(stderr, SD_NOTICE "haproxy-systemd-wrapper: exit, haproxy RC=%d\n",
92b3f8
 			status);
92b3f8
 	return status;
92b3f8
-- 
92b3f8
2.7.4
92b3f8