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