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 optparse import OptionParser
31 from common import FDroidPopen, SdkToolsPopen, BuildException
39 global config, options
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()
50 config = common.read_config(options)
53 if not os.path.isdir(log_dir):
54 logging.info("Creating log directory")
58 if not os.path.isdir(tmp_dir):
59 logging.info("Creating temporary directory")
63 if not os.path.isdir(output_dir):
64 logging.info("Creating output directory")
65 os.makedirs(output_dir)
67 unsigned_dir = 'unsigned'
68 if not os.path.isdir(unsigned_dir):
69 logging.warning("No unsigned directory - nothing to do")
72 for f in [config['keystorepassfile'],
74 config['keypassfile']]:
75 if not os.path.exists(f):
76 logging.error("Config error - missing '{0}'".format(f))
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)
94 keyalias = m.hexdigest()[:8]
95 if keyalias in allaliases:
96 logging.error("There is a keyalias collision - publishing halted")
98 allaliases.append(keyalias)
99 logging.info("{0} apps, {0} key aliases".format(len(allapps),
102 # Process any apks that are waiting to be signed...
103 for apkfile in sorted(glob.glob(os.path.join(unsigned_dir, '*.apk'))):
105 appid, vercode = common.apknameinfo(apkfile)
106 apkfilename = os.path.basename(apkfile)
107 if vercodes and appid not in vercodes:
109 if appid in vercodes and vercodes[appid]:
110 if vercode not in vercodes[appid]:
112 logging.info("Processing " + apkfile)
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))
122 if app.get('Binaries', None):
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
129 srcapk = apkfile + ".binary"
131 # Compare our unsigned one with the downloaded one...
132 compare_result = common.verify_apks(srcapk, apkfile, tmp_dir)
134 logging.error("...verification failed - publish skipped : "
138 # Success! So move the downloaded file to the repo, and remove
140 shutil.move(srcapk, os.path.join(output_dir, apkfilename))
145 # It's a 'normal' app, i.e. we sign and publish it...
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
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('@'):
158 m.update(keyalias[1:])
159 keyalias = m.hexdigest()[:8]
163 keyalias = m.hexdigest()[:8]
164 logging.info("Key alias: " + keyalias)
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'],
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")
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',
191 # TODO keypass should be sent via stdin
192 if p.returncode != 0:
193 raise BuildException("Failed to sign application")
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")
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))
208 logging.info('Published ' + apkfilename)
211 if __name__ == "__main__":