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