Proposal to match behaviour of gethostbyname to glibc

Submitted by Wolf on April 26, 2020, 12:15 a.m.

Details

Message ID 20200426001522.rgwtcn66zquyrufq@wolfsden.cz
State New
Series "Proposal to match behaviour of gethostbyname to glibc"
Headers show

Commit Message

Wolf April 26, 2020, 12:15 a.m.
Hello,

On 2020-04-17 14:46:40 -0400, Rich Felker wrote:
> Actually now that I'm doing this I'm not sure it's correct. The
> existing code reports all matches from the hosts file, not just the
> first one. This patch will prevent getting both ipv4 and ipv6 results,
> or multiple results for the same address family, by stopping after the
> first one.

Well, I've completely missed that. Sorry.

> If you want the canonical name to come from the first result, rather
> than suppressing all but the first result, the code instead needs to
> be changed to remember that it already found one name and not copy any
> others.

I've attached patch v2 doing exactly that. Hopefully this time it's
correct.

W.

Patch hide | download patch | download mbox

diff --git a/src/network/lookup_name.c b/src/network/lookup_name.c
index c93263a9..00f056e6 100644
--- a/src/network/lookup_name.c
+++ b/src/network/lookup_name.c
@@ -50,7 +50,7 @@  static int name_from_hosts(struct address buf[static MAXADDRS], char canon[stati
 {
 	char line[512];
 	size_t l = strlen(name);
-	int cnt = 0, badfam = 0;
+	int cnt = 0, badfam = 0, have_canon = 0;
 	unsigned char _buf[1032];
 	FILE _f, *f = __fopen_rb_ca("/etc/hosts", &_f, _buf, sizeof _buf);
 	if (!f) switch (errno) {
@@ -83,11 +83,16 @@  static int name_from_hosts(struct address buf[static MAXADDRS], char canon[stati
 			continue;
 		}
 
+		if (have_canon) continue;
+
 		/* Extract first name as canonical name */
 		for (; *p && isspace(*p); p++);
 		for (z=p; *z && !isspace(*z); z++);
 		*z = 0;
-		if (is_valid_hostname(p)) memcpy(canon, p, z-p+1);
+		if (is_valid_hostname(p)) {
+			have_canon = 1;
+			memcpy(canon, p, z-p+1);
+		}
 	}
 	__fclose_ca(f);
 	return cnt ? cnt : badfam;