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