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