chiark / gitweb /
Merge branch 'plural' into 'master'
[fdroidserver.git] / fdroidserver / publish.py
1 #!/usr/bin/env python3
2 #
3 # publish.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 import sys
21 import os
22 import re
23 import shutil
24 import glob
25 import hashlib
26 from argparse import ArgumentParser
27 import logging
28 from gettext import ngettext
29
30 from . import _
31 from . import common
32 from . import metadata
33 from .common import FDroidPopen, SdkToolsPopen
34 from .exception import BuildException
35
36 config = None
37 options = None
38
39
40 def main():
41
42     global config, options
43
44     # Parse command line...
45     parser = ArgumentParser(usage="%(prog)s [options] "
46                             "[APPID[:VERCODE] [APPID[:VERCODE] ...]]")
47     common.setup_global_opts(parser)
48     parser.add_argument("appid", nargs='*', help=_("applicationId with optional versionCode in the form APPID[:VERCODE]"))
49     metadata.add_metadata_arguments(parser)
50     options = parser.parse_args()
51     metadata.warnings_action = options.W
52
53     config = common.read_config(options)
54
55     if not ('jarsigner' in config and 'keytool' in config):
56         logging.critical(_('Java JDK not found! Install in standard location or set java_paths!'))
57         sys.exit(1)
58
59     log_dir = 'logs'
60     if not os.path.isdir(log_dir):
61         logging.info(_("Creating log directory"))
62         os.makedirs(log_dir)
63
64     tmp_dir = 'tmp'
65     if not os.path.isdir(tmp_dir):
66         logging.info(_("Creating temporary directory"))
67         os.makedirs(tmp_dir)
68
69     output_dir = 'repo'
70     if not os.path.isdir(output_dir):
71         logging.info(_("Creating output directory"))
72         os.makedirs(output_dir)
73
74     unsigned_dir = 'unsigned'
75     if not os.path.isdir(unsigned_dir):
76         logging.warning(_("No unsigned directory - nothing to do"))
77         sys.exit(1)
78
79     if not os.path.exists(config['keystore']):
80         logging.error("Config error - missing '{0}'".format(config['keystore']))
81         sys.exit(1)
82
83     # It was suggested at
84     #    https://dev.guardianproject.info/projects/bazaar/wiki/FDroid_Audit
85     # that a package could be crafted, such that it would use the same signing
86     # key as an existing app. While it may be theoretically possible for such a
87     # colliding package ID to be generated, it seems virtually impossible that
88     # the colliding ID would be something that would be a) a valid package ID,
89     # and b) a sane-looking ID that would make its way into the repo.
90     # Nonetheless, to be sure, before publishing we check that there are no
91     # collisions, and refuse to do any publishing if that's the case...
92     allapps = metadata.read_metadata()
93     vercodes = common.read_pkg_args(options.appid, True)
94     allaliases = []
95     for appid in allapps:
96         m = hashlib.md5()
97         m.update(appid.encode('utf-8'))
98         keyalias = m.hexdigest()[:8]
99         if keyalias in allaliases:
100             logging.error(_("There is a keyalias collision - publishing halted"))
101             sys.exit(1)
102         allaliases.append(keyalias)
103     logging.info(ngettext('{0} app, {1} key aliases',
104                           '{0} apps, {1} key aliases', len(allapps)).format(len(allapps), len(allaliases)))
105
106     # Process any APKs or ZIPs that are waiting to be signed...
107     for apkfile in sorted(glob.glob(os.path.join(unsigned_dir, '*.apk'))
108                           + glob.glob(os.path.join(unsigned_dir, '*.zip'))):
109
110         appid, vercode = common.publishednameinfo(apkfile)
111         apkfilename = os.path.basename(apkfile)
112         if vercodes and appid not in vercodes:
113             continue
114         if appid in vercodes and vercodes[appid]:
115             if vercode not in vercodes[appid]:
116                 continue
117         logging.info("Processing " + apkfile)
118
119         # There ought to be valid metadata for this app, otherwise why are we
120         # trying to publish it?
121         if appid not in allapps:
122             logging.error("Unexpected {0} found in unsigned directory"
123                           .format(apkfilename))
124             sys.exit(1)
125         app = allapps[appid]
126
127         if app.Binaries:
128
129             # It's an app where we build from source, and verify the apk
130             # contents against a developer's binary, and then publish their
131             # version if everything checks out.
132             # The binary should already have been retrieved during the build
133             # process.
134             srcapk = re.sub(r'.apk$', '.binary.apk', apkfile)
135
136             # Compare our unsigned one with the downloaded one...
137             compare_result = common.verify_apks(srcapk, apkfile, tmp_dir)
138             if compare_result:
139                 logging.error("...verification failed - publish skipped : "
140                               + compare_result)
141                 continue
142
143             # Success! So move the downloaded file to the repo, and remove
144             # our built version.
145             shutil.move(srcapk, os.path.join(output_dir, apkfilename))
146             os.remove(apkfile)
147
148         elif apkfile.endswith('.zip'):
149
150             # OTA ZIPs built by fdroid do not need to be signed by jarsigner,
151             # just to be moved into place in the repo
152             shutil.move(apkfile, os.path.join(output_dir, apkfilename))
153
154         else:
155
156             # It's a 'normal' app, i.e. we sign and publish it...
157
158             # Figure out the key alias name we'll use. Only the first 8
159             # characters are significant, so we'll use the first 8 from
160             # the MD5 of the app's ID and hope there are no collisions.
161             # If a collision does occur later, we're going to have to
162             # come up with a new alogrithm, AND rename all existing keys
163             # in the keystore!
164             if appid in config['keyaliases']:
165                 # For this particular app, the key alias is overridden...
166                 keyalias = config['keyaliases'][appid]
167                 if keyalias.startswith('@'):
168                     m = hashlib.md5()
169                     m.update(keyalias[1:].encode('utf-8'))
170                     keyalias = m.hexdigest()[:8]
171             else:
172                 m = hashlib.md5()
173                 m.update(appid.encode('utf-8'))
174                 keyalias = m.hexdigest()[:8]
175             logging.info("Key alias: " + keyalias)
176
177             # See if we already have a key for this application, and
178             # if not generate one...
179             env_vars = {
180                 'FDROID_KEY_STORE_PASS': config['keystorepass'],
181                 'FDROID_KEY_PASS': config['keypass'],
182             }
183             p = FDroidPopen([config['keytool'], '-list',
184                              '-alias', keyalias, '-keystore', config['keystore'],
185                              '-storepass:env', 'FDROID_KEY_STORE_PASS'], envs=env_vars)
186             if p.returncode != 0:
187                 logging.info("Key does not exist - generating...")
188                 p = FDroidPopen([config['keytool'], '-genkey',
189                                  '-keystore', config['keystore'],
190                                  '-alias', keyalias,
191                                  '-keyalg', 'RSA', '-keysize', '2048',
192                                  '-validity', '10000',
193                                  '-storepass:env', 'FDROID_KEY_STORE_PASS',
194                                  '-keypass:env', 'FDROID_KEY_PASS',
195                                  '-dname', config['keydname']], envs=env_vars)
196                 if p.returncode != 0:
197                     raise BuildException("Failed to generate key")
198
199             signed_apk_path = os.path.join(output_dir, apkfilename)
200             if os.path.exists(signed_apk_path):
201                 raise BuildException("Refusing to sign '{0}' file exists in both "
202                                      "{1} and {2} folder.".format(apkfilename,
203                                                                   unsigned_dir,
204                                                                   output_dir))
205
206             # Sign the application...
207             p = FDroidPopen([config['jarsigner'], '-keystore', config['keystore'],
208                              '-storepass:env', 'FDROID_KEY_STORE_PASS',
209                              '-keypass:env', 'FDROID_KEY_PASS', '-sigalg',
210                              'SHA1withRSA', '-digestalg', 'SHA1',
211                              apkfile, keyalias], envs=env_vars)
212             if p.returncode != 0:
213                 raise BuildException(_("Failed to sign application"))
214
215             # Zipalign it...
216             p = SdkToolsPopen(['zipalign', '-v', '4', apkfile,
217                                os.path.join(output_dir, apkfilename)])
218             if p.returncode != 0:
219                 raise BuildException(_("Failed to align application"))
220             os.remove(apkfile)
221
222         # Move the source tarball into the output directory...
223         tarfilename = apkfilename[:-4] + '_src.tar.gz'
224         tarfile = os.path.join(unsigned_dir, tarfilename)
225         if os.path.exists(tarfile):
226             shutil.move(tarfile, os.path.join(output_dir, tarfilename))
227
228         logging.info('Published ' + apkfilename)
229
230
231 if __name__ == "__main__":
232     main()