fake_dns.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. import android_commands
  5. import constants
  6. import logging
  7. import os
  8. import subprocess
  9. import time
  10. class FakeDns(object):
  11. """Wrapper class for the fake_dns tool."""
  12. _FAKE_DNS_PATH = constants.TEST_EXECUTABLE_DIR + '/fake_dns'
  13. def __init__(self, adb, build_type):
  14. """
  15. Args:
  16. adb: the AndroidCommands to use.
  17. build_type: 'Release' or 'Debug'.
  18. """
  19. self._adb = adb
  20. self._build_type = build_type
  21. self._fake_dns = None
  22. self._original_dns = None
  23. def _PushAndStartFakeDns(self):
  24. """Starts the fake_dns server that replies all name queries 127.0.0.1.
  25. Returns:
  26. subprocess instance connected to the fake_dns process on the device.
  27. """
  28. self._adb.PushIfNeeded(
  29. os.path.join(constants.CHROME_DIR, 'out', self._build_type, 'fake_dns'),
  30. FakeDns._FAKE_DNS_PATH)
  31. return subprocess.Popen(
  32. ['adb', '-s', self._adb._adb.GetSerialNumber(),
  33. 'shell', '%s -D' % FakeDns._FAKE_DNS_PATH])
  34. def SetUp(self):
  35. """Configures the system to point to a DNS server that replies 127.0.0.1.
  36. This can be used in combination with the forwarder to forward all web
  37. traffic to a replay server.
  38. The TearDown() method will perform all cleanup.
  39. """
  40. self._adb.RunShellCommand('ip route add 8.8.8.0/24 via 127.0.0.1 dev lo')
  41. self._fake_dns = self._PushAndStartFakeDns()
  42. self._original_dns = self._adb.RunShellCommand('getprop net.dns1')[0]
  43. self._adb.RunShellCommand('setprop net.dns1 127.0.0.1')
  44. time.sleep(2) # Time for server to start and the setprop to take effect.
  45. def TearDown(self):
  46. """Shuts down the fake_dns."""
  47. if self._fake_dns:
  48. if not self._original_dns or self._original_dns == '127.0.0.1':
  49. logging.warning('Bad original DNS, falling back to Google DNS.')
  50. self._original_dns = '8.8.8.8'
  51. self._adb.RunShellCommand('setprop net.dns1 %s' % self._original_dns)
  52. self._fake_dns.kill()
  53. self._adb.RunShellCommand('ip route del 8.8.8.0/24 via 127.0.0.1 dev lo')