From 2ab5069d8a04c12a28b523323cb51055b02c815c Mon Sep 17 00:00:00 2001
From: Christian Brauner <christian.brauner@ubuntu.com>
Date: Thu, 25 Nov 2021 15:44:32 +0800
Subject: [PATCH] cgfsng: fix cgroup attach cgroup creation

Signed-off-by: Christian Brauner <christian.brauner@ubuntu.com>

(cherry-picked from https://github.com/lxc/lxc/pull/3526)
Signed-off-by: WangFengTu <wangfengtu@huawei.com>

Conflicts:
	src/lxc/cgroups/isulad_cgfsng.c
---
 src/lxc/cgroups/cgfsng.c        | 10 +++++++++-
 src/lxc/cgroups/isulad_cgfsng.c | 10 +++++++++-
 2 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/src/lxc/cgroups/cgfsng.c b/src/lxc/cgroups/cgfsng.c
index 3f81f5c..28ddf55 100644
--- a/src/lxc/cgroups/cgfsng.c
+++ b/src/lxc/cgroups/cgfsng.c
@@ -2090,13 +2090,21 @@ static int cgroup_attach_leaf(const struct lxc_conf *conf, int unified_fd, pid_t
 
 	do {
 		bool rm = false;
-		char attach_cgroup[STRLITERALLEN(".lxc-1000/cgroup.procs") + 1];
+		char attach_cgroup[STRLITERALLEN(".lxc-/cgroup.procs") + INTTYPE_TO_STRLEN(int) + 1];
 		char *slash;
 
 		ret = snprintf(attach_cgroup, sizeof(attach_cgroup), ".lxc-%d/cgroup.procs", idx);
 		if (ret < 0 || (size_t)ret >= sizeof(attach_cgroup))
 			return ret_errno(EIO);
 
+		/*
+		 * This shouldn't really happen but the compiler might complain
+		 * that a short write would cause a buffer overrun. So be on
+		 * the safe side.
+		 */
+		if (ret < STRLITERALLEN(".lxc-/cgroup.procs"))
+			return log_error_errno(-EINVAL, EINVAL, "Unexpected short write would cause buffer-overrun");
+
 		slash = &attach_cgroup[ret] - STRLITERALLEN("/cgroup.procs");
 		*slash = '\0';
 
diff --git a/src/lxc/cgroups/isulad_cgfsng.c b/src/lxc/cgroups/isulad_cgfsng.c
index c80527d..576b424 100644
--- a/src/lxc/cgroups/isulad_cgfsng.c
+++ b/src/lxc/cgroups/isulad_cgfsng.c
@@ -1766,13 +1766,21 @@ static int cgroup_attach_leaf(const struct lxc_conf *conf, int unified_fd, pid_t
 
 	do {
 		bool rm = false;
-		char attach_cgroup[STRLITERALLEN(".lxc-1000/cgroup.procs") + 1];
+		char attach_cgroup[STRLITERALLEN(".lxc-/cgroup.procs") + INTTYPE_TO_STRLEN(int) + 1];
 		char *slash;
 
 		ret = snprintf(attach_cgroup, sizeof(attach_cgroup), ".lxc-%d/cgroup.procs", idx);
 		if (ret < 0 || (size_t)ret >= sizeof(attach_cgroup))
 			return ret_errno(EIO);
 
+		/*
+		 * This shouldn't really happen but the compiler might complain
+		 * that a short write would cause a buffer overrun. So be on
+		 * the safe side.
+		 */
+		if (ret < STRLITERALLEN(".lxc-/cgroup.procs"))
+			return log_error_errno(-EINVAL, EINVAL, "Unexpected short write would cause buffer-overrun");
+
 		slash = &attach_cgroup[ret] - STRLITERALLEN("/cgroup.procs");
 		*slash = '\0';
 
-- 
2.25.1

