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