]> git.decadent.org.uk Git - dak.git/blob - dak/examine_package.py
examine_package
[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 @contact: Debian FTP Master <ftpmaster@debian.org>
7 @copyright: 2000, 2001, 2002, 2003, 2006  James Troup <james@nocrew.org>
8 @copyright: 2009  Joerg Jaspert <joerg@debian.org>
9 @license: GNU General Public License version 2 or later
10 """
11
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2 of the License, or
15 # (at your option) any later version.
16
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 # GNU General Public License for more details.
21
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
26 ################################################################################
27
28 # <Omnic> elmo wrote docs?!!?!?!?!?!?!
29 # <aj> as if he wasn't scary enough before!!
30 # * aj imagines a little red furry toy sitting hunched over a computer
31 #   tapping furiously and giggling to himself
32 # <aj> eventually he stops, and his heads slowly spins around and you
33 #      see this really evil grin and then he sees you, and picks up a
34 #      knife from beside the keyboard and throws it at you, and as you
35 #      breathe your last breath, he starts giggling again
36 # <aj> but i should be telling this to my psychiatrist, not you guys,
37 #      right? :)
38
39 ################################################################################
40
41 import errno
42 import os
43 import pg
44 import re
45 import sys
46 import md5
47 import apt_pkg, apt_inst
48 from daklib import database
49 from daklib import utils
50 from daklib.regexes import html_escaping, re_html_escaping, re_version, re_spacestrip, \
51                            re_contrib, re_nonfree, re_localhost, re_newlinespace, \
52                            re_package, re_doc_directory
53
54 ################################################################################
55
56 Cnf = None
57 projectB = None
58
59 Cnf = utils.get_conf()
60 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
61 database.init(Cnf, projectB)
62
63 printed_copyrights = {}
64
65 # default is to not output html.
66 use_html = 0
67
68 ################################################################################
69
70 def usage (exit_code=0):
71     print """Usage: dak examine-package [PACKAGE]...
72 Check NEW package(s).
73
74   -h, --help                 show this help and exit
75   -H, --html-output          output html page with inspection result
76   -f, --file-name            filename for the html page
77
78 PACKAGE can be a .changes, .dsc, .deb or .udeb filename."""
79
80     sys.exit(exit_code)
81
82 ################################################################################
83 # probably xml.sax.saxutils would work as well
84
85 def escape_if_needed(s):
86     if use_html:
87         return re_html_escaping.sub(lambda x: html_escaping.get(x.group(0)), s)
88     else:
89         return s
90
91 def headline(s, level=2, bodyelement=None):
92     if use_html:
93         if bodyelement:
94             print """<thead>
95                 <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>
96               </thead>"""%{"bodyelement":bodyelement,"title":utils.html_escape(s)}
97         else:
98             print "<h%d>%s</h%d>" % (level, utils.html_escape(s), level)
99     else:
100         print "---- %s ----" % (s)
101
102 # Colour definitions, 'end' isn't really for use
103
104 ansi_colours = {
105   'main': "\033[36m",
106   'contrib': "\033[33m",
107   'nonfree': "\033[31m",
108   'arch': "\033[32m",
109   'end': "\033[0m",
110   'bold': "\033[1m",
111   'maintainer': "\033[32m"}
112
113 html_colours = {
114   'main': ('<span style="color: aqua">',"</span>"),
115   'contrib': ('<span style="color: yellow">',"</span>"),
116   'nonfree': ('<span style="color: red">',"</span>"),
117   'arch': ('<span style="color: green">',"</span>"),
118   'bold': ('<span style="font-weight: bold">',"</span>"),
119   'maintainer': ('<span style="color: green">',"</span>")}
120
121 def colour_output(s, colour):
122     if use_html:
123         return ("%s%s%s" % (html_colours[colour][0], utils.html_escape(s), html_colours[colour][1]))
124     else:
125         return ("%s%s%s" % (ansi_colours[colour], s, ansi_colours['end']))
126
127 def escaped_text(s, strip=False):
128     if use_html:
129         if strip:
130             s = s.strip()
131         return "<pre>%s</pre>" % (s)
132     else:
133         return s
134
135 def formatted_text(s, strip=False):
136     if use_html:
137         if strip:
138             s = s.strip()
139         return "<pre>%s</pre>" % (utils.html_escape(s))
140     else:
141         return s
142
143 def output_row(s):
144     if use_html:
145         return """<tr><td>"""+s+"""</td></tr>"""
146     else:
147         return s
148
149 def format_field(k,v):
150     if use_html:
151         return """<tr><td class="key">%s:</td><td class="val">%s</td></tr>"""%(k,v)
152     else:
153         return "%s: %s"%(k,v)
154
155 def foldable_output(title, elementnameprefix, content, norow=False):
156     d = {'elementnameprefix':elementnameprefix}
157     if use_html:
158         print """<div id="%(elementnameprefix)s-wrap"><a name="%(elementnameprefix)s" />
159                    <table class="infobox rfc822">"""%d
160     headline(title, bodyelement="%(elementnameprefix)s-body"%d)
161     if use_html:
162         print """    <tbody id="%(elementnameprefix)s-body" class="infobody">"""%d
163     if norow:
164         print content
165     else:
166         print output_row(content)
167     if use_html:
168         print """</tbody></table></div>"""
169
170 ################################################################################
171
172 def get_depends_parts(depend) :
173     v_match = re_version.match(depend)
174     if v_match:
175         d_parts = { 'name' : v_match.group(1), 'version' : v_match.group(2) }
176     else :
177         d_parts = { 'name' : depend , 'version' : '' }
178     return d_parts
179
180 def get_or_list(depend) :
181     or_list = depend.split("|")
182     return or_list
183
184 def get_comma_list(depend) :
185     dep_list = depend.split(",")
186     return dep_list
187
188 def split_depends (d_str) :
189     # creates a list of lists of dictionaries of depends (package,version relation)
190
191     d_str = re_spacestrip.sub('',d_str)
192     depends_tree = []
193     # first split depends string up amongs comma delimiter
194     dep_list = get_comma_list(d_str)
195     d = 0
196     while d < len(dep_list):
197         # put depends into their own list
198         depends_tree.append([dep_list[d]])
199         d += 1
200     d = 0
201     while d < len(depends_tree):
202         k = 0
203         # split up Or'd depends into a multi-item list
204         depends_tree[d] = get_or_list(depends_tree[d][0])
205         while k < len(depends_tree[d]):
206             # split depends into {package, version relation}
207             depends_tree[d][k] = get_depends_parts(depends_tree[d][k])
208             k += 1
209         d += 1
210     return depends_tree
211
212 def read_control (filename):
213     recommends = []
214     depends = []
215     section = ''
216     maintainer = ''
217     arch = ''
218
219     deb_file = utils.open_file(filename)
220     try:
221         extracts = apt_inst.debExtractControl(deb_file)
222         control = apt_pkg.ParseSection(extracts)
223     except:
224         print formatted_text("can't parse control info")
225         deb_file.close()
226         raise
227
228     deb_file.close()
229
230     control_keys = control.keys()
231
232     if control.has_key("Depends"):
233         depends_str = control.Find("Depends")
234         # create list of dependancy lists
235         depends = split_depends(depends_str)
236
237     if control.has_key("Recommends"):
238         recommends_str = control.Find("Recommends")
239         recommends = split_depends(recommends_str)
240
241     if control.has_key("Section"):
242         section_str = control.Find("Section")
243
244         c_match = re_contrib.search(section_str)
245         nf_match = re_nonfree.search(section_str)
246         if c_match :
247             # contrib colour
248             section = colour_output(section_str, 'contrib')
249         elif nf_match :
250             # non-free colour
251             section = colour_output(section_str, 'nonfree')
252         else :
253             # main
254             section = colour_output(section_str, 'main')
255     if control.has_key("Architecture"):
256         arch_str = control.Find("Architecture")
257         arch = colour_output(arch_str, 'arch')
258
259     if control.has_key("Maintainer"):
260         maintainer = control.Find("Maintainer")
261         localhost = re_localhost.search(maintainer)
262         if localhost:
263             #highlight bad email
264             maintainer = colour_output(maintainer, 'maintainer')
265         else:
266             maintainer = escape_if_needed(maintainer)
267
268     return (control, control_keys, section, depends, recommends, arch, maintainer)
269
270 def read_changes_or_dsc (suite, filename):
271     dsc = {}
272
273     dsc_file = utils.open_file(filename)
274     try:
275         dsc = utils.parse_changes(filename)
276     except:
277         return formatted_text("can't parse .dsc control info")
278     dsc_file.close()
279
280     filecontents = strip_pgp_signature(filename)
281     keysinorder = []
282     for l in filecontents.split('\n'):
283         m = re.match(r'([-a-zA-Z0-9]*):', l)
284         if m:
285             keysinorder.append(m.group(1))
286
287     for k in dsc.keys():
288         if k in ("build-depends","build-depends-indep"):
289             dsc[k] = create_depends_string(suite, split_depends(dsc[k]))
290         elif k == "architecture":
291             if (dsc["architecture"] != "any"):
292                 dsc['architecture'] = colour_output(dsc["architecture"], 'arch')
293         elif k in ("files","changes","description"):
294             if use_html:
295                 dsc[k] = formatted_text(dsc[k], strip=True)
296             else:
297                 dsc[k] = ('\n'+'\n'.join(map(lambda x: ' '+x, dsc[k].split('\n')))).rstrip()
298         else:
299             dsc[k] = escape_if_needed(dsc[k])
300
301     keysinorder = filter(lambda x: not x.lower().startswith('checksums-'), keysinorder)
302
303     filecontents = '\n'.join(map(lambda x: format_field(x,dsc[x.lower()]), keysinorder))+'\n'
304     return filecontents
305
306 def create_depends_string (suite, depends_tree):
307     result = ""
308     if suite == 'experimental':
309         suite_where = " in ('experimental','unstable')"
310     else:
311         suite_where = " ='%s'" % suite
312
313     comma_count = 1
314     for l in depends_tree:
315         if (comma_count >= 2):
316             result += ", "
317         or_count = 1
318         for d in l:
319             if (or_count >= 2 ):
320                 result += " | "
321             # doesn't do version lookup yet.
322
323             q = projectB.query("SELECT DISTINCT(b.package), b.version, c.name, su.suite_name FROM  binaries b, files fi, location l, component c, bin_associations ba, suite su WHERE b.package='%s' AND b.file = fi.id AND fi.location = l.id AND l.component = c.id AND ba.bin=b.id AND ba.suite = su.id AND su.suite_name %s ORDER BY b.version desc" % (d['name'], suite_where))
324             ql = q.getresult()
325             if ql:
326                 i = ql[0]
327
328                 adepends = d['name']
329                 if d['version'] != '' :
330                     adepends += " (%s)" % (d['version'])
331
332                 if i[2] == "contrib":
333                     result += colour_output(adepends, "contrib")
334                 elif i[2] == "non-free":
335                     result += colour_output(adepends, "nonfree")
336                 else :
337                     result += colour_output(adepends, "main")
338             else:
339                 adepends = d['name']
340                 if d['version'] != '' :
341                     adepends += " (%s)" % (d['version'])
342                 result += colour_output(adepends, "bold")
343             or_count += 1
344         comma_count += 1
345     return result
346
347 def output_deb_info(suite, filename, packagename):
348     (control, control_keys, section, depends, recommends, arch, maintainer) = read_control(filename)
349
350     if control == '':
351         return formatted_text("no control info")
352     to_print = ""
353     for key in control_keys :
354         if key == 'Depends':
355             field_value = create_depends_string(suite, depends)
356         elif key == 'Recommends':
357             field_value = create_depends_string(suite, recommends)
358         elif key == 'Section':
359             field_value = section
360         elif key == 'Architecture':
361             field_value = arch
362         elif key == 'Maintainer':
363             field_value = maintainer
364         elif key == 'Description':
365             if use_html:
366                 field_value = formatted_text(control.Find(key), strip=True)
367             else:
368                 desc = control.Find(key)
369                 desc = re_newlinespace.sub('\n ', desc)
370                 field_value = escape_if_needed(desc)
371         else:
372             field_value = escape_if_needed(control.Find(key))
373         to_print += " "+format_field(key,field_value)+'\n'
374     return to_print
375
376 def do_command (command, filename, escaped=0):
377     o = os.popen("%s %s" % (command, filename))
378     if escaped:
379         return escaped_text(o.read())
380     else:
381         return formatted_text(o.read())
382
383 def do_lintian (filename):
384     if use_html:
385         return do_command("lintian --show-overrides --color html", filename, 1)
386     else:
387         return do_command("lintian --show-overrides --color always", filename, 1)
388
389 def get_copyright (deb_filename):
390     package = re_package.sub(r'\1', deb_filename)
391     o = os.popen("dpkg-deb -c %s | egrep 'usr(/share)?/doc/[^/]*/copyright' | awk '{print $6}' | head -n 1" % (deb_filename))
392     cright = o.read()[:-1]
393
394     if cright == "":
395         return formatted_text("WARNING: No copyright found, please check package manually.")
396
397     doc_directory = re_doc_directory.sub(r'\1', cright)
398     if package != doc_directory:
399         return formatted_text("WARNING: wrong doc directory (expected %s, got %s)." % (package, doc_directory))
400
401     o = os.popen("dpkg-deb --fsys-tarfile %s | tar xvOf - %s 2>/dev/null" % (deb_filename, cright))
402     cright = o.read()
403     copyrightmd5 = md5.md5(cright).hexdigest()
404
405     res = ""
406     if printed_copyrights.has_key(copyrightmd5) and printed_copyrights[copyrightmd5] != "%s (%s)" % (package, deb_filename):
407         res += formatted_text( "NOTE: Copyright is the same as %s.\n\n" % \
408                                (printed_copyrights[copyrightmd5]))
409     else:
410         printed_copyrights[copyrightmd5] = "%s (%s)" % (package, deb_filename)
411     return res+formatted_text(cright)
412
413 def check_dsc (suite, dsc_filename):
414     (dsc) = read_changes_or_dsc(suite, dsc_filename)
415     foldable_output(dsc_filename, "dsc", dsc, norow=True)
416     foldable_output("lintian check for %s" % dsc_filename, "source-lintian", do_lintian(dsc_filename))
417
418 def check_deb (suite, deb_filename):
419     filename = os.path.basename(deb_filename)
420     packagename = filename.split('_')[0]
421
422     if filename.endswith(".udeb"):
423         is_a_udeb = 1
424     else:
425         is_a_udeb = 0
426
427
428     foldable_output("control file for %s" % (filename), "binary-%s-control"%packagename,
429                     output_deb_info(suite, deb_filename, packagename), norow=True)
430
431     if is_a_udeb:
432         foldable_output("skipping lintian check for udeb", "binary-%s-lintian"%packagename,
433                         "")
434     else:
435         foldable_output("lintian check for %s" % (filename), "binary-%s-lintian"%packagename,
436                         do_lintian(deb_filename))
437
438     foldable_output("contents of %s" % (filename), "binary-%s-contents"%packagename,
439                     do_command("dpkg -c", deb_filename))
440
441     if is_a_udeb:
442         foldable_output("skipping copyright for udeb", "binary-%s-copyright"%packagename,
443                         "")
444     else:
445         foldable_output("copyright of %s" % (filename), "binary-%s-copyright"%packagename,
446                         get_copyright(deb_filename))
447
448     foldable_output("file listing of %s" % (filename),  "binary-%s-file-listing"%packagename,
449                     do_command("ls -l", deb_filename))
450
451 # Read a file, strip the signature and return the modified contents as
452 # a string.
453 def strip_pgp_signature (filename):
454     inputfile = utils.open_file (filename)
455     contents = ""
456     inside_signature = 0
457     skip_next = 0
458     for line in inputfile.readlines():
459         if line[:-1] == "":
460             continue
461         if inside_signature:
462             continue
463         if skip_next:
464             skip_next = 0
465             continue
466         if line.startswith("-----BEGIN PGP SIGNED MESSAGE"):
467             skip_next = 1
468             continue
469         if line.startswith("-----BEGIN PGP SIGNATURE"):
470             inside_signature = 1
471             continue
472         if line.startswith("-----END PGP SIGNATURE"):
473             inside_signature = 0
474             continue
475         contents += line
476     inputfile.close()
477     return contents
478
479 def display_changes(suite, changes_filename):
480     changes = read_changes_or_dsc(suite, changes_filename)
481     foldable_output(changes_filename, "changes", changes, norow=True)
482
483 def check_changes (changes_filename):
484     try:
485         changes = utils.parse_changes (changes_filename)
486     except ChangesUnicodeError:
487         utils.warn("Encoding problem with changes file %s" % (changes_filename))
488     display_changes(changes['distribution'], changes_filename)
489
490     files = utils.build_file_list(changes)
491     for f in files.keys():
492         if f.endswith(".deb") or f.endswith(".udeb"):
493             check_deb(changes['distribution'], f)
494         if f.endswith(".dsc"):
495             check_dsc(changes['distribution'], f)
496         # else: => byhand
497
498 def main ():
499     global Cnf, projectB, db_files, waste, excluded
500
501 #    Cnf = utils.get_conf()
502
503     Arguments = [('h',"help","Examine-Package::Options::Help"),
504                  ('H',"html-output","Examine-Package::Options::Html-Output"),
505                 ]
506     for i in [ "Help", "Html-Output", "partial-html" ]:
507         if not Cnf.has_key("Examine-Package::Options::%s" % (i)):
508             Cnf["Examine-Package::Options::%s" % (i)] = ""
509
510     args = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
511     Options = Cnf.SubTree("Examine-Package::Options")
512
513     if Options["Help"]:
514         usage()
515
516     stdout_fd = sys.stdout
517
518     for f in args:
519         try:
520             if not Options["Html-Output"]:
521                 # Pipe output for each argument through less
522                 less_fd = os.popen("less -R -", 'w', 0)
523                 # -R added to display raw control chars for colour
524                 sys.stdout = less_fd
525             try:
526                 if f.endswith(".changes"):
527                     check_changes(f)
528                 elif f.endswith(".deb") or f.endswith(".udeb"):
529                     # default to unstable when we don't have a .changes file
530                     # perhaps this should be a command line option?
531                     check_deb('unstable', file)
532                 elif f.endswith(".dsc"):
533                     check_dsc('unstable', f)
534                 else:
535                     utils.fubar("Unrecognised file type: '%s'." % (f))
536             finally:
537                 if not Options["Html-Output"]:
538                     # Reset stdout here so future less invocations aren't FUBAR
539                     less_fd.close()
540                     sys.stdout = stdout_fd
541         except IOError, e:
542             if errno.errorcode[e.errno] == 'EPIPE':
543                 utils.warn("[examine-package] Caught EPIPE; skipping.")
544                 pass
545             else:
546                 raise
547         except KeyboardInterrupt:
548             utils.warn("[examine-package] Caught C-c; skipping.")
549             pass
550
551 #######################################################################################
552
553 if __name__ == '__main__':
554     main()