# $Id$ # # Copyright (C) 2014 Dragon Research Labs ("DRL") # Portions copyright (C) 2012 Internet Systems Consortium ("ISC") # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notices and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND DRL AND ISC DISCLAIM ALL # WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DRL OR # ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL # DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA # OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # PERFORMANCE OF THIS SOFTWARE. """ Pull HTML pages from a Trac Wiki, feed the useful bits to htmldoc and html2text to generate PDF and flat text documentation. Assumes you're using the TracNav plugin for the Wiki pages, and uses the same list as the TracNav plugin does to determine the set of pages to convert and the order in which they appear in the PDF file. """ # Most of the work of massaging the HTML is done using XSL transforms, # because the template-driven style makes that easy. There's probably # some clever way to use lxml's XPath code to do the same thing in a # more pythonic way with ElementTrees, but I already had the XSL # transforms and there's a point of diminishing returns on this sort of # thing. import sys import os import argparse import lxml.etree import urllib import urlparse import subprocess import tempfile # Main program, up front so it doesn't get lost under all the XSL def main(): base = "https://trac.rpki.net" parser = argparse.ArgumentParser(description = __doc__) parser.add_argument("-b", "--base_url", default = base, help = "base URL for documentation web site") parser.add_argument("-t", "--toc", default = base + "/wiki/doc/RPKI/TOC", help = "table of contents URL") parser.add_argument("-d", "--directory", default = ".", help = "output directory") parser.add_argument("-p", "--pdf_file", default = "manual.pdf", help = "output PDF file") parser.add_argument("-r", "--html2textrc", default = os.path.join(os.path.dirname(sys.argv[0]), "html2textrc"), help = "html2textrc rules file") args = parser.parse_args() urls = str(xsl_get_toc(lxml.etree.parse(urllib.urlopen(args.toc)).getroot(), basename = repr(args.base_url))).splitlines() assert all(urlparse.urlparse(url).path.startswith("/wiki/") for url in urls) htmldoc = subprocess.Popen( ("htmldoc", "--book", "--title", "--outfile", args.pdf_file, "--format", "pdf", "--firstpage", "p1", "--size", "Universal", "--no-duplex", "--fontsize", "11.0", "--fontspacing", "1.1", "--headfootsize", "11.0", "--headingfont", "Helvetica", "--bodyfont", "Times", "--headfootfont", "Helvetica-Oblique", "-"), stdin = subprocess.PIPE) lxml.etree.ElementTree(xml_title).write(htmldoc.stdin) png_fns = [] for url in urls: path = urlparse.urlparse(url).path page = xsl_get_page(lxml.etree.parse(urllib.urlopen(url)).getroot(), basename = repr(args.base_url), path = repr(path)) for img in page.xpath("//img | //object | //embed"): attr = "data" if img.tag == "object" else "src" img_url = img.get(attr) if img_url.endswith(".svg"): #sys.stderr.write("Converting %s to PNG\n" % img_url) png_fd, png_fn = tempfile.mkstemp(suffix = ".png") subprocess.Popen(("svg2png", "-h", "700", "-w", "600", "-", "-"), stdout = png_fd, stdin = subprocess.PIPE).communicate(urllib.urlopen(img_url).read()) os.close(png_fd) img.set(attr, png_fn) png_fns.append(png_fn) page.write(htmldoc.stdin) html2text = subprocess.Popen(("html2text", "-rcfile", args.html2textrc, "-nobs", "-ascii"), stdin = subprocess.PIPE, stdout = subprocess.PIPE) page.write(html2text.stdin) html2text.stdin.close() lines = html2text.stdout.readlines() html2text.stdout.close() html2text.wait() while lines and lines[0].isspace(): del lines[0] fn = os.path.join(args.directory, path[len("/wiki/"):].replace("/", ".")) f = open(fn, "w") want_blank = False for line in lines: blank = line.isspace() if want_blank and not blank: f.write("\n") if not blank: f.write(line) want_blank = blank f.close() sys.stderr.write("Wrote %s\n" % fn) htmldoc.stdin.close() htmldoc.wait() sys.stderr.write("Wrote %s\n" % args.pdf_file) for png_fn in png_fns: os.unlink(png_fn) # HTMLDOC title page. At some point we might want to generate this # dynamically as an ElementTree, but static content will do for the # moment. xml_title = lxml.etree.HTML('''\ RPKI Tools Manual ''') # XSL transform to extract list of Wiki page URLs from the TOC Wiki page xsl_get_toc = lxml.etree.XSLT(lxml.etree.XML('''\ ''')) # XSL transform to extract useful content of a Wiki page. # Django generates weird HTML for ordered lists: it sometimes breaks # up a single ordered list into multiple adjacent
    elements, # using the @start attribute to try to make the result look like a # single ordered list. This looks OK in Firefox but confuses the # bejesus out of both html2text and htmldoc. In some cases this is # probably unavoidable, but most of the uses of this I've seen look # gratuitous, and are probably the result of code modulararity issues # in Django. # # So we try to clean this up, by merging adjacent
      elements where # we can. The merge incantation is an adaptation of: # # http://stackoverflow.com/questions/1806123/merging-adjacent-nodes-of-same-type-xslt-1-0 # # There may be a more efficient way to do this, but I don't think # we care, and this seems to work. # # Original author's explanation: # # The rather convoluted XPath expression for selecting the following # sibling aaa nodes which are merged with the current one: # # following-sibling::aaa[ # following 'aaa' siblings # not(preceding-sibling::*[ # if they are not preceded by # not(self::aaa) and # a non-'aaa' node # not(following-sibling::aaa = current()) # after the current node # ]) # ] xsl_get_page = lxml.etree.XSLT(lxml.etree.XML('''\ NEW PAGE
      _ / .
      ''')) # All the files we want to parse are HTML, so make HTML the default # parser. In theory the HTML produced by Trac is XHTML thus should # parse correctly (in fact, better) as XML, but in practice this seems # not to work properly at the moment, while parsing as HTML does. # Haven't bothered to figure out why, life is too short. # # If you're reading this comment because this script stopped working # after a Trac upgrade, try commenting out this line to see whether # things have changed and Trac's HTML now parses better as XML. lxml.etree.set_default_parser(lxml.etree.HTMLParser()) # Run the main program. main() nterpol */ .highlight .sx { color: #2B2; background-color: #F0FFF0 } /* Literal.String.Other */ .highlight .sr { color: #080; background-color: #FFF0FF } /* Literal.String.Regex */ .highlight .s1 { color: #D20; background-color: #FFF0F0 } /* Literal.String.Single */ .highlight .ss { color: #A60; background-color: #FFF0F0 } /* Literal.String.Symbol */ .highlight .bp { color: #038 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #06B; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #369 } /* Name.Variable.Class */ .highlight .vg { color: #D70 } /* Name.Variable.Global */ .highlight .vi { color: #33B } /* Name.Variable.Instance */ .highlight .vm { color: #369 } /* Name.Variable.Magic */ .highlight .il { color: #00D; font-weight: bold } /* Literal.Number.Integer.Long */
      ****** Running a hierarchical rsync configuration ******
      
      Having every relying party on the Internet contact every publication service is
      not terribly efficient. In many cases, it may make more sense to use a
      hierarchical configuration in which a few "gatherer" relying parties contact
      the publication servers directly, while a collection of other relying parties
      get their raw data from the gatherers.
      
        Note
            The relying parties in this configuration still perform their own
            validation, they just let the gatherers do the work of collecting the
            unvalidated data for them.
      
      A gatherer in a configuration like this would look just like a stand-alone
      relying party as discussed above. The only real difference is that a gatherer
      must also make its unauthenticated data collection available to other relying
      parties. Assuming the standard configuration, this will be the directory /var/
      rcynic/data/unauthenticated and its subdirectories.
      
      There are two slightly different ways to do this with rsync:
      
        1. Via unauthenticated rsync, by configuring an rsyncd.conf "module", or
        2. Via rsync over a secure transport protocol such as ssh.
      
      Since the downstream relying party performs its own validation in any case,
      either of these will work, but using a secure transport such as ssh makes it
      easier to track problems back to their source if a downstream relying party
      concludes that it's been receiving bad data.
      
      Script for a downstream relying party using ssh might look like this:
      
        #!/bin/sh -
      
        PATH=/usr/bin:/bin:/usr/local/bin
        umask 022
        eval `/usr/bin/ssh-agent -s` >/dev/null
        /usr/bin/ssh-add /root/rpki_ssh_id_rsa 2>&1 | /bin/fgrep -v 'Identity added:'
        hosts='larry.example.org moe.example.org curly.example.org'
        for host in $hosts
        do
          /usr/bin/rsync --archive --update --safe-links rpkisync@${host}:/var/
        rcynic/data/unauthenticated/ /var/rcynic/data/unauthenticated.${host}/
        done
        eval `/usr/bin/ssh-agent -s -k` >/dev/null
        for host in $hosts
        do
          /usr/sbin/chroot -u rcynic -g rcynic /var/rcynic /bin/rcynic -c /etc/
        rcynic.conf -u /data/unauthenticated.${host}
          /var/rcynic/bin/rcynic-html /var/rcynic/data/rcynic.xml /usr/local/www/
        data/rcynic.${host}
        done
        cd /var/rcynic/rpki-rtr
        /usr/bin/su -m rcynic -c '/usr/local/bin/rpki-rtr cronjob /var/rcynic/data/
        authenticated'
      
      where /root/rpki_ssh_id_rsa is an SSH private key authorized to log in as user
      "rpkisync" on the gatherer machines. If you want to lock this down a little
      tighter, you could use ssh's command="..." mechanism as described in the sshd
      documentation to restrict the rpkisync user so that it can only run this one
      rsync command.
      
      If you prefer to use insecure rsync, perhaps to avoid allowing the downstream
      relying parties any sort of login access at all on the gatherer machines, the
      configuration would look more like this:
      
        #!/bin/sh -
      
        PATH=/usr/bin:/bin:/usr/local/bin
        umask 022
        hosts='larry.example.org moe.example.org curly.example.org'
        for host in $hosts
        do
          /usr/bin/rsync --archive --update --safe-links rsync://${host}/
        unauthenticated/ /var/rcynic/data/unauthenticated.${host}/
        done
        for host in $hosts
        do
          /usr/sbin/chroot -u rcynic -g rcynic /var/rcynic /bin/rcynic -c /etc/
        rcynic.conf -u /data/unauthenticated.${host}
          /var/rcynic/bin/rcynic-html /var/rcynic/data/rcynic.xml /usr/local/www/
        data/rcynic.${host}
        done
        cd /var/rcynic/rpki-rtr
        /usr/bin/su -m rcynic -c '/usr/local/bin/rpki-rtr cronjob /var/rcynic/data/
        authenticated'
      
      where "unauthenticated" here is an rsync module pointing at /var/rcynic/data/
      unauthenticated on each of the gatherer machines. Configuration for such a
      module would look like:
      
        [unauthenticated]
            read only           = yes
            transfer logging    = yes
            path                = /var/rcynic/data/unauthenticated
            comment             = Unauthenticated RPKI data