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