platformsettings.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. #!/usr/bin/env python
  2. # Copyright 2010 Google Inc. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Provides cross-platform utility functions.
  16. Example:
  17. import platformsettings
  18. ip = platformsettings.get_server_ip_address()
  19. Functions with "_temporary_" in their name automatically clean-up upon
  20. termination (via the atexit module).
  21. For the full list of functions, see the bottom of the file.
  22. """
  23. import atexit
  24. import distutils.spawn
  25. import distutils.version
  26. import fileinput
  27. import logging
  28. import os
  29. import platform
  30. import re
  31. import socket
  32. import stat
  33. import subprocess
  34. import sys
  35. import time
  36. import urlparse
  37. class PlatformSettingsError(Exception):
  38. """Module catch-all error."""
  39. pass
  40. class DnsReadError(PlatformSettingsError):
  41. """Raised when unable to read DNS settings."""
  42. pass
  43. class DnsUpdateError(PlatformSettingsError):
  44. """Raised when unable to update DNS settings."""
  45. pass
  46. class NotAdministratorError(PlatformSettingsError):
  47. """Raised when not running as administrator."""
  48. pass
  49. class CalledProcessError(PlatformSettingsError):
  50. """Raised when a _check_output() process returns a non-zero exit status."""
  51. def __init__(self, returncode, cmd):
  52. super(CalledProcessError, self).__init__()
  53. self.returncode = returncode
  54. self.cmd = cmd
  55. def __str__(self):
  56. return 'Command "%s" returned non-zero exit status %d' % (
  57. ' '.join(self.cmd), self.returncode)
  58. def FindExecutable(executable):
  59. """Finds the given executable in PATH.
  60. Since WPR may be invoked as sudo, meaning PATH is empty, we also hardcode a
  61. few common paths.
  62. Returns:
  63. The fully qualified path with .exe appended if appropriate or None if it
  64. doesn't exist.
  65. """
  66. return distutils.spawn.find_executable(executable,
  67. os.pathsep.join([os.environ['PATH'],
  68. '/sbin',
  69. '/usr/bin',
  70. '/usr/sbin/',
  71. '/usr/local/sbin',
  72. ]))
  73. def HasSniSupport():
  74. try:
  75. import OpenSSL
  76. return (distutils.version.StrictVersion(OpenSSL.__version__) >=
  77. distutils.version.StrictVersion('0.13'))
  78. except ImportError:
  79. return False
  80. def SupportsFdLimitControl():
  81. """Whether the platform supports changing the process fd limit."""
  82. return os.name is 'posix'
  83. def GetFdLimit():
  84. """Returns a tuple of (soft_limit, hard_limit)."""
  85. import resource
  86. return resource.getrlimit(resource.RLIMIT_NOFILE)
  87. def AdjustFdLimit(new_soft_limit, new_hard_limit):
  88. """Sets a new soft and hard limit for max number of fds."""
  89. import resource
  90. resource.setrlimit(resource.RLIMIT_NOFILE, (new_soft_limit, new_hard_limit))
  91. class SystemProxy(object):
  92. """A host/port pair for a HTTP or HTTPS proxy configuration."""
  93. def __init__(self, host, port):
  94. """Initialize a SystemProxy instance.
  95. Args:
  96. host: a host name or IP address string (e.g. "example.com" or "1.1.1.1").
  97. port: a port string or integer (e.g. "8888" or 8888).
  98. """
  99. self.host = host
  100. self.port = int(port) if port else None
  101. def __nonzero__(self):
  102. """True if the host is set."""
  103. return bool(self.host)
  104. @classmethod
  105. def from_url(cls, proxy_url):
  106. """Create a SystemProxy instance.
  107. If proxy_url is None, an empty string, or an invalid URL, the
  108. SystemProxy instance with have None and None for the host and port
  109. (no exception is raised).
  110. Args:
  111. proxy_url: a proxy url string such as "http://proxy.com:8888/".
  112. Returns:
  113. a System proxy instance.
  114. """
  115. if proxy_url:
  116. parse_result = urlparse.urlparse(proxy_url)
  117. return cls(parse_result.hostname, parse_result.port)
  118. return cls(None, None)
  119. class _BasePlatformSettings(object):
  120. def get_system_logging_handler(self):
  121. """Return a handler for the logging module (optional)."""
  122. return None
  123. def rerun_as_administrator(self):
  124. """If needed, rerun the program with administrative privileges.
  125. Raises NotAdministratorError if unable to rerun.
  126. """
  127. pass
  128. def timer(self):
  129. """Return the current time in seconds as a floating point number."""
  130. return time.time()
  131. def get_server_ip_address(self, is_server_mode=False):
  132. """Returns the IP address to use for dnsproxy and ipfw."""
  133. if is_server_mode:
  134. return socket.gethostbyname(socket.gethostname())
  135. return '127.0.0.1'
  136. def get_httpproxy_ip_address(self, is_server_mode=False):
  137. """Returns the IP address to use for httpproxy."""
  138. if is_server_mode:
  139. return '0.0.0.0'
  140. return '127.0.0.1'
  141. def get_system_proxy(self, use_ssl):
  142. """Returns the system HTTP(S) proxy host, port."""
  143. del use_ssl
  144. return SystemProxy(None, None)
  145. def _ipfw_cmd(self):
  146. raise NotImplementedError
  147. def ipfw(self, *args):
  148. ipfw_cmd = (self._ipfw_cmd(), ) + args
  149. return self._check_output(*ipfw_cmd, elevate_privilege=True)
  150. def has_ipfw(self):
  151. try:
  152. self.ipfw('list')
  153. return True
  154. except AssertionError as e:
  155. logging.warning('Failed to start ipfw command. '
  156. 'Error: %s' % e.message)
  157. return False
  158. def _get_cwnd(self):
  159. return None
  160. def _set_cwnd(self, args):
  161. pass
  162. def _elevate_privilege_for_cmd(self, args):
  163. return args
  164. def _check_output(self, *args, **kwargs):
  165. """Run Popen(*args) and return its output as a byte string.
  166. Python 2.7 has subprocess.check_output. This is essentially the same
  167. except that, as a convenience, all the positional args are used as
  168. command arguments and the |elevate_privilege| kwarg is supported.
  169. Args:
  170. *args: sequence of program arguments
  171. elevate_privilege: Run the command with elevated privileges.
  172. Raises:
  173. CalledProcessError if the program returns non-zero exit status.
  174. Returns:
  175. output as a byte string.
  176. """
  177. command_args = [str(a) for a in args]
  178. if os.path.sep not in command_args[0]:
  179. qualified_command = FindExecutable(command_args[0])
  180. assert qualified_command, 'Failed to find %s in path' % command_args[0]
  181. command_args[0] = qualified_command
  182. if kwargs.get('elevate_privilege'):
  183. command_args = self._elevate_privilege_for_cmd(command_args)
  184. logging.debug(' '.join(command_args))
  185. process = subprocess.Popen(
  186. command_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  187. output = process.communicate()[0]
  188. retcode = process.poll()
  189. if retcode:
  190. raise CalledProcessError(retcode, command_args)
  191. return output
  192. def set_temporary_tcp_init_cwnd(self, cwnd):
  193. cwnd = int(cwnd)
  194. original_cwnd = self._get_cwnd()
  195. if original_cwnd is None:
  196. raise PlatformSettingsError('Unable to get current tcp init_cwnd.')
  197. if cwnd == original_cwnd:
  198. logging.info('TCP init_cwnd already set to target value: %s', cwnd)
  199. else:
  200. self._set_cwnd(cwnd)
  201. if self._get_cwnd() == cwnd:
  202. logging.info('Changed cwnd to %s', cwnd)
  203. atexit.register(self._set_cwnd, original_cwnd)
  204. else:
  205. logging.error('Unable to update cwnd to %s', cwnd)
  206. def setup_temporary_loopback_config(self):
  207. """Setup the loopback interface similar to real interface.
  208. We use loopback for much of our testing, and on some systems, loopback
  209. behaves differently from real interfaces.
  210. """
  211. logging.error('Platform does not support loopback configuration.')
  212. def _save_primary_interface_properties(self):
  213. self._orig_nameserver = self.get_original_primary_nameserver()
  214. def _restore_primary_interface_properties(self):
  215. self._set_primary_nameserver(self._orig_nameserver)
  216. def _get_primary_nameserver(self):
  217. raise NotImplementedError
  218. def _set_primary_nameserver(self, _):
  219. raise NotImplementedError
  220. def get_original_primary_nameserver(self):
  221. if not hasattr(self, '_original_nameserver'):
  222. self._original_nameserver = self._get_primary_nameserver()
  223. logging.info('Saved original primary DNS nameserver: %s',
  224. self._original_nameserver)
  225. return self._original_nameserver
  226. def set_temporary_primary_nameserver(self, nameserver):
  227. self._save_primary_interface_properties()
  228. self._set_primary_nameserver(nameserver)
  229. if self._get_primary_nameserver() == nameserver:
  230. logging.info('Changed temporary primary nameserver to %s', nameserver)
  231. atexit.register(self._restore_primary_interface_properties)
  232. else:
  233. raise self._get_dns_update_error()
  234. class _PosixPlatformSettings(_BasePlatformSettings):
  235. # pylint: disable=abstract-method
  236. # Suppress lint check for _get_primary_nameserver & _set_primary_nameserver
  237. def rerun_as_administrator(self):
  238. """If needed, rerun the program with administrative privileges.
  239. Raises NotAdministratorError if unable to rerun.
  240. """
  241. if os.geteuid() != 0:
  242. logging.warn('Rerunning with sudo: %s', sys.argv)
  243. os.execv('/usr/bin/sudo', ['--'] + sys.argv)
  244. def _elevate_privilege_for_cmd(self, args):
  245. def IsSetUID(path):
  246. return (os.stat(path).st_mode & stat.S_ISUID) == stat.S_ISUID
  247. def IsElevated():
  248. p = subprocess.Popen(
  249. ['sudo', '-nv'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  250. stderr=subprocess.STDOUT)
  251. stdout = p.communicate()[0]
  252. # Some versions of sudo set the returncode based on whether sudo requires
  253. # a password currently. Other versions return output when password is
  254. # required and no output when the user is already authenticated.
  255. return not p.returncode and not stdout
  256. if not IsSetUID(args[0]):
  257. args = ['sudo'] + args
  258. if not IsElevated():
  259. print 'WPR needs to run %s under sudo. Please authenticate.' % args[1]
  260. subprocess.check_call(['sudo', '-v']) # Synchronously authenticate.
  261. prompt = ('Would you like to always allow %s to run without sudo '
  262. '(via `sudo chmod +s %s`)? (y/N)' % (args[1], args[1]))
  263. if raw_input(prompt).lower() == 'y':
  264. subprocess.check_call(['sudo', 'chmod', '+s', args[1]])
  265. return args
  266. def get_system_proxy(self, use_ssl):
  267. """Returns the system HTTP(S) proxy host, port."""
  268. proxy_url = os.environ.get('https_proxy' if use_ssl else 'http_proxy')
  269. return SystemProxy.from_url(proxy_url)
  270. def _ipfw_cmd(self):
  271. return 'ipfw'
  272. def _get_dns_update_error(self):
  273. return DnsUpdateError('Did you run under sudo?')
  274. def _sysctl(self, *args, **kwargs):
  275. sysctl_args = [FindExecutable('sysctl')]
  276. if kwargs.get('use_sudo'):
  277. sysctl_args = self._elevate_privilege_for_cmd(sysctl_args)
  278. sysctl_args.extend(str(a) for a in args)
  279. sysctl = subprocess.Popen(
  280. sysctl_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  281. stdout = sysctl.communicate()[0]
  282. return sysctl.returncode, stdout
  283. def has_sysctl(self, name):
  284. if not hasattr(self, 'has_sysctl_cache'):
  285. self.has_sysctl_cache = {}
  286. if name not in self.has_sysctl_cache:
  287. self.has_sysctl_cache[name] = self._sysctl(name)[0] == 0
  288. return self.has_sysctl_cache[name]
  289. def set_sysctl(self, name, value):
  290. rv = self._sysctl('%s=%s' % (name, value), use_sudo=True)[0]
  291. if rv != 0:
  292. logging.error('Unable to set sysctl %s: %s', name, rv)
  293. def get_sysctl(self, name):
  294. rv, value = self._sysctl('-n', name)
  295. if rv == 0:
  296. return value
  297. else:
  298. logging.error('Unable to get sysctl %s: %s', name, rv)
  299. return None
  300. class _OsxPlatformSettings(_PosixPlatformSettings):
  301. LOCAL_SLOWSTART_MIB_NAME = 'net.inet.tcp.local_slowstart_flightsize'
  302. def _scutil(self, cmd):
  303. scutil = subprocess.Popen([FindExecutable('scutil')],
  304. stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  305. return scutil.communicate(cmd)[0]
  306. def _ifconfig(self, *args):
  307. return self._check_output('ifconfig', *args, elevate_privilege=True)
  308. def set_sysctl(self, name, value):
  309. rv = self._sysctl('-w', '%s=%s' % (name, value), use_sudo=True)[0]
  310. if rv != 0:
  311. logging.error('Unable to set sysctl %s: %s', name, rv)
  312. def _get_cwnd(self):
  313. return int(self.get_sysctl(self.LOCAL_SLOWSTART_MIB_NAME))
  314. def _set_cwnd(self, size):
  315. self.set_sysctl(self.LOCAL_SLOWSTART_MIB_NAME, size)
  316. def _get_loopback_mtu(self):
  317. config = self._ifconfig('lo0')
  318. match = re.search(r'\smtu\s+(\d+)', config)
  319. return int(match.group(1)) if match else None
  320. def setup_temporary_loopback_config(self):
  321. """Configure loopback to temporarily use reasonably sized frames.
  322. OS X uses jumbo frames by default (16KB).
  323. """
  324. TARGET_LOOPBACK_MTU = 1500
  325. original_mtu = self._get_loopback_mtu()
  326. if original_mtu is None:
  327. logging.error('Unable to read loopback mtu. Setting left unchanged.')
  328. return
  329. if original_mtu == TARGET_LOOPBACK_MTU:
  330. logging.debug('Loopback MTU already has target value: %d', original_mtu)
  331. else:
  332. self._ifconfig('lo0', 'mtu', TARGET_LOOPBACK_MTU)
  333. if self._get_loopback_mtu() == TARGET_LOOPBACK_MTU:
  334. logging.debug('Set loopback MTU to %d (was %d)',
  335. TARGET_LOOPBACK_MTU, original_mtu)
  336. atexit.register(self._ifconfig, 'lo0', 'mtu', original_mtu)
  337. else:
  338. logging.error('Unable to change loopback MTU from %d to %d',
  339. original_mtu, TARGET_LOOPBACK_MTU)
  340. def _get_dns_service_key(self):
  341. output = self._scutil('show State:/Network/Global/IPv4')
  342. lines = output.split('\n')
  343. for line in lines:
  344. key_value = line.split(' : ')
  345. if key_value[0] == ' PrimaryService':
  346. return 'State:/Network/Service/%s/DNS' % key_value[1]
  347. raise DnsReadError('Unable to find DNS service key: %s', output)
  348. def _get_primary_nameserver(self):
  349. output = self._scutil('show %s' % self._get_dns_service_key())
  350. match = re.search(
  351. br'ServerAddresses\s+:\s+<array>\s+{\s+0\s+:\s+((\d{1,3}\.){3}\d{1,3})',
  352. output)
  353. if match:
  354. return match.group(1)
  355. else:
  356. raise DnsReadError('Unable to find primary DNS server: %s', output)
  357. def _set_primary_nameserver(self, dns):
  358. command = '\n'.join([
  359. 'd.init',
  360. 'd.add ServerAddresses * %s' % dns,
  361. 'set %s' % self._get_dns_service_key()
  362. ])
  363. self._scutil(command)
  364. class _FreeBSDPlatformSettings(_PosixPlatformSettings):
  365. """Partial implementation for FreeBSD. Does not allow a DNS server to be
  366. launched nor ipfw to be used.
  367. """
  368. RESOLV_CONF = '/etc/resolv.conf'
  369. def _get_default_route_line(self):
  370. raise NotImplementedError
  371. def _set_cwnd(self, cwnd):
  372. raise NotImplementedError
  373. def _get_cwnd(self):
  374. raise NotImplementedError
  375. def setup_temporary_loopback_config(self):
  376. raise NotImplementedError
  377. def _write_resolve_conf(self, dns):
  378. raise NotImplementedError
  379. def _get_primary_nameserver(self):
  380. try:
  381. resolv_file = open(self.RESOLV_CONF)
  382. except IOError:
  383. raise DnsReadError()
  384. for line in resolv_file:
  385. if line.startswith('nameserver '):
  386. return line.split()[1]
  387. raise DnsReadError()
  388. def _set_primary_nameserver(self, dns):
  389. raise NotImplementedError
  390. class _LinuxPlatformSettings(_PosixPlatformSettings):
  391. """The following thread recommends a way to update DNS on Linux:
  392. http://ubuntuforums.org/showthread.php?t=337553
  393. sudo cp /etc/dhcp3/dhclient.conf /etc/dhcp3/dhclient.conf.bak
  394. sudo gedit /etc/dhcp3/dhclient.conf
  395. #prepend domain-name-servers 127.0.0.1;
  396. prepend domain-name-servers 208.67.222.222, 208.67.220.220;
  397. prepend domain-name-servers 208.67.222.222, 208.67.220.220;
  398. request subnet-mask, broadcast-address, time-offset, routers,
  399. domain-name, domain-name-servers, host-name,
  400. netbios-name-servers, netbios-scope;
  401. #require subnet-mask, domain-name-servers;
  402. sudo /etc/init.d/networking restart
  403. The code below does not try to change dchp and does not restart networking.
  404. Update this as needed to make it more robust on more systems.
  405. """
  406. RESOLV_CONF = '/etc/resolv.conf'
  407. ROUTE_RE = re.compile('initcwnd (\d+)')
  408. TCP_BASE_MSS = 'net.ipv4.tcp_base_mss'
  409. TCP_MTU_PROBING = 'net.ipv4.tcp_mtu_probing'
  410. def _get_default_route_line(self):
  411. stdout = self._check_output('ip', 'route')
  412. for line in stdout.split('\n'):
  413. if line.startswith('default'):
  414. return line
  415. return None
  416. def _set_cwnd(self, cwnd):
  417. default_line = self._get_default_route_line()
  418. self._check_output(
  419. 'ip', 'route', 'change', default_line, 'initcwnd', str(cwnd))
  420. def _get_cwnd(self):
  421. default_line = self._get_default_route_line()
  422. m = self.ROUTE_RE.search(default_line)
  423. if m:
  424. return int(m.group(1))
  425. # If 'initcwnd' wasn't found, then 0 means it's the system default.
  426. return 0
  427. def setup_temporary_loopback_config(self):
  428. """Setup Linux to temporarily use reasonably sized frames.
  429. Linux uses jumbo frames by default (16KB), using the combination
  430. of MTU probing and a base MSS makes it use normal sized packets.
  431. The reason this works is because tcp_base_mss is only used when MTU
  432. probing is enabled. And since we're using the max value, it will
  433. always use the reasonable size. This is relevant for server-side realism.
  434. The client-side will vary depending on the client TCP stack config.
  435. """
  436. ENABLE_MTU_PROBING = 2
  437. original_probing = self.get_sysctl(self.TCP_MTU_PROBING)
  438. self.set_sysctl(self.TCP_MTU_PROBING, ENABLE_MTU_PROBING)
  439. atexit.register(self.set_sysctl, self.TCP_MTU_PROBING, original_probing)
  440. TCP_FULL_MSS = 1460
  441. original_mss = self.get_sysctl(self.TCP_BASE_MSS)
  442. self.set_sysctl(self.TCP_BASE_MSS, TCP_FULL_MSS)
  443. atexit.register(self.set_sysctl, self.TCP_BASE_MSS, original_mss)
  444. def _write_resolve_conf(self, dns):
  445. is_first_nameserver_replaced = False
  446. # The fileinput module uses sys.stdout as the edited file output.
  447. for line in fileinput.input(self.RESOLV_CONF, inplace=1, backup='.bak'):
  448. if line.startswith('nameserver ') and not is_first_nameserver_replaced:
  449. print 'nameserver %s' % dns
  450. is_first_nameserver_replaced = True
  451. else:
  452. print line,
  453. if not is_first_nameserver_replaced:
  454. raise DnsUpdateError('Could not find a suitable nameserver entry in %s' %
  455. self.RESOLV_CONF)
  456. def _get_primary_nameserver(self):
  457. try:
  458. resolv_file = open(self.RESOLV_CONF)
  459. except IOError:
  460. raise DnsReadError()
  461. for line in resolv_file:
  462. if line.startswith('nameserver '):
  463. return line.split()[1]
  464. raise DnsReadError()
  465. def _set_primary_nameserver(self, dns):
  466. """Replace the first nameserver entry with the one given."""
  467. try:
  468. self._write_resolve_conf(dns)
  469. except OSError, e:
  470. if 'Permission denied' in e:
  471. raise self._get_dns_update_error()
  472. raise
  473. class _WindowsPlatformSettings(_BasePlatformSettings):
  474. # pylint: disable=abstract-method
  475. # Suppress lint check for _ipfw_cmd
  476. def get_system_logging_handler(self):
  477. """Return a handler for the logging module (optional).
  478. For Windows, output can be viewed with DebugView.
  479. http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx
  480. """
  481. import ctypes
  482. output_debug_string = ctypes.windll.kernel32.OutputDebugStringA
  483. output_debug_string.argtypes = [ctypes.c_char_p]
  484. class DebugViewHandler(logging.Handler):
  485. def emit(self, record):
  486. output_debug_string('[wpr] ' + self.format(record))
  487. return DebugViewHandler()
  488. def rerun_as_administrator(self):
  489. """If needed, rerun the program with administrative privileges.
  490. Raises NotAdministratorError if unable to rerun.
  491. """
  492. import ctypes
  493. if not ctypes.windll.shell32.IsUserAnAdmin():
  494. raise NotAdministratorError('Rerun with administrator privileges.')
  495. #os.execv('runas', sys.argv) # TODO: replace needed Windows magic
  496. def timer(self):
  497. """Return the current time in seconds as a floating point number.
  498. From time module documentation:
  499. On Windows, this function [time.clock()] returns wall-clock
  500. seconds elapsed since the first call to this function, as a
  501. floating point number, based on the Win32 function
  502. QueryPerformanceCounter(). The resolution is typically better
  503. than one microsecond.
  504. """
  505. return time.clock()
  506. def _arp(self, *args):
  507. return self._check_output('arp', *args)
  508. def _route(self, *args):
  509. return self._check_output('route', *args)
  510. def _ipconfig(self, *args):
  511. return self._check_output('ipconfig', *args)
  512. def _get_mac_address(self, ip):
  513. """Return the MAC address for the given ip."""
  514. ip_re = re.compile(r'^\s*IP(?:v4)? Address[ .]+:\s+([0-9.]+)')
  515. for line in self._ipconfig('/all').splitlines():
  516. if line[:1].isalnum():
  517. current_ip = None
  518. current_mac = None
  519. elif ':' in line:
  520. line = line.strip()
  521. ip_match = ip_re.match(line)
  522. if ip_match:
  523. current_ip = ip_match.group(1)
  524. elif line.startswith('Physical Address'):
  525. current_mac = line.split(':', 1)[1].lstrip()
  526. if current_ip == ip and current_mac:
  527. return current_mac
  528. return None
  529. def setup_temporary_loopback_config(self):
  530. """On Windows, temporarily route the server ip to itself."""
  531. ip = self.get_server_ip_address()
  532. mac_address = self._get_mac_address(ip)
  533. if self.mac_address:
  534. self._arp('-s', ip, self.mac_address)
  535. self._route('add', ip, ip, 'mask', '255.255.255.255')
  536. atexit.register(self._arp, '-d', ip)
  537. atexit.register(self._route, 'delete', ip, ip, 'mask', '255.255.255.255')
  538. else:
  539. logging.warn('Unable to configure loopback: MAC address not found.')
  540. # TODO(slamm): Configure cwnd, MTU size
  541. def _get_dns_update_error(self):
  542. return DnsUpdateError('Did you run as administrator?')
  543. def _netsh_show_dns(self):
  544. """Return DNS information:
  545. Example output:
  546. Configuration for interface "Local Area Connection 3"
  547. DNS servers configured through DHCP: None
  548. Register with which suffix: Primary only
  549. Configuration for interface "Wireless Network Connection 2"
  550. DNS servers configured through DHCP: 192.168.1.1
  551. Register with which suffix: Primary only
  552. """
  553. return self._check_output('netsh', 'interface', 'ip', 'show', 'dns')
  554. def _netsh_set_dns(self, iface_name, addr):
  555. """Modify DNS information on the primary interface."""
  556. output = self._check_output('netsh', 'interface', 'ip', 'set', 'dns',
  557. iface_name, 'static', addr)
  558. def _netsh_set_dns_dhcp(self, iface_name):
  559. """Modify DNS information on the primary interface."""
  560. output = self._check_output('netsh', 'interface', 'ip', 'set', 'dns',
  561. iface_name, 'dhcp')
  562. def _get_interfaces_with_dns(self):
  563. output = self._netsh_show_dns()
  564. lines = output.split('\n')
  565. iface_re = re.compile(r'^Configuration for interface \"(?P<name>.*)\"')
  566. dns_re = re.compile(r'(?P<kind>.*):\s+(?P<dns>\d+\.\d+\.\d+\.\d+)')
  567. iface_name = None
  568. iface_dns = None
  569. iface_kind = None
  570. ifaces = []
  571. for line in lines:
  572. iface_match = iface_re.match(line)
  573. if iface_match:
  574. iface_name = iface_match.group('name')
  575. dns_match = dns_re.match(line)
  576. if dns_match:
  577. iface_dns = dns_match.group('dns')
  578. iface_dns_config = dns_match.group('kind').strip()
  579. if iface_dns_config == "Statically Configured DNS Servers":
  580. iface_kind = "static"
  581. elif iface_dns_config == "DNS servers configured through DHCP":
  582. iface_kind = "dhcp"
  583. if iface_name and iface_dns and iface_kind:
  584. ifaces.append((iface_dns, iface_name, iface_kind))
  585. iface_name = None
  586. iface_dns = None
  587. return ifaces
  588. def _save_primary_interface_properties(self):
  589. # TODO(etienneb): On windows, an interface can have multiple DNS server
  590. # configured. We should save/restore all of them.
  591. ifaces = self._get_interfaces_with_dns()
  592. self._primary_interfaces = ifaces
  593. def _restore_primary_interface_properties(self):
  594. for iface in self._primary_interfaces:
  595. (iface_dns, iface_name, iface_kind) = iface
  596. self._netsh_set_dns(iface_name, iface_dns)
  597. if iface_kind == "dhcp":
  598. self._netsh_set_dns_dhcp(iface_name)
  599. def _get_primary_nameserver(self):
  600. ifaces = self._get_interfaces_with_dns()
  601. if not len(ifaces):
  602. raise DnsUpdateError("Interface with valid DNS configured not found.")
  603. (iface_dns, iface_name, iface_kind) = ifaces[0]
  604. return iface_dns
  605. def _set_primary_nameserver(self, dns):
  606. for iface in self._primary_interfaces:
  607. (iface_dns, iface_name, iface_kind) = iface
  608. self._netsh_set_dns(iface_name, dns)
  609. class _WindowsXpPlatformSettings(_WindowsPlatformSettings):
  610. def _ipfw_cmd(self):
  611. return (r'third_party\ipfw_win32\ipfw.exe',)
  612. def _new_platform_settings(system, release):
  613. """Make a new instance of PlatformSettings for the current system."""
  614. if system == 'Darwin':
  615. return _OsxPlatformSettings()
  616. if system == 'Linux':
  617. return _LinuxPlatformSettings()
  618. if system == 'Windows' and release == 'XP':
  619. return _WindowsXpPlatformSettings()
  620. if system == 'Windows':
  621. return _WindowsPlatformSettings()
  622. if system == 'FreeBSD':
  623. return _FreeBSDPlatformSettings()
  624. raise NotImplementedError('Sorry %s %s is not supported.' % (system, release))
  625. # Create one instance of the platform-specific settings and
  626. # make the functions available at the module-level.
  627. _inst = _new_platform_settings(platform.system(), platform.release())
  628. get_system_logging_handler = _inst.get_system_logging_handler
  629. rerun_as_administrator = _inst.rerun_as_administrator
  630. timer = _inst.timer
  631. get_server_ip_address = _inst.get_server_ip_address
  632. get_httpproxy_ip_address = _inst.get_httpproxy_ip_address
  633. get_system_proxy = _inst.get_system_proxy
  634. ipfw = _inst.ipfw
  635. has_ipfw = _inst.has_ipfw
  636. set_temporary_tcp_init_cwnd = _inst.set_temporary_tcp_init_cwnd
  637. setup_temporary_loopback_config = _inst.setup_temporary_loopback_config
  638. get_original_primary_nameserver = _inst.get_original_primary_nameserver
  639. set_temporary_primary_nameserver = _inst.set_temporary_primary_nameserver