chiark / gitweb /
Merge branch 'patch-1' into 'master'
[fdroidserver.git] / fdroidserver / init.py
1 #!/usr/bin/env python3
2 #
3 # init.py - part of the FDroid server tools
4 # Copyright (C) 2010-2013, Ciaran Gultnieks, ciaran@ciarang.com
5 # Copyright (C) 2013-2014 Daniel Martí <mvdan@mvdan.cc>
6 # Copyright (C) 2013 Hans-Christoph Steiner <hans@eds.org>
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 glob
22 import os
23 import re
24 import shutil
25 import socket
26 import sys
27 from argparse import ArgumentParser
28 import logging
29
30 from . import _
31 from . import common
32 from .exception import FDroidException
33
34 config = {}
35 options = None
36
37
38 def disable_in_config(key, value):
39     '''write a key/value to the local config.py, then comment it out'''
40     with open('config.py', 'r', encoding='utf8') as f:
41         data = f.read()
42     pattern = '\n[\s#]*' + key + '\s*=\s*"[^"]*"'
43     repl = '\n#' + key + ' = "' + value + '"'
44     data = re.sub(pattern, repl, data)
45     with open('config.py', 'w', encoding='utf8') as f:
46         f.writelines(data)
47
48
49 def main():
50
51     global options, config
52
53     # Parse command line...
54     parser = ArgumentParser()
55     common.setup_global_opts(parser)
56     parser.add_argument("-d", "--distinguished-name", default=None,
57                         help=_("X.509 'Distinguished Name' used when generating keys"))
58     parser.add_argument("--keystore", default=None,
59                         help=_("Path to the keystore for the repo signing key"))
60     parser.add_argument("--repo-keyalias", default=None,
61                         help=_("Alias of the repo signing key in the keystore"))
62     parser.add_argument("--android-home", default=None,
63                         help=_("Path to the Android SDK (sometimes set in ANDROID_HOME)"))
64     parser.add_argument("--no-prompt", action="store_true", default=False,
65                         help=_("Do not prompt for Android SDK path, just fail"))
66     options = parser.parse_args()
67
68     # find root install prefix
69     tmp = os.path.dirname(sys.argv[0])
70     examplesdir = None
71     if os.path.basename(tmp) == 'bin':
72         egg_links = glob.glob(os.path.join(tmp, '..',
73                                            'local/lib/python3.*/site-packages/fdroidserver.egg-link'))
74         if egg_links:
75             # installed from local git repo
76             examplesdir = os.path.join(open(egg_links[0]).readline().rstrip(), 'examples')
77         else:
78             # try .egg layout
79             examplesdir = os.path.dirname(os.path.dirname(__file__)) + '/share/doc/fdroidserver/examples'
80             if not os.path.exists(examplesdir):  # use UNIX layout
81                 examplesdir = os.path.dirname(tmp) + '/share/doc/fdroidserver/examples'
82     else:
83         # we're running straight out of the git repo
84         prefix = os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))
85         examplesdir = prefix + '/examples'
86
87     aapt = None
88     fdroiddir = os.getcwd()
89     test_config = dict()
90     common.fill_config_defaults(test_config)
91
92     # track down where the Android SDK is, the default is to use the path set
93     # in ANDROID_HOME if that exists, otherwise None
94     if options.android_home is not None:
95         test_config['sdk_path'] = options.android_home
96     elif not common.test_sdk_exists(test_config):
97         if os.path.isfile('/usr/bin/aapt'):
98             # remove sdk_path and build_tools, they are not required
99             test_config.pop('sdk_path', None)
100             test_config.pop('build_tools', None)
101             # make sure at least aapt is found, since this can't do anything without it
102             test_config['aapt'] = common.find_sdk_tools_cmd('aapt')
103         else:
104             # if neither --android-home nor the default sdk_path
105             # exist, prompt the user using platform-specific default
106             default_sdk_path = '/opt/android-sdk'
107             if sys.platform == 'win32' or sys.platform == 'cygwin':
108                 p = os.path.join(os.getenv('USERPROFILE'),
109                                  'AppData', 'Local', 'Android', 'android-sdk')
110             elif sys.platform == 'darwin':
111                 # on OSX, Homebrew is common and has an easy path to detect
112                 p = '/usr/local/opt/android-sdk'
113             else:
114                 # if the Debian packages are installed, suggest them
115                 p = '/usr/lib/android-sdk'
116             if os.path.exists(p):
117                 default_sdk_path = p
118
119             while not options.no_prompt:
120                 try:
121                     s = input(_('Enter the path to the Android SDK (%s) here:\n> ') % default_sdk_path)
122                 except KeyboardInterrupt:
123                     print('')
124                     sys.exit(1)
125                 if re.match('^\s*$', s) is not None:
126                     test_config['sdk_path'] = default_sdk_path
127                 else:
128                     test_config['sdk_path'] = s
129                 if common.test_sdk_exists(test_config):
130                     break
131     if not common.test_sdk_exists(test_config):
132         raise FDroidException("Android SDK not found.")
133
134     if not os.path.exists('config.py'):
135         # 'metadata' and 'tmp' are created in fdroid
136         if not os.path.exists('repo'):
137             os.mkdir('repo')
138         shutil.copy(os.path.join(examplesdir, 'fdroid-icon.png'), fdroiddir)
139         shutil.copyfile(os.path.join(examplesdir, 'config.py'), 'config.py')
140         os.chmod('config.py', 0o0600)
141         # If android_home is None, test_config['sdk_path'] will be used and
142         # "$ANDROID_HOME" may be used if the env var is set up correctly.
143         # If android_home is not None, the path given from the command line
144         # will be directly written in the config.
145         if 'sdk_path' in test_config:
146             common.write_to_config(test_config, 'sdk_path', options.android_home)
147     else:
148         logging.warn('Looks like this is already an F-Droid repo, cowardly refusing to overwrite it...')
149         logging.info('Try running `fdroid init` in an empty directory.')
150         raise FDroidException('Repository already exists.')
151
152     if 'aapt' not in test_config or not os.path.isfile(test_config['aapt']):
153         # try to find a working aapt, in all the recent possible paths
154         build_tools = os.path.join(test_config['sdk_path'], 'build-tools')
155         aaptdirs = []
156         aaptdirs.append(os.path.join(build_tools, test_config['build_tools']))
157         aaptdirs.append(build_tools)
158         for f in os.listdir(build_tools):
159             if os.path.isdir(os.path.join(build_tools, f)):
160                 aaptdirs.append(os.path.join(build_tools, f))
161         for d in sorted(aaptdirs, reverse=True):
162             if os.path.isfile(os.path.join(d, 'aapt')):
163                 aapt = os.path.join(d, 'aapt')
164                 break
165         if os.path.isfile(aapt):
166             dirname = os.path.basename(os.path.dirname(aapt))
167             if dirname == 'build-tools':
168                 # this is the old layout, before versioned build-tools
169                 test_config['build_tools'] = ''
170             else:
171                 test_config['build_tools'] = dirname
172             common.write_to_config(test_config, 'build_tools')
173         common.ensure_build_tools_exists(test_config)
174
175     # now that we have a local config.py, read configuration...
176     config = common.read_config(options)
177
178     # the NDK is optional and there may be multiple versions of it, so it's
179     # left for the user to configure
180
181     # find or generate the keystore for the repo signing key. First try the
182     # path written in the default config.py.  Then check if the user has
183     # specified a path from the command line, which will trump all others.
184     # Otherwise, create ~/.local/share/fdroidserver and stick it in there.  If
185     # keystore is set to NONE, that means that Java will look for keys in a
186     # Hardware Security Module aka Smartcard.
187     keystore = config['keystore']
188     if options.keystore:
189         keystore = os.path.abspath(options.keystore)
190         if options.keystore == 'NONE':
191             keystore = options.keystore
192         else:
193             keystore = os.path.abspath(options.keystore)
194             if not os.path.exists(keystore):
195                 logging.info('"' + keystore
196                              + '" does not exist, creating a new keystore there.')
197     common.write_to_config(test_config, 'keystore', keystore)
198     repo_keyalias = None
199     if options.repo_keyalias:
200         repo_keyalias = options.repo_keyalias
201         common.write_to_config(test_config, 'repo_keyalias', repo_keyalias)
202     if options.distinguished_name:
203         keydname = options.distinguished_name
204         common.write_to_config(test_config, 'keydname', keydname)
205     if keystore == 'NONE':  # we're using a smartcard
206         common.write_to_config(test_config, 'repo_keyalias', '1')  # seems to be the default
207         disable_in_config('keypass', 'never used with smartcard')
208         common.write_to_config(test_config, 'smartcardoptions',
209                                ('-storetype PKCS11 -providerName SunPKCS11-OpenSC '
210                                 + '-providerClass sun.security.pkcs11.SunPKCS11 '
211                                 + '-providerArg opensc-fdroid.cfg'))
212         # find opensc-pkcs11.so
213         if not os.path.exists('opensc-fdroid.cfg'):
214             if os.path.exists('/usr/lib/opensc-pkcs11.so'):
215                 opensc_so = '/usr/lib/opensc-pkcs11.so'
216             elif os.path.exists('/usr/lib64/opensc-pkcs11.so'):
217                 opensc_so = '/usr/lib64/opensc-pkcs11.so'
218             else:
219                 files = glob.glob('/usr/lib/' + os.uname()[4] + '-*-gnu/opensc-pkcs11.so')
220                 if len(files) > 0:
221                     opensc_so = files[0]
222                 else:
223                     opensc_so = '/usr/lib/opensc-pkcs11.so'
224                     logging.warn('No OpenSC PKCS#11 module found, ' +
225                                  'install OpenSC then edit "opensc-fdroid.cfg"!')
226             with open(os.path.join(examplesdir, 'opensc-fdroid.cfg'), 'r') as f:
227                 opensc_fdroid = f.read()
228             opensc_fdroid = re.sub('^library.*', 'library = ' + opensc_so, opensc_fdroid,
229                                    flags=re.MULTILINE)
230             with open('opensc-fdroid.cfg', 'w') as f:
231                 f.write(opensc_fdroid)
232     elif not os.path.exists(keystore):
233         password = common.genpassword()
234         c = dict(test_config)
235         c['keystorepass'] = password
236         c['keypass'] = password
237         c['repo_keyalias'] = socket.getfqdn()
238         c['keydname'] = 'CN=' + c['repo_keyalias'] + ', OU=F-Droid'
239         common.write_to_config(test_config, 'keystorepass', password)
240         common.write_to_config(test_config, 'keypass', password)
241         common.write_to_config(test_config, 'repo_keyalias', c['repo_keyalias'])
242         common.write_to_config(test_config, 'keydname', c['keydname'])
243         common.genkeystore(c)
244
245     msg = '\n'
246     msg += _('Built repo based in "%s" with this config:') % fdroiddir
247     msg += '\n\n  Android SDK:\t\t\t' + config['sdk_path']
248     if aapt:
249         msg += '\n  Android SDK Build Tools:\t' + os.path.dirname(aapt)
250     msg += '\n  Android NDK r12b (optional):\t$ANDROID_NDK'
251     msg += '\n  ' + _('Keystore for signing key:\t') + keystore
252     if repo_keyalias is not None:
253         msg += '\n  Alias for key in store:\t' + repo_keyalias
254     msg += '\n\n' + '''To complete the setup, add your APKs to "%s"
255 then run "fdroid update -c; fdroid update".  You might also want to edit
256 "config.py" to set the URL, repo name, and more.  You should also set up
257 a signing key (a temporary one might have been automatically generated).
258
259 For more info: https://f-droid.org/docs/Setup_an_F-Droid_App_Repo
260 and https://f-droid.org/docs/Signing_Process''' % os.path.join(fdroiddir, 'repo')
261     logging.info(msg)