Debian Codegraph @

python-scripts/getentityname/bin/getentityname.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright (C) 2012-2021 SUSE Linux GmbH
5 #
6 # Author:
7 # Tom Schraitle <toms at opensuse dot org>
8 #
9 """
10 This script finds every external parameter entity in the internal subset
11 of the DTD, for example:
12
13 <!DOCTYPE book PUBLIC
14 "-//OASIS//DTD DocBook XML V4.4//EN"
15 "http://www.docbook.org/xml/4.4/docbookx.dtd"
16 [
17 <!-- The external subset -->
18 <!ENTITY % entities SYSTEM "entity-decl.ent">
19 %entities;
20 <!ENTITY % foo.ent SYSTEM "foo.ent">
21 %foo.ent;
22 <!--
23 <!ENTITY % bar.ent SYSTEM "bar.ent">
24 %bar.ent;
25 -->
26 ]>
27
28 The output will be:
29
30 entity-decl.ent foo.ent
31
32 The script detects XML comments inside the internal subset and removes them. In
33 the above example, the "bar.ent" is therefor not in the result list.
34 """
35
36 import argparse
37 import logging
38 import os.path
39 import re
40 import subprocess
41 import sys
42 from logging.config import dictConfig
43 from xml.sax import SAXParseException, make_parser
44 import xml.sax.handler as xmlsh
45
46 __version__ = "2.2.1"
47 __author__ = "Thomas Schraitle <thomas DOT schraitle AT suse DOT de>"
48 __license__ = "GPL 3"
49
50
51 #: The name of our logger
52 LOGGERNAME = "getentities"
53
54 #: Instantiate our logger
55 log = logging.getLogger(LOGGERNAME)
56
57 #: Our config setting for our logger
58 DEFAULT_LOGGING_DICT = {
59 "version": 1,
60 "disable_existing_loggers": False,
61 "formatters": {
62 "standard": {"format": "[%(levelname)s] %(funcName)s: %(message)s"},
63 },
64 "handlers": {
65 "default": {
66 "level": "NOTSET",
67 "formatter": "standard",
68 "class": "logging.StreamHandler",
69 },
70 },
71 "loggers": {
72 LOGGERNAME: {"handlers": ["default"], "level": "INFO", "propagate": True}
73 },
74 }
75
76 #: Map verbosity level (int) to log level
77 LOGLEVELS = {
78 None: logging.WARNING, # 0
79 0: logging.WARNING,
80 1: logging.INFO,
81 2: logging.DEBUG,
82 }
83
84
85 ###
86 # Regular Expressions
87 SPACE = r"[ \t\r\n]" # whitespace
88 S = "%s+" % SPACE # One or more whitespace
89 opS = "%s*" % SPACE # Zero or more whitespace
90 oS = "%s?" % SPACE # Optional whitespace
91 NAME = "[a-zA-Z_:][-a-zA-Z0-9._:]*" # Valid XML name
92 QSTR = "(?:'[^']*'|\"[^\"]*\")" # Quoted XML string
93 QUOTES = "(?:'[^']'|\"[^\"]\")"
94 SYSTEMLITERAL = "(?P<sysid>%s)" % QSTR
95 PUBLICLITERAL = (
96 r'(?P<pubid>"[-\'\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*"|'
97 r"'[-\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*')"
98 )
99 EXTERNALID = (
100 """(?:SYSTEM|PUBLIC{S}{PUBLICLITERAL})""" """{S}{SYSTEMLITERAL}"""
101 ).format(**locals())
102 ENTITY = (
103 """<!ENTITY{S}%{S}""" """(?P<PEDecl>{NAME}){S}""" """{EXTERNALID}{opS}>"""
104 ).format(**locals())
105 r_ENTITY = re.compile(ENTITY, re.VERBOSE | re.DOTALL | re.MULTILINE)
106 DOCTYPE = (
107 """<!DOCTYPE{S}"""
108 "(?P<Name>{NAME})"
109 "("
110 "({S}{EXTERNALID}{opS})?" # noqa: 127
111 r"(?:{S}\[(?P<IntSubset>.*)\])?" # noqa: 127
112 ")?"
113 """{opS}>"""
114 ).format(**locals())
115 r_DOCTYPE = re.compile(DOCTYPE, re.VERBOSE | re.DOTALL | re.MULTILINE)
116 COMMENTOPEN = re.compile("<!--")
117 COMMENTCLOSE = re.compile("-->")
118
119 #: The main catalog (default)
120 MAINCATALOG = "/etc/xml/catalog"
121
122
123 class XMLCatalogError(LookupError):
124 pass
125
126
127 # class MyEntityResolver(xmlsh.EntityResolver):
128 # def __init__(self, *args, **kwargs):
129 # super().__init__(*args, **kwargs)
130 # log.debug("Init in MyEntityResolver")
131 #
132 # def resolveEntity(self, publicId, systemId):
133 # log.debug("Trying to resolve publicid=%r, systemid=%r", publicId, systemId)
134
135
136 def xmlsyntaxcheck(xmlfile):
137 """Check if the XML file is well-formed
138
139 :param str xmlfile: XML filename
140 :return: Nothing if the XML is well-formed, otherwise it raises
141 an exception
142 :raises: :class:`xml.sax.SAXParseException`
143 """
144 log.debug("Try XML parser for XML well-formedness...")
145 parser = make_parser()
146
147 # Set several features of the XML parser
148 featureset = (
149 (xmlsh.feature_validation, False),
150 (xmlsh.feature_external_ges, False),
151 (xmlsh.feature_external_pes, False),
152 )
153 for feature, state in featureset:
154 parser.setFeature(feature, state)
155
156 parser.setContentHandler(xmlsh.ContentHandler())
157 # parser.setEntityResolver(MyEntityResolver())
158
159 # This will fail with a SAXParseException when we have a XML file
160 # with syntax errors:
161 parser.parse(xmlfile)
162 log.debug("XML syntax check ok")
163
164
165 def joinEnts(ents, sep):
166 """Returns a string of names, separated by 'sep'."""
167 return sep.join(ents)
168
169
170 def remove_xml_comments(content):
171 """Remove all XML comments (<!-- ... -->) in a string
172
173 :param str content: the content with possible XML comments
174 :return: a string without any XML comments
175 :rtype: str
176 :raises: ValueError when the end comment '-->' couldn't be find
177 or if there are double dashes '--' inside the comment.
178
179 >>> remove_xml_comments('<!-- hello -->World')
180 'World'
181 >>> remove_xml_comments('<!-- h -->World<!-- is it? -->')
182 'World'
183 >>> remove_xml_comments('<!--A-->Hi <!--B--> World.')
184 'Hi World.'
185 >>> remove_xml_comments('''<!-- <!ENTITY x\
186 "X"> \
187 -->Hello''')
188 'Hello'
189 """
190 while True:
191 if "<!--" not in content:
192 return content
193 start = COMMENTOPEN.search(content).start()
194 match = COMMENTCLOSE.search(content)
195 if not match:
196 raise ValueError("ERROR: Missing '-->' in comment!")
197 end = match.end()
198 # Extract the comment
199 comment = content[start:end][4:-3]
200 if "--" in comment:
201 raise ValueError("ERROR: '--' not allowed in comment")
202
203 # Remove the comment
204 content = content[0:start] + content[end:]
205
206
207 def investigate_identifiers(content, args, base=""):
208 """Investigate some content string for identifiers
209
210 :param str content: string of internal subset
211 :param args: parsed arguments from CLI parser
212 :yield:
213 """
214 for entity in r_ENTITY.finditer(content):
215 publicid = entity.group("pubid")
216 systemid = entity.group("sysid")
217 result = None
218
219 # Remove any quotes from our regex result
220 if systemid and (systemid[0] in ("'", '"')):
221 systemid = systemid.strip()[1:-1]
222 if publicid and (publicid[0] in ("'", '"')):
223 publicid = publicid.strip()[1:-1]
224
225 log.debug("publicid=%r, systemid=%r", publicid, systemid)
226 if args.skip_public and publicid:
227 log.debug(
228 "Skipping public parameter entity %s %s",
229 publicid,
230 systemid,
231 )
232 continue
233 elif publicid is not None:
234 log.debug("Investigate public ID %r...", publicid)
235 result = xmlcatalog(publicid, args.catalog)
236 # check entity
237 elif systemid.startswith("http"):
238 log.debug("Investigate system <ID> %r...", systemid)
239 result = xmlcatalog(systemid, args.catalog)
240 log.debug("%s -> %s", systemid, result)
241 else:
242 log.debug("Investigate local path %r...", systemid)
243 result = os.path.join(base, systemid)
244 log.debug("%s -> %s", systemid, result)
245
246 yield result
247
248
249 def parse_ent_file(entityfile, args):
250 """Parse entity file for other referenced entities
251
252 :param str entityfile: filename to the referenced
253 entity file from XML
254 :param args: parsed arguments from CLI parser
255 :yield: a filename
256 """
257 # HINT: This reads the complete file.
258 log.debug("Investigate entity file %r...", entityfile)
259 base = os.path.dirname(entityfile)
260 content = open(entityfile, "r").read()
261 yield from investigate_identifiers(content, args, base)
262
263
264 def xmlcatalog(uri, catalog=MAINCATALOG, raise_on_error=False):
265 """Call xmlcatalog and parse return
266
267 :param uri: the URI to query for
268 :param catalog: the catalog file to use
269 :param raise_on_error: flag to raise an exception if URL couldn't be found (=True)
270 or return None (=False)
271 :return: the resolved string or None
272 """
273 result = None
274 if catalog and not os.path.exists(catalog):
275 raise XMLCatalogError("Cannot find catalog %r" % catalog)
276
277 log.debug("Trying to find %r in catalog %r", uri, catalog)
278 proc = subprocess.run(["xmlcatalog", catalog, uri], stdout=subprocess.PIPE)
279 log.debug("subprocess of 'xmlcatalog': %s", proc)
280 result = proc.stdout.decode("UTF-8")
281 if proc.returncode:
282 log.warning("URI %r not found in catalog %r", uri, catalog)
283 if raise_on_error:
284 raise XMLCatalogError("Problem with xmlcatalog: %s" % result)
285 return None
286
287 result = result.split("file://")[-1].strip()
288 log.debug("Found %r -> %r", uri, result)
289
290 return result
291
292
293 def preparelines(xmlfile, linenr, showlines=5):
294 """Read lines from xmlfile but output only the first 6 lines by default.
295
296 :param xmlfile: path to the XML filename
297 :param int linenr: number of lines that should be investigated
298 :param int showlines: show lines (couting from zero to showlines)
299 :return: list of lines
300 """
301 lines = []
302 with open(xmlfile, "r") as fh:
303 for i in range(linenr):
304 lines.append(fh.readline())
305
306 if len(lines) > showlines:
307 log.debug("First six lines of file %r:", xmlfile)
308 for i in range(6):
309 log.debug(" line %d: %s", i + 1, lines[i].strip())
310 lines = "".join(lines)
311 return lines
312
313
314 def getentities(args, linenr=50):
315 """Read first 50 lines (default) and return any parameter entity names
316
317 :param args: parsed arguments from CLI parser
318 :param int linenr: number of lines that should be investigated
319 :return: a list of all found entities
320 """
321 # Holds a dictionary of (relative) paths as keys and absolut paths as values:
322 ents = {}
323 seen = set()
324
325 for xmlfile in args.xmlfiles:
326 # Checks for well-formed XML
327 # does nothing if XML is well-formed, otherwise raises a SAXParseException
328 xmlsyntaxcheck(xmlfile)
329
330 # Prepare the first N lines (linenr)
331 lines = preparelines(xmlfile, linenr)
332
333 # Try to find matches
334 match = r_DOCTYPE.search(lines)
335 if match:
336 log.debug("Match: %r", match.string)
337 log.debug("DOCTYPE and internal subset: %s", match.groupdict())
338 internalsubset = match.group("IntSubset")
339 if internalsubset is None:
340 log.debug("No internal subset found in %r", xmlfile)
341 # No internal subset, so continue with next file
342 continue
343
344 content = remove_xml_comments(internalsubset)
345 base = os.path.dirname(xmlfile)
346
347 log.debug("Looking for entities...")
348 for entity in investigate_identifiers(content, args, base):
349 # log.debug("Got %r as file", entity)
350 if (entity is None) or entity in seen:
351 continue
352 seen.add(entity)
353 ents[entity] = entity
354 log.debug("Found entity %r %s", entity, ents)
355
356 resultdict = ents.copy()
357 # Process ents to find other referenced PEs
358 for absolute in ents.values():
359 for entity in parse_ent_file(absolute, args):
360 if entity not in seen:
361 seen.add(entity)
362 resultdict[entity] = os.path.join(os.path.dirname(absolute), entity)
363 return resultdict
364
365
366 def parsecli(cliargs=None):
367 """Parse CLI with :class:`argparse.ArgumentParser` and return parsed result
368
369 :param list cliargs: Arguments to parse or None (=use sys.argv)
370 :return: parsed CLI result
371 :rtype: :class:`argparse.Namespace`
372 """
373 # Setup logging
374 dictConfig(DEFAULT_LOGGING_DICT)
375
376 parser = argparse.ArgumentParser(
377 description=__doc__.strip(),
378 formatter_class=argparse.RawDescriptionHelpFormatter, # noqa: E501
379 usage="%(prog)s [OPTIONS] XMLFILE...",
380 )
381 parser.add_argument("--version", action="version", version=__version__)
382
383 parser.add_argument(
384 "-v",
385 "--verbose",
386 action="count",
387 help="Raise verbosity level",
388 )
389 parser.add_argument(
390 "-A",
391 "--absolute",
392 default=False,
393 action="store_true",
394 help="Make paths absolute (default: %(default)s)",
395 )
396 parser.add_argument(
397 "-P",
398 "--skip-no-public",
399 dest="skip_public",
400 default=True,
401 action="store_false",
402 help=("Skip parameter entities with public reference (default: %(default)s)"),
403 )
404 parser.add_argument(
405 "-s",
406 "--separator",
407 default=" ",
408 help=(
409 "Set the separator between consecutive "
410 "filenames (default '%(default)s'). "
411 "Use '\\n' and '\\t' to "
412 "insert a CR and TAB character. "
413 ),
414 )
415 parser.add_argument(
416 "-c",
417 "--catalog",
418 default=MAINCATALOG,
419 help="Use the catalog to query the input",
420 )
421 parser.add_argument(
422 "xmlfiles", metavar="XMLFILES", nargs="+", help="One or more XML files"
423 )
424
425 args = parser.parse_args(cliargs)
426 level = LOGLEVELS.get(args.verbose, logging.DEBUG)
427 # log.setLevel(LOGLEVELS.get(args.verbose, logging.DEBUG))
428 log.setLevel(level)
429 log.info("CLI args: %s", args)
430 log.debug("")
431 # Save our parser instance:
432 args.parser = parser
433
434 # Fix separators
435 if args.separator == "\\n":
436 args.separator = "\n"
437 elif args.separator == "\\t":
438 args.separator = "\t"
439
440 resultargs = []
441 for fn in args.xmlfiles:
442 if not os.path.exists(fn):
443 raise FileNotFoundError(f"File {fn!r} not found")
444 if not os.path.isabs(fn):
445 fn = os.path.abspath(fn)
446 resultargs.append(fn)
447
448 args.xmlfiles = resultargs
449
450 return args
451
452
453 def main(cliargs=None):
454 """Entry point for the application script
455
456 :param list cliargs: Arguments to parse or None (=use :class:`sys.argv`)
457 :return: error code; 0 => everything was succesfull, !=0 => error
458 :rtype: int
459 """
460 try:
461 args = parsecli(cliargs)
462
463 if not args:
464 args.parser.print_usage()
465 sys.exit(1)
466
467 ents = getentities(args)
468 if args.absolute:
469 print(joinEnts(ents.values(), args.separator))
470 else:
471 print(joinEnts(ents, args.separator))
472 return 0
473
474 except (FileNotFoundError, IOError, SAXParseException, XMLCatalogError) as error:
475 log.fatal(error)
476 return 1
477
478
479 if __name__ == "__main__":
480 sys.exit(main())