f57669
Index: b/resolv/nss_dns/dns-host.c
f57669
===================================================================
f57669
--- a/resolv/nss_dns/dns-host.c
f57669
+++ b/resolv/nss_dns/dns-host.c
f57669
@@ -1051,7 +1051,10 @@ gaih_getanswer_slice (const querybuf *an
f57669
   int h_namelen = 0;
f57669
 
f57669
   if (ancount == 0)
f57669
-    return NSS_STATUS_NOTFOUND;
f57669
+    {
f57669
+      *h_errnop = HOST_NOT_FOUND;
f57669
+      return NSS_STATUS_NOTFOUND;
f57669
+    }
f57669
 
f57669
   while (ancount-- > 0 && cp < end_of_message && had_error == 0)
f57669
     {
f57669
@@ -1228,7 +1231,14 @@ gaih_getanswer_slice (const querybuf *an
f57669
   /* Special case here: if the resolver sent a result but it only
f57669
      contains a CNAME while we are looking for a T_A or T_AAAA record,
f57669
      we fail with NOTFOUND instead of TRYAGAIN.  */
f57669
-  return canon == NULL ? NSS_STATUS_TRYAGAIN : NSS_STATUS_NOTFOUND;
f57669
+  if (canon != NULL)
f57669
+    {
f57669
+      *h_errnop = HOST_NOT_FOUND;
f57669
+      return NSS_STATUS_NOTFOUND;
f57669
+    }
f57669
+
f57669
+  *h_errnop = NETDB_INTERNAL;
f57669
+  return NSS_STATUS_TRYAGAIN;
f57669
 }
f57669
 
f57669
 
f57669
@@ -1242,11 +1252,101 @@ gaih_getanswer (const querybuf *answer1,
f57669
 
f57669
   enum nss_status status = NSS_STATUS_NOTFOUND;
f57669
 
f57669
+  /* Combining the NSS status of two distinct queries requires some
f57669
+     compromise and attention to symmetry (A or AAAA queries can be
f57669
+     returned in any order).  What follows is a breakdown of how this
f57669
+     code is expected to work and why. We discuss only SUCCESS,
f57669
+     TRYAGAIN, NOTFOUND and UNAVAIL, since they are the only returns
f57669
+     that apply (though RETURN and MERGE exist).  We make a distinction
f57669
+     between TRYAGAIN (recoverable) and TRYAGAIN' (not-recoverable).
f57669
+     A recoverable TRYAGAIN is almost always due to buffer size issues
f57669
+     and returns ERANGE in errno and the caller is expected to retry
f57669
+     with a larger buffer.
f57669
+
f57669
+     Lastly, you may be tempted to make significant changes to the
f57669
+     conditions in this code to bring about symmetry between responses.
f57669
+     Please don't change anything without due consideration for
f57669
+     expected application behaviour.  Some of the synthesized responses
f57669
+     aren't very well thought out and sometimes appear to imply that
f57669
+     IPv4 responses are always answer 1, and IPv6 responses are always
f57669
+     answer 2, but that's not true (see the implemetnation of send_dg
f57669
+     and send_vc to see response can arrive in any order, particlarly
f57669
+     for UDP). However, we expect it holds roughly enough of the time
f57669
+     that this code works, but certainly needs to be fixed to make this
f57669
+     a more robust implementation.
f57669
+
f57669
+     ----------------------------------------------
f57669
+     | Answer 1 Status /   | Synthesized | Reason |
f57669
+     | Answer 2 Status     | Status      |        |
f57669
+     |--------------------------------------------|
f57669
+     | SUCCESS/SUCCESS     | SUCCESS     | [1]    |
f57669
+     | SUCCESS/TRYAGAIN    | TRYAGAIN    | [5]    |
f57669
+     | SUCCESS/TRYAGAIN'   | SUCCESS     | [1]    |
f57669
+     | SUCCESS/NOTFOUND    | SUCCESS     | [1]    |
f57669
+     | SUCCESS/UNAVAIL     | SUCCESS     | [1]    |
f57669
+     | TRYAGAIN/SUCCESS    | TRYAGAIN    | [2]    |
f57669
+     | TRYAGAIN/TRYAGAIN   | TRYAGAIN    | [2]    |
f57669
+     | TRYAGAIN/TRYAGAIN'  | TRYAGAIN    | [2]    |
f57669
+     | TRYAGAIN/NOTFOUND   | TRYAGAIN    | [2]    |
f57669
+     | TRYAGAIN/UNAVAIL    | TRYAGAIN    | [2]    |
f57669
+     | TRYAGAIN'/SUCCESS   | SUCCESS     | [3]    |
f57669
+     | TRYAGAIN'/TRYAGAIN  | TRYAGAIN    | [3]    |
f57669
+     | TRYAGAIN'/TRYAGAIN' | TRYAGAIN'   | [3]    |
f57669
+     | TRYAGAIN'/NOTFOUND  | TRYAGAIN'   | [3]    |
f57669
+     | TRYAGAIN'/UNAVAIL   | UNAVAIL     | [3]    |
f57669
+     | NOTFOUND/SUCCESS    | SUCCESS     | [3]    |
f57669
+     | NOTFOUND/TRYAGAIN   | TRYAGAIN    | [3]    |
f57669
+     | NOTFOUND/TRYAGAIN'  | TRYAGAIN'   | [3]    |
f57669
+     | NOTFOUND/NOTFOUND   | NOTFOUND    | [3]    |
f57669
+     | NOTFOUND/UNAVAIL    | UNAVAIL     | [3]    |
f57669
+     | UNAVAIL/SUCCESS     | UNAVAIL     | [4]    |
f57669
+     | UNAVAIL/TRYAGAIN    | UNAVAIL     | [4]    |
f57669
+     | UNAVAIL/TRYAGAIN'   | UNAVAIL     | [4]    |
f57669
+     | UNAVAIL/NOTFOUND    | UNAVAIL     | [4]    |
f57669
+     | UNAVAIL/UNAVAIL     | UNAVAIL     | [4]    |
f57669
+     ----------------------------------------------
f57669
+
f57669
+     [1] If the first response is a success we return success.
f57669
+         This ignores the state of the second answer and in fact
f57669
+         incorrectly sets errno and h_errno to that of the second
f57669
+	 answer.  However because the response is a success we ignore
f57669
+	 *errnop and *h_errnop (though that means you touched errno on
f57669
+         success).  We are being conservative here and returning the
f57669
+         likely IPv4 response in the first answer as a success.
f57669
+
f57669
+     [2] If the first response is a recoverable TRYAGAIN we return
f57669
+	 that instead of looking at the second response.  The
f57669
+	 expectation here is that we have failed to get an IPv4 response
f57669
+	 and should retry both queries.
f57669
+
f57669
+     [3] If the first response was not a SUCCESS and the second
f57669
+	 response is not NOTFOUND (had a SUCCESS, need to TRYAGAIN,
f57669
+	 or failed entirely e.g. TRYAGAIN' and UNAVAIL) then use the
f57669
+	 result from the second response, otherwise the first responses
f57669
+	 status is used.  Again we have some odd side-effects when the
f57669
+	 second response is NOTFOUND because we overwrite *errnop and
f57669
+	 *h_errnop that means that a first answer of NOTFOUND might see
f57669
+	 its *errnop and *h_errnop values altered.  Whether it matters
f57669
+	 in practice that a first response NOTFOUND has the wrong
f57669
+	 *errnop and *h_errnop is undecided.
f57669
+
f57669
+     [4] If the first response is UNAVAIL we return that instead of
f57669
+	 looking at the second response.  The expectation here is that
f57669
+	 it will have failed similarly e.g. configuration failure.
f57669
+
f57669
+     [5] Testing this code is complicated by the fact that truncated
f57669
+	 second response buffers might be returned as SUCCESS if the
f57669
+	 first answer is a SUCCESS.  To fix this we add symmetry to
f57669
+	 TRYAGAIN with the second response.  If the second response
f57669
+	 is a recoverable error we now return TRYAGIN even if the first
f57669
+	 response was SUCCESS.  */
f57669
+
f57669
   if (anslen1 > 0)
f57669
     status = gaih_getanswer_slice(answer1, anslen1, qname,
f57669
 				  &pat, &buffer, &buflen,
f57669
 				  errnop, h_errnop, ttlp,
f57669
 				  &first);
f57669
+
f57669
   if ((status == NSS_STATUS_SUCCESS || status == NSS_STATUS_NOTFOUND
f57669
        || (status == NSS_STATUS_TRYAGAIN
f57669
 	   /* We want to look at the second answer in case of an
f57669
@@ -1262,8 +1362,15 @@ gaih_getanswer (const querybuf *answer1,
f57669
 						     &pat, &buffer, &buflen,
f57669
 						     errnop, h_errnop, ttlp,
f57669
 						     &first);
f57669
+      /* Use the second response status in some cases.  */
f57669
       if (status != NSS_STATUS_SUCCESS && status2 != NSS_STATUS_NOTFOUND)
f57669
 	status = status2;
f57669
+      /* Do not return a truncated second response (unless it was
f57669
+         unavoidable e.g. unrecoverable TRYAGAIN).  */
f57669
+      if (status == NSS_STATUS_SUCCESS
f57669
+	  && (status2 == NSS_STATUS_TRYAGAIN
f57669
+	      && *errnop == ERANGE && *h_errnop != NO_RECOVERY))
f57669
+	status = NSS_STATUS_TRYAGAIN;
f57669
     }
f57669
 
f57669
   return status;
f57669
Index: b/resolv/res_query.c
f57669
===================================================================
f57669
--- a/resolv/res_query.c
f57669
+++ b/resolv/res_query.c
f57669
@@ -396,6 +396,7 @@ __libc_res_nsearch(res_state statp,
f57669
 		  {
f57669
 		    free (*answerp2);
f57669
 		    *answerp2 = NULL;
f57669
+		    *nanswerp2 = 0;
f57669
 		    *answerp2_malloced = 0;
f57669
 		  }
f57669
 	}
f57669
@@ -436,6 +437,7 @@ __libc_res_nsearch(res_state statp,
f57669
 			  {
f57669
 			    free (*answerp2);
f57669
 			    *answerp2 = NULL;
f57669
+			    *nanswerp2 = 0;
f57669
 			    *answerp2_malloced = 0;
f57669
 			  }
f57669
 
f57669
@@ -510,6 +512,7 @@ __libc_res_nsearch(res_state statp,
f57669
 	  {
f57669
 	    free (*answerp2);
f57669
 	    *answerp2 = NULL;
f57669
+	    *nanswerp2 = 0;
f57669
 	    *answerp2_malloced = 0;
f57669
 	  }
f57669
 	if (saved_herrno != -1)
f57669
Index: b/resolv/res_send.c
f57669
===================================================================
f57669
--- a/resolv/res_send.c
f57669
+++ b/resolv/res_send.c
f57669
@@ -1,3 +1,20 @@
f57669
+/* Copyright (C) 2016 Free Software Foundation, Inc.
f57669
+   This file is part of the GNU C Library.
f57669
+
f57669
+   The GNU C Library is free software; you can redistribute it and/or
f57669
+   modify it under the terms of the GNU Lesser General Public
f57669
+   License as published by the Free Software Foundation; either
f57669
+   version 2.1 of the License, or (at your option) any later version.
f57669
+
f57669
+   The GNU C Library is distributed in the hope that it will be useful,
f57669
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
f57669
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
f57669
+   Lesser General Public License for more details.
f57669
+
f57669
+   You should have received a copy of the GNU Lesser General Public
f57669
+   License along with the GNU C Library; if not, see
f57669
+   <http://www.gnu.org/licenses/>.  */
f57669
+
f57669
 /*
f57669
  * Copyright (c) 1985, 1989, 1993
f57669
  *    The Regents of the University of California.  All rights reserved.
f57669
@@ -360,6 +377,8 @@ __libc_res_nsend(res_state statp, const
f57669
 #ifdef USE_HOOKS
f57669
 	if (__builtin_expect (statp->qhook || statp->rhook, 0)) {
f57669
 		if (anssiz < MAXPACKET && ansp) {
f57669
+			/* Always allocate MAXPACKET, callers expect
f57669
+			   this specific size.  */
f57669
 			u_char *buf = malloc (MAXPACKET);
f57669
 			if (buf == NULL)
f57669
 				return (-1);
f57669
@@ -653,6 +672,77 @@ libresolv_hidden_def (res_nsend)
f57669
 
f57669
 /* Private */
f57669
 
f57669
+/* The send_vc function is responsible for sending a DNS query over TCP
f57669
+   to the nameserver numbered NS from the res_state STATP i.e.
f57669
+   EXT(statp).nssocks[ns].  The function supports sending both IPv4 and
f57669
+   IPv6 queries at the same serially on the same socket.
f57669
+
f57669
+   Please note that for TCP there is no way to disable sending both
f57669
+   queries, unlike UDP, which honours RES_SNGLKUP and RES_SNGLKUPREOP
f57669
+   and sends the queries serially and waits for the result after each
f57669
+   sent query.  This implemetnation should be corrected to honour these
f57669
+   options.
f57669
+
f57669
+   Please also note that for TCP we send both queries over the same
f57669
+   socket one after another.  This technically violates best practice
f57669
+   since the server is allowed to read the first query, respond, and
f57669
+   then close the socket (to service another client).  If the server
f57669
+   does this, then the remaining second query in the socket data buffer
f57669
+   will cause the server to send the client an RST which will arrive
f57669
+   asynchronously and the client's OS will likely tear down the socket
f57669
+   receive buffer resulting in a potentially short read and lost
f57669
+   response data.  This will force the client to retry the query again,
f57669
+   and this process may repeat until all servers and connection resets
f57669
+   are exhausted and then the query will fail.  It's not known if this
f57669
+   happens with any frequency in real DNS server implementations.  This
f57669
+   implementation should be corrected to use two sockets by default for
f57669
+   parallel queries.
f57669
+
f57669
+   The query stored in BUF of BUFLEN length is sent first followed by
f57669
+   the query stored in BUF2 of BUFLEN2 length.  Queries are sent
f57669
+   serially on the same socket.
f57669
+
f57669
+   Answers to the query are stored firstly in *ANSP up to a max of
f57669
+   *ANSSIZP bytes.  If more than *ANSSIZP bytes are needed and ANSCP
f57669
+   is non-NULL (to indicate that modifying the answer buffer is allowed)
f57669
+   then malloc is used to allocate a new response buffer and ANSCP and
f57669
+   ANSP will both point to the new buffer.  If more than *ANSSIZP bytes
f57669
+   are needed but ANSCP is NULL, then as much of the response as
f57669
+   possible is read into the buffer, but the results will be truncated.
f57669
+   When truncation happens because of a small answer buffer the DNS
f57669
+   packets header feild TC will bet set to 1, indicating a truncated
f57669
+   message and the rest of the socket data will be read and discarded.
f57669
+
f57669
+   Answers to the query are stored secondly in *ANSP2 up to a max of
f57669
+   *ANSSIZP2 bytes, with the actual response length stored in
f57669
+   *RESPLEN2.  If more than *ANSSIZP bytes are needed and ANSP2
f57669
+   is non-NULL (required for a second query) then malloc is used to
f57669
+   allocate a new response buffer, *ANSSIZP2 is set to the new buffer
f57669
+   size and *ANSP2_MALLOCED is set to 1.
f57669
+
f57669
+   The ANSP2_MALLOCED argument will eventually be removed as the
f57669
+   change in buffer pointer can be used to detect the buffer has
f57669
+   changed and that the caller should use free on the new buffer.
f57669
+
f57669
+   Note that the answers may arrive in any order from the server and
f57669
+   therefore the first and second answer buffers may not correspond to
f57669
+   the first and second queries.
f57669
+
f57669
+   It is not supported to call this function with a non-NULL ANSP2
f57669
+   but a NULL ANSCP.  Put another way, you can call send_vc with a
f57669
+   single unmodifiable buffer or two modifiable buffers, but no other
f57669
+   combination is supported.
f57669
+
f57669
+   It is the caller's responsibility to free the malloc allocated
f57669
+   buffers by detecting that the pointers have changed from their
f57669
+   original values i.e. *ANSCP or *ANSP2 has changed.
f57669
+
f57669
+   If errors are encountered then *TERRNO is set to an appropriate
f57669
+   errno value and a zero result is returned for a recoverable error,
f57669
+   and a less-than zero result is returned for a non-recoverable error.
f57669
+
f57669
+   If no errors are encountered then *TERRNO is left unmodified and
f57669
+   a the length of the first response in bytes is returned.  */
f57669
 static int
f57669
 send_vc(res_state statp,
f57669
 	const u_char *buf, int buflen, const u_char *buf2, int buflen2,
f57669
@@ -662,11 +752,7 @@ send_vc(res_state statp,
f57669
 {
f57669
 	const HEADER *hp = (HEADER *) buf;
f57669
 	const HEADER *hp2 = (HEADER *) buf2;
f57669
-	u_char *ans = *ansp;
f57669
-	int orig_anssizp = *anssizp;
f57669
-	// XXX REMOVE
f57669
-	// int anssiz = *anssizp;
f57669
-	HEADER *anhp = (HEADER *) ans;
f57669
+	HEADER *anhp = (HEADER *) *ansp;
f57669
 	struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
f57669
 	int truncating, connreset, resplen, n;
f57669
 	struct iovec iov[4];
f57669
@@ -742,6 +828,8 @@ send_vc(res_state statp,
f57669
 	 * Receive length & response
f57669
 	 */
f57669
 	int recvresp1 = 0;
f57669
+	/* Skip the second response if there is no second query.
f57669
+           To do that we mark the second response as received.  */
f57669
 	int recvresp2 = buf2 == NULL;
f57669
 	uint16_t rlen16;
f57669
  read_len:
f57669
@@ -778,33 +866,14 @@ send_vc(res_state statp,
f57669
 	u_char **thisansp;
f57669
 	int *thisresplenp;
f57669
 	if ((recvresp1 | recvresp2) == 0 || buf2 == NULL) {
f57669
+		/* We have not received any responses
f57669
+		   yet or we only have one response to
f57669
+		   receive.  */
f57669
 		thisanssizp = anssizp;
f57669
 		thisansp = anscp ?: ansp;
f57669
 		assert (anscp != NULL || ansp2 == NULL);
f57669
 		thisresplenp = &resplen;
f57669
 	} else {
f57669
-		if (*anssizp != MAXPACKET) {
f57669
-			/* No buffer allocated for the first
f57669
-			   reply.  We can try to use the rest
f57669
-			   of the user-provided buffer.  */
f57669
-#ifdef _STRING_ARCH_unaligned
f57669
-			*anssizp2 = orig_anssizp - resplen;
f57669
-			*ansp2 = *ansp + resplen;
f57669
-#else
f57669
-			int aligned_resplen
f57669
-			  = ((resplen + __alignof__ (HEADER) - 1)
f57669
-			     & ~(__alignof__ (HEADER) - 1));
f57669
-			*anssizp2 = orig_anssizp - aligned_resplen;
f57669
-			*ansp2 = *ansp + aligned_resplen;
f57669
-#endif
f57669
-		} else {
f57669
-			/* The first reply did not fit into the
f57669
-			   user-provided buffer.  Maybe the second
f57669
-			   answer will.  */
f57669
-			*anssizp2 = orig_anssizp;
f57669
-			*ansp2 = *ansp;
f57669
-		}
f57669
-
f57669
 		thisanssizp = anssizp2;
f57669
 		thisansp = ansp2;
f57669
 		thisresplenp = resplen2;
f57669
@@ -812,10 +881,14 @@ send_vc(res_state statp,
f57669
 	anhp = (HEADER *) *thisansp;
f57669
 
f57669
 	*thisresplenp = rlen;
f57669
-	if (rlen > *thisanssizp) {
f57669
-		/* Yes, we test ANSCP here.  If we have two buffers
f57669
-		   both will be allocatable.  */
f57669
-		if (__builtin_expect (anscp != NULL, 1)) {
f57669
+	/* Is the answer buffer too small?  */
f57669
+	if (*thisanssizp < rlen) {
f57669
+		/* If the current buffer is non-NULL and it's not
f57669
+		   pointing at the static user-supplied buffer then
f57669
+		   we can reallocate it.  */
f57669
+		if (thisansp != NULL && thisansp != ansp) {
f57669
+			/* Always allocate MAXPACKET, callers expect
f57669
+			   this specific size.  */
f57669
 			u_char *newp = malloc (MAXPACKET);
f57669
 			if (newp == NULL) {
f57669
 				*terrno = ENOMEM;
f57669
@@ -827,6 +900,9 @@ send_vc(res_state statp,
f57669
 			if (thisansp == ansp2)
f57669
 			  *ansp2_malloced = 1;
f57669
 			anhp = (HEADER *) newp;
f57669
+			/* A uint16_t can't be larger than MAXPACKET
f57669
+			   thus it's safe to allocate MAXPACKET but
f57669
+			   read RLEN bytes instead.  */
f57669
 			len = rlen;
f57669
 		} else {
f57669
 			Dprint(statp->options & RES_DEBUG,
f57669
@@ -990,6 +1066,66 @@ reopen (res_state statp, int *terrno, in
f57669
 	return 1;
f57669
 }
f57669
 
f57669
+/* The send_dg function is responsible for sending a DNS query over UDP
f57669
+   to the nameserver numbered NS from the res_state STATP i.e.
f57669
+   EXT(statp).nssocks[ns].  The function supports IPv4 and IPv6 queries
f57669
+   along with the ability to send the query in parallel for both stacks
f57669
+   (default) or serially (RES_SINGLKUP).  It also supports serial lookup
f57669
+   with a close and reopen of the socket used to talk to the server
f57669
+   (RES_SNGLKUPREOP) to work around broken name servers.
f57669
+
f57669
+   The query stored in BUF of BUFLEN length is sent first followed by
f57669
+   the query stored in BUF2 of BUFLEN2 length.  Queries are sent
f57669
+   in parallel (default) or serially (RES_SINGLKUP or RES_SNGLKUPREOP).
f57669
+
f57669
+   Answers to the query are stored firstly in *ANSP up to a max of
f57669
+   *ANSSIZP bytes.  If more than *ANSSIZP bytes are needed and ANSCP
f57669
+   is non-NULL (to indicate that modifying the answer buffer is allowed)
f57669
+   then malloc is used to allocate a new response buffer and ANSCP and
f57669
+   ANSP will both point to the new buffer.  If more than *ANSSIZP bytes
f57669
+   are needed but ANSCP is NULL, then as much of the response as
f57669
+   possible is read into the buffer, but the results will be truncated.
f57669
+   When truncation happens because of a small answer buffer the DNS
f57669
+   packets header feild TC will bet set to 1, indicating a truncated
f57669
+   message, while the rest of the UDP packet is discarded.
f57669
+
f57669
+   Answers to the query are stored secondly in *ANSP2 up to a max of
f57669
+   *ANSSIZP2 bytes, with the actual response length stored in
f57669
+   *RESPLEN2.  If more than *ANSSIZP bytes are needed and ANSP2
f57669
+   is non-NULL (required for a second query) then malloc is used to
f57669
+   allocate a new response buffer, *ANSSIZP2 is set to the new buffer
f57669
+   size and *ANSP2_MALLOCED is set to 1.
f57669
+
f57669
+   The ANSP2_MALLOCED argument will eventually be removed as the
f57669
+   change in buffer pointer can be used to detect the buffer has
f57669
+   changed and that the caller should use free on the new buffer.
f57669
+
f57669
+   Note that the answers may arrive in any order from the server and
f57669
+   therefore the first and second answer buffers may not correspond to
f57669
+   the first and second queries.
f57669
+
f57669
+   It is not supported to call this function with a non-NULL ANSP2
f57669
+   but a NULL ANSCP.  Put another way, you can call send_vc with a
f57669
+   single unmodifiable buffer or two modifiable buffers, but no other
f57669
+   combination is supported.
f57669
+
f57669
+   It is the caller's responsibility to free the malloc allocated
f57669
+   buffers by detecting that the pointers have changed from their
f57669
+   original values i.e. *ANSCP or *ANSP2 has changed.
f57669
+
f57669
+   If an answer is truncated because of UDP datagram DNS limits then
f57669
+   *V_CIRCUIT is set to 1 and the return value non-zero to indicate to
f57669
+   the caller to retry with TCP.  The value *GOTSOMEWHERE is set to 1
f57669
+   if any progress was made reading a response from the nameserver and
f57669
+   is used by the caller to distinguish between ECONNREFUSED and
f57669
+   ETIMEDOUT (the latter if *GOTSOMEWHERE is 1).
f57669
+
f57669
+   If errors are encountered then *TERRNO is set to an appropriate
f57669
+   errno value and a zero result is returned for a recoverable error,
f57669
+   and a less-than zero result is returned for a non-recoverable error.
f57669
+
f57669
+   If no errors are encountered then *TERRNO is left unmodified and
f57669
+   a the length of the first response in bytes is returned.  */
f57669
 static int
f57669
 send_dg(res_state statp,
f57669
 	const u_char *buf, int buflen, const u_char *buf2, int buflen2,
f57669
@@ -999,8 +1135,6 @@ send_dg(res_state statp,
f57669
 {
f57669
 	const HEADER *hp = (HEADER *) buf;
f57669
 	const HEADER *hp2 = (HEADER *) buf2;
f57669
-	u_char *ans = *ansp;
f57669
-	int orig_anssizp = *anssizp;
f57669
 	struct timespec now, timeout, finish;
f57669
 	struct pollfd pfd[1];
f57669
 	int ptimeout;
f57669
@@ -1033,6 +1167,8 @@ send_dg(res_state statp,
f57669
 	int need_recompute = 0;
f57669
 	int nwritten = 0;
f57669
 	int recvresp1 = 0;
f57669
+	/* Skip the second response if there is no second query.
f57669
+           To do that we mark the second response as received.  */
f57669
 	int recvresp2 = buf2 == NULL;
f57669
 	pfd[0].fd = EXT(statp).nssocks[ns];
f57669
 	pfd[0].events = POLLOUT;
f57669
@@ -1196,52 +1332,54 @@ send_dg(res_state statp,
f57669
 		int *thisresplenp;
f57669
 
f57669
 		if ((recvresp1 | recvresp2) == 0 || buf2 == NULL) {
f57669
+			/* We have not received any responses
f57669
+			   yet or we only have one response to
f57669
+			   receive.  */
f57669
 			thisanssizp = anssizp;
f57669
 			thisansp = anscp ?: ansp;
f57669
 			assert (anscp != NULL || ansp2 == NULL);
f57669
 			thisresplenp = &resplen;
f57669
 		} else {
f57669
-			if (*anssizp != MAXPACKET) {
f57669
-				/* No buffer allocated for the first
f57669
-				   reply.  We can try to use the rest
f57669
-				   of the user-provided buffer.  */
f57669
-#ifdef _STRING_ARCH_unaligned
f57669
-				*anssizp2 = orig_anssizp - resplen;
f57669
-				*ansp2 = *ansp + resplen;
f57669
-#else
f57669
-				int aligned_resplen
f57669
-				  = ((resplen + __alignof__ (HEADER) - 1)
f57669
-				     & ~(__alignof__ (HEADER) - 1));
f57669
-				*anssizp2 = orig_anssizp - aligned_resplen;
f57669
-				*ansp2 = *ansp + aligned_resplen;
f57669
-#endif
f57669
-			} else {
f57669
-				/* The first reply did not fit into the
f57669
-				   user-provided buffer.  Maybe the second
f57669
-				   answer will.  */
f57669
-				*anssizp2 = orig_anssizp;
f57669
-				*ansp2 = *ansp;
f57669
-			}
f57669
-
f57669
 			thisanssizp = anssizp2;
f57669
 			thisansp = ansp2;
f57669
 			thisresplenp = resplen2;
f57669
 		}
f57669
 
f57669
 		if (*thisanssizp < MAXPACKET
f57669
-		    /* Yes, we test ANSCP here.  If we have two buffers
f57669
-		       both will be allocatable.  */
f57669
-		    && anscp
f57669
+		    /* If the current buffer is non-NULL and it's not
f57669
+		       pointing at the static user-supplied buffer then
f57669
+		       we can reallocate it.  */
f57669
+		    && (thisansp != NULL && thisansp != ansp)
f57669
+		    /* Is the size too small?  */
f57669
 		    && (ioctl (pfd[0].fd, FIONREAD, thisresplenp) < 0
f57669
-			|| *thisanssizp < *thisresplenp)) {
f57669
+			|| *thisanssizp < *thisresplenp)
f57669
+		    ) {
f57669
+			/* Always allocate MAXPACKET, callers expect
f57669
+			   this specific size.  */
f57669
 			u_char *newp = malloc (MAXPACKET);
f57669
 			if (newp != NULL) {
f57669
-				*anssizp = MAXPACKET;
f57669
-				*thisansp = ans = newp;
f57669
+				*thisanssizp = MAXPACKET;
f57669
+				*thisansp = newp;
f57669
 				if (thisansp == ansp2)
f57669
 				  *ansp2_malloced = 1;
f57669
 			}
f57669
 		}
f57669
+		/* We could end up with truncation if anscp was NULL
f57669
+		   (not allowed to change caller's buffer) and the
f57669
+		   response buffer size is too small.  This isn't a
f57669
+		   reliable way to detect truncation because the ioctl
f57669
+		   may be an inaccurate report of the UDP message size.
f57669
+		   Therefore we use this only to issue debug output.
f57669
+		   To do truncation accurately with UDP we need
f57669
+		   MSG_TRUNC which is only available on Linux.  We
f57669
+		   can abstract out the Linux-specific feature in the
f57669
+		   future to detect truncation.  */
f57669
+		if (__glibc_unlikely (*thisanssizp < *thisresplenp)) {
f57669
+			Dprint(statp->options & RES_DEBUG,
f57669
+			       (stdout, ";; response may be truncated (UDP)\n")
f57669
+			);
f57669
+		}
f57669
+
f57669
 		HEADER *anhp = (HEADER *) *thisansp;
f57669
 		socklen_t fromlen = sizeof(struct sockaddr_in6);
f57669
 		assert (sizeof(from) <= fromlen);