~ubuntu-core-dev/ubuntu/wily/apport/ubuntu

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
#!/usr/bin/python

# Collect information about a crash and create a report in /var/crash/.
# See https://wiki.ubuntu.com/AutomatedProblemReports for details.
#
# Copyright (c) 2006 Canonical Ltd.
# Author: Martin Pitt <martin.pitt@ubuntu.com>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.  See http://www.gnu.org/copyleft/pgl.html for
# the full text of the license.

import sys, os, os.path, subprocess, time, traceback
import tempfile, shutil, glob, apt_pkg

import problem_report


#################################################################
#
# functions
#
#################################################################

def _read_file(f):
    '''Try to read given file and return its contents, or return a textual
    error if it failed.'''

    try:
	return open(f).read().strip()
    except IOError, e:
	error_log('_read_file %s: %s' % (f, str(e)))
	return 'Error: ' + str(e)

def _command_output(command, input = None, stderr = subprocess.STDOUT):
    '''Try to execute given command (array) and return its stdout, or return
    a textual error if it failed.'''

    try:
	sp = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=stderr, close_fds=True)
    except OSError, e:
	error_log('_command_output Popen(%s): %s' % (str(command), str(e)))
	return 'Error: ' + str(e)

    out = sp.communicate(input)[0]
    if sp.returncode == 0:
	return out
    else:
	error_log('_command_output %s failed with exit code %i: %s' % (
	    str(command), sp.returncode, out))
	return 'Error: command %s failed with exit code %i: %s' % (
	    str(command), sp.returncode, out)

def drop_privileges(pid):
    '''Change user and group to match the given target process.'''

    stat = None
    try:
	stat = os.stat('/proc/' + pid)
    except OSError:
	raise ValueError, 'Invalid process ID'

    os.setgid(stat.st_gid)
    os.setuid(stat.st_uid)
    assert os.getuid() == stat.st_uid

def init_error_log():
    '''Open a suitable error log if sys.stderr is not a tty.'''

    if not os.isatty(sys.stderr.fileno()):
	try:
	    f = open('/var/log/apport.log', 'a')
	except IOError: # on a permission error, don't touch stderr
	    return
	os.dup2(f.fileno(), sys.stderr.fileno())
	os.dup2(f.fileno(), sys.stdout.fileno())

def error_log(msg):
    '''Output something to the error log.'''

    print >> sys.stderr, 'apport (pid %s) %s:' % (os.getpid(),
	time.asctime()), msg

def transitive_dependencies(package, depends_set, cache):
    '''Recursively add dependencies of package to depends_set, using the given
    apt_pkg cache.'''

    cur_ver = cache[package].CurrentVer
    if not cur_ver:
	return
    for p in cur_ver.DependsList.get('Depends', []) + cur_ver.DependsList.get('PreDepends', []):
	name = p[0].TargetPkg.Name
	if not name in depends_set:
	    depends_set.add(name)
	    transitive_dependencies(name, depends_set, cache)

#################################################################
#
# classes
#
#################################################################

