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