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