+done:
+ /* All done. */
+ dstr_destroy(&d);
+ if (fp) fclose(fp);
+ return (rc);
+}
+
+/* Convert the IPv4 socket address IN into the equivalent IPv4-mapped IPv6
+ * address OUT.
+ */
+static void map_v4(struct socket *out, const struct socket *in)
+{
+ unsigned i;
+ in_addr_t a4 = ntohl(in->addr.ipv4.s_addr);
+
+ for (i = 0; i < 10; i++) out->addr.ipv6.s6_addr[i] = 0;
+ for (i = 10; i < 12; i++) out->addr.ipv6.s6_addr[i] = 0xff;
+ for (i = 0; i < 4; i++) out->addr.ipv6.s6_addr[15 - i] = (a4 >> 8*i)&0xff;
+ out->port = in->port;
+}
+
+/* Convert the IPv4-mapped IPv6 socket address IN into the equivalent IPv4
+ * address OUT; return -1 if the IN address isn't actually IPv4-mapped.
+ */
+static int unmap_v4(struct socket *out, const struct socket *in)
+{
+ unsigned i;
+ in_addr_t a4 = 0;
+
+ for (i = 0; i < 10; i++) if (in->addr.ipv6.s6_addr[i] != 0) return (-1);
+ for (i = 10; i < 12; i++) if (in->addr.ipv6.s6_addr[i] != 0xff) return (-1);
+ for (i = 0; i < 4; i++) a4 |= in->addr.ipv6.s6_addr[15 - i] << 8*i;
+ out->addr.ipv4.s_addr = htonl(a4);
+ out->port = in->port;
+ return (0);
+}
+
+/* Find out who is responsible for the connection described in the query Q.
+ * Write the answer to Q. Errors are logged and reported via the query
+ * structure.
+ */
+void identify(struct query *q)
+{
+ FILE *fp = 0;
+ dstr d = DSTR_INIT;
+ char *p, *pp;
+ struct socket s[4];
+ int i;
+ int gwp = 0;
+ unsigned fl;
+#define F_SADDR 1u
+#define F_SPORT 2u
+#define F_DADDR 4u
+#define F_DPORT 8u
+#define F_ALL (F_SADDR | F_SPORT | F_DADDR | F_DPORT)
+#define F_ESTAB 16u
+
+ /* If we have a default gateway, and it matches the remote address then
+ * this may be a proxy connection from our NAT, so remember this, and don't
+ * inspect the remote addresses in the TCP tables.
+ */
+ if (!get_default_gw(q->ao->af, &s[0].addr) &&
+ q->ao->addreq(&s[0].addr, &q->s[R].addr))
+ gwp = 1;
+
+ /* Search the main `tcp' table. */
+ if (search_tcp_file(q, gwp, q->ao, q->s)) goto done;
+
+ /* Oh, dear. If this is IPv4, then the entry might actually be in the IPv6
+ * table, with weird addresses. So we must try again.
+ */