Thread (104 messages) 104 messages, 5 authors, 2016-06-15

[PATCH 36/67] remote-ext: simplify git pkt-line generation

flat view
STALE3765d

From: Jeff King <hidden>
Date: 2016-06-15 23:06:33
Subsystem: the rest · Maintainer: Linus Torvalds

We format a pkt-line into a heap buffer, which requires
manual computation of the required size. We can just use a
strbuf instead, which handles this for us, and lets us drop
some bare sprintf calls.

Note that we _could_ also use a fixed-size buffer here, as
we are limited by 16-bit pkt-line limit. But we'd still have
to worry about the length computation in that case, and the
allocation overhead is not important here.

Signed-off-by: Jeff King <redacted>
---
 builtin/remote-ext.c | 32 +++++++++-----------------------
 1 file changed, 9 insertions(+), 23 deletions(-)
diff --git a/builtin/remote-ext.c b/builtin/remote-ext.c
index 3b8c22c..1d991d9 100644
--- a/builtin/remote-ext.c
+++ b/builtin/remote-ext.c
@@ -142,36 +142,22 @@ static const char **parse_argv(const char *arg, const char *service)
 static void send_git_request(int stdin_fd, const char *serv, const char *repo,
 	const char *vhost)
 {
-	size_t bufferspace;
-	size_t wpos = 0;
-	char *buffer;
+	struct strbuf buffer = STRBUF_INIT;
 
-	/*
-	 * Request needs 12 bytes extra if there is vhost (xxxx \0host=\0) and
-	 * 6 bytes extra (xxxx \0) if there is no vhost.
-	 */
+	/* Generate packet with a dummy size header */
+	strbuf_addf(&buffer, "0000%s %s%c", serv, repo, 0);
 	if (vhost)
-		bufferspace = strlen(serv) + strlen(repo) + strlen(vhost) + 12;
-	else
-		bufferspace = strlen(serv) + strlen(repo) + 6;
+		strbuf_addf(&buffer, "host=%s%c", vhost, 0);
 
-	if (bufferspace > 0xFFFF)
+	/* Now go back and fill in the size */
+	if (buffer.len > 0xFFFF)
 		die("Request too large to send");
-	buffer = xmalloc(bufferspace);
-
-	/* Make the packet. */
-	wpos = sprintf(buffer, "%04x%s %s%c", (unsigned)bufferspace,
-		serv, repo, 0);
-
-	/* Add vhost if any. */
-	if (vhost)
-		sprintf(buffer + wpos, "host=%s%c", vhost, 0);
+	xsnprintf(buffer.buf, buffer.alloc, "%04x", (unsigned)buffer.len);
 
-	/* Send the request */
-	if (write_in_full(stdin_fd, buffer, bufferspace) < 0)
+	if (write_in_full(stdin_fd, buffer.buf, buffer.len) < 0)
 		die_errno("Failed to send request");
 
-	free(buffer);
+	strbuf_release(&buffer);
 }
 
 static int run_child(const char *arg, const char *service)
-- 
2.6.0.rc2.408.ga2926b9
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help