]> git.decadent.org.uk Git - dak.git/blob - daklib/command.py
Merge branch 'backports-merge'
[dak.git] / daklib / command.py
1 """module to handle command files
2
3 @contact: Debian FTP Master <ftpmaster@debian.org>
4 @copyright: 2012, Ansgar Burchardt <ansgar@debian.org>
5 @license: GPL-2+
6 """
7
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with this program; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 import apt_pkg
23 import os
24 import re
25 import tempfile
26
27 from daklib.config import Config
28 from daklib.dbconn import *
29 from daklib.gpg import SignedFile
30 from daklib.regexes import re_field_package
31 from daklib.textutils import fix_maintainer
32 from daklib.utils import gpg_get_key_addresses, send_mail, TemplateSubst
33
34 class CommandError(Exception):
35     pass
36
37 class CommandFile(object):
38     def __init__(self, path, log=None):
39         if log is None:
40             from daklib.daklog import Logger
41             log = Logger()
42         self.cc = []
43         self.result = []
44         self.log = log
45         self.path = path
46         self.filename = os.path.basename(path)
47
48     def _check_replay(self, signed_file, session):
49         """check for replays
50
51         @note: Will commit changes to the database.
52
53         @type signed_file: L{daklib.gpg.SignedFile}
54
55         @param session: database session
56         """
57         # Mark commands file as seen to prevent replays.
58         signature_history = SignatureHistory.from_signed_file(signed_file)
59         session.add(signature_history)
60         session.commit()
61
62     def _evaluate_sections(self, sections, session):
63         session.rollback()
64         try:
65             while True:
66                 sections.next()
67                 section = sections.section
68
69                 action = section.get('Action', None)
70                 if action is None:
71                     raise CommandError('Encountered section without Action field')
72                 self.result.append('Action: {0}'.format(action))
73
74                 if action == 'dm':
75                     self.action_dm(self.fingerprint, section, session)
76                 elif action == 'break-the-archive':
77                     self.action_break_the_archive(self.fingerprint, section, session)
78                 else:
79                     raise CommandError('Unknown action: {0}'.format(action))
80
81                 self.result.append('')
82         except StopIteration:
83             pass
84         finally:
85             session.rollback()
86
87     def _notify_uploader(self):
88         cnf = Config()
89
90         bcc = 'X-DAK: dak process-command'
91         if 'Dinstall::Bcc' in cnf:
92             bcc = '{0}\nBcc: {1}'.format(bcc, cnf['Dinstall::Bcc'])
93
94         cc = set(fix_maintainer(address)[1] for address in self.cc)
95
96         subst = {
97             '__DAK_ADDRESS__': cnf['Dinstall::MyEmailAddress'],
98             '__MAINTAINER_TO__': fix_maintainer(self.uploader)[1],
99             '__CC__': ", ".join(cc),
100             '__BCC__': bcc,
101             '__RESULTS__': "\n".join(self.result),
102             '__FILENAME__': self.filename,
103             }
104
105         message = TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'process-command.processed'))
106
107         send_mail(message)
108
109     def evaluate(self):
110         """evaluate commands file
111
112         @rtype:   bool
113         @returns: C{True} if the file was processed sucessfully,
114                   C{False} otherwise
115         """
116         result = True
117
118         session = DBConn().session()
119
120         keyrings = session.query(Keyring).filter_by(active=True).order_by(Keyring.priority)
121         keyring_files = [ k.keyring_name for k in keyrings ]
122
123         raw_contents = open(self.path, 'r').read()
124         signed_file = SignedFile(raw_contents, keyring_files)
125         if not signed_file.valid:
126             self.log.log(['invalid signature', self.filename])
127             return False
128
129         self.fingerprint = session.query(Fingerprint).filter_by(fingerprint=signed_file.primary_fingerprint).one()
130         if self.fingerprint.keyring is None:
131             self.log.log(['singed by key in unknown keyring', self.filename])
132             return False
133         assert self.fingerprint.keyring.active
134
135         self.log.log(['processing', self.filename, 'signed-by={0}'.format(self.fingerprint.fingerprint)])
136
137         with tempfile.TemporaryFile() as fh:
138             fh.write(signed_file.contents)
139             fh.seek(0)
140             sections = apt_pkg.TagFile(fh)
141
142         self.uploader = None
143         addresses = gpg_get_key_addresses(self.fingerprint.fingerprint)
144         if len(addresses) > 0:
145             self.uploader = addresses[0]
146
147         try:
148             sections.next()
149             section = sections.section
150             if 'Uploader' in section:
151                 self.uploader = section['Uploader']
152             # TODO: Verify first section has valid Archive field
153             if 'Archive' not in section:
154                 raise CommandError('No Archive field in first section.')
155
156             # TODO: send mail when we detected a replay.
157             self._check_replay(signed_file, session)
158
159             self._evaluate_sections(sections, session)
160             self.result.append('')
161         except Exception as e:
162             self.log.log(['ERROR', e])
163             self.result.append("There was an error processing this section. No changes were committed.\nDetails:\n{0}".format(e))
164             result = False
165
166         self._notify_uploader()
167
168         session.close()
169
170         return result
171
172     def _split_packages(self, value):
173         names = value.split()
174         for name in names:
175             if not re_field_package.match(name):
176                 raise CommandError('Invalid package name "{0}"'.format(name))
177         return names
178
179     def action_dm(self, fingerprint, section, session):
180         cnf = Config()
181
182         if 'Command::DM::AdminKeyrings' not in cnf \
183                 or 'Command::DM::ACL' not in cnf \
184                 or 'Command::DM::Keyrings' not in cnf:
185             raise CommandError('DM command is not configured for this archive.')
186
187         allowed_keyrings = cnf.value_list('Command::DM::AdminKeyrings')
188         if fingerprint.keyring.keyring_name not in allowed_keyrings:
189             raise CommandError('Key {0} is not allowed to set DM'.format(fingerprint.fingerprint))
190
191         acl_name = cnf.get('Command::DM::ACL', 'dm')
192         acl = session.query(ACL).filter_by(name=acl_name).one()
193
194         fpr_hash = section['Fingerprint'].translate(None, ' ')
195         fpr = session.query(Fingerprint).filter_by(fingerprint=fpr_hash).one()
196         if fpr.keyring is None or fpr.keyring.keyring_name not in cnf.value_list('Command::DM::Keyrings'):
197             raise CommandError('Key {0} is not in DM keyring.'.format(fpr.fingerprint))
198         addresses = gpg_get_key_addresses(fpr.fingerprint)
199         if len(addresses) > 0:
200             self.cc.append(addresses[0])
201
202         self.log.log(['dm', 'fingerprint', fpr.fingerprint])
203         self.result.append('Fingerprint: {0}'.format(fpr.fingerprint))
204         if len(addresses) > 0:
205             self.log.log(['dm', 'uid', addresses[0]])
206             self.result.append('Uid: {0}'.format(addresses[0]))
207
208         for source in self._split_packages(section.get('Allow', '')):
209             # Check for existance of source package to catch typos
210             if session.query(DBSource).filter_by(source=source).first() is None:
211                 raise CommandError('Tried to grant permissions for unknown source package: {0}'.format(source))
212
213             if session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr, source=source).first() is None:
214                 aps = ACLPerSource()
215                 aps.acl = acl
216                 aps.fingerprint = fpr
217                 aps.source = source
218                 aps.created_by = fingerprint
219                 aps.reason = section.get('Reason')
220                 session.add(aps)
221                 self.log.log(['dm', 'allow', fpr.fingerprint, source])
222                 self.result.append('Allowed: {0}'.format(source))
223             else:
224                 self.result.append('Already-Allowed: {0}'.format(source))
225
226         session.flush()
227
228         for source in self._split_packages(section.get('Deny', '')):
229             count = session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr, source=source).delete()
230             if count == 0:
231                 raise CommandError('Tried to remove upload permissions for package {0}, '
232                                    'but no upload permissions were granted before.'.format(source))
233
234             self.log.log(['dm', 'deny', fpr.fingerprint, source])
235             self.result.append('Denied: {0}'.format(source))
236
237         session.commit()
238
239     def action_break_the_archive(self, fingerprint, section, session):
240         name = 'Dave'
241         uid = fingerprint.uid
242         if uid is not None and uid.name is not None:
243             name = uid.name.split()[0]
244
245         self.result.append("DAK9000: I'm sorry, {0}. I'm afraid I can't do that.".format(name))