-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.py
executable file
·316 lines (258 loc) · 9.37 KB
/
config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#!/usr/bin/python3
"""python3 config hook for Spreed WebRTC"""
import collections
import configparser
import os
import subprocess
import sys
import yaml
SPREED_WEBRTC_DATA_PATH = os.environ['SNAP_APP_DATA_PATH']
SPREED_WEBRTC_VERSION = os.environ['SNAP_VERSION']
SPREED_WEBRTC_CONFIG_FILE = os.path.join(SPREED_WEBRTC_DATA_PATH,
'server.conf')
START_CONFIG_FILE = os.path.join(SPREED_WEBRTC_DATA_PATH, 'start.conf')
SPREED_WEBRTC_CONFIG_FILE_IN = os.path.join(os.environ['SNAP_APP_PATH'],
'server.conf.in')
DEFAULT_REDIRECTOR_PORT = 8000
DEFAULT_REVERSE_PORT = 8080
DEFAULT_HTTPS_PORT = 8443
OPENSSL = "/usr/bin/openssl"
if not os.path.exists(OPENSSL):
OPENSSL = os.path.join(os.path.join(os.environ['SNAP_APP_PATH'],
'usr', 'bin', 'openssl'))
class SimpleConfig:
"""SimpleConfig is a parser for simple key=value files"""
def __init__(self):
# We use a ordered dict similar to configparser.
self.data = collections.OrderedDict()
def read(self, fn):
try:
with open(fn, 'r') as f:
for line in f:
name, var = line.partition('=')[::2]
name = name.strip()
if name:
self.data[name] = var.strip()
except EnvironmentError:
pass
def write(self, f):
for k, v in self.data.items():
if k:
f.write('%s=%s\n' % (k, v))
def get(self, key, value=''):
return self.data.get(key, value)
def set(self, key, value=''):
self.data[key] = value
def main():
"""main is the main function"""
args = sys.argv[1:]
if args:
if args[0] == "update":
return run(None, update=True)
return hook()
def hook():
"""hook reads the config from sys.stdin and applies it"""
config_in = yaml.load(sys.stdin)
run(config_in)
def run(config_in, update=False):
"""run takes the config_in configuration and applies it"""
spreed_config = start_config = None
if config_in:
config_out, spreed_config, start_config = set_config(config_in)
config_out, spreed_config, start_config = \
get_config(spreed_config, start_config)
if not (os.path.exists(SPREED_WEBRTC_CONFIG_FILE) and
os.path.exists(START_CONFIG_FILE)):
# Set read configuration, to bring in defaults.
config_out, spreed_config, start_config = set_config(config_out)
config_in = config_out
if config_in or update:
with open(SPREED_WEBRTC_CONFIG_FILE, 'w') as f:
spreed_config.write(f, space_around_delimiters=True)
with open(START_CONFIG_FILE, 'w') as f:
start_config.write(f)
yaml.dump(config_out, stream=sys.stdout, default_flow_style=False)
sys.exit(0)
def exec_cmd_and_get_output(command, **kwargs):
"""exec_cmd executes a given command as subprocess"""
assert isinstance(command, list), 'exec_cmd command must be a list'
return subprocess.check_output(command, **kwargs)
def get_random_hex(bytes=32):
"""get_random_hex generates random hex strings with OpenSSL"""
return exec_cmd_and_get_output([OPENSSL, "rand", "-hex",
"%d" % bytes]).strip().decode("UTF-8")
def load_config():
"""load_config loads the configuration from file and
return spreed_config and start_config"""
spreed_config = configparser.ConfigParser()
if os.path.exists(SPREED_WEBRTC_CONFIG_FILE):
spreed_config.read(SPREED_WEBRTC_CONFIG_FILE)
else:
spreed_config.read(SPREED_WEBRTC_CONFIG_FILE_IN)
# Add our defaults.
try:
spreed_config.remove_option('http', 'listen')
except configparser.NoSectionError:
pass
spreed_config['http']['root'] = 'www' # Will be replaced on start.
spreed_config['https']['listen'] = ':%s' % DEFAULT_HTTPS_PORT
spreed_config['https']['certificate'] = 'tls.crt'
spreed_config['https']['key'] = 'tls.key'
spreed_config['https']['minVersion'] = 'TLSv1'
spreed_config['app']['sessionSecret'] = get_random_hex(64)
spreed_config['app']['encryptionSecret'] = get_random_hex(32)
spreed_config['app']['serverToken'] = get_random_hex(16)
start_config = SimpleConfig()
if os.path.exists(START_CONFIG_FILE):
start_config.read(START_CONFIG_FILE)
else:
# Add our defaults.
start_config.set("REDIRECTOR_PORT", DEFAULT_REDIRECTOR_PORT)
start_config.set("WEBAPP_PORT", DEFAULT_HTTPS_PORT)
return spreed_config, start_config
def set_config(config_yaml):
"""set_config sets a configuration and returns config,
spreed_config and start_config"""
config = config_yaml['config']['spreed-webrtc']
app = config.get('app', {})
http = config.get('http', {})
https = config.get('https', {})
ports = config.get('ports', {})
spreed_config, start_config = load_config()
# set value
def sv(section, name, value):
if not spreed_config.has_section(section):
spreed_config.add_section(section)
spreed_config[section][name] = value
# get value
def gv(section, name, value=None):
if spreed_config.has_section(section):
return spreed_config[section].get(name, value)
return value
# from yaml to ini
def tc(section, name):
c = config.get(section, {})
if name in c:
sv(section, name, c[name])
tc('app', 'title')
tc('app', 'globalRoom')
tc('app', 'defaultRoomEnabled')
tc('app', 'serverRealm')
tc('app', 'contentSecurityPolicy')
tc('https', 'minVersion')
ports_internal = ports.get('internal', {})
ports_external = ports.get('external', {})
http_reverse = http.get('reverse', gv('http', 'listen') and True)
http_ui = http.get('ui', start_config.get('REDIRECTOR_PORT') and True)
https_enabled = https.get('enabled', gv('https', 'listen') and True)
if http_reverse:
port = DEFAULT_REVERSE_PORT
if 'reverse' in ports_internal:
port = int(ports_internal['reverse']['port'])
listen = "127.0.0.1:%s" % port
sv('http', 'listen', listen)
else:
try:
spreed_config.remove_option('http', 'listen')
except configparser.NoSectionError:
pass
if http_ui:
port = DEFAULT_REDIRECTOR_PORT
if 'ui' in ports_external:
port = int(ports_external['ui']['port'])
start_config.set('REDIRECTOR_PORT', port)
else:
start_config.set('REDIRECTOR_PORT', '')
if https_enabled:
port = DEFAULT_HTTPS_PORT
if 'webapp' in ports_external:
port = int(ports_external['webapp']['port'])
listen = ":%s" % port
sv('https', 'listen', listen)
sv('https', 'https', 'on')
start_config.set('WEBAPP_PORT', port)
else:
try:
spreed_config.remove_option('https', 'listen')
except configparser.NoSectionError:
pass
sv('https', 'https', 'off')
config_out = {
'config': {
'spreed-webrtc': config
}
}
return config_out, spreed_config, start_config
def get_config(spreed_config, start_config):
"""get_config returns config with the current configuration,
spreed_config and start_config"""
config = {}
app = config.setdefault('app', {})
http = config.setdefault('http', {})
https = config.setdefault('https', {})
ports = {}
if not spreed_config or not start_config:
spreed_config, start_config = load_config()
# from ini to yaml
def tc(section, name):
c = config.setdefault(section, {})
try:
c[name] = spreed_config[section][name]
except KeyError:
pass
tc('app', 'title')
tc('app', 'defaultRoomEnabled')
tc('app', 'globalRoom')
tc('app', 'defaultRoomEnabled')
tc('app', 'serverRealm')
tc('app', 'contentSecurityPolicy')
tc('https', 'minVersion')
try:
http_listen = spreed_config['http'].get('listen', None)
except KeyError:
http_listen = None
if http_listen:
port = http_listen.rsplit(":", 1)[1]
internal = ports.setdefault('internal', {})
internal['reverse'] = {
'port': int(port)
}
http['reverse'] = True
else:
http['reverse'] = False
try:
https_listen = spreed_config['https'].get('listen', None)
except KeyError:
https_listen = None
if https_listen:
port = https_listen.rsplit(":", 1)[1]
external = ports.setdefault('external', {})
external['webapp'] = {
'port': int(port)
}
https['enabled'] = True
else:
https['enabled'] = False
redirector_port = start_config.get("REDIRECTOR_PORT",
DEFAULT_REDIRECTOR_PORT)
if redirector_port:
http['ui'] = True
external = ports.setdefault('external', {})
external['ui'] = {
'port': int(redirector_port)
}
else:
http['ui'] = False
if ports:
config['ports'] = ports
config_out = {
'config': {
'spreed-webrtc': config
}
}
return config_out, spreed_config, start_config
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass