]> git.ipfire.org Git - thirdparty/git.git/commitdiff
wrapper: add function to compare strings with different NUL termination
authorbrian m. carlson <sandals@crustytoothpaste.net>
Mon, 25 May 2020 19:58:50 +0000 (19:58 +0000)
committerJunio C Hamano <gitster@pobox.com>
Wed, 27 May 2020 17:07:06 +0000 (10:07 -0700)
When parsing capabilities for the pack protocol, there are times we'll
want to compare the value of a capability to a NUL-terminated string.
Since the data we're reading will be space-terminated, not
NUL-terminated, we need a function that compares the two strings, but
also checks that they're the same length.  Otherwise, if we used strncmp
to compare these strings, we might accidentally accept a parameter that
was a prefix of the expected value.

Add a function, xstrncmpz, that takes a NUL-terminated string and a
non-NUL-terminated string, plus a length, and compares them, ensuring
that they are the same length.

Signed-off-by: brian m. carlson <sandals@crustytoothpaste.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
git-compat-util.h
wrapper.c

index 8ba576e81e3e52843cc84350978a26df8e3344e7..a3dcfc8613a821a4b96c2e15403365da30c495f4 100644 (file)
@@ -868,6 +868,12 @@ char *xgetcwd(void);
 FILE *fopen_for_writing(const char *path);
 FILE *fopen_or_warn(const char *path, const char *mode);
 
+/*
+ * Like strncmp, but only return zero if s is NUL-terminated and exactly len
+ * characters long.  If it is not, consider it greater than t.
+ */
+int xstrncmpz(const char *s, const char *t, size_t len);
+
 /*
  * FREE_AND_NULL(ptr) is like free(ptr) followed by ptr = NULL. Note
  * that ptr is used twice, so don't pass e.g. ptr++.
index 3a1c0e052677dca8d1bc19121d609e0c226e88ee..4ff4a9c3db0e1c797bce777eac5358d74c0bc5c6 100644 (file)
--- a/wrapper.c
+++ b/wrapper.c
@@ -105,6 +105,14 @@ char *xstrndup(const char *str, size_t len)
        return xmemdupz(str, p ? p - str : len);
 }
 
+int xstrncmpz(const char *s, const char *t, size_t len)
+{
+       int res = strncmp(s, t, len);
+       if (res)
+               return res;
+       return s[len] == '\0' ? 0 : 1;
+}
+
 void *xrealloc(void *ptr, size_t size)
 {
        void *ret;