]> git.decadent.org.uk Git - dak.git/blob - daklib/command.py
Implement dm-remove and dm-migrate commands.
[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 _quote_section(self, section):
63         lines = []
64         for l in str(section).splitlines():
65             lines.append("> {0}".format(l))
66         return "\n".join(lines)
67
68     def _evaluate_sections(self, sections, session):
69         session.rollback()
70         try:
71             while True:
72                 sections.next()
73                 section = sections.section
74                 self.result.append(self._quote_section(section))
75
76                 action = section.get('Action', None)
77                 if action is None:
78                     raise CommandError('Encountered section without Action field')
79
80                 if action == 'dm':
81                     self.action_dm(self.fingerprint, section, session)
82                 elif action == 'dm-remove':
83                     self.action_dm_remove(self.fingerprint, section, session)
84                 elif action == 'dm-migrate':
85                     self.action_dm_migrate(self.fingerprint, section, session)
86                 elif action == 'break-the-archive':
87                     self.action_break_the_archive(self.fingerprint, section, session)
88                 else:
89                     raise CommandError('Unknown action: {0}'.format(action))
90
91                 self.result.append('')
92         except StopIteration:
93             pass
94         finally:
95             session.rollback()
96
97     def _notify_uploader(self):
98         cnf = Config()
99
100         bcc = 'X-DAK: dak process-command'
101         if 'Dinstall::Bcc' in cnf:
102             bcc = '{0}\nBcc: {1}'.format(bcc, cnf['Dinstall::Bcc'])
103
104         cc = set(fix_maintainer(address)[1] for address in self.cc)
105
106         subst = {
107             '__DAK_ADDRESS__': cnf['Dinstall::MyEmailAddress'],
108             '__MAINTAINER_TO__': fix_maintainer(self.uploader)[1],
109             '__CC__': ", ".join(cc),
110             '__BCC__': bcc,
111             '__RESULTS__': "\n".join(self.result),
112             '__FILENAME__': self.filename,
113             }
114
115         message = TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'process-command.processed'))
116
117         send_mail(message)
118
119     def evaluate(self):
120         """evaluate commands file
121
122         @rtype:   bool
123         @returns: C{True} if the file was processed sucessfully,
124                   C{False} otherwise
125         """
126         result = True
127
128         session = DBConn().session()
129
130         keyrings = session.query(Keyring).filter_by(active=True).order_by(Keyring.priority)
131         keyring_files = [ k.keyring_name for k in keyrings ]
132
133         raw_contents = open(self.path, 'r').read()
134         signed_file = SignedFile(raw_contents, keyring_files)
135         if not signed_file.valid:
136             self.log.log(['invalid signature', self.filename])
137             return False
138
139         self.fingerprint = session.query(Fingerprint).filter_by(fingerprint=signed_file.primary_fingerprint).one()
140         if self.fingerprint.keyring is None:
141             self.log.log(['singed by key in unknown keyring', self.filename])
142             return False
143         assert self.fingerprint.keyring.active
144
145         self.log.log(['processing', self.filename, 'signed-by={0}'.format(self.fingerprint.fingerprint)])
146
147         with tempfile.TemporaryFile() as fh:
148             fh.write(signed_file.contents)
149             fh.seek(0)
150             sections = apt_pkg.TagFile(fh)
151
152         self.uploader = None
153         addresses = gpg_get_key_addresses(self.fingerprint.fingerprint)
154         if len(addresses) > 0:
155             self.uploader = addresses[0]
156
157         try:
158             sections.next()
159             section = sections.section
160             if 'Uploader' in section:
161                 self.uploader = section['Uploader']
162             # TODO: Verify first section has valid Archive field
163             if 'Archive' not in section:
164                 raise CommandError('No Archive field in first section.')
165
166             # TODO: send mail when we detected a replay.
167             self._check_replay(signed_file, session)
168
169             self._evaluate_sections(sections, session)
170             self.result.append('')
171         except Exception as e:
172             self.log.log(['ERROR', e])
173             self.result.append("There was an error processing this section. No changes were committed.\nDetails:\n{0}".format(e))
174             result = False
175
176         self._notify_uploader()
177
178         session.close()
179
180         return result
181
182     def _split_packages(self, value):
183         names = value.split()
184         for name in names:
185             if not re_field_package.match(name):
186                 raise CommandError('Invalid package name "{0}"'.format(name))
187         return names
188
189     def action_dm(self, fingerprint, section, session):
190         cnf = Config()
191
192         if 'Command::DM::AdminKeyrings' not in cnf \
193                 or 'Command::DM::ACL' not in cnf \
194                 or 'Command::DM::Keyrings' not in cnf:
195             raise CommandError('DM command is not configured for this archive.')
196
197         allowed_keyrings = cnf.value_list('Command::DM::AdminKeyrings')
198         if fingerprint.keyring.keyring_name not in allowed_keyrings:
199             raise CommandError('Key {0} is not allowed to set DM'.format(fingerprint.fingerprint))
200
201         acl_name = cnf.get('Command::DM::ACL', 'dm')
202         acl = session.query(ACL).filter_by(name=acl_name).one()
203
204         fpr_hash = section['Fingerprint'].translate(None, ' ')
205         fpr = session.query(Fingerprint).filter_by(fingerprint=fpr_hash).first()
206         if fpr is None:
207             raise CommandError('Unknown fingerprint {0}'.format(fpr_hash))
208         if fpr.keyring is None or fpr.keyring.keyring_name not in cnf.value_list('Command::DM::Keyrings'):
209             raise CommandError('Key {0} is not in DM keyring.'.format(fpr.fingerprint))
210         addresses = gpg_get_key_addresses(fpr.fingerprint)
211         if len(addresses) > 0:
212             self.cc.append(addresses[0])
213
214         self.log.log(['dm', 'fingerprint', fpr.fingerprint])
215         self.result.append('Fingerprint: {0}'.format(fpr.fingerprint))
216         if len(addresses) > 0:
217             self.log.log(['dm', 'uid', addresses[0]])
218             self.result.append('Uid: {0}'.format(addresses[0]))
219
220         for source in self._split_packages(section.get('Allow', '')):
221             # Check for existance of source package to catch typos
222             if session.query(DBSource).filter_by(source=source).first() is None:
223                 raise CommandError('Tried to grant permissions for unknown source package: {0}'.format(source))
224
225             if session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr, source=source).first() is None:
226                 aps = ACLPerSource()
227                 aps.acl = acl
228                 aps.fingerprint = fpr
229                 aps.source = source
230                 aps.created_by = fingerprint
231                 aps.reason = section.get('Reason')
232                 session.add(aps)
233                 self.log.log(['dm', 'allow', fpr.fingerprint, source])
234                 self.result.append('Allowed: {0}'.format(source))
235             else:
236                 self.result.append('Already-Allowed: {0}'.format(source))
237
238         session.flush()
239
240         for source in self._split_packages(section.get('Deny', '')):
241             count = session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr, source=source).delete()
242             if count == 0:
243                 raise CommandError('Tried to remove upload permissions for package {0}, '
244                                    'but no upload permissions were granted before.'.format(source))
245
246             self.log.log(['dm', 'deny', fpr.fingerprint, source])
247             self.result.append('Denied: {0}'.format(source))
248
249         session.commit()
250
251     def _action_dm_admin_common(self, fingerprint, section, session):
252         cnf = Config()
253
254         if 'Command::DM-Admin::AdminFingerprints' not in cnf \
255                 or 'Command::DM::ACL' not in cnf:
256             raise CommandError('DM admin command is not configured for this archive.')
257
258         allowed_fingerprints = cnf.value_list('Command::DM-Admin::AdminFingerprints')
259         if fingerprint.fingerprint not in allowed_fingerprints:
260             raise CommandError('Key {0} is not allowed to admin DM'.format(fingerprint.fingerprint))
261
262     def action_dm_remove(self, fingerprint, section, session):
263         self._action_dm_admin_common(fingerprint, section, session)
264
265         cnf = Config()
266         acl_name = cnf.get('Command::DM::ACL', 'dm')
267         acl = session.query(ACL).filter_by(name=acl_name).one()
268
269         fpr_hash = section['Fingerprint'].translate(None, ' ')
270         fpr = session.query(Fingerprint).filter_by(fingerprint=fpr_hash).first()
271         if fpr is None:
272             self.result.append('Unknown fingerprint: {0}\nNo action taken.'.format(fpr_hash))
273             return
274
275         self.log.log(['dm-remove', fpr.fingerprint])
276
277         count = 0
278         for entry in session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr):
279             self.log.log(['dm-remove', fpr.fingerprint, 'source={0}'.format(entry.source)])
280             count += 1
281             session.delete(entry)
282
283         self.result.append('Removed: {0}.\n{1} acl entries removed.'.format(fpr.fingerprint, count))
284
285         session.commit()
286
287     def action_dm_migrate(self, fingerprint, section, session):
288         self._action_dm_admin_common(fingerprint, section, session)
289         cnf = Config()
290         acl_name = cnf.get('Command::DM::ACL', 'dm')
291         acl = session.query(ACL).filter_by(name=acl_name).one()
292
293         fpr_hash_from = section['From'].translate(None, ' ')
294         fpr_from = session.query(Fingerprint).filter_by(fingerprint=fpr_hash_from).first()
295         if fpr_from is None:
296             self.result.append('Unknown fingerprint (From): {0}\nNo action taken.'.format(fpr_hash_from))
297             return
298
299         fpr_hash_to = section['To'].translate(None, ' ')
300         fpr_to = session.query(Fingerprint).filter_by(fingerprint=fpr_hash_to).first()
301         if fpr_to is None:
302             self.result.append('Unknown fingerprint (To): {0}\nNo action taken.'.format(fpr_hash_to))
303             return
304         if fpr_to.keyring is None or fpr_to.keyring.keyring_name not in cnf.value_list('Command::DM::Keyrings'):
305             self.result.append('Key (To) {0} is not in DM keyring.\nNo action taken.'.format(fpr_to.fingerprint))
306             return
307
308         self.log.log(['dm-migrate', 'from={0}'.format(fpr_hash_from), 'to={0}'.format(fpr_hash_to)])
309
310         count = 0
311         for entry in session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr_from):
312             self.log.log(['dm-migrate', 'from={0}'.format(fpr_hash_from), 'to={0}'.format(fpr_hash_to), 'source={0}'.format(entry.source)])
313             entry.fingerprint = fpr_to
314             count += 1
315
316         self.result.append('Migrated {0} to {1}.\n{2} acl entries changed.'.format(fpr_hash_from, fpr_hash_to, count))
317
318         session.commit()
319
320     def action_break_the_archive(self, fingerprint, section, session):
321         name = 'Dave'
322         uid = fingerprint.uid
323         if uid is not None and uid.name is not None:
324             name = uid.name.split()[0]
325
326         self.result.append("DAK9000: I'm sorry, {0}. I'm afraid I can't do that.".format(name))