Merge 9c1fbfbc0e7c928087c24ef6d6ffb430fcad13e1 on remote branch

Change-Id: I4c4a6282b224994bced7db6a257f1bcadf80d6cc
diff --git a/net/test/all_tests.py b/net/test/all_tests.py
index 5f6c583..17d9701 100755
--- a/net/test/all_tests.py
+++ b/net/test/all_tests.py
@@ -18,6 +18,8 @@
 import sys
 import unittest
 
+import namespace
+
 test_modules = [
     'anycast_test',
     'bpf_test',
@@ -46,6 +48,9 @@
 ]
 
 if __name__ == '__main__':
+  # Check whether ADB over TCP is occupying TCP port 5555.
+  if namespace.HasEstablishedTcpSessionOnPort(5555):
+    namespace.IfPossibleEnterNewNetworkNamespace()
   # First, run InjectTests on all modules, to ensure that any parameterized
   # tests in those modules are injected.
   for name in test_modules:
diff --git a/net/test/namespace.py b/net/test/namespace.py
index 1144892..85db654 100644
--- a/net/test/namespace.py
+++ b/net/test/namespace.py
@@ -19,8 +19,11 @@
 import ctypes
 import ctypes.util
 import os
+import socket
 
 import net_test
+import sock_diag
+import tcp_test
 
 # //include/linux/fs.h
 MNT_FORCE       = 1         # Attempt to forcibily umount
@@ -76,7 +79,7 @@
   ret = libc.mount(src, tgt, fs, flags, None)
   if ret < 0:
     errno = ctypes.get_errno()
-    raise OSError(errno, '%s mounting %s on %s (fs=%s flags=%x)'
+    raise OSError(errno, '%s mounting %s on %s (fs=%s flags=0x%x)'
                   % (os.strerror(errno), src, tgt, fs, flags))
 
 
@@ -94,7 +97,7 @@
   open(f, 'w').write(s)
 
 
-def SetHostName(s):
+def SetHostname(s):
   ret = libc.sethostname(s, len(s))
   if ret < 0:
     errno = ctypes.get_errno()
@@ -105,7 +108,7 @@
   ret = libc.unshare(flags)
   if ret < 0:
     errno = ctypes.get_errno()
-    raise OSError(errno, '%s while unshare(%x)' % (os.strerror(errno), flags))
+    raise OSError(errno, '%s while unshare(0x%x)' % (os.strerror(errno), flags))
 
 
 def DumpMounts(hdr):
@@ -132,10 +135,11 @@
 
   try:
     # DumpMounts('Before:')
+    Mount('none', '/', None, MS_REC|MS_PRIVATE)
     ReMountProc()
     ReMountSys()
     # DumpMounts('After:')
-    SetHostName('netns')
+    SetHostname('netns')
     SetFileContents('/proc/sys/net/ipv4/ping_group_range', '0 2147483647')
     net_test.SetInterfaceUp('lo')
   except:
@@ -145,3 +149,17 @@
 
   print 'succeeded.'
   return True
+
+
+def HasEstablishedTcpSessionOnPort(port):
+  sd = sock_diag.SockDiag()
+
+  sock_id = sd._EmptyInetDiagSockId()
+  sock_id.sport = port
+
+  states = 1 << tcp_test.TCP_ESTABLISHED
+
+  matches = sd.DumpAllInetSockets(socket.IPPROTO_TCP, "",
+                                  sock_id=sock_id, states=states)
+
+  return len(matches) > 0