]> git.decadent.org.uk Git - dak.git/blob - dak/examine_package.py
examine_package
[dak.git] / dak / examine_package.py
1 #!/usr/bin/env python
2
3 """
4 Script to automate some parts of checking NEW packages
5
6 @contact: Debian FTP Master <ftpmaster@debian.org>
7 @copyright: 2000, 2001, 2002, 2003, 2006  James Troup <james@nocrew.org>
8 @copyright: 2009  Joerg Jaspert <joerg@debian.org>
9 @license: GNU General Public License version 2 or later
10 """
11
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2 of the License, or
15 # (at your option) any later version.
16
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 # GNU General Public License for more details.
21
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
26 ################################################################################
27
28 # <Omnic> elmo wrote docs?!!?!?!?!?!?!
29 # <aj> as if he wasn't scary enough before!!
30 # * aj imagines a little red furry toy sitting hunched over a computer
31 #   tapping furiously and giggling to himself
32 # <aj> eventually he stops, and his heads slowly spins around and you
33 #      see this really evil grin and then he sees you, and picks up a
34 #      knife from beside the keyboard and throws it at you, and as you
35 #      breathe your last breath, he starts giggling again
36 # <aj> but i should be telling this to my psychiatrist, not you guys,
37 #      right? :)
38
39 ################################################################################
40
41 import errno
42 import os
43 import pg
44 import re
45 import sys
46 import md5
47 import apt_pkg, apt_inst
48 from daklib import database
49 from daklib import utils
50 from daklib.regexes import html_escaping, re_html_escaping, re_version, re_spacestrip, \
51                            re_contrib, re_nonfree, re_localhost, re_newlinespace, \
52                            re_package, re_doc_directory
53
54 ################################################################################
55
56 Cnf = None
57 projectB = None
58
59 Cnf = utils.get_conf()
60 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
61 database.init(Cnf, projectB)
62
63 printed_copyrights = {}
64 package_relations = {}
65
66 # default is to not output html.
67 use_html = 0
68
69 ################################################################################
70
71 def usage (exit_code=0):
72     print """Usage: dak examine-package [PACKAGE]...
73 Check NEW package(s).
74
75   -h, --help                 show this help and exit
76   -H, --html-output          output html page with inspection result
77   -f, --file-name            filename for the html page
78
79 PACKAGE can be a .changes, .dsc, .deb or .udeb filename."""
80
81     sys.exit(exit_code)
82
83 ################################################################################
84 # probably xml.sax.saxutils would work as well
85
86 def escape_if_needed(s):
87     if use_html:
88         return re_html_escaping.sub(lambda x: html_escaping.get(x.group(0)), s)
89     else:
90         return s
91
92 def headline(s, level=2, bodyelement=None):
93     if use_html:
94         if bodyelement:
95             print """<thead>
96                 <tr><th colspan="2" class="title" onclick="toggle('%(bodyelement)s', 'table-row-group', 'table-row-group')">%(title)s <span class="toggle-msg">(click to toggle)</span></th></tr>
97               </thead>"""%{"bodyelement":bodyelement,"title":utils.html_escape(s)}
98         else:
99             print "<h%d>%s</h%d>" % (level, utils.html_escape(s), level)
100     else:
101         print "---- %s ----" % (s)
102
103 # Colour definitions, 'end' isn't really for use
104
105 ansi_colours = {
106   'main': "\033[36m",
107   'contrib': "\033[33m",
108   'nonfree': "\033[31m",
109   'arch': "\033[32m",
110   'end': "\033[0m",
111   'bold': "\033[1m",
112   'maintainer': "\033[32m"}
113
114 html_colours = {
115   'main': ('<span style="color: aqua">',"</span>"),
116   'contrib': ('<span style="color: yellow">',"</span>"),
117   'nonfree': ('<span style="color: red">',"</span>"),
118   'arch': ('<span style="color: green">',"</span>"),
119   'bold': ('<span style="font-weight: bold">',"</span>"),
120   'maintainer': ('<span style="color: green">',"</span>")}
121
122 def colour_output(s, colour):
123     if use_html:
124         return ("%s%s%s" % (html_colours[colour][0], utils.html_escape(s), html_colours[colour][1]))
125     else:
126         return ("%s%s%s" % (ansi_colours[colour], s, ansi_colours['end']))
127
128 def escaped_text(s, strip=False):
129     if use_html:
130         if strip:
131             s = s.strip()
132         return "<pre>%s</pre>" % (s)
133     else:
134         return s
135
136 def formatted_text(s, strip=False):
137     if use_html:
138         if strip:
139             s = s.strip()
140         return "<pre>%s</pre>" % (utils.html_escape(s))
141     else:
142         return s
143
144 def output_row(s):
145     if use_html:
146         return """<tr><td>"""+s+"""</td></tr>"""
147     else:
148         return s
149
150 def format_field(k,v):
151     if use_html:
152         return """<tr><td class="key">%s:</td><td class="val">%s</td></tr>"""%(k,v)
153     else:
154         return "%s: %s"%(k,v)
155
156 def foldable_output(title, elementnameprefix, content, norow=False):
157     d = {'elementnameprefix':elementnameprefix}
158     if use_html:
159         print """<div id="%(elementnameprefix)s-wrap"><a name="%(elementnameprefix)s" />
160                    <table class="infobox rfc822">"""%d
161     headline(title, bodyelement="%(elementnameprefix)s-body"%d)
162     if use_html:
163         print """    <tbody id="%(elementnameprefix)s-body" class="infobody">"""%d
164     if norow:
165         print content
166     else:
167         print output_row(content)
168     if use_html:
169         print """</tbody></table></div>"""
170
171 ################################################################################
172
173 def get_depends_parts(depend) :
174     v_match = re_version.match(depend)
175     if v_match:
176         d_parts = { 'name' : v_match.group(1), 'version' : v_match.group(2) }
177     else :
178         d_parts = { 'name' : depend , 'version' : '' }
179     return d_parts
180
181 def get_or_list(depend) :
182     or_list = depend.split("|")
183     return or_list
184
185 def get_comma_list(depend) :
186     dep_list = depend.split(",")
187     return dep_list
188
189 def split_depends (d_str) :
190     # creates a list of lists of dictionaries of depends (package,version relation)
191
192     d_str = re_spacestrip.sub('',d_str)
193     depends_tree = []
194     # first split depends string up amongs comma delimiter
195     dep_list = get_comma_list(d_str)
196     d = 0
197     while d < len(dep_list):
198         # put depends into their own list
199         depends_tree.append([dep_list[d]])
200         d += 1
201     d = 0
202     while d < len(depends_tree):
203         k = 0
204         # split up Or'd depends into a multi-item list
205         depends_tree[d] = get_or_list(depends_tree[d][0])
206         while k < len(depends_tree[d]):
207             # split depends into {package, version relation}
208             depends_tree[d][k] = get_depends_parts(depends_tree[d][k])
209             k += 1
210         d += 1
211     return depends_tree
212
213 def read_control (filename):
214     recommends = []
215     depends = []
216     section = ''
217     maintainer = ''
218     arch = ''
219
220     deb_file = utils.open_file(filename)
221     try:
222         extracts = apt_inst.debExtractControl(deb_file)
223         control = apt_pkg.ParseSection(extracts)
224     except:
225         print formatted_text("can't parse control info")
226         deb_file.close()
227         raise
228
229     deb_file.close()
230
231     control_keys = control.keys()
232
233     if control.has_key("Depends"):
234         depends_str = control.Find("Depends")
235         # create list of dependancy lists
236         depends = split_depends(depends_str)
237
238     if control.has_key("Recommends"):
239         recommends_str = control.Find("Recommends")
240         recommends = split_depends(recommends_str)
241
242     if control.has_key("Section"):
243         section_str = control.Find("Section")
244
245         c_match = re_contrib.search(section_str)
246         nf_match = re_nonfree.search(section_str)
247         if c_match :
248             # contrib colour
249             section = colour_output(section_str, 'contrib')
250         elif nf_match :
251             # non-free colour
252             section = colour_output(section_str, 'nonfree')
253         else :
254             # main
255             section = colour_output(section_str, 'main')
256     if control.has_key("Architecture"):
257         arch_str = control.Find("Architecture")
258         arch = colour_output(arch_str, 'arch')
259
260     if control.has_key("Maintainer"):
261         maintainer = control.Find("Maintainer")
262         localhost = re_localhost.search(maintainer)
263         if localhost:
264             #highlight bad email
265             maintainer = colour_output(maintainer, 'maintainer')
266         else:
267             maintainer = escape_if_needed(maintainer)
268
269     return (control, control_keys, section, depends, recommends, arch, maintainer)
270
271 def read_changes_or_dsc (suite, filename):
272     dsc = {}
273
274     dsc_file = utils.open_file(filename)
275     try:
276         dsc = utils.parse_changes(filename)
277     except:
278         return formatted_text("can't parse .dsc control info")
279     dsc_file.close()
280
281     filecontents = strip_pgp_signature(filename)
282     keysinorder = []
283     for l in filecontents.split('\n'):
284         m = re.match(r'([-a-zA-Z0-9]*):', l)
285         if m:
286             keysinorder.append(m.group(1))
287
288     for k in dsc.keys():
289         if k in ("build-depends","build-depends-indep"):
290             dsc[k] = create_depends_string(suite, split_depends(dsc[k]))
291         elif k == "architecture":
292             if (dsc["architecture"] != "any"):
293                 dsc['architecture'] = colour_output(dsc["architecture"], 'arch')
294         elif k in ("files","changes","description"):
295             if use_html:
296                 dsc[k] = formatted_text(dsc[k], strip=True)
297             else:
298                 dsc[k] = ('\n'+'\n'.join(map(lambda x: ' '+x, dsc[k].split('\n')))).rstrip()
299         else:
300             dsc[k] = escape_if_needed(dsc[k])
301
302     keysinorder = filter(lambda x: not x.lower().startswith('checksums-'), keysinorder)
303
304     filecontents = '\n'.join(map(lambda x: format_field(x,dsc[x.lower()]), keysinorder))+'\n'
305     return filecontents
306
307 def create_depends_string (suite, depends_tree):
308     result = ""
309     if suite == 'experimental':
310         suite_where = " in ('experimental','unstable')"
311     else:
312         suite_where = " ='%s'" % suite
313
314     comma_count = 1
315     for l in depends_tree:
316         if (comma_count >= 2):
317             result += ", "
318         or_count = 1
319         for d in l:
320             if (or_count >= 2 ):
321                 result += " | "
322             # doesn't do version lookup yet.
323
324             q = projectB.query("SELECT DISTINCT(b.package), b.version, c.name, su.suite_name FROM  binaries b, files fi, location l, component c, bin_associations ba, suite su WHERE b.package='%s' AND b.file = fi.id AND fi.location = l.id AND l.component = c.id AND ba.bin=b.id AND ba.suite = su.id AND su.suite_name %s ORDER BY b.version desc" % (d['name'], suite_where))
325             ql = q.getresult()
326             if ql:
327                 i = ql[0]
328
329                 adepends = d['name']
330                 if d['version'] != '' :
331                     adepends += " (%s)" % (d['version'])
332
333                 if i[2] == "contrib":
334                     result += colour_output(adepends, "contrib")
335                 elif i[2] == "non-free":
336                     result += colour_output(adepends, "nonfree")
337                 else :
338                     result += colour_output(adepends, "main")
339             else:
340                 adepends = d['name']
341                 if d['version'] != '' :
342                     adepends += " (%s)" % (d['version'])
343                 result += colour_output(adepends, "bold")
344             or_count += 1
345         comma_count += 1
346     return result
347
348 def output_package_relations ():
349     """
350     Output the package relations, if there is more than one package checked in this run.
351     """
352
353     if len(package_relations) < 2:
354         # Only list something if we have more than one binary to compare
355         return
356
357     to_print = ""
358     for package in package_relations:
359         for relation in package_relations[package]:
360             to_print += "%-15s: (%s) %s\n" % (package, relation, package_relations[package][relation])
361
362     foldable_output("Package relations", "relations", to_print)
363
364 def output_deb_info(suite, filename, packagename):
365     (control, control_keys, section, depends, recommends, arch, maintainer) = read_control(filename)
366
367     if control == '':
368         return formatted_text("no control info")
369     to_print = ""
370     if not package_relations.has_key(packagename):
371         package_relations[packagename] = {}
372     for key in control_keys :
373         if key == 'Depends':
374             field_value = create_depends_string(suite, depends)
375             package_relations[packagename][key] = field_value
376         elif key == 'Recommends':
377             field_value = create_depends_string(suite, recommends)
378             package_relations[packagename][key] = field_value
379         elif key == 'Section':
380             field_value = section
381         elif key == 'Architecture':
382             field_value = arch
383         elif key == 'Maintainer':
384             field_value = maintainer
385         elif key == 'Description':
386             if use_html:
387                 field_value = formatted_text(control.Find(key), strip=True)
388             else:
389                 desc = control.Find(key)
390                 desc = re_newlinespace.sub('\n ', desc)
391                 field_value = escape_if_needed(desc)
392         else:
393             field_value = escape_if_needed(control.Find(key))
394         to_print += " "+format_field(key,field_value)+'\n'
395     return to_print
396
397 def do_command (command, filename, escaped=0):
398     o = os.popen("%s %s" % (command, filename))
399     if escaped:
400         return escaped_text(o.read())
401     else:
402         return formatted_text(o.read())
403
404 def do_lintian (filename):
405     if use_html:
406         return do_command("lintian --show-overrides --color html", filename, 1)
407     else:
408         return do_command("lintian --show-overrides --color always", filename, 1)
409
410 def get_copyright (deb_filename):
411     package = re_package.sub(r'\1', deb_filename)
412     o = os.popen("dpkg-deb -c %s | egrep 'usr(/share)?/doc/[^/]*/copyright' | awk '{print $6}' | head -n 1" % (deb_filename))
413     cright = o.read()[:-1]
414
415     if cright == "":
416         return formatted_text("WARNING: No copyright found, please check package manually.")
417
418     doc_directory = re_doc_directory.sub(r'\1', cright)
419     if package != doc_directory:
420         return formatted_text("WARNING: wrong doc directory (expected %s, got %s)." % (package, doc_directory))
421
422     o = os.popen("dpkg-deb --fsys-tarfile %s | tar xvOf - %s 2>/dev/null" % (deb_filename, cright))
423     cright = o.read()
424     copyrightmd5 = md5.md5(cright).hexdigest()
425
426     res = ""
427     if printed_copyrights.has_key(copyrightmd5) and printed_copyrights[copyrightmd5] != "%s (%s)" % (package, deb_filename):
428         res += formatted_text( "NOTE: Copyright is the same as %s.\n\n" % \
429                                (printed_copyrights[copyrightmd5]))
430     else:
431         printed_copyrights[copyrightmd5] = "%s (%s)" % (package, deb_filename)
432     return res+formatted_text(cright)
433
434 def check_dsc (suite, dsc_filename):
435     (dsc) = read_changes_or_dsc(suite, dsc_filename)
436     foldable_output(dsc_filename, "dsc", dsc, norow=True)
437     foldable_output("lintian check for %s" % dsc_filename, "source-lintian", do_lintian(dsc_filename))
438
439 def check_deb (suite, deb_filename):
440     filename = os.path.basename(deb_filename)
441     packagename = filename.split('_')[0]
442
443     if filename.endswith(".udeb"):
444         is_a_udeb = 1
445     else:
446         is_a_udeb = 0
447
448
449     foldable_output("control file for %s" % (filename), "binary-%s-control"%packagename,
450                     output_deb_info(suite, deb_filename, packagename), norow=True)
451
452     if is_a_udeb:
453         foldable_output("skipping lintian check for udeb", "binary-%s-lintian"%packagename,
454                         "")
455     else:
456         foldable_output("lintian check for %s" % (filename), "binary-%s-lintian"%packagename,
457                         do_lintian(deb_filename))
458
459     foldable_output("contents of %s" % (filename), "binary-%s-contents"%packagename,
460                     do_command("dpkg -c", deb_filename))
461
462     if is_a_udeb:
463         foldable_output("skipping copyright for udeb", "binary-%s-copyright"%packagename,
464                         "")
465     else:
466         foldable_output("copyright of %s" % (filename), "binary-%s-copyright"%packagename,
467                         get_copyright(deb_filename))
468
469     foldable_output("file listing of %s" % (filename),  "binary-%s-file-listing"%packagename,
470                     do_command("ls -l", deb_filename))
471
472 # Read a file, strip the signature and return the modified contents as
473 # a string.
474 def strip_pgp_signature (filename):
475     inputfile = utils.open_file (filename)
476     contents = ""
477     inside_signature = 0
478     skip_next = 0
479     for line in inputfile.readlines():
480         if line[:-1] == "":
481             continue
482         if inside_signature:
483             continue
484         if skip_next:
485             skip_next = 0
486             continue
487         if line.startswith("-----BEGIN PGP SIGNED MESSAGE"):
488             skip_next = 1
489             continue
490         if line.startswith("-----BEGIN PGP SIGNATURE"):
491             inside_signature = 1
492             continue
493         if line.startswith("-----END PGP SIGNATURE"):
494             inside_signature = 0
495             continue
496         contents += line
497     inputfile.close()
498     return contents
499
500 def display_changes(suite, changes_filename):
501     changes = read_changes_or_dsc(suite, changes_filename)
502     foldable_output(changes_filename, "changes", changes, norow=True)
503
504 def check_changes (changes_filename):
505     try:
506         changes = utils.parse_changes (changes_filename)
507     except ChangesUnicodeError:
508         utils.warn("Encoding problem with changes file %s" % (changes_filename))
509     display_changes(changes['distribution'], changes_filename)
510
511     files = utils.build_file_list(changes)
512     for f in files.keys():
513         if f.endswith(".deb") or f.endswith(".udeb"):
514             check_deb(changes['distribution'], f)
515         if f.endswith(".dsc"):
516             check_dsc(changes['distribution'], f)
517         # else: => byhand
518
519 def main ():
520     global Cnf, projectB, db_files, waste, excluded
521
522 #    Cnf = utils.get_conf()
523
524     Arguments = [('h',"help","Examine-Package::Options::Help"),
525                  ('H',"html-output","Examine-Package::Options::Html-Output"),
526                 ]
527     for i in [ "Help", "Html-Output", "partial-html" ]:
528         if not Cnf.has_key("Examine-Package::Options::%s" % (i)):
529             Cnf["Examine-Package::Options::%s" % (i)] = ""
530
531     args = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
532     Options = Cnf.SubTree("Examine-Package::Options")
533
534     if Options["Help"]:
535         usage()
536
537     stdout_fd = sys.stdout
538
539     for f in args:
540         try:
541             if not Options["Html-Output"]:
542                 # Pipe output for each argument through less
543                 less_fd = os.popen("less -R -", 'w', 0)
544                 # -R added to display raw control chars for colour
545                 sys.stdout = less_fd
546             try:
547                 if f.endswith(".changes"):
548                     check_changes(f)
549                 elif f.endswith(".deb") or f.endswith(".udeb"):
550                     # default to unstable when we don't have a .changes file
551                     # perhaps this should be a command line option?
552                     check_deb('unstable', file)
553                 elif f.endswith(".dsc"):
554                     check_dsc('unstable', f)
555                 else:
556                     utils.fubar("Unrecognised file type: '%s'." % (f))
557             finally:
558                 output_package_relations()
559                 if not Options["Html-Output"]:
560                     # Reset stdout here so future less invocations aren't FUBAR
561                     less_fd.close()
562                     sys.stdout = stdout_fd
563         except IOError, e:
564             if errno.errorcode[e.errno] == 'EPIPE':
565                 utils.warn("[examine-package] Caught EPIPE; skipping.")
566                 pass
567             else:
568                 raise
569         except KeyboardInterrupt:
570             utils.warn("[examine-package] Caught C-c; skipping.")
571             pass
572
573 #######################################################################################
574
575 if __name__ == '__main__':
576     main()