chiark / gitweb /
f0089d862e9f619d9c10390a055dd8ef1a8eecc1
[fdroidserver.git] / fdroidserver / publish.py
1 #!/usr/bin/env python2
2 # -*- coding: utf-8 -*-
3 #
4 # publish.py - part of the FDroid server tools
5 # Copyright (C) 2010-13, Ciaran Gultnieks, ciaran@ciarang.com
6 # Copyright (C) 2013-2014 Daniel Martí <mvdan@mvdan.cc>
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU Affero General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU Affero General Public License for more details.
17 #
18 # You should have received a copy of the GNU Affero General Public License
19 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21 import sys
22 import os
23 import shutil
24 import md5
25 import glob
26 from argparse import ArgumentParser
27 import logging
28
29 import common
30 import metadata
31 from common import FDroidPopen, SdkToolsPopen, 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     options = parser.parse_args()
47
48     config = common.read_config(options)
49
50     if not ('jarsigner' in config and 'keytool' in config):
51         logging.critical('Java JDK not found! Install in standard location or set java_paths!')
52         sys.exit(1)
53
54     log_dir = 'logs'
55     if not os.path.isdir(log_dir):
56         logging.info("Creating log directory")
57         os.makedirs(log_dir)
58
59     tmp_dir = 'tmp'
60     if not os.path.isdir(tmp_dir):
61         logging.info("Creating temporary directory")
62         os.makedirs(tmp_dir)
63
64     output_dir = 'repo'
65     if not os.path.isdir(output_dir):
66         logging.info("Creating output directory")
67         os.makedirs(output_dir)
68
69     unsigned_dir = 'unsigned'
70     if not os.path.isdir(unsigned_dir):
71         logging.warning("No unsigned directory - nothing to do")
72         sys.exit(1)
73
74     for f in [config['keystorepassfile'],
75               config['keystore'],
76               config['keypassfile']]:
77         if not os.path.exists(f):
78             logging.error("Config error - missing '{0}'".format(f))
79             sys.exit(1)
80
81     # It was suggested at
82     #    https://dev.guardianproject.info/projects/bazaar/wiki/FDroid_Audit
83     # that a package could be crafted, such that it would use the same signing
84     # key as an existing app. While it may be theoretically possible for such a
85     # colliding package ID to be generated, it seems virtually impossible that
86     # the colliding ID would be something that would be a) a valid package ID,
87     # and b) a sane-looking ID that would make its way into the repo.
88     # Nonetheless, to be sure, before publishing we check that there are no
89     # collisions, and refuse to do any publishing if that's the case...
90     allapps = metadata.read_metadata()
91     vercodes = common.read_pkg_args(options.appid, True)
92     allaliases = []
93     for appid in allapps:
94         m = md5.new()
95         m.update(appid)
96         keyalias = m.hexdigest()[:8]
97         if keyalias in allaliases:
98             logging.error("There is a keyalias collision - publishing halted")
99             sys.exit(1)
100         allaliases.append(keyalias)
101     logging.info("{0} apps, {0} key aliases".format(len(allapps),
102                                                     len(allaliases)))
103
104     # Process any apks that are waiting to be signed...
105     for apkfile in sorted(glob.glob(os.path.join(unsigned_dir, '*.apk'))):
106
107         appid, vercode = common.apknameinfo(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 is not None:
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         else:
146
147             # It's a 'normal' app, i.e. we sign and publish it...
148
149             # Figure out the key alias name we'll use. Only the first 8
150             # characters are significant, so we'll use the first 8 from
151             # the MD5 of the app's ID and hope there are no collisions.
152             # If a collision does occur later, we're going to have to
153             # come up with a new alogrithm, AND rename all existing keys
154             # in the keystore!
155             if appid in config['keyaliases']:
156                 # For this particular app, the key alias is overridden...
157                 keyalias = config['keyaliases'][appid]
158                 if keyalias.startswith('@'):
159                     m = md5.new()
160                     m.update(keyalias[1:])
161                     keyalias = m.hexdigest()[:8]
162             else:
163                 m = md5.new()
164                 m.update(appid)
165                 keyalias = m.hexdigest()[:8]
166             logging.info("Key alias: " + keyalias)
167
168             # See if we already have a key for this application, and
169             # if not generate one...
170             p = FDroidPopen([config['keytool'], '-list',
171                              '-alias', keyalias, '-keystore', config['keystore'],
172                              '-storepass:file', config['keystorepassfile']])
173             if p.returncode != 0:
174                 logging.info("Key does not exist - generating...")
175                 p = FDroidPopen([config['keytool'], '-genkey',
176                                  '-keystore', config['keystore'],
177                                  '-alias', keyalias,
178                                  '-keyalg', 'RSA', '-keysize', '2048',
179                                  '-validity', '10000',
180                                  '-storepass:file', config['keystorepassfile'],
181                                  '-keypass:file', config['keypassfile'],
182                                  '-dname', config['keydname']])
183                 # TODO keypass should be sent via stdin
184                 if p.returncode != 0:
185                     raise BuildException("Failed to generate key")
186
187             # Sign the application...
188             p = FDroidPopen([config['jarsigner'], '-keystore', config['keystore'],
189                              '-storepass:file', config['keystorepassfile'],
190                              '-keypass:file', config['keypassfile'], '-sigalg',
191                              'SHA1withRSA', '-digestalg', 'SHA1',
192                              apkfile, keyalias])
193             # TODO keypass should be sent via stdin
194             if p.returncode != 0:
195                 raise BuildException("Failed to sign application")
196
197             # Zipalign it...
198             p = SdkToolsPopen(['zipalign', '-v', '4', apkfile,
199                                os.path.join(output_dir, apkfilename)])
200             if p.returncode != 0:
201                 raise BuildException("Failed to align application")
202             os.remove(apkfile)
203
204         # Move the source tarball into the output directory...
205         tarfilename = apkfilename[:-4] + '_src.tar.gz'
206         tarfile = os.path.join(unsigned_dir, tarfilename)
207         if os.path.exists(tarfile):
208             shutil.move(tarfile, os.path.join(output_dir, tarfilename))
209
210         logging.info('Published ' + apkfilename)
211
212
213 if __name__ == "__main__":
214     main()