chiark / gitweb /
Adapt publish to new format, improve completion
[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 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 subprocess
25 import md5
26 import glob
27 from optparse import OptionParser
28
29 import common, metadata
30 from common import BuildException
31
32 config = None
33 options = None
34
35 def main():
36
37     global config, options
38
39     # Parse command line...
40     parser = OptionParser()
41     parser = OptionParser(usage="Usage: %prog [options] [APPID[:VERCODE] [APPID[:VERCODE] ...]]")
42     parser.add_option("-v", "--verbose", action="store_true", default=False,
43                       help="Spew out even more information than normal")
44     (options, args) = parser.parse_args()
45
46     config = common.read_config(options)
47
48     log_dir = 'logs'
49     if not os.path.isdir(log_dir):
50         print "Creating log directory"
51         os.makedirs(log_dir)
52
53     tmp_dir = 'tmp'
54     if not os.path.isdir(tmp_dir):
55         print "Creating temporary directory"
56         os.makedirs(tmp_dir)
57
58     output_dir = 'repo'
59     if not os.path.isdir(output_dir):
60         print "Creating output directory"
61         os.makedirs(output_dir)
62
63     unsigned_dir = 'unsigned'
64     if not os.path.isdir(unsigned_dir):
65         print "No unsigned directory - nothing to do"
66         sys.exit(0)
67
68     # It was suggested at https://dev.guardianproject.info/projects/bazaar/wiki/FDroid_Audit
69     # that a package could be crafted, such that it would use the same signing
70     # key as an existing app. While it may be theoretically possible for such a
71     # colliding package ID to be generated, it seems virtually impossible that
72     # the colliding ID would be something that would be a) a valid package ID,
73     # and b) a sane-looking ID that would make its way into the repo.
74     # Nonetheless, to be sure, before publishing we check that there are no
75     # collisions, and refuse to do any publishing if that's the case...
76     allapps = metadata.read_metadata()
77     vercodes = common.read_pkg_args(args, True)
78     allaliases = []
79     for app in allapps:
80         m = md5.new()
81         m.update(app['id'])
82         keyalias = m.hexdigest()[:8]
83         if keyalias in allaliases:
84             print "There is a keyalias collision - publishing halted"
85             sys.exit(1)
86         allaliases.append(keyalias)
87     if options.verbose:
88         print "{0} apps, {0} key aliases".format(len(allapps), len(allaliases))
89
90     # Process any apks that are waiting to be signed...
91     for apkfile in sorted(glob.glob(os.path.join(unsigned_dir, '*.apk'))):
92
93         appid, vercode = common.apknameinfo(apkfile)
94         apkfilename = os.path.basename(apkfile)
95         if vercodes and appid not in vercodes:
96             continue
97         if appid in vercodes and vercodes[appid]:
98             if vercode not in vercodes[appid]:
99                 continue
100         print "Processing " + apkfile
101
102         # Figure out the key alias name we'll use. Only the first 8
103         # characters are significant, so we'll use the first 8 from
104         # the MD5 of the app's ID and hope there are no collisions.
105         # If a collision does occur later, we're going to have to
106         # come up with a new alogrithm, AND rename all existing keys
107         # in the keystore!
108         if appid in config['keyaliases']:
109             # For this particular app, the key alias is overridden...
110             keyalias = config['keyaliases'][appid]
111             if keyalias.startswith('@'):
112                 m = md5.new()
113                 m.update(keyalias[1:])
114                 keyalias = m.hexdigest()[:8]
115         else:
116             m = md5.new()
117             m.update(appid)
118             keyalias = m.hexdigest()[:8]
119         print "Key alias: " + keyalias
120
121         # See if we already have a key for this application, and
122         # if not generate one...
123         p = subprocess.Popen(['keytool', '-list',
124             '-alias', keyalias, '-keystore', config['keystore'],
125             '-storepass', config['keystorepass']], stdout=subprocess.PIPE)
126         output = p.communicate()[0]
127         if p.returncode !=0:
128             print "Key does not exist - generating..."
129             p = subprocess.Popen(['keytool', '-genkey',
130                 '-keystore', config['keystore'], '-alias', keyalias,
131                 '-keyalg', 'RSA', '-keysize', '2048',
132                 '-validity', '10000',
133                 '-storepass', config['keystorepass'],
134                 '-keypass', config['keypass'],
135                 '-dname', config['keydname']], stdout=subprocess.PIPE)
136             output = p.communicate()[0]
137             print output
138             if p.returncode != 0:
139                 raise BuildException("Failed to generate key")
140
141         # Sign the application...
142         p = subprocess.Popen(['jarsigner', '-keystore', config['keystore'],
143             '-storepass', config['keystorepass'],
144             '-keypass', config['keypass'], '-sigalg',
145             'MD5withRSA', '-digestalg', 'SHA1',
146                 apkfile, keyalias], stdout=subprocess.PIPE)
147         output = p.communicate()[0]
148         print output
149         if p.returncode != 0:
150             raise BuildException("Failed to sign application")
151
152         # Zipalign it...
153         p = subprocess.Popen([os.path.join(config['sdk_path'],'tools','zipalign'),
154                             '-v', '4', apkfile,
155                             os.path.join(output_dir, apkfilename)],
156                             stdout=subprocess.PIPE)
157         output = p.communicate()[0]
158         print output
159         if p.returncode != 0:
160             raise BuildException("Failed to align application")
161         os.remove(apkfile)
162
163         # Move the source tarball into the output directory...
164         tarfilename = apkfilename[:-4] + '_src.tar.gz'
165         shutil.move(os.path.join(unsigned_dir, tarfilename),
166                 os.path.join(output_dir, tarfilename))
167
168         print 'Published ' + apkfilename
169
170
171 if __name__ == "__main__":
172     main()
173