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