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