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