michael@0: # Copyright (c) 2012 The Chromium Authors. All rights reserved. michael@0: # Use of this source code is governed by a BSD-style license that can be michael@0: # found in the LICENSE file. michael@0: michael@0: import android_commands michael@0: import constants michael@0: import logging michael@0: import os michael@0: import subprocess michael@0: import time michael@0: michael@0: michael@0: class FakeDns(object): michael@0: """Wrapper class for the fake_dns tool.""" michael@0: _FAKE_DNS_PATH = constants.TEST_EXECUTABLE_DIR + '/fake_dns' michael@0: michael@0: def __init__(self, adb, build_type): michael@0: """ michael@0: Args: michael@0: adb: the AndroidCommands to use. michael@0: build_type: 'Release' or 'Debug'. michael@0: """ michael@0: self._adb = adb michael@0: self._build_type = build_type michael@0: self._fake_dns = None michael@0: self._original_dns = None michael@0: michael@0: def _PushAndStartFakeDns(self): michael@0: """Starts the fake_dns server that replies all name queries 127.0.0.1. michael@0: michael@0: Returns: michael@0: subprocess instance connected to the fake_dns process on the device. michael@0: """ michael@0: self._adb.PushIfNeeded( michael@0: os.path.join(constants.CHROME_DIR, 'out', self._build_type, 'fake_dns'), michael@0: FakeDns._FAKE_DNS_PATH) michael@0: return subprocess.Popen( michael@0: ['adb', '-s', self._adb._adb.GetSerialNumber(), michael@0: 'shell', '%s -D' % FakeDns._FAKE_DNS_PATH]) michael@0: michael@0: def SetUp(self): michael@0: """Configures the system to point to a DNS server that replies 127.0.0.1. michael@0: michael@0: This can be used in combination with the forwarder to forward all web michael@0: traffic to a replay server. michael@0: michael@0: The TearDown() method will perform all cleanup. michael@0: """ michael@0: self._adb.RunShellCommand('ip route add 8.8.8.0/24 via 127.0.0.1 dev lo') michael@0: self._fake_dns = self._PushAndStartFakeDns() michael@0: self._original_dns = self._adb.RunShellCommand('getprop net.dns1')[0] michael@0: self._adb.RunShellCommand('setprop net.dns1 127.0.0.1') michael@0: time.sleep(2) # Time for server to start and the setprop to take effect. michael@0: michael@0: def TearDown(self): michael@0: """Shuts down the fake_dns.""" michael@0: if self._fake_dns: michael@0: if not self._original_dns or self._original_dns == '127.0.0.1': michael@0: logging.warning('Bad original DNS, falling back to Google DNS.') michael@0: self._original_dns = '8.8.8.8' michael@0: self._adb.RunShellCommand('setprop net.dns1 %s' % self._original_dns) michael@0: self._fake_dns.kill() michael@0: self._adb.RunShellCommand('ip route del 8.8.8.0/24 via 127.0.0.1 dev lo')