2 # -*- coding: utf-8 -*-
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>
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.
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.
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/>.
26 from argparse import ArgumentParser
31 from common import FDroidPopen, SdkToolsPopen, BuildException
39 global config, options
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()
48 config = common.read_config(options)
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!')
55 if not os.path.isdir(log_dir):
56 logging.info("Creating log directory")
60 if not os.path.isdir(tmp_dir):
61 logging.info("Creating temporary directory")
65 if not os.path.isdir(output_dir):
66 logging.info("Creating output directory")
67 os.makedirs(output_dir)
69 unsigned_dir = 'unsigned'
70 if not os.path.isdir(unsigned_dir):
71 logging.warning("No unsigned directory - nothing to do")
74 for f in [config['keystorepassfile'],
76 config['keypassfile']]:
77 if not os.path.exists(f):
78 logging.error("Config error - missing '{0}'".format(f))
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)
96 keyalias = m.hexdigest()[:8]
97 if keyalias in allaliases:
98 logging.error("There is a keyalias collision - publishing halted")
100 allaliases.append(keyalias)
101 logging.info("{0} apps, {0} key aliases".format(len(allapps),
104 # Process any apks that are waiting to be signed...
105 for apkfile in sorted(glob.glob(os.path.join(unsigned_dir, '*.apk'))):
107 appid, vercode = common.apknameinfo(apkfile)
108 apkfilename = os.path.basename(apkfile)
109 if vercodes and appid not in vercodes:
111 if appid in vercodes and vercodes[appid]:
112 if vercode not in vercodes[appid]:
114 logging.info("Processing " + apkfile)
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))
124 if app.Binaries is not None:
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
131 srcapk = apkfile + ".binary"
133 # Compare our unsigned one with the downloaded one...
134 compare_result = common.verify_apks(srcapk, apkfile, tmp_dir)
136 logging.error("...verification failed - publish skipped : "
140 # Success! So move the downloaded file to the repo, and remove
142 shutil.move(srcapk, os.path.join(output_dir, apkfilename))
147 # It's a 'normal' app, i.e. we sign and publish it...
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
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('@'):
160 m.update(keyalias[1:])
161 keyalias = m.hexdigest()[:8]
165 keyalias = m.hexdigest()[:8]
166 logging.info("Key alias: " + keyalias)
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'],
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")
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',
193 # TODO keypass should be sent via stdin
194 if p.returncode != 0:
195 raise BuildException("Failed to sign application")
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")
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))
210 logging.info('Published ' + apkfilename)
213 if __name__ == "__main__":