]> git.decadent.org.uk Git - dak.git/blob - dak/security_install.py
Remove debug output
[dak.git] / dak / security_install.py
1 #!/usr/bin/env python
2
3 # Wrapper for Debian Security team
4 # Copyright (C) 2002, 2003, 2004, 2006  James Troup <james@nocrew.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 # USA
20
21 ################################################################################
22
23 # <aj> neuro: <usual question>?
24 # <neuro> aj: PPG: the movie!  july 3!
25 # <aj> _PHWOAR_!!!!!
26 # <aj> (you think you can distract me, and you're right)
27 # <aj> urls?!
28 # <aj> promo videos?!
29 # <aj> where, where!?
30
31 ################################################################################
32
33 import commands, os, pwd, re, sys, time
34 import apt_pkg
35 import daklib.queue 
36 import daklib.utils
37
38 ################################################################################
39
40 Cnf = None
41 Options = None
42 Upload = None
43
44 re_taint_free = re.compile(r"^['/;\-\+\.\s\w]+$")
45
46 ################################################################################
47
48 def usage (exit_code=0):
49     print """Usage: dak security-install ADV_NUMBER CHANGES_FILE[...]
50 Install CHANGES_FILE(s) as security advisory ADV_NUMBER
51
52   -h, --help                 show this help and exit
53   -n, --no-action            don't do anything
54
55 """
56     sys.exit(exit_code)
57
58 ################################################################################
59
60 def do_upload(changes_files):
61     file_list = ""
62     suites = {}
63     component_mapping = {}
64     for component in Cnf.SubTree("Security-Install::ComponentMappings").List():
65         component_mapping[component] = Cnf["Security-Install::ComponentMappings::%s" % (component)]
66     uploads = {}; # uploads[uri] = file_list
67     changesfiles = {}; # changesfiles[uri] = file_list
68     package_list = {} # package_list[source_name][version]
69     changes_files.sort(daklib.utils.changes_compare)
70     for changes_file in changes_files:
71         changes_file = daklib.utils.validate_changes_file_arg(changes_file)
72         # Reset variables
73         components = {}
74         upload_uris = {}
75         file_list = []
76         Upload.init_vars()
77         # Parse the .dak file for the .changes file
78         Upload.pkg.changes_file = changes_file
79         Upload.update_vars()
80         files = Upload.pkg.files
81         changes = Upload.pkg.changes
82         dsc = Upload.pkg.dsc
83         # We have the changes, now return if its amd64, to not upload them to ftp-master
84         if changes["architecture"].has_key("amd64"):
85             print "Not uploading amd64 part to ftp-master\n"
86             continue
87         if changes["distribution"].has_key("oldstable"):
88             print "Not uploading oldstable-security changes to ftp-master\n"
89             continue
90         # Build the file list for this .changes file
91         for file in files.keys():
92             poolname = os.path.join(Cnf["Dir::Root"], Cnf["Dir::PoolRoot"],
93                                     daklib.utils.poolify(changes["source"], files[file]["component"]),
94                                     file)
95             file_list.append(poolname)
96             orig_component = files[file].get("original component", files[file]["component"])
97             components[orig_component] = ""
98         # Determine the upload uri for this .changes file
99         for component in components.keys():
100             upload_uri = component_mapping.get(component)
101             if upload_uri:
102                 upload_uris[upload_uri] = ""
103         num_upload_uris = len(upload_uris.keys())
104         if num_upload_uris == 0:
105             daklib.utils.fubar("%s: No valid upload URI found from components (%s)."
106                         % (changes_file, ", ".join(components.keys())))
107         elif num_upload_uris > 1:
108             daklib.utils.fubar("%s: more than one upload URI (%s) from components (%s)."
109                         % (changes_file, ", ".join(upload_uris.keys()),
110                            ", ".join(components.keys())))
111         upload_uri = upload_uris.keys()[0]
112         # Update the file list for the upload uri
113         if not uploads.has_key(upload_uri):
114             uploads[upload_uri] = []
115         uploads[upload_uri].extend(file_list)
116         # Update the changes list for the upload uri
117         if not changesfiles.has_key(upload_uri):
118             changesfiles[upload_uri] = []
119         changesfiles[upload_uri].append(changes_file)
120         # Remember the suites and source name/version
121         for suite in changes["distribution"].keys():
122             suites[suite] = ""
123         # Remember the source name and version
124         if changes["architecture"].has_key("source") and \
125            changes["distribution"].has_key("testing"):
126             if not package_list.has_key(dsc["source"]):
127                 package_list[dsc["source"]] = {}
128             package_list[dsc["source"]][dsc["version"]] = ""
129
130     if not Options["No-Action"]:
131         answer = yes_no("Upload to files to main archive (Y/n)?")
132         if answer != "y":
133             return
134
135     for uri in uploads.keys():
136         uploads[uri].extend(changesfiles[uri])
137         (host, path) = uri.split(":")
138         file_list = " ".join(uploads[uri])
139         print "Uploading files to %s..." % (host)
140         spawn("lftp -c 'open %s; cd %s; put %s'" % (host, path, file_list))
141
142     if not Options["No-Action"]:
143         filename = "%s/testing-processed" % (Cnf["Dir::Log"])
144         file = daklib.utils.open_file(filename, 'a')
145         for source in package_list.keys():
146             for version in package_list[source].keys():
147                 file.write(" ".join([source, version])+'\n')
148         file.close()
149
150 ######################################################################
151 # This function was originally written by aj and NIHishly merged into
152 # 'dak security-install' by me.
153
154 def make_advisory(advisory_nr, changes_files):
155     adv_packages = []
156     updated_pkgs = {};  # updated_pkgs[distro][arch][file] = {path,md5,size}
157
158     for arg in changes_files:
159         arg = daklib.utils.validate_changes_file_arg(arg)
160         Upload.pkg.changes_file = arg
161         Upload.init_vars()
162         Upload.update_vars()
163
164         src = Upload.pkg.changes["source"]
165         if src not in adv_packages:
166             adv_packages += [src]
167
168         suites = Upload.pkg.changes["distribution"].keys()
169         for suite in suites:
170             if not updated_pkgs.has_key(suite):
171                 updated_pkgs[suite] = {}
172
173         files = Upload.pkg.files
174         for file in files.keys():
175             arch = files[file]["architecture"]
176             md5 = files[file]["md5sum"]
177             size = files[file]["size"]
178             poolname = Cnf["Dir::PoolRoot"] + \
179                 daklib.utils.poolify(src, files[file]["component"])
180             if arch == "source" and file.endswith(".dsc"):
181                 dscpoolname = poolname
182             for suite in suites:
183                 if not updated_pkgs[suite].has_key(arch):
184                     updated_pkgs[suite][arch] = {}
185                 updated_pkgs[suite][arch][file] = {
186                     "md5": md5, "size": size,
187                     "poolname": poolname }
188
189         dsc_files = Upload.pkg.dsc_files
190         for file in dsc_files.keys():
191             arch = "source"
192             if not dsc_files[file].has_key("files id"):
193                 continue
194
195             # otherwise, it's already in the pool and needs to be
196             # listed specially
197             md5 = dsc_files[file]["md5sum"]
198             size = dsc_files[file]["size"]
199             for suite in suites:
200                 if not updated_pkgs[suite].has_key(arch):
201                     updated_pkgs[suite][arch] = {}
202                 updated_pkgs[suite][arch][file] = {
203                     "md5": md5, "size": size,
204                     "poolname": dscpoolname }
205
206     if os.environ.has_key("SUDO_UID"):
207         whoami = long(os.environ["SUDO_UID"])
208     else:
209         whoami = os.getuid()
210     whoamifull = pwd.getpwuid(whoami)
211     username = whoamifull[4].split(",")[0]
212
213     Subst = {
214         "__ADVISORY__": advisory_nr,
215         "__WHOAMI__": username,
216         "__DATE__": time.strftime("%B %d, %Y", time.gmtime(time.time())),
217         "__PACKAGE__": ", ".join(adv_packages),
218         "__DAK_ADDRESS__": Cnf["Dinstall::MyEmailAddress"]
219         }
220
221     if Cnf.has_key("Dinstall::Bcc"):
222         Subst["__BCC__"] = "Bcc: %s" % (Cnf["Dinstall::Bcc"])
223
224     adv = ""
225     archive = Cnf["Archive::%s::PrimaryMirror" % (daklib.utils.where_am_i())]
226     for suite in updated_pkgs.keys():
227         suite_header = "%s %s (%s)" % (Cnf["Dinstall::MyDistribution"],
228                                        Cnf["Suite::%s::Version" % suite], suite)
229         adv += "%s\n%s\n\n" % (suite_header, "-"*len(suite_header))
230
231         arches = Cnf.ValueList("Suite::%s::Architectures" % suite)
232         if "source" in arches:
233             arches.remove("source")
234         if "all" in arches:
235             arches.remove("all")
236         arches.sort()
237
238         adv += "  %s was released for %s.\n\n" % (
239                 suite.capitalize(), daklib.utils.join_with_commas_and(arches))
240
241         for a in ["source", "all"] + arches:
242             if not updated_pkgs[suite].has_key(a):
243                 continue
244
245             if a == "source":
246                 adv += "  Source archives:\n\n"
247             elif a == "all":
248                 adv += "  Architecture independent packages:\n\n"
249             else:
250                 adv += "  %s architecture (%s)\n\n" % (a,
251                         Cnf["Architectures::%s" % a])
252
253             for file in updated_pkgs[suite][a].keys():
254                 adv += "    http://%s/%s%s\n" % (
255                                 archive, updated_pkgs[suite][a][file]["poolname"], file)
256                 adv += "      Size/MD5 checksum: %8s %s\n" % (
257                         updated_pkgs[suite][a][file]["size"],
258                         updated_pkgs[suite][a][file]["md5"])
259             adv += "\n"
260     adv = adv.rstrip()
261
262     Subst["__ADVISORY_TEXT__"] = adv
263
264     adv = daklib.utils.TemplateSubst(Subst, Cnf["Dir::Templates"]+"/security-install.advisory")
265     if not Options["No-Action"]:
266         daklib.utils.send_mail (adv)
267     else:
268         print "[<Would send template advisory mail>]"
269
270 ######################################################################
271
272 def init():
273     global Cnf, Upload, Options
274
275     apt_pkg.init()
276     Cnf = daklib.utils.get_conf()
277
278     Arguments = [('h', "help", "Security-Install::Options::Help"),
279                  ('n', "no-action", "Security-Install::Options::No-Action")]
280
281     for i in [ "help", "no-action" ]:
282         Cnf["Security-Install::Options::%s" % (i)] = ""
283
284     arguments = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
285     Options = Cnf.SubTree("Security-Install::Options")
286     Upload = daklib.queue.Upload(Cnf)
287
288     if Options["Help"]:
289         usage(0)
290
291     if not arguments:
292         usage(1)
293
294     advisory_number = arguments[0]
295     changes_files = arguments[1:]
296     if advisory_number.endswith(".changes"):
297         daklib.utils.warn("first argument must be the advisory number.")
298         usage(1)
299     for file in changes_files:
300         file = daklib.utils.validate_changes_file_arg(file)
301     return (advisory_number, changes_files)
302
303 ######################################################################
304
305 def yes_no(prompt):
306     while 1:
307         answer = daklib.utils.our_raw_input(prompt+" ").lower()
308         if answer == "y" or answer == "n":
309             break
310         else:
311             print "Invalid answer; please try again."
312     return answer
313
314 ######################################################################
315
316 def spawn(command):
317     if not re_taint_free.match(command):
318         daklib.utils.fubar("Invalid character in \"%s\"." % (command))
319
320     if Options["No-Action"]:
321         print "[%s]" % (command)
322     else:
323         (result, output) = commands.getstatusoutput(command)
324         if (result != 0):
325             daklib.utils.fubar("Invocation of '%s' failed:\n%s\n" % (command, output), result)
326
327 ######################################################################
328
329
330 def main():
331     (advisory_number, changes_files) = init()
332
333     if not Options["No-Action"]:
334         print "About to install the following files: "
335         for file in changes_files:
336             print "  %s" % (file)
337         answer = yes_no("Continue (Y/n)?")
338         if answer == "n":
339             sys.exit(0)
340
341     os.chdir(Cnf["Dir::Queue::Accepted"])
342     print "Installing packages into the archive..."
343     spawn("dak process-accepted -pa %s" % (Cnf["Dir::Dak"], " ".join(changes_files)))
344     os.chdir(Cnf["Dir::Dak"])
345     print "Updating file lists for apt-ftparchive..."
346     spawn("dak make-suite-file-list")
347     print "Updating Packages and Sources files..."
348     spawn("apt-ftparchive generate %s" % (daklib.utils.which_apt_conf_file()))
349     print "Updating Release files..."
350     spawn("dak generate-releases")
351
352     if not Options["No-Action"]:
353         os.chdir(Cnf["Dir::Queue::Done"])
354     else:
355         os.chdir(Cnf["Dir::Queue::Accepted"])
356     print "Generating template advisory..."
357     make_advisory(advisory_number, changes_files)
358
359     # Trigger security mirrors
360     spawn("sudo -u archvsync /home/archvsync/signal_security")
361
362     do_upload(changes_files)
363
364 ################################################################################
365
366 if __name__ == '__main__':
367     main()
368
369 ################################################################################