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