Guest User

common.py

a guest
Mar 15th, 2016
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 76.26 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. #
  3. # common.py - part of the FDroid server tools
  4. # Copyright (C) 2010-13, Ciaran Gultnieks, ciaran@ciarang.com
  5. # Copyright (C) 2013-2014 Daniel Martí <mvdan@mvdan.cc>
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program.  If not, see <http://www.gnu.org/licenses/>.
  19.  
  20. # common.py is imported by all modules, so do not import third-party
  21. # libraries here as they will become a requirement for all commands.
  22.  
  23. import io
  24. import os
  25. import sys
  26. import re
  27. import shutil
  28. import glob
  29. import stat
  30. import subprocess
  31. import time
  32. import operator
  33. import logging
  34. import hashlib
  35. import socket
  36. import base64
  37. import xml.etree.ElementTree as XMLElementTree
  38.  
  39. from queue import Queue
  40.  
  41. from zipfile import ZipFile
  42.  
  43. import fdroidserver.metadata
  44. from .asynchronousfilereader import AsynchronousFileReader
  45.  
  46.  
  47. XMLElementTree.register_namespace('android', 'http://schemas.android.com/apk/res/android')
  48.  
  49. config = None
  50. options = None
  51. env = None
  52. orig_path = None
  53.  
  54.  
  55. default_config = {
  56.     'sdk_path': "$ANDROID_HOME",
  57.     'ndk_paths': {
  58.         'r9b': None,
  59.         'r10e': "$ANDROID_NDK",
  60.     },
  61.     'build_tools': "23.0.2",
  62.     'java_paths': None,
  63.     'ant': "ant",
  64.     'mvn3': "mvn",
  65.     'gradle': 'gradle',
  66.     'accepted_formats': ['txt', 'yaml'],
  67.     'sync_from_local_copy_dir': False,
  68.     'per_app_repos': False,
  69.     'make_current_version_link': True,
  70.     'current_version_name_source': 'Name',
  71.     'update_stats': False,
  72.     'stats_ignore': [],
  73.     'stats_server': None,
  74.     'stats_user': None,
  75.     'stats_to_carbon': False,
  76.     'repo_maxage': 0,
  77.     'build_server_always': False,
  78.     'keystore': 'keystore.jks',
  79.     'smartcardoptions': [],
  80.     'char_limits': {
  81.         'Summary': 80,
  82.         'Description': 4000,
  83.     },
  84.     'keyaliases': {},
  85.     'repo_url': "https://MyFirstFDroidRepo.org/fdroid/repo",
  86.     'repo_name': "My First FDroid Repo Demo",
  87.     'repo_icon': "fdroid-icon.png",
  88.     'repo_description': '''
  89.        This is a repository of apps to be used with FDroid. Applications in this
  90.        repository are either official binaries built by the original application
  91.        developers, or are binaries built from source by the admin of f-droid.org
  92.        using the tools on https://gitlab.com/u/fdroid.
  93.        ''',
  94.     'archive_older': 0,
  95. }
  96.  
  97.  
  98. def setup_global_opts(parser):
  99.     parser.add_argument("-v", "--verbose", action="store_true", default=False,
  100.                         help="Spew out even more information than normal")
  101.     parser.add_argument("-q", "--quiet", action="store_true", default=False,
  102.                         help="Restrict output to warnings and errors")
  103.  
  104.  
  105. def fill_config_defaults(thisconfig):
  106.     for k, v in default_config.items():
  107.         if k not in thisconfig:
  108.             thisconfig[k] = v
  109.  
  110.     # Expand paths (~users and $vars)
  111.     def expand_path(path):
  112.         if path is None:
  113.             return None
  114.         orig = path
  115.         path = os.path.expanduser(path)
  116.         path = os.path.expandvars(path)
  117.         if orig == path:
  118.             return None
  119.         return path
  120.  
  121.     for k in ['sdk_path', 'ant', 'mvn3', 'gradle', 'keystore', 'repo_icon']:
  122.         v = thisconfig[k]
  123.         exp = expand_path(v)
  124.         if exp is not None:
  125.             thisconfig[k] = exp
  126.             thisconfig[k + '_orig'] = v
  127.  
  128.     # find all installed JDKs for keytool, jarsigner, and JAVA[6-9]_HOME env vars
  129.     if thisconfig['java_paths'] is None:
  130.         thisconfig['java_paths'] = dict()
  131.         pathlist = []
  132.         pathlist += glob.glob('/usr/lib/jvm/j*[6-9]*')
  133.         pathlist += glob.glob('/usr/java/jdk1.[6-9]*')
  134.         pathlist += glob.glob('/System/Library/Java/JavaVirtualMachines/1.[6-9].0.jdk')
  135.         pathlist += glob.glob('/Library/Java/JavaVirtualMachines/*jdk*[6-9]*')
  136.         if os.getenv('JAVA_HOME') is not None:
  137.             pathlist += os.getenv('JAVA_HOME')
  138.         if os.getenv('PROGRAMFILES') is not None:
  139.             pathlist += glob.glob(os.path.join(os.getenv('PROGRAMFILES'), 'Java', 'jdk1.[6-9].*'))
  140.         print('pathlist: '),
  141.         print(sorted(pathlist))
  142.         for d in sorted(pathlist):
  143.             if os.path.islink(d):
  144.                 continue
  145.             print('d: ' + d)
  146.             #d = os.path.abspath(d)
  147.             print('d: ' + d)
  148.             j = os.path.basename(d)
  149.             # the last one found will be the canonical one, so order appropriately
  150.             for regex in [
  151.                     r'^1\.([6-9])\.0\.jdk$',  # OSX
  152.                     r'^jdk1\.([6-9])\.0_[0-9]+.jdk$',  # OSX and Oracle tarball
  153.                     r'^jdk1\.([6-9])\.0_[0-9]+$',  # Oracle Windows
  154.                     r'^jdk([6-9])-openjdk$',  # Arch
  155.                     r'^java-([6-9])-openjdk$',  # Arch
  156.                     r'^java-([6-9])-jdk$',  # Arch (oracle)
  157.                     r'^java-1\.([6-9])\.0-.*$',  # RedHat
  158.                     r'^java-([6-9])-oracle$',  # Debian WebUpd8
  159.                     r'^jdk-([6-9])-oracle-.*$',  # Debian make-jpkg
  160.                     r'^java-([6-9])-openjdk-[^c][^o][^m].*$',  # Debian
  161.                     ]:
  162.                 m = re.match(regex, j)
  163.                 if not m:
  164.                     continue
  165.                 osxhome = os.path.join(d, 'Contents', 'Home')
  166.                 if os.path.exists(osxhome):
  167.                     thisconfig['java_paths'][m.group(1)] = osxhome
  168.                 else:
  169.                     thisconfig['java_paths'][m.group(1)] = d
  170.  
  171.     for java_version in ('7', '8', '9'):
  172.         if java_version not in thisconfig['java_paths']:
  173.             continue
  174.         java_home = thisconfig['java_paths'][java_version]
  175.         print('java_home: ' + java_home)
  176.         jarsigner = os.path.join(java_home, 'bin', 'jarsigner')
  177.         print('jarsigner: ' + jarsigner)
  178.         if os.path.exists(jarsigner):
  179.             thisconfig['jarsigner'] = jarsigner
  180.             thisconfig['keytool'] = os.path.join(java_home, 'bin', 'keytool')
  181.             break  # Java7 is preferred, so quit if found
  182.  
  183.     for k in ['ndk_paths', 'java_paths']:
  184.         d = thisconfig[k]
  185.         for k2 in d.copy():
  186.             v = d[k2]
  187.             exp = expand_path(v)
  188.             if exp is not None:
  189.                 thisconfig[k][k2] = exp
  190.                 thisconfig[k][k2 + '_orig'] = v
  191.     print('jarsigner: ' + thisconfig['jarsigner'])
  192.     print('keytool: ' + thisconfig['keytool'])
  193.  
  194.  
  195. def regsub_file(pattern, repl, path):
  196.     with open(path, 'r') as f:
  197.         text = f.read()
  198.     text = re.sub(pattern, repl, text)
  199.     with open(path, 'w') as f:
  200.         f.write(text)
  201.  
  202.  
  203. def read_config(opts, config_file='config.py'):
  204.     """Read the repository config
  205.  
  206.    The config is read from config_file, which is in the current directory when
  207.    any of the repo management commands are used.
  208.    """
  209.     global config, options, env, orig_path
  210.  
  211.     if config is not None:
  212.         return config
  213.     if not os.path.isfile(config_file):
  214.         logging.critical("Missing config file - is this a repo directory?")
  215.         sys.exit(2)
  216.  
  217.     options = opts
  218.  
  219.     config = {}
  220.  
  221.     logging.debug("Reading %s" % config_file)
  222.     with io.open(config_file, "rb") as f:
  223.         code = compile(f.read(), config_file, 'exec')
  224.         exec(code, None, config)
  225.  
  226.     # smartcardoptions must be a list since its command line args for Popen
  227.     if 'smartcardoptions' in config:
  228.         config['smartcardoptions'] = config['smartcardoptions'].split(' ')
  229.     elif 'keystore' in config and config['keystore'] == 'NONE':
  230.         # keystore='NONE' means use smartcard, these are required defaults
  231.         config['smartcardoptions'] = ['-storetype', 'PKCS11', '-providerName',
  232.                                       'SunPKCS11-OpenSC', '-providerClass',
  233.                                       'sun.security.pkcs11.SunPKCS11',
  234.                                       '-providerArg', 'opensc-fdroid.cfg']
  235.  
  236.     if any(k in config for k in ["keystore", "keystorepass", "keypass"]):
  237.         st = os.stat(config_file)
  238.         if st.st_mode & stat.S_IRWXG or st.st_mode & stat.S_IRWXO:
  239.             logging.warn("unsafe permissions on {0} (should be 0600)!".format(config_file))
  240.  
  241.     fill_config_defaults(config)
  242.  
  243.     # There is no standard, so just set up the most common environment
  244.     # variables
  245.     env = os.environ
  246.     orig_path = env['PATH']
  247.     for n in ['ANDROID_HOME', 'ANDROID_SDK']:
  248.         env[n] = config['sdk_path']
  249.  
  250.     for k, v in config['java_paths'].items():
  251.         env['JAVA%s_HOME' % k] = v
  252.  
  253.     for k in ["keystorepass", "keypass"]:
  254.         if k in config:
  255.             write_password_file(k)
  256.  
  257.     for k in ["repo_description", "archive_description"]:
  258.         if k in config:
  259.             config[k] = clean_description(config[k])
  260.  
  261.     if 'serverwebroot' in config:
  262.         if isinstance(config['serverwebroot'], str):
  263.             roots = [config['serverwebroot']]
  264.         elif all(isinstance(item, str) for item in config['serverwebroot']):
  265.             roots = config['serverwebroot']
  266.         else:
  267.             raise TypeError('only accepts strings, lists, and tuples')
  268.         rootlist = []
  269.         for rootstr in roots:
  270.             # since this is used with rsync, where trailing slashes have
  271.             # meaning, ensure there is always a trailing slash
  272.             if rootstr[-1] != '/':
  273.                 rootstr += '/'
  274.             rootlist.append(rootstr.replace('//', '/'))
  275.         config['serverwebroot'] = rootlist
  276.  
  277.     return config
  278.  
  279.  
  280. def find_sdk_tools_cmd(cmd):
  281.     '''find a working path to a tool from the Android SDK'''
  282.  
  283.     tooldirs = []
  284.     if config is not None and 'sdk_path' in config and os.path.exists(config['sdk_path']):
  285.         # try to find a working path to this command, in all the recent possible paths
  286.         if 'build_tools' in config:
  287.             build_tools = os.path.join(config['sdk_path'], 'build-tools')
  288.             # if 'build_tools' was manually set and exists, check only that one
  289.             configed_build_tools = os.path.join(build_tools, config['build_tools'])
  290.             if os.path.exists(configed_build_tools):
  291.                 tooldirs.append(configed_build_tools)
  292.             else:
  293.                 # no configed version, so hunt known paths for it
  294.                 for f in sorted(os.listdir(build_tools), reverse=True):
  295.                     if os.path.isdir(os.path.join(build_tools, f)):
  296.                         tooldirs.append(os.path.join(build_tools, f))
  297.                 tooldirs.append(build_tools)
  298.         sdk_tools = os.path.join(config['sdk_path'], 'tools')
  299.         if os.path.exists(sdk_tools):
  300.             tooldirs.append(sdk_tools)
  301.         sdk_platform_tools = os.path.join(config['sdk_path'], 'platform-tools')
  302.         if os.path.exists(sdk_platform_tools):
  303.             tooldirs.append(sdk_platform_tools)
  304.     tooldirs.append('/usr/bin')
  305.     for d in tooldirs:
  306.         if os.path.isfile(os.path.join(d, cmd)):
  307.             return os.path.join(d, cmd)
  308.     # did not find the command, exit with error message
  309.     ensure_build_tools_exists(config)
  310.  
  311.  
  312. def test_sdk_exists(thisconfig):
  313.     if 'sdk_path' not in thisconfig:
  314.         if 'aapt' in thisconfig and os.path.isfile(thisconfig['aapt']):
  315.             return True
  316.         else:
  317.             logging.error("'sdk_path' not set in config.py!")
  318.             return False
  319.     if thisconfig['sdk_path'] == default_config['sdk_path']:
  320.         logging.error('No Android SDK found!')
  321.         logging.error('You can use ANDROID_HOME to set the path to your SDK, i.e.:')
  322.         logging.error('\texport ANDROID_HOME=/opt/android-sdk')
  323.         return False
  324.     print("thisconfig['sdk_path']: " + thisconfig['sdk_path'])
  325.     if not os.path.exists(thisconfig['sdk_path']):
  326.         logging.critical('Android SDK path "' + thisconfig['sdk_path'] + '" does not exist!')
  327.         return False
  328.     if not os.path.isdir(thisconfig['sdk_path']):
  329.         logging.critical('Android SDK path "' + thisconfig['sdk_path'] + '" is not a directory!')
  330.         return False
  331.     for d in ['build-tools', 'platform-tools', 'tools']:
  332.         if not os.path.isdir(os.path.join(thisconfig['sdk_path'], d)):
  333.             logging.critical('Android SDK path "%s" does not contain "%s/"!' % (
  334.                 thisconfig['sdk_path'], d))
  335.             return False
  336.     return True
  337.  
  338.  
  339. def ensure_build_tools_exists(thisconfig):
  340.     if not test_sdk_exists(thisconfig):
  341.         sys.exit(3)
  342.     build_tools = os.path.join(thisconfig['sdk_path'], 'build-tools')
  343.     versioned_build_tools = os.path.join(build_tools, thisconfig['build_tools'])
  344.     if not os.path.isdir(versioned_build_tools):
  345.         logging.critical('Android Build Tools path "'
  346.                          + versioned_build_tools + '" does not exist!')
  347.         sys.exit(3)
  348.  
  349.  
  350. def write_password_file(pwtype, password=None):
  351.     '''
  352.    writes out passwords to a protected file instead of passing passwords as
  353.    command line argments
  354.    '''
  355.     filename = '.fdroid.' + pwtype + '.txt'
  356.     fd = os.open(filename, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0o600)
  357.     if password is None:
  358.         os.write(fd, config[pwtype].encode('utf-8'))
  359.     else:
  360.         os.write(fd, password.encode('utf-8'))
  361.     os.close(fd)
  362.     config[pwtype + 'file'] = filename
  363.  
  364.  
  365. # Given the arguments in the form of multiple appid:[vc] strings, this returns
  366. # a dictionary with the set of vercodes specified for each package.
  367. def read_pkg_args(args, allow_vercodes=False):
  368.  
  369.     vercodes = {}
  370.     if not args:
  371.         return vercodes
  372.  
  373.     for p in args:
  374.         if allow_vercodes and ':' in p:
  375.             package, vercode = p.split(':')
  376.         else:
  377.             package, vercode = p, None
  378.         if package not in vercodes:
  379.             vercodes[package] = [vercode] if vercode else []
  380.             continue
  381.         elif vercode and vercode not in vercodes[package]:
  382.             vercodes[package] += [vercode] if vercode else []
  383.  
  384.     return vercodes
  385.  
  386.  
  387. # On top of what read_pkg_args does, this returns the whole app metadata, but
  388. # limiting the builds list to the builds matching the vercodes specified.
  389. def read_app_args(args, allapps, allow_vercodes=False):
  390.  
  391.     vercodes = read_pkg_args(args, allow_vercodes)
  392.  
  393.     if not vercodes:
  394.         return allapps
  395.  
  396.     apps = {}
  397.     for appid, app in allapps.items():
  398.         if appid in vercodes:
  399.             apps[appid] = app
  400.  
  401.     if len(apps) != len(vercodes):
  402.         for p in vercodes:
  403.             if p not in allapps:
  404.                 logging.critical("No such package: %s" % p)
  405.         raise FDroidException("Found invalid app ids in arguments")
  406.     if not apps:
  407.         raise FDroidException("No packages specified")
  408.  
  409.     error = False
  410.     for appid, app in apps.items():
  411.         vc = vercodes[appid]
  412.         if not vc:
  413.             continue
  414.         app.builds = [b for b in app.builds if b.vercode in vc]
  415.         if len(app.builds) != len(vercodes[appid]):
  416.             error = True
  417.             allvcs = [b.vercode for b in app.builds]
  418.             for v in vercodes[appid]:
  419.                 if v not in allvcs:
  420.                     logging.critical("No such vercode %s for app %s" % (v, appid))
  421.  
  422.     if error:
  423.         raise FDroidException("Found invalid vercodes for some apps")
  424.  
  425.     return apps
  426.  
  427.  
  428. def get_extension(filename):
  429.     base, ext = os.path.splitext(filename)
  430.     if not ext:
  431.         return base, ''
  432.     return base, ext.lower()[1:]
  433.  
  434.  
  435. def has_extension(filename, ext):
  436.     _, f_ext = get_extension(filename)
  437.     return ext == f_ext
  438.  
  439.  
  440. apk_regex = re.compile(r"^(.+)_([0-9]+)\.apk$")
  441.  
  442.  
  443. def clean_description(description):
  444.     'Remove unneeded newlines and spaces from a block of description text'
  445.     returnstring = ''
  446.     # this is split up by paragraph to make removing the newlines easier
  447.     for paragraph in re.split(r'\n\n', description):
  448.         paragraph = re.sub('\r', '', paragraph)
  449.         paragraph = re.sub('\n', ' ', paragraph)
  450.         paragraph = re.sub(' {2,}', ' ', paragraph)
  451.         paragraph = re.sub('^\s*(\w)', r'\1', paragraph)
  452.         returnstring += paragraph + '\n\n'
  453.     return returnstring.rstrip('\n')
  454.  
  455.  
  456. def apknameinfo(filename):
  457.     filename = os.path.basename(filename)
  458.     m = apk_regex.match(filename)
  459.     try:
  460.         result = (m.group(1), m.group(2))
  461.     except AttributeError:
  462.         raise FDroidException("Invalid apk name: %s" % filename)
  463.     return result
  464.  
  465.  
  466. def getapkname(app, build):
  467.     return "%s_%s.apk" % (app.id, build.vercode)
  468.  
  469.  
  470. def getsrcname(app, build):
  471.     return "%s_%s_src.tar.gz" % (app.id, build.vercode)
  472.  
  473.  
  474. def getappname(app):
  475.     if app.Name:
  476.         return app.Name
  477.     if app.AutoName:
  478.         return app.AutoName
  479.     return app.id
  480.  
  481.  
  482. def getcvname(app):
  483.     return '%s (%s)' % (app.CurrentVersion, app.CurrentVersionCode)
  484.  
  485.  
  486. def getvcs(vcstype, remote, local):
  487.     if vcstype == 'git':
  488.         return vcs_git(remote, local)
  489.     if vcstype == 'git-svn':
  490.         return vcs_gitsvn(remote, local)
  491.     if vcstype == 'hg':
  492.         return vcs_hg(remote, local)
  493.     if vcstype == 'bzr':
  494.         return vcs_bzr(remote, local)
  495.     if vcstype == 'srclib':
  496.         if local != os.path.join('build', 'srclib', remote):
  497.             raise VCSException("Error: srclib paths are hard-coded!")
  498.         return getsrclib(remote, os.path.join('build', 'srclib'), raw=True)
  499.     if vcstype == 'svn':
  500.         raise VCSException("Deprecated vcs type 'svn' - please use 'git-svn' instead")
  501.     raise VCSException("Invalid vcs type " + vcstype)
  502.  
  503.  
  504. def getsrclibvcs(name):
  505.     if name not in fdroidserver.metadata.srclibs:
  506.         raise VCSException("Missing srclib " + name)
  507.     return fdroidserver.metadata.srclibs[name]['Repo Type']
  508.  
  509.  
  510. class vcs:
  511.  
  512.     def __init__(self, remote, local):
  513.  
  514.         # svn, git-svn and bzr may require auth
  515.         self.username = None
  516.         if self.repotype() in ('git-svn', 'bzr'):
  517.             if '@' in remote:
  518.                 if self.repotype == 'git-svn':
  519.                     raise VCSException("Authentication is not supported for git-svn")
  520.                 self.username, remote = remote.split('@')
  521.                 if ':' not in self.username:
  522.                     raise VCSException("Password required with username")
  523.                 self.username, self.password = self.username.split(':')
  524.  
  525.         self.remote = remote
  526.         self.local = local
  527.         self.clone_failed = False
  528.         self.refreshed = False
  529.         self.srclib = None
  530.  
  531.     def repotype(self):
  532.         return None
  533.  
  534.     # Take the local repository to a clean version of the given revision, which
  535.     # is specificed in the VCS's native format. Beforehand, the repository can
  536.     # be dirty, or even non-existent. If the repository does already exist
  537.     # locally, it will be updated from the origin, but only once in the
  538.     # lifetime of the vcs object.
  539.     # None is acceptable for 'rev' if you know you are cloning a clean copy of
  540.     # the repo - otherwise it must specify a valid revision.
  541.     def gotorevision(self, rev, refresh=True):
  542.  
  543.         if self.clone_failed:
  544.             raise VCSException("Downloading the repository already failed once, not trying again.")
  545.  
  546.         # The .fdroidvcs-id file for a repo tells us what VCS type
  547.         # and remote that directory was created from, allowing us to drop it
  548.         # automatically if either of those things changes.
  549.         fdpath = os.path.join(self.local, '..',
  550.                               '.fdroidvcs-' + os.path.basename(self.local))
  551.         fdpath = os.path.normpath(fdpath)
  552.         cdata = self.repotype() + ' ' + self.remote
  553.         writeback = True
  554.         deleterepo = False
  555.         if os.path.exists(self.local):
  556.             if os.path.exists(fdpath):
  557.                 with open(fdpath, 'r') as f:
  558.                     fsdata = f.read().strip()
  559.                 if fsdata == cdata:
  560.                     writeback = False
  561.                 else:
  562.                     deleterepo = True
  563.                     logging.info("Repository details for %s changed - deleting" % (
  564.                         self.local))
  565.             else:
  566.                 deleterepo = True
  567.                 logging.info("Repository details for %s missing - deleting" % (
  568.                     self.local))
  569.         if deleterepo:
  570.             shutil.rmtree(self.local)
  571.  
  572.         exc = None
  573.         if not refresh:
  574.             self.refreshed = True
  575.  
  576.         try:
  577.             self.gotorevisionx(rev)
  578.         except FDroidException as e:
  579.             exc = e
  580.  
  581.         # If necessary, write the .fdroidvcs file.
  582.         if writeback and not self.clone_failed:
  583.             os.makedirs(os.path.dirname(fdpath), exist_ok=True)
  584.             with open(fdpath, 'w+') as f:
  585.                 f.write(cdata)
  586.  
  587.         if exc is not None:
  588.             raise exc
  589.  
  590.     # Derived classes need to implement this. It's called once basic checking
  591.     # has been performend.
  592.     def gotorevisionx(self, rev):
  593.         raise VCSException("This VCS type doesn't define gotorevisionx")
  594.  
  595.     # Initialise and update submodules
  596.     def initsubmodules(self):
  597.         raise VCSException('Submodules not supported for this vcs type')
  598.  
  599.     # Get a list of all known tags
  600.     def gettags(self):
  601.         if not self._gettags:
  602.             raise VCSException('gettags not supported for this vcs type')
  603.         rtags = []
  604.         for tag in self._gettags():
  605.             if re.match('[-A-Za-z0-9_. /]+$', tag):
  606.                 rtags.append(tag)
  607.         return rtags
  608.  
  609.     # Get a list of all the known tags, sorted from newest to oldest
  610.     def latesttags(self):
  611.         raise VCSException('latesttags not supported for this vcs type')
  612.  
  613.     # Get current commit reference (hash, revision, etc)
  614.     def getref(self):
  615.         raise VCSException('getref not supported for this vcs type')
  616.  
  617.     # Returns the srclib (name, path) used in setting up the current
  618.     # revision, or None.
  619.     def getsrclib(self):
  620.         return self.srclib
  621.  
  622.  
  623. class vcs_git(vcs):
  624.  
  625.     def repotype(self):
  626.         return 'git'
  627.  
  628.     # If the local directory exists, but is somehow not a git repository, git
  629.     # will traverse up the directory tree until it finds one that is (i.e.
  630.     # fdroidserver) and then we'll proceed to destroy it! This is called as
  631.     # a safety check.
  632.     def checkrepo(self):
  633.         p = FDroidPopen(['git', 'rev-parse', '--show-toplevel'], cwd=self.local, output=False)
  634.         result = p.output.rstrip()
  635.         if not result.endswith(self.local):
  636.             raise VCSException('Repository mismatch')
  637.  
  638.     def gotorevisionx(self, rev):
  639.         if not os.path.exists(self.local):
  640.             # Brand new checkout
  641.             p = FDroidPopen(['git', 'clone', self.remote, self.local])
  642.             if p.returncode != 0:
  643.                 self.clone_failed = True
  644.                 raise VCSException("Git clone failed", p.output)
  645.             self.checkrepo()
  646.         else:
  647.             self.checkrepo()
  648.             # Discard any working tree changes
  649.             p = FDroidPopen(['git', 'submodule', 'foreach', '--recursive',
  650.                              'git', 'reset', '--hard'], cwd=self.local, output=False)
  651.             if p.returncode != 0:
  652.                 raise VCSException("Git reset failed", p.output)
  653.             # Remove untracked files now, in case they're tracked in the target
  654.             # revision (it happens!)
  655.             p = FDroidPopen(['git', 'submodule', 'foreach', '--recursive',
  656.                              'git', 'clean', '-dffx'], cwd=self.local, output=False)
  657.             if p.returncode != 0:
  658.                 raise VCSException("Git clean failed", p.output)
  659.             if not self.refreshed:
  660.                 # Get latest commits and tags from remote
  661.                 p = FDroidPopen(['git', 'fetch', 'origin'], cwd=self.local)
  662.                 if p.returncode != 0:
  663.                     raise VCSException("Git fetch failed", p.output)
  664.                 p = FDroidPopen(['git', 'fetch', '--prune', '--tags', 'origin'], cwd=self.local, output=False)
  665.                 if p.returncode != 0:
  666.                     raise VCSException("Git fetch failed", p.output)
  667.                 # Recreate origin/HEAD as git clone would do it, in case it disappeared
  668.                 p = FDroidPopen(['git', 'remote', 'set-head', 'origin', '--auto'], cwd=self.local, output=False)
  669.                 if p.returncode != 0:
  670.                     lines = p.output.splitlines()
  671.                     if 'Multiple remote HEAD branches' not in lines[0]:
  672.                         raise VCSException("Git remote set-head failed", p.output)
  673.                     branch = lines[1].split(' ')[-1]
  674.                     p2 = FDroidPopen(['git', 'remote', 'set-head', 'origin', branch], cwd=self.local, output=False)
  675.                     if p2.returncode != 0:
  676.                         raise VCSException("Git remote set-head failed", p.output + '\n' + p2.output)
  677.                 self.refreshed = True
  678.         # origin/HEAD is the HEAD of the remote, e.g. the "default branch" on
  679.         # a github repo. Most of the time this is the same as origin/master.
  680.         rev = rev or 'origin/HEAD'
  681.         p = FDroidPopen(['git', 'checkout', '-f', rev], cwd=self.local, output=False)
  682.         if p.returncode != 0:
  683.             raise VCSException("Git checkout of '%s' failed" % rev, p.output)
  684.         # Get rid of any uncontrolled files left behind
  685.         p = FDroidPopen(['git', 'clean', '-dffx'], cwd=self.local, output=False)
  686.         if p.returncode != 0:
  687.             raise VCSException("Git clean failed", p.output)
  688.  
  689.     def initsubmodules(self):
  690.         self.checkrepo()
  691.         submfile = os.path.join(self.local, '.gitmodules')
  692.         if not os.path.isfile(submfile):
  693.             raise VCSException("No git submodules available")
  694.  
  695.         # fix submodules not accessible without an account and public key auth
  696.         with open(submfile, 'r') as f:
  697.             lines = f.readlines()
  698.         with open(submfile, 'w') as f:
  699.             for line in lines:
  700.                 if 'git@github.com' in line:
  701.                     line = line.replace('git@github.com:', 'https://github.com/')
  702.                 if 'git@gitlab.com' in line:
  703.                     line = line.replace('git@gitlab.com:', 'https://gitlab.com/')
  704.                 f.write(line)
  705.  
  706.         p = FDroidPopen(['git', 'submodule', 'sync'], cwd=self.local, output=False)
  707.         if p.returncode != 0:
  708.             raise VCSException("Git submodule sync failed", p.output)
  709.         p = FDroidPopen(['git', 'submodule', 'update', '--init', '--force', '--recursive'], cwd=self.local)
  710.         if p.returncode != 0:
  711.             raise VCSException("Git submodule update failed", p.output)
  712.  
  713.     def _gettags(self):
  714.         self.checkrepo()
  715.         p = FDroidPopen(['git', 'tag'], cwd=self.local, output=False)
  716.         return p.output.splitlines()
  717.  
  718.     tag_format = re.compile(r'.*tag: ([^),]*).*')
  719.  
  720.     def latesttags(self):
  721.         self.checkrepo()
  722.         p = FDroidPopen(['git', 'log', '--tags',
  723.                          '--simplify-by-decoration', '--pretty=format:%d'],
  724.                         cwd=self.local, output=False)
  725.         tags = []
  726.         for line in p.output.splitlines():
  727.             m = self.tag_format.match(line)
  728.             if not m:
  729.                 continue
  730.             tag = m.group(1)
  731.             tags.append(tag)
  732.         return tags
  733.  
  734.  
  735. class vcs_gitsvn(vcs):
  736.  
  737.     def repotype(self):
  738.         return 'git-svn'
  739.  
  740.     # If the local directory exists, but is somehow not a git repository, git
  741.     # will traverse up the directory tree until it finds one that is (i.e.
  742.     # fdroidserver) and then we'll proceed to destory it! This is called as
  743.     # a safety check.
  744.     def checkrepo(self):
  745.         p = FDroidPopen(['git', 'rev-parse', '--show-toplevel'], cwd=self.local, output=False)
  746.         result = p.output.rstrip()
  747.         if not result.endswith(self.local):
  748.             raise VCSException('Repository mismatch')
  749.  
  750.     def gotorevisionx(self, rev):
  751.         if not os.path.exists(self.local):
  752.             # Brand new checkout
  753.             gitsvn_args = ['git', 'svn', 'clone']
  754.             if ';' in self.remote:
  755.                 remote_split = self.remote.split(';')
  756.                 for i in remote_split[1:]:
  757.                     if i.startswith('trunk='):
  758.                         gitsvn_args.extend(['-T', i[6:]])
  759.                     elif i.startswith('tags='):
  760.                         gitsvn_args.extend(['-t', i[5:]])
  761.                     elif i.startswith('branches='):
  762.                         gitsvn_args.extend(['-b', i[9:]])
  763.                 gitsvn_args.extend([remote_split[0], self.local])
  764.                 p = FDroidPopen(gitsvn_args, output=False)
  765.                 if p.returncode != 0:
  766.                     self.clone_failed = True
  767.                     raise VCSException("Git svn clone failed", p.output)
  768.             else:
  769.                 gitsvn_args.extend([self.remote, self.local])
  770.                 p = FDroidPopen(gitsvn_args, output=False)
  771.                 if p.returncode != 0:
  772.                     self.clone_failed = True
  773.                     raise VCSException("Git svn clone failed", p.output)
  774.             self.checkrepo()
  775.         else:
  776.             self.checkrepo()
  777.             # Discard any working tree changes
  778.             p = FDroidPopen(['git', 'reset', '--hard'], cwd=self.local, output=False)
  779.             if p.returncode != 0:
  780.                 raise VCSException("Git reset failed", p.output)
  781.             # Remove untracked files now, in case they're tracked in the target
  782.             # revision (it happens!)
  783.             p = FDroidPopen(['git', 'clean', '-dffx'], cwd=self.local, output=False)
  784.             if p.returncode != 0:
  785.                 raise VCSException("Git clean failed", p.output)
  786.             if not self.refreshed:
  787.                 # Get new commits, branches and tags from repo
  788.                 p = FDroidPopen(['git', 'svn', 'fetch'], cwd=self.local, output=False)
  789.                 if p.returncode != 0:
  790.                     raise VCSException("Git svn fetch failed")
  791.                 p = FDroidPopen(['git', 'svn', 'rebase'], cwd=self.local, output=False)
  792.                 if p.returncode != 0:
  793.                     raise VCSException("Git svn rebase failed", p.output)
  794.                 self.refreshed = True
  795.  
  796.         rev = rev or 'master'
  797.         if rev:
  798.             nospaces_rev = rev.replace(' ', '%20')
  799.             # Try finding a svn tag
  800.             for treeish in ['origin/', '']:
  801.                 p = FDroidPopen(['git', 'checkout', treeish + 'tags/' + nospaces_rev], cwd=self.local, output=False)
  802.                 if p.returncode == 0:
  803.                     break
  804.             if p.returncode != 0:
  805.                 # No tag found, normal svn rev translation
  806.                 # Translate svn rev into git format
  807.                 rev_split = rev.split('/')
  808.  
  809.                 p = None
  810.                 for treeish in ['origin/', '']:
  811.                     if len(rev_split) > 1:
  812.                         treeish += rev_split[0]
  813.                         svn_rev = rev_split[1]
  814.  
  815.                     else:
  816.                         # if no branch is specified, then assume trunk (i.e. 'master' branch):
  817.                         treeish += 'master'
  818.                         svn_rev = rev
  819.  
  820.                     svn_rev = svn_rev if svn_rev[0] == 'r' else 'r' + svn_rev
  821.  
  822.                     p = FDroidPopen(['git', 'svn', 'find-rev', '--before', svn_rev, treeish], cwd=self.local, output=False)
  823.                     git_rev = p.output.rstrip()
  824.  
  825.                     if p.returncode == 0 and git_rev:
  826.                         break
  827.  
  828.                 if p.returncode != 0 or not git_rev:
  829.                     # Try a plain git checkout as a last resort
  830.                     p = FDroidPopen(['git', 'checkout', rev], cwd=self.local, output=False)
  831.                     if p.returncode != 0:
  832.                         raise VCSException("No git treeish found and direct git checkout of '%s' failed" % rev, p.output)
  833.                 else:
  834.                     # Check out the git rev equivalent to the svn rev
  835.                     p = FDroidPopen(['git', 'checkout', git_rev], cwd=self.local, output=False)
  836.                     if p.returncode != 0:
  837.                         raise VCSException("Git checkout of '%s' failed" % rev, p.output)
  838.  
  839.         # Get rid of any uncontrolled files left behind
  840.         p = FDroidPopen(['git', 'clean', '-dffx'], cwd=self.local, output=False)
  841.         if p.returncode != 0:
  842.             raise VCSException("Git clean failed", p.output)
  843.  
  844.     def _gettags(self):
  845.         self.checkrepo()
  846.         for treeish in ['origin/', '']:
  847.             d = os.path.join(self.local, '.git', 'svn', 'refs', 'remotes', treeish, 'tags')
  848.             if os.path.isdir(d):
  849.                 return os.listdir(d)
  850.  
  851.     def getref(self):
  852.         self.checkrepo()
  853.         p = FDroidPopen(['git', 'svn', 'find-rev', 'HEAD'], cwd=self.local, output=False)
  854.         if p.returncode != 0:
  855.             return None
  856.         return p.output.strip()
  857.  
  858.  
  859. class vcs_hg(vcs):
  860.  
  861.     def repotype(self):
  862.         return 'hg'
  863.  
  864.     def gotorevisionx(self, rev):
  865.         if not os.path.exists(self.local):
  866.             p = FDroidPopen(['hg', 'clone', self.remote, self.local], output=False)
  867.             if p.returncode != 0:
  868.                 self.clone_failed = True
  869.                 raise VCSException("Hg clone failed", p.output)
  870.         else:
  871.             p = FDroidPopen(['hg', 'status', '-uS'], cwd=self.local, output=False)
  872.             if p.returncode != 0:
  873.                 raise VCSException("Hg status failed", p.output)
  874.             for line in p.output.splitlines():
  875.                 if not line.startswith('? '):
  876.                     raise VCSException("Unexpected output from hg status -uS: " + line)
  877.                 FDroidPopen(['rm', '-rf', line[2:]], cwd=self.local, output=False)
  878.             if not self.refreshed:
  879.                 p = FDroidPopen(['hg', 'pull'], cwd=self.local, output=False)
  880.                 if p.returncode != 0:
  881.                     raise VCSException("Hg pull failed", p.output)
  882.                 self.refreshed = True
  883.  
  884.         rev = rev or 'default'
  885.         if not rev:
  886.             return
  887.         p = FDroidPopen(['hg', 'update', '-C', rev], cwd=self.local, output=False)
  888.         if p.returncode != 0:
  889.             raise VCSException("Hg checkout of '%s' failed" % rev, p.output)
  890.         p = FDroidPopen(['hg', 'purge', '--all'], cwd=self.local, output=False)
  891.         # Also delete untracked files, we have to enable purge extension for that:
  892.         if "'purge' is provided by the following extension" in p.output:
  893.             with open(os.path.join(self.local, '.hg', 'hgrc'), "a") as myfile:
  894.                 myfile.write("\n[extensions]\nhgext.purge=\n")
  895.             p = FDroidPopen(['hg', 'purge', '--all'], cwd=self.local, output=False)
  896.             if p.returncode != 0:
  897.                 raise VCSException("HG purge failed", p.output)
  898.         elif p.returncode != 0:
  899.             raise VCSException("HG purge failed", p.output)
  900.  
  901.     def _gettags(self):
  902.         p = FDroidPopen(['hg', 'tags', '-q'], cwd=self.local, output=False)
  903.         return p.output.splitlines()[1:]
  904.  
  905.  
  906. class vcs_bzr(vcs):
  907.  
  908.     def repotype(self):
  909.         return 'bzr'
  910.  
  911.     def gotorevisionx(self, rev):
  912.         if not os.path.exists(self.local):
  913.             p = FDroidPopen(['bzr', 'branch', self.remote, self.local], output=False)
  914.             if p.returncode != 0:
  915.                 self.clone_failed = True
  916.                 raise VCSException("Bzr branch failed", p.output)
  917.         else:
  918.             p = FDroidPopen(['bzr', 'clean-tree', '--force', '--unknown', '--ignored'], cwd=self.local, output=False)
  919.             if p.returncode != 0:
  920.                 raise VCSException("Bzr revert failed", p.output)
  921.             if not self.refreshed:
  922.                 p = FDroidPopen(['bzr', 'pull'], cwd=self.local, output=False)
  923.                 if p.returncode != 0:
  924.                     raise VCSException("Bzr update failed", p.output)
  925.                 self.refreshed = True
  926.  
  927.         revargs = list(['-r', rev] if rev else [])
  928.         p = FDroidPopen(['bzr', 'revert'] + revargs, cwd=self.local, output=False)
  929.         if p.returncode != 0:
  930.             raise VCSException("Bzr revert of '%s' failed" % rev, p.output)
  931.  
  932.     def _gettags(self):
  933.         p = FDroidPopen(['bzr', 'tags'], cwd=self.local, output=False)
  934.         return [tag.split('   ')[0].strip() for tag in
  935.                 p.output.splitlines()]
  936.  
  937.  
  938. def unescape_string(string):
  939.     if len(string) < 2:
  940.         return string
  941.     if string[0] == '"' and string[-1] == '"':
  942.         return string[1:-1]
  943.  
  944.     return string.replace("\\'", "'")
  945.  
  946.  
  947. def retrieve_string(app_dir, string, xmlfiles=None):
  948.  
  949.     if not string.startswith('@string/'):
  950.         return unescape_string(string)
  951.  
  952.     if xmlfiles is None:
  953.         xmlfiles = []
  954.         for res_dir in [
  955.             os.path.join(app_dir, 'res'),
  956.             os.path.join(app_dir, 'src', 'main', 'res'),
  957.         ]:
  958.             for r, d, f in os.walk(res_dir):
  959.                 if os.path.basename(r) == 'values':
  960.                     xmlfiles += [os.path.join(r, x) for x in f if x.endswith('.xml')]
  961.  
  962.     name = string[len('@string/'):]
  963.  
  964.     def element_content(element):
  965.         if element.text is None:
  966.             return ""
  967.         s = XMLElementTree.tostring(element, encoding='utf-8', method='text')
  968.         return s.decode('utf-8').strip()
  969.  
  970.     for path in xmlfiles:
  971.         if not os.path.isfile(path):
  972.             continue
  973.         xml = parse_xml(path)
  974.         element = xml.find('string[@name="' + name + '"]')
  975.         if element is not None:
  976.             content = element_content(element)
  977.             return retrieve_string(app_dir, content, xmlfiles)
  978.  
  979.     return ''
  980.  
  981.  
  982. def retrieve_string_singleline(app_dir, string, xmlfiles=None):
  983.     return retrieve_string(app_dir, string, xmlfiles).replace('\n', ' ').strip()
  984.  
  985.  
  986. # Return list of existing files that will be used to find the highest vercode
  987. def manifest_paths(app_dir, flavours):
  988.  
  989.     possible_manifests = \
  990.         [os.path.join(app_dir, 'AndroidManifest.xml'),
  991.          os.path.join(app_dir, 'src', 'main', 'AndroidManifest.xml'),
  992.          os.path.join(app_dir, 'src', 'AndroidManifest.xml'),
  993.          os.path.join(app_dir, 'build.gradle')]
  994.  
  995.     for flavour in flavours:
  996.         if flavour == 'yes':
  997.             continue
  998.         possible_manifests.append(
  999.             os.path.join(app_dir, 'src', flavour, 'AndroidManifest.xml'))
  1000.  
  1001.     return [path for path in possible_manifests if os.path.isfile(path)]
  1002.  
  1003.  
  1004. # Retrieve the package name. Returns the name, or None if not found.
  1005. def fetch_real_name(app_dir, flavours):
  1006.     for path in manifest_paths(app_dir, flavours):
  1007.         if not has_extension(path, 'xml') or not os.path.isfile(path):
  1008.             continue
  1009.         logging.debug("fetch_real_name: Checking manifest at " + path)
  1010.         xml = parse_xml(path)
  1011.         app = xml.find('application')
  1012.         if app is None:
  1013.             continue
  1014.         if "{http://schemas.android.com/apk/res/android}label" not in app.attrib:
  1015.             continue
  1016.         label = app.attrib["{http://schemas.android.com/apk/res/android}label"]
  1017.         result = retrieve_string_singleline(app_dir, label)
  1018.         if result:
  1019.             result = result.strip()
  1020.         return result
  1021.     return None
  1022.  
  1023.  
  1024. def get_library_references(root_dir):
  1025.     libraries = []
  1026.     proppath = os.path.join(root_dir, 'project.properties')
  1027.     if not os.path.isfile(proppath):
  1028.         return libraries
  1029.     with open(proppath, 'r') as f:
  1030.         for line in f:
  1031.             if not line.startswith('android.library.reference.'):
  1032.                 continue
  1033.             path = line.split('=')[1].strip()
  1034.             relpath = os.path.join(root_dir, path)
  1035.             if not os.path.isdir(relpath):
  1036.                 continue
  1037.             logging.debug("Found subproject at %s" % path)
  1038.             libraries.append(path)
  1039.     return libraries
  1040.  
  1041.  
  1042. def ant_subprojects(root_dir):
  1043.     subprojects = get_library_references(root_dir)
  1044.     for subpath in subprojects:
  1045.         subrelpath = os.path.join(root_dir, subpath)
  1046.         for p in get_library_references(subrelpath):
  1047.             relp = os.path.normpath(os.path.join(subpath, p))
  1048.             if relp not in subprojects:
  1049.                 subprojects.insert(0, relp)
  1050.     return subprojects
  1051.  
  1052.  
  1053. def remove_debuggable_flags(root_dir):
  1054.     # Remove forced debuggable flags
  1055.     logging.debug("Removing debuggable flags from %s" % root_dir)
  1056.     for root, dirs, files in os.walk(root_dir):
  1057.         if 'AndroidManifest.xml' in files:
  1058.             regsub_file(r'android:debuggable="[^"]*"',
  1059.                         '',
  1060.                         os.path.join(root, 'AndroidManifest.xml'))
  1061.  
  1062.  
  1063. vcsearch_g = re.compile(r'.*versionCode *=* *["\']*([0-9]+)["\']*').search
  1064. vnsearch_g = re.compile(r'.*versionName *=* *(["\'])((?:(?=(\\?))\3.)*?)\1.*').search
  1065. psearch_g = re.compile(r'.*(packageName|applicationId) *=* *["\']([^"]+)["\'].*').search
  1066.  
  1067.  
  1068. def app_matches_packagename(app, package):
  1069.     if not package:
  1070.         return False
  1071.     appid = app.UpdateCheckName or app.id
  1072.     if appid is None or appid == "Ignore":
  1073.         return True
  1074.     return appid == package
  1075.  
  1076.  
  1077. # Extract some information from the AndroidManifest.xml at the given path.
  1078. # Returns (version, vercode, package), any or all of which might be None.
  1079. # All values returned are strings.
  1080. def parse_androidmanifests(paths, app):
  1081.  
  1082.     ignoreversions = app.UpdateCheckIgnore
  1083.     ignoresearch = re.compile(ignoreversions).search if ignoreversions else None
  1084.  
  1085.     if not paths:
  1086.         return (None, None, None)
  1087.  
  1088.     max_version = None
  1089.     max_vercode = None
  1090.     max_package = None
  1091.  
  1092.     for path in paths:
  1093.  
  1094.         if not os.path.isfile(path):
  1095.             continue
  1096.  
  1097.         logging.debug("Parsing manifest at {0}".format(path))
  1098.         gradle = has_extension(path, 'gradle')
  1099.         version = None
  1100.         vercode = None
  1101.         package = None
  1102.  
  1103.         if gradle:
  1104.             with open(path, 'r') as f:
  1105.                 for line in f:
  1106.                     if gradle_comment.match(line):
  1107.                         continue
  1108.                     # Grab first occurence of each to avoid running into
  1109.                     # alternative flavours and builds.
  1110.                     if not package:
  1111.                         matches = psearch_g(line)
  1112.                         if matches:
  1113.                             s = matches.group(2)
  1114.                             if app_matches_packagename(app, s):
  1115.                                 package = s
  1116.                     if not version:
  1117.                         matches = vnsearch_g(line)
  1118.                         if matches:
  1119.                             version = matches.group(2)
  1120.                     if not vercode:
  1121.                         matches = vcsearch_g(line)
  1122.                         if matches:
  1123.                             vercode = matches.group(1)
  1124.         else:
  1125.             try:
  1126.                 xml = parse_xml(path)
  1127.                 if "package" in xml.attrib:
  1128.                     s = xml.attrib["package"]
  1129.                     if app_matches_packagename(app, s):
  1130.                         package = s
  1131.                 if "{http://schemas.android.com/apk/res/android}versionName" in xml.attrib:
  1132.                     version = xml.attrib["{http://schemas.android.com/apk/res/android}versionName"]
  1133.                     base_dir = os.path.dirname(path)
  1134.                     version = retrieve_string_singleline(base_dir, version)
  1135.                 if "{http://schemas.android.com/apk/res/android}versionCode" in xml.attrib:
  1136.                     a = xml.attrib["{http://schemas.android.com/apk/res/android}versionCode"]
  1137.                     if string_is_integer(a):
  1138.                         vercode = a
  1139.             except Exception:
  1140.                 logging.warning("Problem with xml at {0}".format(path))
  1141.  
  1142.         # Remember package name, may be defined separately from version+vercode
  1143.         if package is None:
  1144.             package = max_package
  1145.  
  1146.         logging.debug("..got package={0}, version={1}, vercode={2}"
  1147.                       .format(package, version, vercode))
  1148.  
  1149.         # Always grab the package name and version name in case they are not
  1150.         # together with the highest version code
  1151.         if max_package is None and package is not None:
  1152.             max_package = package
  1153.         if max_version is None and version is not None:
  1154.             max_version = version
  1155.  
  1156.         if max_vercode is None or (vercode is not None and vercode > max_vercode):
  1157.             if not ignoresearch or not ignoresearch(version):
  1158.                 if version is not None:
  1159.                     max_version = version
  1160.                 if vercode is not None:
  1161.                     max_vercode = vercode
  1162.                 if package is not None:
  1163.                     max_package = package
  1164.             else:
  1165.                 max_version = "Ignore"
  1166.  
  1167.     if max_version is None:
  1168.         max_version = "Unknown"
  1169.  
  1170.     if max_package and not is_valid_package_name(max_package):
  1171.         raise FDroidException("Invalid package name {0}".format(max_package))
  1172.  
  1173.     return (max_version, max_vercode, max_package)
  1174.  
  1175.  
  1176. def is_valid_package_name(name):
  1177.     return re.match("[A-Za-z_][A-Za-z_0-9.]+$", name)
  1178.  
  1179.  
  1180. class FDroidException(Exception):
  1181.  
  1182.     def __init__(self, value, detail=None):
  1183.         self.value = value
  1184.         self.detail = detail
  1185.  
  1186.     def shortened_detail(self):
  1187.         if len(self.detail) < 16000:
  1188.             return self.detail
  1189.         return '[...]\n' + self.detail[-16000:]
  1190.  
  1191.     def get_wikitext(self):
  1192.         ret = repr(self.value) + "\n"
  1193.         if self.detail:
  1194.             ret += "=detail=\n"
  1195.             ret += "<pre>\n" + self.shortened_detail() + "</pre>\n"
  1196.         return ret
  1197.  
  1198.     def __str__(self):
  1199.         ret = self.value
  1200.         if self.detail:
  1201.             ret += "\n==== detail begin ====\n%s\n==== detail end ====" % self.detail.strip()
  1202.         return ret
  1203.  
  1204.  
  1205. class VCSException(FDroidException):
  1206.     pass
  1207.  
  1208.  
  1209. class BuildException(FDroidException):
  1210.     pass
  1211.  
  1212.  
  1213. # Get the specified source library.
  1214. # Returns the path to it. Normally this is the path to be used when referencing
  1215. # it, which may be a subdirectory of the actual project. If you want the base
  1216. # directory of the project, pass 'basepath=True'.
  1217. def getsrclib(spec, srclib_dir, subdir=None, basepath=False,
  1218.               raw=False, prepare=True, preponly=False, refresh=True):
  1219.  
  1220.     number = None
  1221.     subdir = None
  1222.     if raw:
  1223.         name = spec
  1224.         ref = None
  1225.     else:
  1226.         name, ref = spec.split('@')
  1227.         if ':' in name:
  1228.             number, name = name.split(':', 1)
  1229.         if '/' in name:
  1230.             name, subdir = name.split('/', 1)
  1231.  
  1232.     if name not in fdroidserver.metadata.srclibs:
  1233.         raise VCSException('srclib ' + name + ' not found.')
  1234.  
  1235.     srclib = fdroidserver.metadata.srclibs[name]
  1236.  
  1237.     sdir = os.path.join(srclib_dir, name)
  1238.  
  1239.     if not preponly:
  1240.         vcs = getvcs(srclib["Repo Type"], srclib["Repo"], sdir)
  1241.         vcs.srclib = (name, number, sdir)
  1242.         if ref:
  1243.             vcs.gotorevision(ref, refresh)
  1244.  
  1245.         if raw:
  1246.             return vcs
  1247.  
  1248.     libdir = None
  1249.     if subdir:
  1250.         libdir = os.path.join(sdir, subdir)
  1251.     elif srclib["Subdir"]:
  1252.         for subdir in srclib["Subdir"]:
  1253.             libdir_candidate = os.path.join(sdir, subdir)
  1254.             if os.path.exists(libdir_candidate):
  1255.                 libdir = libdir_candidate
  1256.                 break
  1257.  
  1258.     if libdir is None:
  1259.         libdir = sdir
  1260.  
  1261.     remove_signing_keys(sdir)
  1262.     remove_debuggable_flags(sdir)
  1263.  
  1264.     if prepare:
  1265.  
  1266.         if srclib["Prepare"]:
  1267.             cmd = replace_config_vars(srclib["Prepare"], None)
  1268.  
  1269.             p = FDroidPopen(['bash', '-x', '-c', cmd], cwd=libdir)
  1270.             if p.returncode != 0:
  1271.                 raise BuildException("Error running prepare command for srclib %s"
  1272.                                      % name, p.output)
  1273.  
  1274.     if basepath:
  1275.         libdir = sdir
  1276.  
  1277.     return (name, number, libdir)
  1278.  
  1279. gradle_version_regex = re.compile(r"[^/]*'com\.android\.tools\.build:gradle:([^\.]+\.[^\.]+).*'.*")
  1280.  
  1281.  
  1282. # Prepare the source code for a particular build
  1283. #  'vcs'         - the appropriate vcs object for the application
  1284. #  'app'         - the application details from the metadata
  1285. #  'build'       - the build details from the metadata
  1286. #  'build_dir'   - the path to the build directory, usually
  1287. #                   'build/app.id'
  1288. #  'srclib_dir'  - the path to the source libraries directory, usually
  1289. #                   'build/srclib'
  1290. #  'extlib_dir'  - the path to the external libraries directory, usually
  1291. #                   'build/extlib'
  1292. # Returns the (root, srclibpaths) where:
  1293. #   'root' is the root directory, which may be the same as 'build_dir' or may
  1294. #          be a subdirectory of it.
  1295. #   'srclibpaths' is information on the srclibs being used
  1296. def prepare_source(vcs, app, build, build_dir, srclib_dir, extlib_dir, onserver=False, refresh=True):
  1297.  
  1298.     # Optionally, the actual app source can be in a subdirectory
  1299.     if build.subdir:
  1300.         root_dir = os.path.join(build_dir, build.subdir)
  1301.     else:
  1302.         root_dir = build_dir
  1303.  
  1304.     # Get a working copy of the right revision
  1305.     logging.info("Getting source for revision " + build.commit)
  1306.     vcs.gotorevision(build.commit, refresh)
  1307.  
  1308.     # Initialise submodules if required
  1309.     if build.submodules:
  1310.         logging.info("Initialising submodules")
  1311.         vcs.initsubmodules()
  1312.  
  1313.     # Check that a subdir (if we're using one) exists. This has to happen
  1314.     # after the checkout, since it might not exist elsewhere
  1315.     if not os.path.exists(root_dir):
  1316.         raise BuildException('Missing subdir ' + root_dir)
  1317.  
  1318.     # Run an init command if one is required
  1319.     if build.init:
  1320.         cmd = replace_config_vars(build.init, build)
  1321.         logging.info("Running 'init' commands in %s" % root_dir)
  1322.  
  1323.         p = FDroidPopen(['bash', '-x', '-c', cmd], cwd=root_dir)
  1324.         if p.returncode != 0:
  1325.             raise BuildException("Error running init command for %s:%s" %
  1326.                                  (app.id, build.version), p.output)
  1327.  
  1328.     # Apply patches if any
  1329.     if build.patch:
  1330.         logging.info("Applying patches")
  1331.         for patch in build.patch:
  1332.             patch = patch.strip()
  1333.             logging.info("Applying " + patch)
  1334.             patch_path = os.path.join('metadata', app.id, patch)
  1335.             p = FDroidPopen(['patch', '-p1', '-i', os.path.abspath(patch_path)], cwd=build_dir)
  1336.             if p.returncode != 0:
  1337.                 raise BuildException("Failed to apply patch %s" % patch_path)
  1338.  
  1339.     # Get required source libraries
  1340.     srclibpaths = []
  1341.     if build.srclibs:
  1342.         logging.info("Collecting source libraries")
  1343.         for lib in build.srclibs:
  1344.             srclibpaths.append(getsrclib(lib, srclib_dir, build, preponly=onserver, refresh=refresh))
  1345.  
  1346.     for name, number, libpath in srclibpaths:
  1347.         place_srclib(root_dir, int(number) if number else None, libpath)
  1348.  
  1349.     basesrclib = vcs.getsrclib()
  1350.     # If one was used for the main source, add that too.
  1351.     if basesrclib:
  1352.         srclibpaths.append(basesrclib)
  1353.  
  1354.     # Update the local.properties file
  1355.     localprops = [os.path.join(build_dir, 'local.properties')]
  1356.     if build.subdir:
  1357.         parts = build.subdir.split(os.sep)
  1358.         cur = build_dir
  1359.         for d in parts:
  1360.             cur = os.path.join(cur, d)
  1361.             localprops += [os.path.join(cur, 'local.properties')]
  1362.     for path in localprops:
  1363.         props = ""
  1364.         if os.path.isfile(path):
  1365.             logging.info("Updating local.properties file at %s" % path)
  1366.             with open(path, 'r') as f:
  1367.                 props += f.read()
  1368.             props += '\n'
  1369.         else:
  1370.             logging.info("Creating local.properties file at %s" % path)
  1371.         # Fix old-fashioned 'sdk-location' by copying
  1372.         # from sdk.dir, if necessary
  1373.         if build.oldsdkloc:
  1374.             sdkloc = re.match(r".*^sdk.dir=(\S+)$.*", props,
  1375.                               re.S | re.M).group(1)
  1376.             props += "sdk-location=%s\n" % sdkloc
  1377.         else:
  1378.             props += "sdk.dir=%s\n" % config['sdk_path']
  1379.             props += "sdk-location=%s\n" % config['sdk_path']
  1380.         ndk_path = build.ndk_path()
  1381.         if ndk_path:
  1382.             # Add ndk location
  1383.             props += "ndk.dir=%s\n" % ndk_path
  1384.             props += "ndk-location=%s\n" % ndk_path
  1385.         # Add java.encoding if necessary
  1386.         if build.encoding:
  1387.             props += "java.encoding=%s\n" % build.encoding
  1388.         with open(path, 'w') as f:
  1389.             f.write(props)
  1390.  
  1391.     flavours = []
  1392.     if build.build_method() == 'gradle':
  1393.         flavours = build.gradle
  1394.  
  1395.         if build.target:
  1396.             n = build.target.split('-')[1]
  1397.             regsub_file(r'compileSdkVersion[ =]+[0-9]+',
  1398.                         r'compileSdkVersion %s' % n,
  1399.                         os.path.join(root_dir, 'build.gradle'))
  1400.  
  1401.     # Remove forced debuggable flags
  1402.     remove_debuggable_flags(root_dir)
  1403.  
  1404.     # Insert version code and number into the manifest if necessary
  1405.     if build.forceversion:
  1406.         logging.info("Changing the version name")
  1407.         for path in manifest_paths(root_dir, flavours):
  1408.             if not os.path.isfile(path):
  1409.                 continue
  1410.             if has_extension(path, 'xml'):
  1411.                 regsub_file(r'android:versionName="[^"]*"',
  1412.                             r'android:versionName="%s"' % build.version,
  1413.                             path)
  1414.             elif has_extension(path, 'gradle'):
  1415.                 regsub_file(r"""(\s*)versionName[\s'"=]+.*""",
  1416.                             r"""\1versionName '%s'""" % build.version,
  1417.                             path)
  1418.  
  1419.     if build.forcevercode:
  1420.         logging.info("Changing the version code")
  1421.         for path in manifest_paths(root_dir, flavours):
  1422.             if not os.path.isfile(path):
  1423.                 continue
  1424.             if has_extension(path, 'xml'):
  1425.                 regsub_file(r'android:versionCode="[^"]*"',
  1426.                             r'android:versionCode="%s"' % build.vercode,
  1427.                             path)
  1428.             elif has_extension(path, 'gradle'):
  1429.                 regsub_file(r'versionCode[ =]+[0-9]+',
  1430.                             r'versionCode %s' % build.vercode,
  1431.                             path)
  1432.  
  1433.     # Delete unwanted files
  1434.     if build.rm:
  1435.         logging.info("Removing specified files")
  1436.         for part in getpaths(build_dir, build.rm):
  1437.             dest = os.path.join(build_dir, part)
  1438.             logging.info("Removing {0}".format(part))
  1439.             if os.path.lexists(dest):
  1440.                 if os.path.islink(dest):
  1441.                     FDroidPopen(['unlink', dest], output=False)
  1442.                 else:
  1443.                     FDroidPopen(['rm', '-rf', dest], output=False)
  1444.             else:
  1445.                 logging.info("...but it didn't exist")
  1446.  
  1447.     remove_signing_keys(build_dir)
  1448.  
  1449.     # Add required external libraries
  1450.     if build.extlibs:
  1451.         logging.info("Collecting prebuilt libraries")
  1452.         libsdir = os.path.join(root_dir, 'libs')
  1453.         if not os.path.exists(libsdir):
  1454.             os.mkdir(libsdir)
  1455.         for lib in build.extlibs:
  1456.             lib = lib.strip()
  1457.             logging.info("...installing extlib {0}".format(lib))
  1458.             libf = os.path.basename(lib)
  1459.             libsrc = os.path.join(extlib_dir, lib)
  1460.             if not os.path.exists(libsrc):
  1461.                 raise BuildException("Missing extlib file {0}".format(libsrc))
  1462.             shutil.copyfile(libsrc, os.path.join(libsdir, libf))
  1463.  
  1464.     # Run a pre-build command if one is required
  1465.     if build.prebuild:
  1466.         logging.info("Running 'prebuild' commands in %s" % root_dir)
  1467.  
  1468.         cmd = replace_config_vars(build.prebuild, build)
  1469.  
  1470.         # Substitute source library paths into prebuild commands
  1471.         for name, number, libpath in srclibpaths:
  1472.             libpath = os.path.relpath(libpath, root_dir)
  1473.             cmd = cmd.replace('$$' + name + '$$', libpath)
  1474.  
  1475.         p = FDroidPopen(['bash', '-x', '-c', cmd], cwd=root_dir)
  1476.         if p.returncode != 0:
  1477.             raise BuildException("Error running prebuild command for %s:%s" %
  1478.                                  (app.id, build.version), p.output)
  1479.  
  1480.     # Generate (or update) the ant build file, build.xml...
  1481.     if build.build_method() == 'ant' and build.update != ['no']:
  1482.         parms = ['android', 'update', 'lib-project']
  1483.         lparms = ['android', 'update', 'project']
  1484.  
  1485.         if build.target:
  1486.             parms += ['-t', build.target]
  1487.             lparms += ['-t', build.target]
  1488.         if build.update:
  1489.             update_dirs = build.update
  1490.         else:
  1491.             update_dirs = ant_subprojects(root_dir) + ['.']
  1492.  
  1493.         for d in update_dirs:
  1494.             subdir = os.path.join(root_dir, d)
  1495.             if d == '.':
  1496.                 logging.debug("Updating main project")
  1497.                 cmd = parms + ['-p', d]
  1498.             else:
  1499.                 logging.debug("Updating subproject %s" % d)
  1500.                 cmd = lparms + ['-p', d]
  1501.             p = SdkToolsPopen(cmd, cwd=root_dir)
  1502.             # Check to see whether an error was returned without a proper exit
  1503.             # code (this is the case for the 'no target set or target invalid'
  1504.             # error)
  1505.             if p.returncode != 0 or p.output.startswith("Error: "):
  1506.                 raise BuildException("Failed to update project at %s" % d, p.output)
  1507.             # Clean update dirs via ant
  1508.             if d != '.':
  1509.                 logging.info("Cleaning subproject %s" % d)
  1510.                 p = FDroidPopen(['ant', 'clean'], cwd=subdir)
  1511.  
  1512.     return (root_dir, srclibpaths)
  1513.  
  1514.  
  1515. # Extend via globbing the paths from a field and return them as a map from
  1516. # original path to resulting paths
  1517. def getpaths_map(build_dir, globpaths):
  1518.     paths = dict()
  1519.     for p in globpaths:
  1520.         p = p.strip()
  1521.         full_path = os.path.join(build_dir, p)
  1522.         full_path = os.path.normpath(full_path)
  1523.         paths[p] = [r[len(build_dir) + 1:] for r in glob.glob(full_path)]
  1524.         if not paths[p]:
  1525.             raise FDroidException("glob path '%s' did not match any files/dirs" % p)
  1526.     return paths
  1527.  
  1528.  
  1529. # Extend via globbing the paths from a field and return them as a set
  1530. def getpaths(build_dir, globpaths):
  1531.     paths_map = getpaths_map(build_dir, globpaths)
  1532.     paths = set()
  1533.     for k, v in paths_map.items():
  1534.         for p in v:
  1535.             paths.add(p)
  1536.     return paths
  1537.  
  1538.  
  1539. def natural_key(s):
  1540.     return [int(sp) if sp.isdigit() else sp for sp in re.split(r'(\d+)', s)]
  1541.  
  1542.  
  1543. class KnownApks:
  1544.  
  1545.     def __init__(self):
  1546.         self.path = os.path.join('stats', 'known_apks.txt')
  1547.         self.apks = {}
  1548.         if os.path.isfile(self.path):
  1549.             with open(self.path, 'r') as f:
  1550.                 for line in f:
  1551.                     t = line.rstrip().split(' ')
  1552.                     if len(t) == 2:
  1553.                         self.apks[t[0]] = (t[1], None)
  1554.                     else:
  1555.                         self.apks[t[0]] = (t[1], time.strptime(t[2], '%Y-%m-%d'))
  1556.         self.changed = False
  1557.  
  1558.     def writeifchanged(self):
  1559.         if not self.changed:
  1560.             return
  1561.  
  1562.         if not os.path.exists('stats'):
  1563.             os.mkdir('stats')
  1564.  
  1565.         lst = []
  1566.         for apk, app in self.apks.items():
  1567.             appid, added = app
  1568.             line = apk + ' ' + appid
  1569.             if added:
  1570.                 line += ' ' + time.strftime('%Y-%m-%d', added)
  1571.             lst.append(line)
  1572.  
  1573.         with open(self.path, 'w') as f:
  1574.             for line in sorted(lst, key=natural_key):
  1575.                 f.write(line + '\n')
  1576.  
  1577.     # Record an apk (if it's new, otherwise does nothing)
  1578.     # Returns the date it was added.
  1579.     def recordapk(self, apk, app):
  1580.         if apk not in self.apks:
  1581.             self.apks[apk] = (app, time.gmtime(time.time()))
  1582.             self.changed = True
  1583.         _, added = self.apks[apk]
  1584.         return added
  1585.  
  1586.     # Look up information - given the 'apkname', returns (app id, date added/None).
  1587.     # Or returns None for an unknown apk.
  1588.     def getapp(self, apkname):
  1589.         if apkname in self.apks:
  1590.             return self.apks[apkname]
  1591.         return None
  1592.  
  1593.     # Get the most recent 'num' apps added to the repo, as a list of package ids
  1594.     # with the most recent first.
  1595.     def getlatest(self, num):
  1596.         apps = {}
  1597.         for apk, app in self.apks.items():
  1598.             appid, added = app
  1599.             if added:
  1600.                 if appid in apps:
  1601.                     if apps[appid] > added:
  1602.                         apps[appid] = added
  1603.                 else:
  1604.                     apps[appid] = added
  1605.         sortedapps = sorted(apps.items(), key=operator.itemgetter(1))[-num:]
  1606.         lst = [app for app, _ in sortedapps]
  1607.         lst.reverse()
  1608.         return lst
  1609.  
  1610.  
  1611. def isApkDebuggable(apkfile, config):
  1612.     """Returns True if the given apk file is debuggable
  1613.  
  1614.    :param apkfile: full path to the apk to check"""
  1615.  
  1616.     p = SdkToolsPopen(['aapt', 'dump', 'xmltree', apkfile, 'AndroidManifest.xml'],
  1617.                       output=False)
  1618.     if p.returncode != 0:
  1619.         logging.critical("Failed to get apk manifest information")
  1620.         sys.exit(1)
  1621.     for line in p.output.splitlines():
  1622.         if 'android:debuggable' in line and not line.endswith('0x0'):
  1623.             return True
  1624.     return False
  1625.  
  1626.  
  1627. class PopenResult:
  1628.     def __init__(self):
  1629.         self.returncode = None
  1630.         self.output = None
  1631.  
  1632.  
  1633. def SdkToolsPopen(commands, cwd=None, output=True):
  1634.     cmd = commands[0]
  1635.     if cmd not in config:
  1636.         config[cmd] = find_sdk_tools_cmd(commands[0])
  1637.     abscmd = config[cmd]
  1638.     if abscmd is None:
  1639.         logging.critical("Could not find '%s' on your system" % cmd)
  1640.         sys.exit(1)
  1641.     return FDroidPopen([abscmd] + commands[1:],
  1642.                        cwd=cwd, output=output)
  1643.  
  1644.  
  1645. def FDroidPopenBytes(commands, cwd=None, output=True, stderr_to_stdout=True):
  1646.     """
  1647.    Run a command and capture the possibly huge output as bytes.
  1648.  
  1649.    :param commands: command and argument list like in subprocess.Popen
  1650.    :param cwd: optionally specifies a working directory
  1651.    :returns: A PopenResult.
  1652.    """
  1653.  
  1654.     global env
  1655.  
  1656.     if cwd:
  1657.         cwd = os.path.normpath(cwd)
  1658.         logging.debug("Directory: %s" % cwd)
  1659.     logging.debug("> %s" % ' '.join(commands))
  1660.  
  1661.     stderr_param = subprocess.STDOUT if stderr_to_stdout else subprocess.PIPE
  1662.     result = PopenResult()
  1663.     p = None
  1664.     try:
  1665.         p = subprocess.Popen(commands, cwd=cwd, shell=False, env=env,
  1666.                              stdout=subprocess.PIPE, stderr=stderr_param)
  1667.     except OSError as e:
  1668.         raise BuildException("OSError while trying to execute " +
  1669.                              ' '.join(commands) + ': ' + str(e))
  1670.  
  1671.     if not stderr_to_stdout and options.verbose:
  1672.         stderr_queue = Queue()
  1673.         stderr_reader = AsynchronousFileReader(p.stderr, stderr_queue)
  1674.  
  1675.         while not stderr_reader.eof():
  1676.             while not stderr_queue.empty():
  1677.                 line = stderr_queue.get()
  1678.                 sys.stderr.buffer.write(line)
  1679.                 sys.stderr.flush()
  1680.  
  1681.             time.sleep(0.1)
  1682.  
  1683.     stdout_queue = Queue()
  1684.     stdout_reader = AsynchronousFileReader(p.stdout, stdout_queue)
  1685.     buf = io.BytesIO()
  1686.  
  1687.     # Check the queue for output (until there is no more to get)
  1688.     while not stdout_reader.eof():
  1689.         while not stdout_queue.empty():
  1690.             line = stdout_queue.get()
  1691.             if output and options.verbose:
  1692.                 # Output directly to console
  1693.                 sys.stderr.buffer.write(line)
  1694.                 sys.stderr.flush()
  1695.             buf.write(line)
  1696.  
  1697.         time.sleep(0.1)
  1698.  
  1699.     result.returncode = p.wait()
  1700.     result.output = buf.getvalue()
  1701.     buf.close()
  1702.     return result
  1703.  
  1704.  
  1705. def FDroidPopen(commands, cwd=None, output=True, stderr_to_stdout=True):
  1706.     """
  1707.    Run a command and capture the possibly huge output as a str.
  1708.  
  1709.    :param commands: command and argument list like in subprocess.Popen
  1710.    :param cwd: optionally specifies a working directory
  1711.    :returns: A PopenResult.
  1712.    """
  1713.     result = FDroidPopenBytes(commands, cwd, output, stderr_to_stdout)
  1714.     result.output = result.output.decode('utf-8')
  1715.     return result
  1716.  
  1717.  
  1718. gradle_comment = re.compile(r'[ ]*//')
  1719. gradle_signing_configs = re.compile(r'^[\t ]*signingConfigs[ \t]*{[ \t]*$')
  1720. gradle_line_matches = [
  1721.     re.compile(r'^[\t ]*signingConfig [^ ]*$'),
  1722.     re.compile(r'.*android\.signingConfigs\.[^{]*$'),
  1723.     re.compile(r'.*\.readLine\(.*'),
  1724. ]
  1725.  
  1726.  
  1727. def remove_signing_keys(build_dir):
  1728.     for root, dirs, files in os.walk(build_dir):
  1729.         if 'build.gradle' in files:
  1730.             path = os.path.join(root, 'build.gradle')
  1731.  
  1732.             with open(path, "r") as o:
  1733.                 lines = o.readlines()
  1734.  
  1735.             changed = False
  1736.  
  1737.             opened = 0
  1738.             i = 0
  1739.             with open(path, "w") as o:
  1740.                 while i < len(lines):
  1741.                     line = lines[i]
  1742.                     i += 1
  1743.                     while line.endswith('\\\n'):
  1744.                         line = line.rstrip('\\\n') + lines[i]
  1745.                         i += 1
  1746.  
  1747.                     if gradle_comment.match(line):
  1748.                         o.write(line)
  1749.                         continue
  1750.  
  1751.                     if opened > 0:
  1752.                         opened += line.count('{')
  1753.                         opened -= line.count('}')
  1754.                         continue
  1755.  
  1756.                     if gradle_signing_configs.match(line):
  1757.                         changed = True
  1758.                         opened += 1
  1759.                         continue
  1760.  
  1761.                     if any(s.match(line) for s in gradle_line_matches):
  1762.                         changed = True
  1763.                         continue
  1764.  
  1765.                     if opened == 0:
  1766.                         o.write(line)
  1767.  
  1768.             if changed:
  1769.                 logging.info("Cleaned build.gradle of keysigning configs at %s" % path)
  1770.  
  1771.         for propfile in [
  1772.                 'project.properties',
  1773.                 'build.properties',
  1774.                 'default.properties',
  1775.                 'ant.properties', ]:
  1776.             if propfile in files:
  1777.                 path = os.path.join(root, propfile)
  1778.  
  1779.                 with open(path, "r") as o:
  1780.                     lines = o.readlines()
  1781.  
  1782.                 changed = False
  1783.  
  1784.                 with open(path, "w") as o:
  1785.                     for line in lines:
  1786.                         if any(line.startswith(s) for s in ('key.store', 'key.alias')):
  1787.                             changed = True
  1788.                             continue
  1789.  
  1790.                         o.write(line)
  1791.  
  1792.                 if changed:
  1793.                     logging.info("Cleaned %s of keysigning configs at %s" % (propfile, path))
  1794.  
  1795.  
  1796. def reset_env_path():
  1797.     global env, orig_path
  1798.     env['PATH'] = orig_path
  1799.  
  1800.  
  1801. def add_to_env_path(path):
  1802.     global env
  1803.     paths = env['PATH'].split(os.pathsep)
  1804.     if path in paths:
  1805.         return
  1806.     paths.append(path)
  1807.     env['PATH'] = os.pathsep.join(paths)
  1808.  
  1809.  
  1810. def replace_config_vars(cmd, build):
  1811.     global env
  1812.     cmd = cmd.replace('$$SDK$$', config['sdk_path'])
  1813.     # env['ANDROID_NDK'] is set in build_local right before prepare_source
  1814.     cmd = cmd.replace('$$NDK$$', env['ANDROID_NDK'])
  1815.     cmd = cmd.replace('$$MVN3$$', config['mvn3'])
  1816.     if build is not None:
  1817.         cmd = cmd.replace('$$COMMIT$$', build.commit)
  1818.         cmd = cmd.replace('$$VERSION$$', build.version)
  1819.         cmd = cmd.replace('$$VERCODE$$', build.vercode)
  1820.     return cmd
  1821.  
  1822.  
  1823. def place_srclib(root_dir, number, libpath):
  1824.     if not number:
  1825.         return
  1826.     relpath = os.path.relpath(libpath, root_dir)
  1827.     proppath = os.path.join(root_dir, 'project.properties')
  1828.  
  1829.     lines = []
  1830.     if os.path.isfile(proppath):
  1831.         with open(proppath, "r") as o:
  1832.             lines = o.readlines()
  1833.  
  1834.     with open(proppath, "w") as o:
  1835.         placed = False
  1836.         for line in lines:
  1837.             if line.startswith('android.library.reference.%d=' % number):
  1838.                 o.write('android.library.reference.%d=%s\n' % (number, relpath))
  1839.                 placed = True
  1840.             else:
  1841.                 o.write(line)
  1842.         if not placed:
  1843.             o.write('android.library.reference.%d=%s\n' % (number, relpath))
  1844.  
  1845. apk_sigfile = re.compile(r'META-INF/[0-9A-Za-z]+\.(SF|RSA)')
  1846.  
  1847.  
  1848. def verify_apks(signed_apk, unsigned_apk, tmp_dir):
  1849.     """Verify that two apks are the same
  1850.  
  1851.    One of the inputs is signed, the other is unsigned. The signature metadata
  1852.    is transferred from the signed to the unsigned apk, and then jarsigner is
  1853.    used to verify that the signature from the signed apk is also varlid for
  1854.    the unsigned one.
  1855.    :param signed_apk: Path to a signed apk file
  1856.    :param unsigned_apk: Path to an unsigned apk file expected to match it
  1857.    :param tmp_dir: Path to directory for temporary files
  1858.    :returns: None if the verification is successful, otherwise a string
  1859.              describing what went wrong.
  1860.    """
  1861.     with ZipFile(signed_apk) as signed_apk_as_zip:
  1862.         meta_inf_files = ['META-INF/MANIFEST.MF']
  1863.         for f in signed_apk_as_zip.namelist():
  1864.             if apk_sigfile.match(f):
  1865.                 meta_inf_files.append(f)
  1866.         if len(meta_inf_files) < 3:
  1867.             return "Signature files missing from {0}".format(signed_apk)
  1868.         signed_apk_as_zip.extractall(tmp_dir, meta_inf_files)
  1869.     with ZipFile(unsigned_apk, mode='a') as unsigned_apk_as_zip:
  1870.         for meta_inf_file in meta_inf_files:
  1871.             unsigned_apk_as_zip.write(os.path.join(tmp_dir, meta_inf_file), arcname=meta_inf_file)
  1872.  
  1873.     if subprocess.call([config['jarsigner'], '-verify', unsigned_apk]) != 0:
  1874.         logging.info("...NOT verified - {0}".format(signed_apk))
  1875.         return compare_apks(signed_apk, unsigned_apk, tmp_dir)
  1876.     logging.info("...successfully verified")
  1877.     return None
  1878.  
  1879. apk_badchars = re.compile('''[/ :;'"]''')
  1880.  
  1881.  
  1882. def compare_apks(apk1, apk2, tmp_dir):
  1883.     """Compare two apks
  1884.  
  1885.    Returns None if the apk content is the same (apart from the signing key),
  1886.    otherwise a string describing what's different, or what went wrong when
  1887.    trying to do the comparison.
  1888.    """
  1889.  
  1890.     apk1dir = os.path.join(tmp_dir, apk_badchars.sub('_', apk1[0:-4]))  # trim .apk
  1891.     apk2dir = os.path.join(tmp_dir, apk_badchars.sub('_', apk2[0:-4]))  # trim .apk
  1892.     for d in [apk1dir, apk2dir]:
  1893.         if os.path.exists(d):
  1894.             shutil.rmtree(d)
  1895.         os.mkdir(d)
  1896.         os.mkdir(os.path.join(d, 'jar-xf'))
  1897.  
  1898.     if subprocess.call(['jar', 'xf',
  1899.                         os.path.abspath(apk1)],
  1900.                        cwd=os.path.join(apk1dir, 'jar-xf')) != 0:
  1901.         return("Failed to unpack " + apk1)
  1902.     if subprocess.call(['jar', 'xf',
  1903.                         os.path.abspath(apk2)],
  1904.                        cwd=os.path.join(apk2dir, 'jar-xf')) != 0:
  1905.         return("Failed to unpack " + apk2)
  1906.  
  1907.     # try to find apktool in the path, if it hasn't been manually configed
  1908.     if 'apktool' not in config:
  1909.         tmp = find_command('apktool')
  1910.         if tmp is not None:
  1911.             config['apktool'] = tmp
  1912.     if 'apktool' in config:
  1913.         if subprocess.call([config['apktool'], 'd', os.path.abspath(apk1), '--output', 'apktool'],
  1914.                            cwd=apk1dir) != 0:
  1915.             return("Failed to unpack " + apk1)
  1916.         if subprocess.call([config['apktool'], 'd', os.path.abspath(apk2), '--output', 'apktool'],
  1917.                            cwd=apk2dir) != 0:
  1918.             return("Failed to unpack " + apk2)
  1919.  
  1920.     p = FDroidPopen(['diff', '-r', apk1dir, apk2dir], output=False)
  1921.     lines = p.output.splitlines()
  1922.     if len(lines) != 1 or 'META-INF' not in lines[0]:
  1923.         meld = find_command('meld')
  1924.         if meld is not None:
  1925.             p = FDroidPopen(['meld', apk1dir, apk2dir], output=False)
  1926.         return("Unexpected diff output - " + p.output)
  1927.  
  1928.     # since everything verifies, delete the comparison to keep cruft down
  1929.     shutil.rmtree(apk1dir)
  1930.     shutil.rmtree(apk2dir)
  1931.  
  1932.     # If we get here, it seems like they're the same!
  1933.     return None
  1934.  
  1935.  
  1936. def find_command(command):
  1937.     '''find the full path of a command, or None if it can't be found in the PATH'''
  1938.  
  1939.     def is_exe(fpath):
  1940.         return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
  1941.  
  1942.     fpath, fname = os.path.split(command)
  1943.     if fpath:
  1944.         if is_exe(command):
  1945.             return command
  1946.     else:
  1947.         for path in os.environ["PATH"].split(os.pathsep):
  1948.             path = path.strip('"')
  1949.             exe_file = os.path.join(path, command)
  1950.             if is_exe(exe_file):
  1951.                 return exe_file
  1952.  
  1953.     return None
  1954.  
  1955.  
  1956. def genpassword():
  1957.     '''generate a random password for when generating keys'''
  1958.     h = hashlib.sha256()
  1959.     h.update(os.urandom(16))  # salt
  1960.     h.update(socket.getfqdn().encode('utf-8'))
  1961.     passwd = base64.b64encode(h.digest()).strip()
  1962.     return passwd.decode('utf-8')
  1963.  
  1964.  
  1965. def genkeystore(localconfig):
  1966.     '''Generate a new key with random passwords and add it to new keystore'''
  1967.     logging.info('Generating a new key in "' + localconfig['keystore'] + '"...')
  1968.     keystoredir = os.path.dirname(localconfig['keystore'])
  1969.     if keystoredir is None or keystoredir == '':
  1970.         keystoredir = os.path.join(os.getcwd(), keystoredir)
  1971.     if not os.path.exists(keystoredir):
  1972.         os.makedirs(keystoredir, mode=0o700)
  1973.  
  1974.     write_password_file("keystorepass", localconfig['keystorepass'])
  1975.     write_password_file("keypass", localconfig['keypass'])
  1976.     p = FDroidPopen([config['keytool'], '-genkey',
  1977.                      '-keystore', localconfig['keystore'],
  1978.                      '-alias', localconfig['repo_keyalias'],
  1979.                      '-keyalg', 'RSA', '-keysize', '4096',
  1980.                      '-sigalg', 'SHA256withRSA',
  1981.                      '-validity', '10000',
  1982.                      '-storepass:file', config['keystorepassfile'],
  1983.                      '-keypass:file', config['keypassfile'],
  1984.                      '-dname', localconfig['keydname']])
  1985.     # TODO keypass should be sent via stdin
  1986.     if p.returncode != 0:
  1987.         raise BuildException("Failed to generate key", p.output)
  1988.     os.chmod(localconfig['keystore'], 0o0600)
  1989.     # now show the lovely key that was just generated
  1990.     p = FDroidPopen([config['keytool'], '-list', '-v',
  1991.                      '-keystore', localconfig['keystore'],
  1992.                      '-alias', localconfig['repo_keyalias'],
  1993.                      '-storepass:file', config['keystorepassfile']])
  1994.     logging.info(p.output.strip() + '\n\n')
  1995.  
  1996.  
  1997. def write_to_config(thisconfig, key, value=None):
  1998.     '''write a key/value to the local config.py'''
  1999.     if value is None:
  2000.         origkey = key + '_orig'
  2001.         value = thisconfig[origkey] if origkey in thisconfig else thisconfig[key]
  2002.     with open('config.py', 'r') as f:
  2003.         data = f.read()
  2004.     pattern = '\n[\s#]*' + key + '\s*=\s*"[^"]*"'
  2005.     repl = '\n' + key + ' = "' + value + '"'
  2006.     data = re.sub(pattern, repl, data)
  2007.     # if this key is not in the file, append it
  2008.     if not re.match('\s*' + key + '\s*=\s*"', data):
  2009.         data += repl
  2010.     # make sure the file ends with a carraige return
  2011.     if not re.match('\n$', data):
  2012.         data += '\n'
  2013.     with open('config.py', 'w') as f:
  2014.         f.writelines(data)
  2015.  
  2016.  
  2017. def parse_xml(path):
  2018.     return XMLElementTree.parse(path).getroot()
  2019.  
  2020.  
  2021. def string_is_integer(string):
  2022.     try:
  2023.         int(string)
  2024.         return True
  2025.     except ValueError:
  2026.         return False
  2027.  
  2028.  
  2029. def get_per_app_repos():
  2030.     '''per-app repos are dirs named with the packageName of a single app'''
  2031.  
  2032.     # Android packageNames are Java packages, they may contain uppercase or
  2033.     # lowercase letters ('A' through 'Z'), numbers, and underscores
  2034.     # ('_'). However, individual package name parts may only start with
  2035.     # letters. https://developer.android.com/guide/topics/manifest/manifest-element.html#package
  2036.     p = re.compile('^([a-zA-Z][a-zA-Z0-9_]*(\\.[a-zA-Z][a-zA-Z0-9_]*)*)?$')
  2037.  
  2038.     repos = []
  2039.     for root, dirs, files in os.walk(os.getcwd()):
  2040.         for d in dirs:
  2041.             print('checking', root, 'for', d)
  2042.             if d in ('archive', 'metadata', 'repo', 'srclibs', 'tmp'):
  2043.                 # standard parts of an fdroid repo, so never packageNames
  2044.                 continue
  2045.             elif p.match(d) \
  2046.                     and os.path.exists(os.path.join(d, 'fdroid', 'repo', 'index.jar')):
  2047.                 repos.append(d)
  2048.         break
  2049.     return repos
Add Comment
Please, Sign In to add comment