weston-launch: check string truncation

Since weston-launch is a setuid-root program we should be extra careful:
Check for a potential string trunction. Move the check in a separate
function and return with error in case trunction has happened.

Signed-off-by: Stefan Agner <stefan@agner.ch>
diff --git a/libweston/weston-launch.c b/libweston/weston-launch.c
index bfe70a7..911748a 100644
--- a/libweston/weston-launch.c
+++ b/libweston/weston-launch.c
@@ -295,6 +295,19 @@
 }
 
 static int
+open_tty_by_number(int ttynr)
+{
+	int ret;
+	char filename[16];
+
+	ret = snprintf(filename, sizeof filename, "/dev/tty%d", ttynr);
+	if (ret < 0)
+		return -1;
+
+	return open(filename, O_RDWR | O_NOCTTY);
+}
+
+static int
 send_reply(struct weston_launch *wl, int reply)
 {
 	int len;
@@ -557,7 +570,6 @@
 			wl->tty = open(tty, O_RDWR | O_NOCTTY);
 	} else {
 		int tty0 = open("/dev/tty0", O_WRONLY | O_CLOEXEC);
-		char filename[16];
 
 		if (tty0 < 0) {
 			fprintf(stderr, "weston: could not open tty0: %s\n",
@@ -572,8 +584,7 @@
 			return -1;
 		}
 
-		snprintf(filename, sizeof filename, "/dev/tty%d", wl->ttynr);
-		wl->tty = open(filename, O_RDWR | O_NOCTTY);
+		wl->tty = open_tty_by_number(wl->ttynr);
 		close(tty0);
 	}