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)
51 if not os.path.isdir(log_dir):
52 logging.info("Creating log directory")
56 if not os.path.isdir(tmp_dir):
57 logging.info("Creating temporary directory")
61 if not os.path.isdir(output_dir):
62 logging.info("Creating output directory")
63 os.makedirs(output_dir)
65 unsigned_dir = 'unsigned'
66 if not os.path.isdir(unsigned_dir):
67 logging.warning("No unsigned directory - nothing to do")
70 for f in [config['keystorepassfile'],
72 config['keypassfile']]:
73 if not os.path.exists(f):
74 logging.error("Config error - missing '{0}'".format(f))
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)
92 keyalias = m.hexdigest()[:8]
93 if keyalias in allaliases:
94 logging.error("There is a keyalias collision - publishing halted")
96 allaliases.append(keyalias)
97 logging.info("{0} apps, {0} key aliases".format(len(allapps),
100 # Process any apks that are waiting to be signed...
101 for apkfile in sorted(glob.glob(os.path.join(unsigned_dir, '*.apk'))):
103 appid, vercode = common.apknameinfo(apkfile)
104 apkfilename = os.path.basename(apkfile)
105 if vercodes and appid not in vercodes:
107 if appid in vercodes and vercodes[appid]:
108 if vercode not in vercodes[appid]:
110 logging.info("Processing " + apkfile)
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))
120 if app.Binaries is not None:
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
127 srcapk = apkfile + ".binary"
129 # Compare our unsigned one with the downloaded one...
130 compare_result = common.verify_apks(srcapk, apkfile, tmp_dir)
132 logging.error("...verification failed - publish skipped : "
136 # Success! So move the downloaded file to the repo, and remove
138 shutil.move(srcapk, os.path.join(output_dir, apkfilename))
143 # It's a 'normal' app, i.e. we sign and publish it...
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
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('@'):
156 m.update(keyalias[1:])
157 keyalias = m.hexdigest()[:8]
161 keyalias = m.hexdigest()[:8]
162 logging.info("Key alias: " + keyalias)
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'],
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")
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',
189 # TODO keypass should be sent via stdin
190 if p.returncode != 0:
191 raise BuildException("Failed to sign application")
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")
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))
206 logging.info('Published ' + apkfilename)
209 if __name__ == "__main__":