xgethostname: handle long hostnames

If the full hostname doesn't fit in the buffer supplied to gethostname, POSIX does not specify whether the buffer will be null-terminated, so to be safe, we should do it ourselves. Introduce new function, xgethostname, which ensures that there is always a \0 at the end of the buffer. Signed-off-by: David Turner <dturner@twosigma.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

David Turner committed Apr 18, 2017 at 17:57 UTC 5781a9a2703e96b01587bb95ceebcc53f2cee91c
6 files changed +19 -4
builtin/gc.c
+1 -1
@@ -232,7 +232,7 @@ static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
232 /* already locked */
233 return NULL;
234
235 - if (gethostname(my_host, sizeof(my_host)))
235 + if (xgethostname(my_host, sizeof(my_host)))
236 xsnprintf(my_host, sizeof(my_host), "unknown");
237
238 pidfile_path = git_pathdup("gc.pid");
builtin/receive-pack.c
+1 -1
@@ -1660,7 +1660,7 @@ static const char *unpack(int err_fd, struct shallow_info *si)
1660 argv_array_pushl(&child.args, "index-pack",
1661 "--stdin", hdr_arg, NULL);
1662
1663 - if (gethostname(hostname, sizeof(hostname)))
1663 + if (xgethostname(hostname, sizeof(hostname)))
1664 xsnprintf(hostname, sizeof(hostname), "localhost");
1665 argv_array_pushf(&child.args,
1666 "--keep=receive-pack %"PRIuMAX" on %s",
fetch-pack.c
+1 -1
@@ -746,7 +746,7 @@ static int get_pack(struct fetch_pack_args *args,
746 argv_array_push(&cmd.args, "--fix-thin");
747 if (args->lock_pack || unpack_limit) {
748 char hostname[HOST_NAME_MAX + 1];
749 - if (gethostname(hostname, sizeof(hostname)))
749 + if (xgethostname(hostname, sizeof(hostname)))
750 xsnprintf(hostname, sizeof(hostname), "localhost");
751 argv_array_pushf(&cmd.args,
752 "--keep=fetch-pack %"PRIuMAX " on %s",
git-compat-util.h
+2
@@ -882,6 +882,8 @@ extern int xsnprintf(char *dst, size_t max, const char *fmt, ...);
882 #define HOST_NAME_MAX 256
883 #endif
884
885 +extern int xgethostname(char *buf, size_t len);
886 +
887 /* in ctype.c, for kwset users */
888 extern const unsigned char tolower_trans_tbl[256];
889
ident.c
+1 -1
@@ -122,7 +122,7 @@ static void add_domainname(struct strbuf *out, int *is_bogus)
122 {
123 char buf[HOST_NAME_MAX + 1];
124
125 - if (gethostname(buf, sizeof(buf))) {
125 + if (xgethostname(buf, sizeof(buf))) {
126 warning_errno("cannot get host name");
127 strbuf_addstr(out, "(none)");
128 *is_bogus = 1;
wrapper.c
+13
@@ -679,3 +679,16 @@ void sleep_millisec(int millisec)
679 {
680 poll(NULL, 0, millisec);
681 }
682 +
683 +int xgethostname(char *buf, size_t len)
684 +{
685 + /*
686 + * If the full hostname doesn't fit in buf, POSIX does not
687 + * specify whether the buffer will be null-terminated, so to
688 + * be safe, do it ourselves.
689 + */
690 + int ret = gethostname(buf, len);
691 + if (!ret)
692 + buf[len - 1] = 0;
693 + return ret;
694 +}