Advertisement
here2share

cmd_simplesis.py

Jul 24th, 2017
434
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. ##############################################################################
  5. #
  6. # cmd_simplesis.py - Ensymble command line tool, simplesis command
  7. # Copyright 2006, 2007, 2008, 2009 Jussi Yl?nen
  8. #
  9. # This file is part of Ensymble developer utilities for Symbian OS(TM).
  10. #
  11. # Ensymble is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # Ensymble is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License
  22. # along with Ensymble; if not, write to the Free Software
  23. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  24. #
  25. ##############################################################################
  26.  
  27. import sys
  28. import os
  29. import re
  30. import getopt
  31. import getpass
  32. import locale
  33. import struct
  34. import zlib
  35.  
  36. from utils import sisfile
  37. from utils import sisfield
  38. from utils import symbianutil
  39. from utils import rscfile
  40. from utils import miffile
  41.  
  42.  
  43. ##############################################################################
  44. # Help texts
  45. ##############################################################################
  46.  
  47. shorthelp = 'Create a SIS package from a directory structure'
  48. longhelp  = '''simplesis
  49.    [--uid=0x01234567] [--version=1.0.0] [--lang=EN,...]
  50.    [--caption="Package Name",...] [--drive=C] [--textfile=mytext_%C.txt]
  51.    [--cert=mycert.cer] [--privkey=mykey.key] [--passphrase=12345]
  52.    [--vendor="Vendor Name",...] [--encoding=terminal,filesystem]
  53.    [--verbose]
  54.    <srcdir> [sisfile]
  55.  
  56. Create a SIS package from a directory structure. Only supports very
  57. simple SIS files. There is no support for conditionally included
  58. files, dependencies etc.
  59.  
  60. Options:
  61.    srcdir       - Source directory
  62.    sisfile      - Path of the created SIS file
  63.    uid          - Symbian OS UID for the SIS package
  64.    version      - SIS package version: X.Y.Z or X,Y,Z (major, minor, build)
  65.    lang         - Comma separated list of two-character language codes
  66.    caption      - Comma separated list of package names in all languages
  67.    drive        - Drive where the package will be installed (any by default)
  68.    textfile     - Text file (or pattern, see below) to display during install
  69.    cert         - Certificate to use for signing (PEM format)
  70.    privkey      - Private key of the certificate (PEM format)
  71.    passphrase   - Pass phrase of the private key (insecure, use stdin instead)
  72.    vendor       - Vendor name or a comma separated list of names in all lang.
  73.    encoding     - Local character encodings for terminal and filesystem
  74.    verbose      - Print extra statistics
  75.  
  76. If no certificate and its private key are given, a default self-signed
  77. certificate is used to sign the SIS file. Software authors are encouraged
  78. to create their own unique certificates for SIS packages that are to be
  79. distributed.
  80.  
  81. Text to display uses UTF-8 encoding. The file name may contain formatting
  82. characters that are substituted for each selected language. If no formatting
  83. characters are present, the same text will be used for all languages.
  84.  
  85.    %%           - literal %
  86.    %n           - language number (01 - 99)
  87.    %c           - two-character language code in lowercase letters
  88.    %C           - two-character language code in capital letters
  89.    %l           - language name in English, using only lowercase letters
  90.    %l           - language name in English, using mixed case letters
  91. '''
  92.  
  93.  
  94. ##############################################################################
  95. # Parameters
  96. ##############################################################################
  97.  
  98. MAXPASSPHRASELENGTH     = 256
  99. MAXCERTIFICATELENGTH    = 65536
  100. MAXPRIVATEKEYLENGTH     = 65536
  101. MAXFILESIZE             = 1024 * 1024 * 8   # Eight megabytes
  102. MAXTEXTFILELENGTH       = 1024
  103.  
  104.  
  105. ##############################################################################
  106. # Global variables
  107. ##############################################################################
  108.  
  109. debug = False
  110.  
  111.  
  112. ##############################################################################
  113. # Public module-level functions
  114. ##############################################################################
  115.  
  116. def run(pgmname, argv):
  117.     global debug
  118.  
  119.     # Determine system character encodings.
  120.     try:
  121.         # getdefaultlocale() may sometimes return None.
  122.         # Fall back to ASCII encoding in that case.
  123.         terminalenc = locale.getdefaultlocale()[1] + ""
  124.    except TypeError:
  125.        # Invalid locale, fall back to ASCII terminal encoding.
  126.        terminalenc = "ascii"
  127.  
  128.    try:
  129.        # sys.getfilesystemencoding() was introduced in Python v2.3 and
  130.        # it can sometimes return None. Fall back to ASCII if something
  131.        # goes wrong.
  132.        filesystemenc = sys.getfilesystemencoding() + ""
  133.     except (AttributeError, TypeError):
  134.         filesystemenc = "ascii"
  135.  
  136.     try:
  137.         gopt = getopt.gnu_getopt
  138.     except:
  139.         # Python <v2.3, GNU-style parameter ordering not supported.
  140.         gopt = getopt.getopt
  141.  
  142.     # Parse command line arguments.
  143.     short_opts = "u:r:l:c:f:t:a:k:p:d:e:vh"
  144.     long_opts = [
  145.         "uid=", "version=", "lang=", "caption=",
  146.         "drive=", "textfile=", "cert=", "privkey=", "passphrase=", "vendor=",
  147.         "encoding=", "verbose", "debug", "help"
  148.     ]
  149.     args = gopt(argv, short_opts, long_opts)
  150.  
  151.     opts = dict(args[0])
  152.     pargs = args[1]
  153.  
  154.     if len(pargs) == 0:
  155.         raise ValueError("no source file name given")
  156.  
  157.     # Override character encoding of command line and filesystem.
  158.     encs = opts.get("--encoding", opts.get("-e", "%s,%s" % (terminalenc,
  159.                                                             filesystemenc)))
  160.     try:
  161.         terminalenc, filesystemenc = encs.split(",")
  162.     except (ValueError, TypeError):
  163.         raise ValueError("invalid encoding string '%s'" % encs)
  164.  
  165.     # Get source directory name.
  166.     src = pargs[0].decode(terminalenc).encode(filesystemenc)
  167.     if os.path.isdir(src):
  168.         # Remove trailing slashes (or whatever the separator is).
  169.         src = os.path.split(src + os.sep)[0]
  170.  
  171.         # Use last directory component as the name.
  172.         basename = os.path.basename(src)
  173.  
  174.         # Source is a directory, recursively collect files it contains.
  175.         srcdir = src
  176.         srcfiles = []
  177.         prefixlen = len(srcdir) + len(os.sep)
  178.         def getfiles(arg, dirname, names):
  179.             for name in names:
  180.                 path = os.path.join(dirname, name)
  181.                 if not os.path.isdir(path):
  182.                     arg.append(path[prefixlen:])
  183.         os.path.walk(srcdir, getfiles, srcfiles)
  184.     else:
  185.         raise ValueError("%s: not a directory" % src)
  186.  
  187.     # Parse version string, use 1.0.0 by default.
  188.     version = opts.get("--version", opts.get("-r", None))
  189.     if version == None:
  190.         version = "1.0.0"
  191.         print ("%s: warning: no package version given, "
  192.                "using %s" % (pgmname, version))
  193.     try:
  194.         version = parseversion(version)
  195.     except (ValueError, IndexError, TypeError):
  196.         raise ValueError("invalid version string '%s'" % version)
  197.  
  198.     # Determine output SIS file name.
  199.     if len(pargs) == 1:
  200.         # Derive output file name from input file name.
  201.         outfile = "%s_v%d_%d_%d.sis" % (basename, version[0],
  202.                                         version[1], version[2])
  203.     elif len(pargs) == 2:
  204.         outfile = pargs[1].decode(terminalenc).encode(filesystemenc)
  205.         if os.path.isdir(outfile):
  206.             # Output to directory, derive output name from input file name.
  207.             outfile = os.path.join(outfile, "%s_v%d_%d_%d.sis" % (
  208.                 basename, version[0], version[1], version[2]))
  209.         if not outfile.lower().endswith(".sis"):
  210.             outfile += ".sis"
  211.     else:
  212.         raise ValueError("wrong number of arguments")
  213.  
  214.     # Auto-generate a test-range UID from basename.
  215.     autouid = symbianutil.uidfromname(basename.decode(filesystemenc))
  216.  
  217.     # Get package UID.
  218.     puid = opts.get("--uid", opts.get("-u", None))
  219.     if puid == None:
  220.         # No UID given, use auto-generated UID.
  221.         puid = autouid
  222.         print ("%s: warning: no UID given, using auto-generated "
  223.                "test-range UID 0x%08x" % (pgmname, puid))
  224.     elif puid.lower().startswith("0x"):
  225.         # Prefer hex UIDs with leading "0x".
  226.         puid = long(puid, 16)
  227.     else:
  228.         try:
  229.             if len(puid) == 8:
  230.                 # Assuming hex UID even without leading "0x".
  231.                 print ('%s: warning: assuming hex UID even '
  232.                        'without leading "0x"' % pgmname)
  233.                 puid = long(puid, 16)
  234.             else:
  235.                 # Decimal UID.
  236.                 puid = long(puid)
  237.                 print ('%s: warning: decimal UID converted to 0x%08x' %
  238.                        (pgmname, puid))
  239.         except ValueError:
  240.             raise ValueError("invalid UID string '%s'" % puid)
  241.  
  242.     # Warn against specifying a test-range UID manually.
  243.     if puid & 0xf0000000L == 0xe0000000L and puid != autouid:
  244.         print ("%s: warning: manually specifying a test-range UID is "
  245.                "not recommended" % pgmname)
  246.  
  247.     # Determine package language(s), use "EN" by default.
  248.     lang = opts.get("--lang", opts.get("-l", "EN")).split(",")
  249.     numlang = len(lang)
  250.  
  251.     # Verify that the language codes are correct.
  252.     for l in lang:
  253.         try:
  254.             symbianutil.langidtonum[l]
  255.         except KeyError:
  256.             raise ValueError("%s: no such language code" % l)
  257.  
  258.     # Determine package caption(s), use basename by default.
  259.     caption = opts.get("--caption", opts.get("-c", ""))
  260.    caption = caption.decode(terminalenc)
  261.    if len(caption) == 0:
  262.        # Caption not given, use basename.
  263.        caption = [basename] * numlang
  264.    else:
  265.        caption = caption.split(",")
  266.  
  267.    # Compare the number of languages and captions.
  268.    if len(caption) != numlang:
  269.        raise ValueError("invalid number of captions")
  270.  
  271.    # Determine installation drive, any by default.
  272.    drive = opts.get("--drive", opts.get("-f", "any")).upper()
  273.    if drive == "ANY" or drive == "!":
  274.        drive = "!"
  275.    elif drive != "C" and drive != "E":
  276.        raise ValueError("%s: invalid drive letter" % drive)
  277.  
  278.    # Determine vendor name(s), use "Ensymble" by default.
  279.    vendor = opts.get("--vendor", opts.get("-d", "Ensymble"))
  280.    vendor = vendor.decode(terminalenc)
  281.    vendor = vendor.split(",")
  282.    if len(vendor) == 1:
  283.        # Only one vendor name given, use it for all languages.
  284.        vendor = vendor * numlang
  285.    elif len(vendor) != numlang:
  286.        raise ValueError("invalid number of vendor names")
  287.  
  288.    # Load text files.
  289.    texts = []
  290.    textfile = opts.get("--textfile", opts.get("-t", None))
  291.    if textfile != None:
  292.        texts = readtextfiles(textfile, lang)
  293.  
  294.    # Get certificate and its private key file names.
  295.    cert = opts.get("--cert", opts.get("-a", None))
  296.    privkey = opts.get("--privkey", opts.get("-k", None))
  297.    if cert != None and privkey != None:
  298.        # Convert file names from terminal encoding to filesystem encoding.
  299.        cert = cert.decode(terminalenc).encode(filesystemenc)
  300.        privkey = privkey.decode(terminalenc).encode(filesystemenc)
  301.  
  302.        # Read certificate file.
  303.        f = file(cert, "rb")
  304.        certdata = f.read(MAXCERTIFICATELENGTH + 1)
  305.        f.close()
  306.  
  307.        if len(certdata) > MAXCERTIFICATELENGTH:
  308.            raise ValueError("certificate file too large")
  309.  
  310.        # Read private key file.
  311.        f = file(privkey, "rb")
  312.        privkeydata = f.read(MAXPRIVATEKEYLENGTH + 1)
  313.        f.close()
  314.  
  315.        if len(privkeydata) > MAXPRIVATEKEYLENGTH:
  316.            raise ValueError("private key file too large")
  317.    elif cert == None and privkey == None:
  318.        # No certificate given, use the Ensymble default certificate.
  319.        # defaultcert.py is not imported when not needed. This speeds
  320.        # up program start-up a little.
  321.        from utils import defaultcert
  322.        certdata = defaultcert.cert
  323.        privkeydata = defaultcert.privkey
  324.  
  325.        print ("%s: warning: no certificate given, using "
  326.               "insecure built-in one" % pgmname)
  327.  
  328.        # Warn if the UID is in the protected range.
  329.        # Resulting SIS file will probably not install.
  330.        if puid < 0x80000000L:
  331.            print ("%s: warning: UID is in the protected range "
  332.                   "(0x00000000 - 0x7ffffff)" % pgmname)
  333.    else:
  334.        raise ValueError("missing certificate or private key")
  335.  
  336.    # Get pass phrase. Pass phrase remains in terminal encoding.
  337.    passphrase = opts.get("--passphrase", opts.get("-p", None))
  338.    if passphrase == None and privkey != None:
  339.        # Private key given without "--passphrase" option, ask it.
  340.        if sys.stdin.isatty():
  341.            # Standard input is a TTY, ask password interactively.
  342.            passphrase = getpass.getpass("Enter private key pass phrase:")
  343.        else:
  344.            # Not connected to a TTY, read stdin non-interactively instead.
  345.            passphrase = sys.stdin.read(MAXPASSPHRASELENGTH + 1)
  346.  
  347.            if len(passphrase) > MAXPASSPHRASELENGTH:
  348.                raise ValueError("pass phrase too long")
  349.  
  350.            passphrase = passphrase.strip()
  351.  
  352.    # Determine verbosity.
  353.    verbose = False
  354.    if "--verbose" in opts.keys() or "-v" in opts.keys():
  355.        verbose = True
  356.  
  357.    # Determine if debug output is requested.
  358.    if "--debug" in opts.keys():
  359.        debug = True
  360.  
  361.        # Enable debug output for OpenSSL-related functions.
  362.        import cryptutil
  363.        cryptutil.setdebug(True)
  364.  
  365.    # Ingredients for successful SIS generation:
  366.    #
  367.    # terminalenc   Terminal character encoding (autodetected)
  368.    # filesystemenc File system name encoding (autodetected)
  369.    # basename      Base for generated file names on host, filesystemenc encoded
  370.    # srcdir        Directory of source files, filesystemenc encoded
  371.    # srcfiles      List of filesystemenc encoded source file names in srcdir
  372.    # outfile       Output SIS file name, filesystemenc encoded
  373.    # puid          Package UID, long integer
  374.    # version       A triple-item tuple (major, minor, build)
  375.    # lang          List of two-character language codes, ASCII strings
  376.    # caption       List of Unicode package captions, one per language
  377.    # drive         Installation drive letter or "!"
  378.    # textfile      File name pattern of text file(s) to display during install
  379.    # texts         Actual texts to display during install, one per language
  380.    # cert          Certificate in PEM format
  381.    # privkey       Certificate private key in PEM format
  382.    # passphrase    Pass phrase of private key, terminalenc encoded string
  383.    # vendor        List of Unicode vendor names, one per language
  384.    # verbose       Boolean indicating verbose terminal output
  385.  
  386.    if verbose:
  387.        print
  388.        print "Input files         %s"          % " ".join(
  389.            [s.decode(filesystemenc).encode(terminalenc) for s in srcfiles])
  390.        print "Output SIS file     %s"          % (
  391.            outfile.decode(filesystemenc).encode(terminalenc))
  392.        print "UID                 0x%08x"      % puid
  393.        print "Version             %d.%d.%d"    % (
  394.            version[0], version[1], version[2])
  395.        print "Language(s)         %s"          % ", ".join(lang)
  396.        print "Package caption(s)  %s"          % ", ".join(
  397.            [s.encode(terminalenc) for s in caption])
  398.        print "Install drive       %s"        % ((drive == "!") and
  399.            "<any>" or drive)
  400.        print "Text file(s)        %s"          % ((textfile and
  401.            textfile.decode(filesystemenc).encode(terminalenc)) or "<none>")
  402.        print "Certificate         %s"          % ((cert and
  403.            cert.decode(filesystemenc).encode(terminalenc)) or "<default>")
  404.        print "Private key         %s"          % ((privkey and
  405.            privkey.decode(filesystemenc).encode(terminalenc)) or "<default>")
  406.        print "Vendor name(s)      %s"          % ", ".join(
  407.            [s.encode(terminalenc) for s in vendor])
  408.        print
  409.  
  410.    # Generate SimpleSISWriter object.
  411.    sw = sisfile.SimpleSISWriter(lang, caption, puid, version,
  412.                                 vendor[0], vendor)
  413.  
  414.    # Add text file or files to the SIS object. Text dialog is
  415.    # supposed to be displayed before anything else is installed.
  416.    if len(texts) == 1:
  417.        sw.addfile(texts[0], operation = sisfield.EOpText)
  418.    elif len(texts) > 1:
  419.        sw.addlangdepfile(texts, operation = sisfield.EOpText)
  420.  
  421.    # Add files to SIS object.
  422.    sysbinprefix = os.path.join("sys", "bin", "")
  423.     for srcfile in srcfiles:
  424.         # Read file.
  425.         f = file(os.path.join(srcdir, srcfile), "rb")
  426.         string = f.read(MAXFILESIZE + 1)
  427.         f.close()
  428.  
  429.         if len(string) > MAXFILESIZE:
  430.             raise ValueError("input file too large")
  431.  
  432.         # Check if the file is an E32Image (EXE or DLL).
  433.         caps = symbianutil.e32imagecaps(string)
  434.  
  435.         if caps != None and not srcfile.startswith(sysbinprefix):
  436.             print ("%s: warning: %s is an E32Image (EXE or DLL) outside %s%s" %
  437.                     (pgmname, srcfile, os.sep, sysbinprefix))
  438.  
  439.         # Add file to the SIS object.
  440.         target = srcfile.decode(filesystemenc).replace(os.sep, "\\")
  441.         sw.addfile(string, "%s:\\%s" % (drive, target), capabilities = caps)
  442.         del string
  443.  
  444.     # Add target device dependency.
  445.     sw.addtargetdevice(0x101f7961L, (0, 0, 0), None,
  446.                        ["Series60ProductID"] * numlang)
  447.  
  448.     # Add certificate.
  449.     sw.addcertificate(privkeydata, certdata, passphrase)
  450.  
  451.     # Generate SIS file out of the SimpleSISWriter object.
  452.     sw.tofile(outfile)
  453.  
  454.  
  455. ##############################################################################
  456. # Module-level functions which are normally only used by this module
  457. ##############################################################################
  458.  
  459. def parseversion(version):
  460.     '''Parse a version string: "v1.2.3" or similar.
  461.  
  462.    Initial "v" can optionally be a capital "V" or omitted altogether. Minor
  463.    and build numbers can also be omitted. Separator can be a comma or a
  464.    period.'''
  465.  
  466.     version = version.strip().lower()
  467.  
  468.     # Strip initial "v" or "V".
  469.     if version[0] == "v":
  470.         version = version[1:]
  471.  
  472.     if "." in version:
  473.         parts = [int(n) for n in version.split(".")]
  474.     else:
  475.         parts = [int(n) for n in version.split(",")]
  476.  
  477.     # Allow missing minor and build numbers.
  478.     parts.extend([0, 0])
  479.  
  480.     return parts[0:3]
  481.  
  482. def readtextfiles(pattern, languages):
  483.     '''Read language dependent text files.
  484.  
  485.    Files are assumed to be in UTF-8 encoding and re-encoded
  486.    in UCS-2 (UTF-16LE) for Symbian OS to display during installation.'''
  487.  
  488.     if "%" not in pattern:
  489.         # Only one file, read it.
  490.         filenames = [pattern]
  491.     else:
  492.         filenames = []
  493.         for langid in languages:
  494.             langnum  = symbianutil.langidtonum[langid]
  495.             langname = symbianutil.langnumtoname[langnum]
  496.  
  497.             # Replace formatting characters in file name pattern.
  498.             filename = pattern
  499.             filename = filename.replace("%n", "%02d" % langnum)
  500.             filename = filename.replace("%c", langid.lower())
  501.             filename = filename.replace("%C", langid.upper())
  502.             filename = filename.replace("%l", langname.lower())
  503.             filename = filename.replace("%L", langname)
  504.             filename = filename.replace("%%", "%")
  505.  
  506.             filenames.append(filename)
  507.  
  508.     texts = []
  509.  
  510.     for filename in filenames:
  511.         f = file(filename, "r") # Read as text.
  512.         text = f.read(MAXTEXTFILELENGTH + 1)
  513.         f.close()
  514.  
  515.         if len(text) > MAXTEXTFILELENGTH:
  516.             raise ValueError("%s: text file too large" % filename)
  517.  
  518.         texts.append(text.decode("UTF-8").encode("UTF-16LE"))
  519.  
  520.     return texts
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement