1# Copyright 2013 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
5import distutils.spawn
6import logging
7import os
8import re
9import stat
10import subprocess
11import sys
12
13from telemetry.internal.platform import desktop_platform_backend
14from telemetry.internal.util import ps_util
15
16
17def _BinaryExistsInSudoersFiles(path, sudoers_file_contents):
18  """Returns True if the binary in |path| features in the sudoers file.
19  """
20  for line in sudoers_file_contents.splitlines():
21    if re.match(r'\s*\(.+\) NOPASSWD: %s(\s\S+)*$' % re.escape(path), line):
22      return True
23  return False
24
25
26def _CanRunElevatedWithSudo(path):
27  """Returns True if the binary at |path| appears in the sudoers file.
28  If this function returns true then the binary at |path| can be run via sudo
29  without prompting for a password.
30  """
31  sudoers = subprocess.check_output(['/usr/bin/sudo', '-l'])
32  return _BinaryExistsInSudoersFiles(path, sudoers)
33
34
35class PosixPlatformBackend(desktop_platform_backend.DesktopPlatformBackend):
36
37  # This is an abstract class. It is OK to have abstract methods.
38  # pylint: disable=abstract-method
39
40  def RunCommand(self, args):
41    return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0]
42
43  def GetFileContents(self, path):
44    with open(path, 'r') as f:
45      return f.read()
46
47  def GetPsOutput(self, columns, pid=None):
48    """Returns output of the 'ps' command as a list of lines.
49    Subclass should override this function.
50
51    Args:
52      columns: A list of require columns, e.g., ['pid', 'pss'].
53      pid: If not None, returns only the information of the process
54         with the pid.
55    """
56    return ps_util.GetPsOutputWithPlatformBackend(self, columns, pid)
57
58  def _GetTopOutput(self, pid, columns):
59    """Returns output of the 'top' command as a list of lines.
60
61    Args:
62      pid: pid of process to examine.
63      columns: A list of require columns, e.g., ['idlew', 'vsize'].
64    """
65    args = ['top']
66    args.extend(['-pid', str(pid), '-l', '1', '-s', '0', '-stats',
67        ','.join(columns)])
68    return self.RunCommand(args).splitlines()
69
70  def GetChildPids(self, pid):
71    """Returns a list of child pids of |pid|."""
72    ps_output = self.GetPsOutput(['pid', 'ppid', 'state'])
73    ps_line_re = re.compile(
74        r'\s*(?P<pid>\d+)\s*(?P<ppid>\d+)\s*(?P<state>\S*)\s*')
75    processes = []
76    for pid_ppid_state in ps_output:
77      m = ps_line_re.match(pid_ppid_state)
78      assert m, 'Did not understand ps output: %s' % pid_ppid_state
79      processes.append((m.group('pid'), m.group('ppid'), m.group('state')))
80    return ps_util.GetChildPids(processes, pid)
81
82  def GetCommandLine(self, pid):
83    command = self.GetPsOutput(['command'], pid)
84    return command[0] if command else None
85
86  def CanLaunchApplication(self, application):
87    return bool(distutils.spawn.find_executable(application))
88
89  def IsApplicationRunning(self, application):
90    ps_output = self.GetPsOutput(['command'])
91    application_re = re.compile(
92        r'(.*%s|^)%s(\s|$)' % (os.path.sep, application))
93    return any(application_re.match(cmd) for cmd in ps_output)
94
95  def LaunchApplication(
96      self, application, parameters=None, elevate_privilege=False):
97    assert application, 'Must specify application to launch'
98
99    if os.path.sep not in application:
100      application = distutils.spawn.find_executable(application)
101      assert application, 'Failed to find application in path'
102
103    args = [application]
104
105    if parameters:
106      assert isinstance(parameters, list), 'parameters must be a list'
107      args += parameters
108
109    def IsElevated():
110      """ Returns True if the current process is elevated via sudo i.e. running
111      sudo will not prompt for a password. Returns False if not authenticated
112      via sudo or if telemetry is run on a non-interactive TTY."""
113      # `sudo -v` will always fail if run from a non-interactive TTY.
114      p = subprocess.Popen(
115          ['/usr/bin/sudo', '-nv'], stdin=subprocess.PIPE,
116          stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
117      stdout = p.communicate()[0]
118      # Some versions of sudo set the returncode based on whether sudo requires
119      # a password currently. Other versions return output when password is
120      # required and no output when the user is already authenticated.
121      return not p.returncode and not stdout
122
123    def IsSetUID(path):
124      """Returns True if the binary at |path| has the setuid bit set."""
125      return (os.stat(path).st_mode & stat.S_ISUID) == stat.S_ISUID
126
127    if elevate_privilege and not IsSetUID(application):
128      args = ['/usr/bin/sudo'] + args
129      if not _CanRunElevatedWithSudo(application) and not IsElevated():
130        if not sys.stdout.isatty():
131          # Without an interactive terminal (or a configured 'askpass', but
132          # that is rarely relevant), there's no way to prompt the user for
133          # sudo. Fail with a helpful error message. For more information, see:
134          #   https://code.google.com/p/chromium/issues/detail?id=426720
135          text = ('Telemetry needs to run %s with elevated privileges, but the '
136                 'setuid bit is not set and there is no interactive terminal '
137                 'for a prompt. Please ask an administrator to set the setuid '
138                 'bit on this executable and ensure that it is owned by a user '
139                 'with the necessary privileges. Aborting.' % application)
140          print text
141          raise Exception(text)
142        # Else, there is a tty that can be used for a useful interactive prompt.
143        print ('Telemetry needs to run %s under sudo. Please authenticate.' %
144               application)
145        # Synchronously authenticate.
146        subprocess.check_call(['/usr/bin/sudo', '-v'])
147
148    stderror_destination = subprocess.PIPE
149    if logging.getLogger().isEnabledFor(logging.DEBUG):
150      stderror_destination = None
151
152    return subprocess.Popen(
153        args, stdout=subprocess.PIPE, stderr=stderror_destination)
154