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