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