[PATCH] ui-shared: fix segfault in cgit_set_title_from_path

Eric Wong e at 80x24.org
Wed Jan 2 07:50:04 CET 2019


The following invocation of strncat uses a bogus size and
caused segfaults on my system:

  strncat(new_title, ctx.page.title, sizeof(new_title) - strlen(new_title) - 1);

Since str*cat functions are all bug-prone and slow (need to
search for '\0' at every invocation), switch to the safer and
easier-to-use strbuf* git API instead.
---
 ui-shared.c | 24 ++++++++++--------------
 1 file changed, 10 insertions(+), 14 deletions(-)

diff --git a/ui-shared.c b/ui-shared.c
index 7a4c726..bef8a78 100644
--- a/ui-shared.c
+++ b/ui-shared.c
@@ -1192,15 +1192,14 @@ void cgit_print_snapshot_links(const struct cgit_repo *repo, const char *ref,
 
 void cgit_set_title_from_path(const char *path)
 {
-	size_t path_len, path_index, path_last_end, line_len;
-	char *new_title;
+	size_t path_len, path_index, path_last_end;
+	struct strbuf sb;
 
 	if (!path)
 		return;
 
 	path_len = strlen(path);
-	new_title = xmalloc(path_len + 3 + strlen(ctx.page.title) + 1);
-	new_title[0] = '\0';
+	strbuf_init(&sb, path_len + 3 + strlen(ctx.page.title) + 1);
 
 	for (path_index = path_len, path_last_end = path_len; path_index-- > 0;) {
 		if (path[path_index] == '/') {
@@ -1208,19 +1207,16 @@ void cgit_set_title_from_path(const char *path)
 				path_last_end = path_index - 1;
 				continue;
 			}
-			strncat(new_title, &path[path_index + 1], path_last_end - path_index - 1);
-			line_len = strlen(new_title);
-			new_title[line_len++] = '\\';
-			new_title[line_len] = '\0';
+			strbuf_add(&sb, &path[path_index + 1],
+			           path_last_end - path_index - 1);
+			strbuf_addch(&sb, '\\');
 			path_last_end = path_index;
 		}
 	}
 	if (path_last_end)
-		strncat(new_title, path, path_last_end);
+		strbuf_add(&sb, path, path_last_end);
 
-	line_len = strlen(new_title);
-	memcpy(&new_title[line_len], " - ", 3);
-	new_title[line_len + 3] = '\0';
-	strncat(new_title, ctx.page.title, sizeof(new_title) - strlen(new_title) - 1);
-	ctx.page.title = new_title;
+	strbuf_add(&sb, " - ", 3);
+	strbuf_addstr(&sb, ctx.page.title);
+	ctx.page.title = strbuf_detach(&sb, NULL);
 }
-- 
EW



More information about the CGit mailing list