1 """module to handle command files
3 @contact: Debian FTP Master <ftpmaster@debian.org>
4 @copyright: 2012, Ansgar Burchardt <ansgar@debian.org>
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.
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.
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.
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
34 class CommandError(Exception):
37 class CommandFile(object):
38 def __init__(self, path, log=None):
40 from daklib.daklog import Logger
46 self.filename = os.path.basename(path)
48 def _check_replay(self, signed_file, session):
51 @note: Will commit changes to the database.
53 @type signed_file: L{daklib.gpg.SignedFile}
55 @param session: database session
57 # Mark commands file as seen to prevent replays.
58 signature_history = SignatureHistory.from_signed_file(signed_file)
59 session.add(signature_history)
62 def _evaluate_sections(self, sections, session):
66 section = sections.section
68 action = section.get('Action', None)
70 raise CommandError('Encountered section without Action field')
71 self.result.append('Action: {0}'.format(action))
74 self.action_dm(self.fingerprint, section, session)
75 elif action == 'break-the-archive':
76 self.action_break_the_archive(self.fingerprint, section, session)
78 raise CommandError('Unknown action: {0}'.format(action))
84 def _notify_uploader(self):
87 bcc = 'X-DAK: dak process-command'
88 if 'Dinstall::Bcc' in cnf:
89 bcc = '{0}\nBcc: {1}'.format(bcc, cnf['Dinstall::Bcc'])
91 cc = set(fix_maintainer(address)[1] for address in self.cc)
94 '__DAK_ADDRESS__': cnf['Dinstall::MyEmailAddress'],
95 '__MAINTAINER_TO__': fix_maintainer(self.uploader)[1],
96 '__CC__': ", ".join(cc),
98 '__RESULTS__': "\n".join(self.result),
99 '__FILENAME__': self.filename,
102 message = TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'process-command.processed'))
107 """evaluate commands file
110 @returns: C{True} if the file was processed sucessfully,
115 session = DBConn().session()
117 keyrings = session.query(Keyring).filter_by(active=True).order_by(Keyring.priority)
118 keyring_files = [ k.keyring_name for k in keyrings ]
120 raw_contents = open(self.path, 'r').read()
121 signed_file = SignedFile(raw_contents, keyring_files)
122 if not signed_file.valid:
123 self.log.log(['invalid signature', self.filename])
126 self.fingerprint = session.query(Fingerprint).filter_by(fingerprint=signed_file.primary_fingerprint).one()
127 if self.fingerprint.keyring is None:
128 self.log.log(['singed by key in unknown keyring', self.filename])
130 assert self.fingerprint.keyring.active
132 self.log.log(['processing', self.filename, 'signed-by={0}'.format(self.fingerprint.fingerprint)])
134 with tempfile.TemporaryFile() as fh:
135 fh.write(signed_file.contents)
137 sections = apt_pkg.TagFile(fh)
140 addresses = gpg_get_key_addresses(self.fingerprint.fingerprint)
141 if len(addresses) > 0:
142 self.uploader = addresses[0]
146 section = sections.section
147 if 'Uploader' in section:
148 self.uploader = section['Uploader']
149 # TODO: Verify first section has valid Archive field
150 if 'Archive' not in section:
151 raise CommandError('No Archive field in first section.')
153 # TODO: send mail when we detected a replay.
154 self._check_replay(signed_file, session)
156 self._evaluate_sections(sections, session)
157 self.result.append('')
158 except Exception as e:
159 self.log.log(['ERROR', e])
160 self.result.append("There was an error processing this section. No changes were committed.\nDetails:\n{0}".format(e))
163 self._notify_uploader()
166 self.log.log(['done', self.filename])
170 def _split_packages(self, value):
171 names = value.split()
173 if not re_field_package.match(name):
174 raise CommandError('Invalid package name "{0}"'.format(name))
177 def action_dm(self, fingerprint, section, session):
180 if 'Command::DM::AdminKeyrings' not in cnf \
181 or 'Command::DM::ACL' not in cnf \
182 or 'Command::DM::Keyrings' not in cnf:
183 raise CommandError('DM command is not configured for this archive.')
185 allowed_keyrings = cnf.value_list('Command::DM::AdminKeyrings')
186 if fingerprint.keyring.keyring_name not in allowed_keyrings:
187 raise CommandError('Key {0} is not allowed to set DM'.format(fingerprint.fingerprint))
189 acl_name = cnf.get('Command::DM::ACL', 'dm')
190 acl = session.query(ACL).filter_by(name=acl_name).one()
192 fpr = session.query(Fingerprint).filter_by(fingerprint=section['Fingerprint']).one()
193 if fpr.keyring is None or fpr.keyring.keyring_name not in cnf.value_list('Command::DM::Keyrings'):
194 raise CommandError('Key {0} is not in DM keyring.'.format(fpr.fingerprint))
195 addresses = gpg_get_key_addresses(fpr.fingerprint)
196 if len(addresses) > 0:
197 self.cc.append(addresses[0])
199 self.log.log(['dm', 'fingerprint', fpr.fingerprint])
200 self.result.append('Fingerprint: {0}'.format(fpr.fingerprint))
201 if len(addresses) > 0:
202 self.log.log(['dm', 'uid', addresses[0]])
203 self.result.append('Uid: {0}'.format(addresses[0]))
205 for source in self._split_packages(section.get('Allow', '')):
206 # Check for existance of source package to catch typos
207 if session.query(DBSource).filter_by(source=source).first() is None:
208 raise CommandError('Tried to grant permissions for unknown source package: {0}'.format(source))
210 if session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr, source=source).first() is None:
213 aps.fingerprint = fpr
215 aps.created_by = fingerprint
216 aps.reason = section.get('Reason')
218 self.log.log(['dm', 'allow', fpr.fingerprint, source])
219 self.result.append('Allowed: {0}'.format(source))
221 self.result.append('Already-Allowed: {0}'.format(source))
225 for source in self._split_packages(section.get('Deny', '')):
226 count = session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr, source=source).delete()
228 raise CommandError('Tried to remove upload permissions for package {0}, '
229 'but no upload permissions were granted before.'.format(source))
231 self.log.log(['dm', 'deny', fpr.fingerprint, source])
232 self.result.append('Denied: {0}'.format(source))
236 def action_break_the_archive(self, fingerprint, section, session):
238 uid = fingerprint.uid
239 if uid is not None and uid.name is not None:
240 name = uid.name.split()[0]
242 self.result.append("DAK9000: I'm sorry, {0}. I'm afraid I can't do that.".format(name))