class InformationCollector:
    '''Collect and store information about the crash.
    
    Fields with acquired data:
    - Signal: signal that caused the crash
    - ExecutablePath: path to the crashed executable
    - Stacktrace: stack trace
    - ThreadStacktrace: thread apply all bt full
    - Package: package name and version; not present if info['ExecutablePath'] does
      not belong to a package
    - Dependencies: names and versions of depending packages; not present if
      Package is not present
    - ProcCmdline: /proc/<pid>/cmdline
    - ProcEnviron: /proc/<pid>/environ
    - ProcStatus: /proc/<pid>/status
    - ProcMaps: /proc/<pid>/maps
    - DistroRelease: lsb_release -sir
    - Uname: uname -a

    TODO: StackFrame
    '''

    def __init__(self, pid, signum):
	'Collects all information and stores them in the appropriate fields.'

	self.info = problem_report.ProblemReport('Crash')
	self.info['Signal'] = signum
	self.pid = pid

	# determine program name
	self.info['ExecutablePath'] = os.readlink('/proc/' + pid + '/exe')

	# reading /proc after drop_privileges() (when called from the kernel)
	# does not work, so do this with original privileges.
	self._get_proc()

	drop_privileges(pid)

	self.workdir = tempfile.mkdtemp()
	self._get_pkg()
	self._get_os()
	self._get_gdb()

    def __del__(self):
	if self.workdir:
	    shutil.rmtree(self.workdir)

    def _get_proc(self):
	'''Collect information from /proc.'''

	self.info['ProcEnviron'] = _read_file('/proc/'+ self.pid + '/environ'). \
	    replace('\n', '\\n').replace('\0', '\n').strip()
	self.info['ProcStatus'] = _read_file('/proc/' + self.pid + '/status')
	self.info['ProcCmdline'] = _read_file('/proc/' + self.pid + '/cmdline').rstrip('\0')
	self.info['ProcMaps'] = _read_file('/proc/' + self.pid + '/maps')

    def _get_pkg(self):
	'''Check whether executable belongs to a package and determine its
	name, version, and the versions of its dependencies.'''

	# get dpkg -s <package> output
	out = _command_output(['dpkg', '-S', self.info['ExecutablePath']])
	if out.startswith('Error:'):
	    return 
	pkg = out.split(':', 1)[0]

	apt_pkg.init()
	cache = apt_pkg.GetCache()

	self.info['Package'] = '%s %s' % (pkg, cache[pkg].CurrentVer.VerStr)

	# get set of all transitive dependencies
	dependencies = set([])
	transitive_dependencies(pkg, dependencies, cache)

	# get dependency versions
	self.info['Dependencies'] = ''
	for dep in dependencies:
	    cur_ver = cache[dep].CurrentVer
	    if cur_ver:
		if self.info['Dependencies']:
		    self.info['Dependencies'] += '\n'
		self.info['Dependencies'] += '%s %s' % (dep, cur_ver.VerStr)

    def _get_os(self):
	'''Collect information about system.'''

	self.info['DistroRelease'] = _command_output(['lsb_release', '-sir']).strip().replace('\n', ' ')
	self.info['Uname'] = _command_output(['uname', '-a']).strip()

    def _get_gdb(self):
	'''Get information from gdb.'''

	corefile = os.path.join(self.workdir, 'core')
	self.info['Stacktrace'] = _command_output(['gdb', '--batch', '--ex',
	    'generate-core-file %s' % corefile, '--ex',
	    'bt full', self.info['ExecutablePath'], self.pid], 
	    stderr=open('/dev/null')).replace('\n\n', '\n.\n').strip()
	if os.path.exists(corefile):
	    self.info['CoreDump'] = (corefile,)
	self.info['ThreadStacktrace'] = _command_output(['gdb', '--batch', '--ex',
	    'thread apply all bt full', self.info['ExecutablePath'], self.pid], 
	    stderr=open('/dev/null')).replace('\n\n', '\n.\n').strip()

#################################################################
#
# main
#
#################################################################

init_error_log()

if len(sys.argv) != 3:
    print >> sys.stderr, 'Usage:', sys.argv[0], '<pid> <signal number>'
    sys.exit(-1)

error_log('called with: ' + str(sys.argv))

(pid, signum) = sys.argv[1:]

# Create crash report file descriptor. We prefer to create the report in
# /var/crash/ if we can create a file there; if not, we just use stderr.

try:
    pidstat = os.stat('/proc/' + pid)
except OSError:
    error_log('Invalid PID')
    sys.exit(1)

exename = os.readlink('/proc/' + pid + '/exe')

# ignore non-package binaries
if subprocess.call(['fgrep', '-qx', exename] + glob.glob('/var/lib/dpkg/info/*.list')) != 0:
    error_log('executable does not belong to a package, ignoring')
    sys.exit(0)

try:
    report = '/var/crash/%s.%i.crash' % (exename.replace('/', '_'), pidstat.st_uid)
    if os.path.exists(report):
	error_log('apport: report %s already exists, doing nothing to avoid disk usage DoS' % report)
	sys.exit(1)
    reportfile = open(report, 'w')
    os.chmod(report, 0600)
    os.chown(report, pidstat.st_uid, 0)
except (OSError, IOError):
    reportfile = sys.stderr

try:
    ic = InformationCollector(pid, signum)
    ic.info.write(reportfile)
except Exception, e:
    error_log('Unhandled exception:')
    traceback.print_exc()
    print >> sys.stderr, 'pid: %i, uid: %i, gid: %i, euid: %i, egid: %i' % (
       os.getpid(), os.getuid(), os.getgid(), os.geteuid(), os.getegid())