check_ethernet: improve find_ssh_client for IPv6

This function had a number of problems:

(a) doesn't satisfy its description: it could print more than 1 IP,
    which its callers wouldn't really like
(b) it has this minor shellcheck warning:
    "SC1004: This backslash+linefeed is literal. Break outside single
     quotes if you just want to break the line."
(c) it only handles IPv4 properly (IPv6 has colons in the address, so we
    were only dumping the first hextet)

Fixes applied here:

 * netstat -l (listening) -- contradicts our search for "established"
 * netstat -p (program name) -- we ignore this
 * netstat -a (listening and non-listening) -- again, we're only looking
     for "established"
 * netstat -t -- add this, to limit the output netstat has to generate
 * netstat -W -- need wide printing, to fit IPv6 addresses
 * convert awk pattern to match columns more precisely, instead of a
     regex across the entire line
 * only look for the last colon when stripping the port (i.e.,
     dead:beef:...:22 -> dead:beef:...)
 * exit after the first match

Also, while netstat sort of gives us a time-ordered listing of
connections, it doesn't sort across different protocols (e.g., v4 vs.
v6). So just drop the "first" comment -- it's not really important to
the logic, as long as this finds some valid address.

BUG=none
TEST=none

Change-Id: I4d92d22572c5fd3bc8f85b97749a38cace8a0fb9
Reviewed-on: https://chromium-review.googlesource.com/1714130
Tested-by: Brian Norris <briannorris@chromium.org>
Commit-Ready: Brian Norris <briannorris@chromium.org>
Legacy-Commit-Queue: Commit Bot <commit-bot@chromium.org>
Reviewed-by: Grant Grundler <grundler@chromium.org>
Reviewed-by: Alex Khouderchah <akhouderchah@chromium.org>
diff --git a/recover_duts/hooks/check_ethernet.hook b/recover_duts/hooks/check_ethernet.hook
index 8e35c34..b36edbe 100755
--- a/recover_duts/hooks/check_ethernet.hook
+++ b/recover_duts/hooks/check_ethernet.hook
@@ -84,10 +84,15 @@
   return 1
 }
 
-# Return the remote IP address of the first established SSH connection
+# Return the remote IP address of an established SSH connection.
 find_ssh_client() {
-  netstat -lanp | awk '/tcp.*:22 .*ESTABLISHED.*/ {split($5,a,":");  \
-                         if (a[1] != "127.0.0.1") print a[1]}'
+  netstat -ntW | awk '$1 ~ /^tcp[6]?$/ && $4 ~ /:22$/ && $6 == "ESTABLISHED" {
+                         sub(/:[^:]*$/, "", $5);
+                         if ($5 != "127.0.0.1" && $5 != "::1") {
+                           print $5
+                           exit
+                         }
+                       }'
 }
 
 # Return the IP address of a neighbor reachable via ethernet