~brian-murray/apport/add-apport-version

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
#!/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


#################################################################
#
# 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:
	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)
    except OSError, e:
	return 'Error: ' + str(e)

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

def write_debcontrol(file, fields):
    '''Write dictionary 'fields' into the given file-like object, using Debian
    control file format.'''

    for k, v in fields.iteritems():
	if v.find('\n') >= 0:
	    assert v.find('\n\n') < 0
	    print >> file, k + ':'
	    print >> file, '', v.replace('\n', '\n ')
	else:
	    print >> file, k + ':', v

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

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

class InformationCollector:
    '''Collect and store information about the crash.
    
    Fields with acquired data:
    - signal: signal that caused the crash
    - executable: path to the crashed executable
    - stacktrace: stack trace
    - thread_stacktrace: thread apply all bt full
    - environment: env variables from /proc/<pid>/environ
    - pkg: package name and version; not present if info['executable'] does not
      belong to a package
    - dependencies: names and versions of depending packages; not present if
      pkg is not present
    - procstatus: /proc/<pid>/status
    - lsb_release: lsb_release -sir
    - uname: uname -a
    '''

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

	self.info = {}
	self.info['signal'] = signal
	self.pid = pid

	# determine program name
	try:
	    self.info['executable'] = os.readlink('/proc/' + pid + '/exe')
	except OSError:
	    return

	self._get_proc()
	self._get_pkg()
	self._get_os()
	self._get_gdb()

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

	self.info['environment'] = _read_file('/proc/'+ self.pid + '/environ'). \
	    replace('\n', '\\n').replace('\0', '\n').strip()
	self.info['procstatus'] = _read_file('/proc/' + self.pid + '/status')

    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['executable']])
	if out.startswith('Error:'):
	    return 
	pkg = out.split(':', 1)[0]
	pkgstatus = _command_output(['dpkg', '-s', pkg])
	if pkgstatus.startswith('Error:'):
	    return 

	for l in pkgstatus.splitlines():
	    if l.startswith('Version:'):
		self.info['pkg'] = '%s %s' % (pkg, l.split(None, 1)[1])
		break

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

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

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

	self.info['stacktrace'] = _command_output(['gdb', '--batch', '--ex',
	    'bt full', self.info['executable'], self.pid], 
	    stderr=open('/dev/null')).replace('\n\n', '\n.\n').strip()
	self.info['thread_stacktrace'] = _command_output(['gdb', '--batch', '--ex',
	    'thread apply all bt full', self.info['executable'], self.pid], 
	    stderr=open('/dev/null')).replace('\n\n', '\n.\n').strip()

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

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

(pid, signal) = 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:
    print >> sys.stderr, 'Invalid PID'
    sys.exit(1)

try:
    exename = os.readlink('/proc/' + pid + '/exe').replace('/', '_')
    report = '/var/crash/%s.%i.crash' % (exename, pidstat.st_uid)
    if os.path.exists(report):
	print >> sys.stderr, 'crash-reporter: 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

drop_privileges(pid)

ic = InformationCollector(pid, signal)

write_debcontrol(reportfile, ic.info)