chiark / gitweb /
Merge branch 'changelog' of https://gitlab.com/krt/fdroidserver
[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 optparse import OptionParser
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 = OptionParser(usage="Usage: %prog [options] "
43                           "[APPID[:VERCODE] [APPID[:VERCODE] ...]]")
44     parser.add_option("-v", "--verbose", action="store_true", default=False,
45                       help="Spew out even more information than normal")
46     parser.add_option("-q", "--quiet", action="store_true", default=False,
47                       help="Restrict output to warnings and errors")
48     (options, args) = parser.parse_args()
49
50     config = common.read_config(options)
51
52     log_dir = 'logs'
53     if not os.path.isdir(log_dir):
54         logging.info("Creating log directory")
55         os.makedirs(log_dir)
56
57     tmp_dir = 'tmp'
58     if not os.path.isdir(tmp_dir):
59         logging.info("Creating temporary directory")
60         os.makedirs(tmp_dir)
61
62     output_dir = 'repo'
63     if not os.path.isdir(output_dir):
64         logging.info("Creating output directory")
65         os.makedirs(output_dir)
66
67     unsigned_dir = 'unsigned'
68     if not os.path.isdir(unsigned_dir):
69         logging.warning("No unsigned directory - nothing to do")
70         sys.exit(1)
71
72     for f in [config['keystorepassfile'],
73               config['keystore'],
74               config['keypassfile']]:
75         if not os.path.exists(f):
76             logging.error("Config error - missing '{0}'".format(f))
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(args, True)
90     allaliases = []
91     for appid in allapps:
92         m = md5.new()
93         m.update(appid)
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 that are waiting to be signed...
103     for apkfile in sorted(glob.glob(os.path.join(unsigned_dir, '*.apk'))):
104
105         appid, vercode = common.apknameinfo(apkfile)
106         apkfilename = os.path.basename(apkfile)
107         if vercodes and appid not in vercodes:
108             continue
109         if appid in vercodes and vercodes[appid]:
110             if vercode not in vercodes[appid]:
111                 continue
112         logging.info("Processing " + apkfile)
113
114         # There ought to be valid metadata for this app, otherwise why are we
115         # trying to publish it?
116         if appid not in allapps:
117             logging.error("Unexpected {0} found in unsigned directory"
118                           .format(apkfilename))
119             sys.exit(1)
120         app = allapps[appid]
121
122         if app.get('Binaries', None):
123
124             # It's an app where we build from source, and verify the apk
125             # contents against a developer's binary, and then publish their
126             # version if everything checks out.
127             # The binary should already have been retrieved during the build
128             # process.
129             srcapk = apkfile + ".binary"
130
131             # Compare our unsigned one with the downloaded one...
132             compare_result = common.verify_apks(srcapk, apkfile, tmp_dir)
133             if compare_result:
134                 logging.error("...verification failed - publish skipped : "
135                               + compare_result)
136                 continue
137
138             # Success! So move the downloaded file to the repo, and remove
139             # our built version.
140             shutil.move(srcapk, os.path.join(output_dir, apkfilename))
141             os.remove(apkfile)
142
143         else:
144
145             # It's a 'normal' app, i.e. we sign and publish it...
146
147             # Figure out the key alias name we'll use. Only the first 8
148             # characters are significant, so we'll use the first 8 from
149             # the MD5 of the app's ID and hope there are no collisions.
150             # If a collision does occur later, we're going to have to
151             # come up with a new alogrithm, AND rename all existing keys
152             # in the keystore!
153             if appid in config['keyaliases']:
154                 # For this particular app, the key alias is overridden...
155                 keyalias = config['keyaliases'][appid]
156                 if keyalias.startswith('@'):
157                     m = md5.new()
158                     m.update(keyalias[1:])
159                     keyalias = m.hexdigest()[:8]
160             else:
161                 m = md5.new()
162                 m.update(appid)
163                 keyalias = m.hexdigest()[:8]
164             logging.info("Key alias: " + keyalias)
165
166             # See if we already have a key for this application, and
167             # if not generate one...
168             p = FDroidPopen(['keytool', '-list',
169                              '-alias', keyalias, '-keystore', config['keystore'],
170                              '-storepass:file', config['keystorepassfile']])
171             if p.returncode != 0:
172                 logging.info("Key does not exist - generating...")
173                 p = FDroidPopen(['keytool', '-genkey',
174                                  '-keystore', config['keystore'],
175                                  '-alias', keyalias,
176                                  '-keyalg', 'RSA', '-keysize', '2048',
177                                  '-validity', '10000',
178                                  '-storepass:file', config['keystorepassfile'],
179                                  '-keypass:file', config['keypassfile'],
180                                  '-dname', config['keydname']])
181                 # TODO keypass should be sent via stdin
182                 if p.returncode != 0:
183                     raise BuildException("Failed to generate key")
184
185             # Sign the application...
186             p = FDroidPopen(['jarsigner', '-keystore', config['keystore'],
187                              '-storepass:file', config['keystorepassfile'],
188                              '-keypass:file', config['keypassfile'], '-sigalg',
189                              'MD5withRSA', '-digestalg', 'SHA1',
190                              apkfile, keyalias])
191             # TODO keypass should be sent via stdin
192             if p.returncode != 0:
193                 raise BuildException("Failed to sign application")
194
195             # Zipalign it...
196             p = SdkToolsPopen(['zipalign', '-v', '4', apkfile,
197                                os.path.join(output_dir, apkfilename)])
198             if p.returncode != 0:
199                 raise BuildException("Failed to align application")
200             os.remove(apkfile)
201
202         # Move the source tarball into the output directory...
203         tarfilename = apkfilename[:-4] + '_src.tar.gz'
204         tarfile = os.path.join(unsigned_dir, tarfilename)
205         if os.path.exists(tarfile):
206             shutil.move(tarfile, os.path.join(output_dir, tarfilename))
207
208         logging.info('Published ' + apkfilename)
209
210
211 if __name__ == "__main__":
212     main()