]> git.decadent.org.uk Git - dak.git/blob - daklib/command.py
Merge branch 'new-dm'
[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 == 'break-the-archive':
83                     self.action_break_the_archive(self.fingerprint, section, session)
84                 else:
85                     raise CommandError('Unknown action: {0}'.format(action))
86
87                 self.result.append('')
88         except StopIteration:
89             pass
90         finally:
91             session.rollback()
92
93     def _notify_uploader(self):
94         cnf = Config()
95
96         bcc = 'X-DAK: dak process-command'
97         if 'Dinstall::Bcc' in cnf:
98             bcc = '{0}\nBcc: {1}'.format(bcc, cnf['Dinstall::Bcc'])
99
100         cc = set(fix_maintainer(address)[1] for address in self.cc)
101
102         subst = {
103             '__DAK_ADDRESS__': cnf['Dinstall::MyEmailAddress'],
104             '__MAINTAINER_TO__': fix_maintainer(self.uploader)[1],
105             '__CC__': ", ".join(cc),
106             '__BCC__': bcc,
107             '__RESULTS__': "\n".join(self.result),
108             '__FILENAME__': self.filename,
109             }
110
111         message = TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'process-command.processed'))
112
113         send_mail(message)
114
115     def evaluate(self):
116         """evaluate commands file
117
118         @rtype:   bool
119         @returns: C{True} if the file was processed sucessfully,
120                   C{False} otherwise
121         """
122         result = True
123
124         session = DBConn().session()
125
126         keyrings = session.query(Keyring).filter_by(active=True).order_by(Keyring.priority)
127         keyring_files = [ k.keyring_name for k in keyrings ]
128
129         raw_contents = open(self.path, 'r').read()
130         signed_file = SignedFile(raw_contents, keyring_files)
131         if not signed_file.valid:
132             self.log.log(['invalid signature', self.filename])
133             return False
134
135         self.fingerprint = session.query(Fingerprint).filter_by(fingerprint=signed_file.primary_fingerprint).one()
136         if self.fingerprint.keyring is None:
137             self.log.log(['singed by key in unknown keyring', self.filename])
138             return False
139         assert self.fingerprint.keyring.active
140
141         self.log.log(['processing', self.filename, 'signed-by={0}'.format(self.fingerprint.fingerprint)])
142
143         with tempfile.TemporaryFile() as fh:
144             fh.write(signed_file.contents)
145             fh.seek(0)
146             sections = apt_pkg.TagFile(fh)
147
148         self.uploader = None
149         addresses = gpg_get_key_addresses(self.fingerprint.fingerprint)
150         if len(addresses) > 0:
151             self.uploader = addresses[0]
152
153         try:
154             sections.next()
155             section = sections.section
156             if 'Uploader' in section:
157                 self.uploader = section['Uploader']
158             # TODO: Verify first section has valid Archive field
159             if 'Archive' not in section:
160                 raise CommandError('No Archive field in first section.')
161
162             # TODO: send mail when we detected a replay.
163             self._check_replay(signed_file, session)
164
165             self._evaluate_sections(sections, session)
166             self.result.append('')
167         except Exception as e:
168             self.log.log(['ERROR', e])
169             self.result.append("There was an error processing this section. No changes were committed.\nDetails:\n{0}".format(e))
170             result = False
171
172         self._notify_uploader()
173
174         session.close()
175
176         return result
177
178     def _split_packages(self, value):
179         names = value.split()
180         for name in names:
181             if not re_field_package.match(name):
182                 raise CommandError('Invalid package name "{0}"'.format(name))
183         return names
184
185     def action_dm(self, fingerprint, section, session):
186         cnf = Config()
187
188         if 'Command::DM::AdminKeyrings' not in cnf \
189                 or 'Command::DM::ACL' not in cnf \
190                 or 'Command::DM::Keyrings' not in cnf:
191             raise CommandError('DM command is not configured for this archive.')
192
193         allowed_keyrings = cnf.value_list('Command::DM::AdminKeyrings')
194         if fingerprint.keyring.keyring_name not in allowed_keyrings:
195             raise CommandError('Key {0} is not allowed to set DM'.format(fingerprint.fingerprint))
196
197         acl_name = cnf.get('Command::DM::ACL', 'dm')
198         acl = session.query(ACL).filter_by(name=acl_name).one()
199
200         fpr_hash = section['Fingerprint'].translate(None, ' ')
201         fpr = session.query(Fingerprint).filter_by(fingerprint=fpr_hash).one()
202         if fpr.keyring is None or fpr.keyring.keyring_name not in cnf.value_list('Command::DM::Keyrings'):
203             raise CommandError('Key {0} is not in DM keyring.'.format(fpr.fingerprint))
204         addresses = gpg_get_key_addresses(fpr.fingerprint)
205         if len(addresses) > 0:
206             self.cc.append(addresses[0])
207
208         self.log.log(['dm', 'fingerprint', fpr.fingerprint])
209         self.result.append('Fingerprint: {0}'.format(fpr.fingerprint))
210         if len(addresses) > 0:
211             self.log.log(['dm', 'uid', addresses[0]])
212             self.result.append('Uid: {0}'.format(addresses[0]))
213
214         for source in self._split_packages(section.get('Allow', '')):
215             # Check for existance of source package to catch typos
216             if session.query(DBSource).filter_by(source=source).first() is None:
217                 raise CommandError('Tried to grant permissions for unknown source package: {0}'.format(source))
218
219             if session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr, source=source).first() is None:
220                 aps = ACLPerSource()
221                 aps.acl = acl
222                 aps.fingerprint = fpr
223                 aps.source = source
224                 aps.created_by = fingerprint
225                 aps.reason = section.get('Reason')
226                 session.add(aps)
227                 self.log.log(['dm', 'allow', fpr.fingerprint, source])
228                 self.result.append('Allowed: {0}'.format(source))
229             else:
230                 self.result.append('Already-Allowed: {0}'.format(source))
231
232         session.flush()
233
234         for source in self._split_packages(section.get('Deny', '')):
235             count = session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr, source=source).delete()
236             if count == 0:
237                 raise CommandError('Tried to remove upload permissions for package {0}, '
238                                    'but no upload permissions were granted before.'.format(source))
239
240             self.log.log(['dm', 'deny', fpr.fingerprint, source])
241             self.result.append('Denied: {0}'.format(source))
242
243         session.commit()
244
245     def action_break_the_archive(self, fingerprint, section, session):
246         name = 'Dave'
247         uid = fingerprint.uid
248         if uid is not None and uid.name is not None:
249             name = uid.name.split()[0]
250
251         self.result.append("DAK9000: I'm sorry, {0}. I'm afraid I can't do that.".format(name))