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