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