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