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