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