-
Notifications
You must be signed in to change notification settings - Fork 1
/
confconsole.py
567 lines (430 loc) · 18.5 KB
/
confconsole.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
#!/usr/bin/python
# Copyright (c) 2008 Alon Swartz <[email protected]> - all rights reserved
"""TurnKey Configuration Console
Options:
--usage Display usage screen without Advanced Menu
"""
import os
import sys
import dialog
import ipaddr
from string import Template
import ifutil
import netinfo
import executil
import conf
from StringIO import StringIO
import traceback
class Error(Exception):
pass
def fatal(e):
print >> sys.stderr, "error: " + str(e)
sys.exit(1)
def usage(e=None):
if e:
print >> sys.stderr, "error: " + str(e)
print >> sys.stderr, "Syntax: %s" % (sys.argv[0])
print >> sys.stderr, __doc__.strip()
sys.exit(1)
class Console:
def __init__(self, title=None, width=60, height=20):
self.width = width
self.height = height
self.console = dialog.Dialog(dialog="dialog")
self.console.add_persistent_args(["--no-collapse"])
self.console.add_persistent_args(["--ok-label", "Select"])
self.console.add_persistent_args(["--cancel-label", "Back"])
self.console.add_persistent_args(["--colors"])
if title:
self.console.add_persistent_args(["--backtitle", title])
def _handle_exitcode(self, retcode):
if retcode == 2: # ESC, ALT+?
text = "Do you really want to quit?"
if self.console.yesno(text) == 0:
sys.exit(0)
return False
return True
def _wrapper(self, dialog, text, *args, **kws):
try:
method = getattr(self.console, dialog)
except AttributeError:
raise Error("dialog not supported: " + dialog)
while 1:
ret = method("\n" + text, *args, **kws)
if type(ret) is int:
retcode = ret
else:
retcode = ret[0]
if self._handle_exitcode(retcode):
break
return ret
def infobox(self, text):
return self._wrapper("infobox", text)
def yesno(self, text):
return self._wrapper("yesno", text)
def msgbox(self, title, text, button_label="ok"):
return self._wrapper("msgbox", text, self.height, self.width,
title=title, ok_label=button_label)
def menu(self, title, text, choices, no_cancel=False):
return self._wrapper("menu", text, self.height, self.width,
menu_height=len(choices)+1,
title=title, choices=choices, no_cancel=no_cancel)
def form(self, title, text, fields, ok_label="Apply", cancel_label="Cancel"):
return self._wrapper("form", text, self.height, self.width,
form_height=len(fields)+1,
title=title, fields=fields,
ok_label=ok_label, cancel_label=cancel_label)
class Installer:
def __init__(self, path):
self.path = path
self.available = self._is_available()
def _is_available(self):
if not os.path.exists(self.path):
return False
fh = file('/proc/cmdline')
cmdline = fh.readline()
fh.close()
for cmd in cmdline.split():
if cmd == "boot=casper":
return True
return False
def execute(self):
if not self.available:
raise Error("installer is not available to be executed")
executil.system(self.path)
class TurnkeyConsole:
OK = 0
CANCEL = 1
def __init__(self, advanced_enabled=True):
title = "Chitanka Configuration Console"
self.width = 60
self.height = 20
self.console = Console(title, self.width, self.height)
self.appname = "%s" % netinfo.get_hostname().upper()
self.installer = Installer(path='/usr/bin/di-live')
self.advanced_enabled = advanced_enabled
@staticmethod
def _get_filtered_ifnames():
ifnames = []
for ifname in netinfo.get_ifnames():
if ifname.startswith(('lo', 'tap', 'br', 'tun', 'vmnet', 'wmaster')):
continue
ifnames.append(ifname)
ifnames.sort()
return ifnames
@classmethod
def _get_default_nic(cls):
def _validip(ifname):
ip = ifutil.get_ipconf(ifname)[0]
if ip and not ip.startswith('169'):
return True
return False
ifname = conf.Conf().default_nic
if ifname and _validip(ifname):
return ifname
for ifname in cls._get_filtered_ifnames():
if _validip(ifname):
return ifname
return None
def _get_advmenu(self):
items = []
items.append(("UPDATENOW", "Get latest books"))
items.append(("Repair", "Repair and update Chitanka"))
items.append(("Reboot", "Reboot the appliance"))
items.append(("Shutdown", "Shutdown the appliance"))
#items.append(("Share", "Share content folder in LAN"))
#items.append(("Noshare", "Remove shared content folder"))
items.append(("Networking", "Configure appliance networking"))
items.append(("Ping", "Test internet connection"))
items.append(("ClearCache", "Clear chitanka cache"))
items.append(("ClearSpace", "Clear free space"))
return items
def _get_netmenu(self):
menu = []
for ifname in self._get_filtered_ifnames():
addr = ifutil.get_ipconf(ifname)[0]
ifmethod = ifutil.get_ifmethod(ifname)
if addr:
desc = addr
if ifmethod:
desc += " (%s)" % ifmethod
if ifname == self._get_default_nic():
desc += " [*]"
else:
desc = "not configured"
menu.append((ifname, desc))
return menu
def _get_ifconfmenu(self, ifname):
menu = []
menu.append(("DHCP", "Configure networking automatically"))
menu.append(("StaticIP", "Configure networking manually"))
#if not ifname == self._get_default_nic() and \
# len(self._get_filtered_ifnames()) > 1 and \
# ifutil.get_ipconf(ifname)[0] is not None:
# menu.append(("Default", "Show this adapter's IP address in Usage"))
return menu
def _get_ifconftext(self, ifname):
addr, netmask, gateway, nameservers = ifutil.get_ipconf(ifname)
if addr is None:
return "Network adapter is not configured\n"
text = "IP Address: %s\n" % addr
text += "Netmask: %s\n" % netmask
text += "Default Gateway: %s\n" % gateway
text += "Name Server(s): %s\n\n" % " ".join(nameservers)
ifmethod = ifutil.get_ifmethod(ifname)
if ifmethod:
text += "Networking configuration method: %s\n" % ifmethod
if len(self._get_filtered_ifnames()) > 1:
text += "Is this adapter's IP address displayed in Usage: "
if ifname == self._get_default_nic():
text += "yes\n"
else:
text += "no\n"
return text
def usage(self):
if self.advanced_enabled:
default_button_label = "Advanced Menu"
default_return_value = "advanced"
else:
default_button_label = "Quit"
default_return_value = "quit"
#if no interfaces at all - display error and go to advanced
if len(self._get_filtered_ifnames()) == 0:
error = "No network adapters detected"
if not self.advanced_enabled:
fatal(error)
self.console.msgbox("Error", error)
return "advanced"
#if interfaces but no default - display error and go to networking
ifname = self._get_default_nic()
if not ifname:
error = "Networking is not yet configured"
if not self.advanced_enabled:
fatal(error)
self.console.msgbox("Error", error)
return "networking"
#tklbam integration
try:
tklbam_status = executil.getoutput("tklbam-status --short")
except executil.ExecError, e:
if e.exitcode in (10, 11): #not initialized, no backups
tklbam_status = e.output
else:
tklbam_status = ''
#display usage
ipaddr = ifutil.get_ipconf(ifname)[0]
hostname = netinfo.get_hostname().upper()
try:
#backwards compatible - use usage.txt if it exists
t = file(conf.path("usage.txt"), 'r').read()
text = Template(t).substitute(hostname=hostname, ipaddr=ipaddr)
retcode = self.console.msgbox("Usage", text,
button_label=default_button_label)
except conf.Error:
t = file(conf.path("services.txt"), 'r').read().rstrip()
text = Template(t).substitute(ipaddr=ipaddr)
retcode = self.console.msgbox("%s appliance services" % hostname,
text, button_label=default_button_label)
if retcode is not self.OK:
self.running = False
return default_return_value
def advanced(self):
#dont display cancel button when no interfaces at all
no_cancel = False
if len(self._get_filtered_ifnames()) == 0:
no_cancel = True
retcode, choice = self.console.menu("Advanced Menu",
self.appname + " Advanced Menu\n",
self._get_advmenu(),
no_cancel=no_cancel)
if retcode is not self.OK:
return "usage"
return "_adv_" + choice.lower()
def networking(self):
ifnames = self._get_filtered_ifnames()
#if no interfaces at all - display error and go to advanced
if len(ifnames) == 0:
self.console.msgbox("Error", "No network adapters detected")
return "advanced"
# if only 1 interface, dont display menu - just configure it
if len(ifnames) == 1:
self.ifname = ifnames[0]
return "ifconf"
# display networking
text = "Choose network adapter to configure\n"
if self._get_default_nic():
text += "[*] This adapter's IP address is displayed in Usage"
retcode, self.ifname = self.console.menu("Networking configuration",
text, self._get_netmenu())
if retcode is not self.OK:
return "advanced"
return "ifconf"
def ifconf(self):
retcode, choice = self.console.menu("%s configuration" % self.ifname,
self._get_ifconftext(self.ifname),
self._get_ifconfmenu(self.ifname))
if retcode is not self.OK:
# if multiple interfaces go back to networking
if len(self._get_filtered_ifnames()) > 1:
return "networking"
return "advanced"
return "_ifconf_" + choice.lower()
def _ifconf_staticip(self):
def _validate(addr, netmask, gateway, nameservers):
"""Validate Static IP form parameters. Returns an empty array on
success, an array of strings describing errors otherwise"""
errors = []
if not addr:
errors.append("No IP address provided")
elif not ipaddr.is_legal_ip(addr):
errors.append("Invalid IP address: %s" % addr)
if not netmask:
errors.append("No netmask provided")
elif not ipaddr.is_legal_ip(netmask):
errors.append("Invalid netmask: %s" % netmask)
for nameserver in nameservers:
if nameserver and not ipaddr.is_legal_ip(nameserver):
errors.append("Invalid nameserver: %s" % nameserver)
if len(nameservers) != len(set(nameservers)):
errors.append("Duplicate nameservers specified")
if errors:
return errors
if gateway:
if not ipaddr.is_legal_ip(gateway):
return [ "Invalid gateway: %s" % gateway ]
else:
iprange = ipaddr.IPRange(addr, netmask)
if gateway not in iprange:
return [ "Gateway (%s) not in IP range (%s)" % (gateway,
iprange) ]
return []
addr, netmask, gateway, nameservers = ifutil.get_ipconf(self.ifname)
input = [addr, netmask, gateway]
input.extend(nameservers)
# include minimum 2 nameserver fields and 1 blank one
if len(input) < 4:
input.append('')
if input[-1]:
input.append('')
field_width = 30
field_limit = 15
while 1:
fields = [
("IP Address", input[0], field_width, field_limit),
("Netmask", input[1], field_width, field_limit),
("Default Gateway", input[2], field_width, field_limit),
]
for i in range(len(input[3:])):
fields.append(("Name Server", input[3+i], field_width, field_limit))
text = "Static IP configuration (%s)" % self.ifname
retcode, input = self.console.form("Network settings", text, fields)
if retcode is not self.OK:
break
# remove any whitespaces the user might of included
for i in range(len(input)):
input[i] = input[i].strip()
# unconfigure the nic if all entries are empty
if not input[0] and not input[1] and not input[2] and not input[3]:
ifutil.unconfigure_if(self.ifname)
break
addr, netmask, gateway = input[:3]
nameservers = input[3:]
for i in range(nameservers.count('')):
nameservers.remove('')
err = _validate(addr, netmask, gateway, nameservers)
if err:
err = "\n".join(err)
else:
err = ifutil.set_static(self.ifname, addr, netmask,
gateway, nameservers)
if not err:
break
self.console.msgbox("Error", err)
return "ifconf"
def _ifconf_dhcp(self):
self.console.infobox("Requesting DHCP for %s..." % self.ifname)
err = ifutil.set_dhcp(self.ifname)
if err:
self.console.msgbox("Error", err)
return "ifconf"
def _ifconf_default(self):
conf.Conf().set_default_nic(self.ifname)
return "ifconf"
def _adv_install(self):
text = "Please note that any changes you may have made to the\n"
text += "live system will *not* be installed to the hard disk.\n\n"
self.console.msgbox("Installer", text)
self.installer.execute()
return "advanced"
def _shutdown(self, text, opt):
if self.console.yesno(text) == self.OK:
self.running = False
cmd = "shutdown %s now" % opt
fgvt = os.environ.get("FGVT")
if fgvt:
cmd = "chvt %s; " % fgvt + cmd
executil.system(cmd)
return "advanced"
def _adv_reboot(self):
return self._shutdown("Reboot the appliance?", "-r")
def _adv_shutdown(self):
return self._shutdown("Shutdown the appliance?", "-h")
def _adv_quit(self):
default_return_value = "advanced" if self.advanced_enabled else "usage"
if self.console.yesno("Do you really want to quit?") == self.OK:
self.running = False
return default_return_value
def _adv_ping(self):
executil.system("clear; echo 'CHECKING INTERNET CONNECTION...\n(Wait 10 seconds and press Ctrl+C)'; if ping -w 1000 -c 4 8.8.8.8 | grep Unreachable > /dev/null 2>&1; then echo '\n NO INTERNET CONNECTION! \n\nCheck your router or VirtualBox settings.'; else echo '\n INTERNET CONNECTION IS OK!'; fi; sleep 5")
return "advanced"
def _adv_repair(self):
executil.system("rm /update* 2>/dev/null 1>/dev/null; wget https://raw.githubusercontent.com/chitanka/sites-files/master/update 2>/dev/null 1>/dev/null; sh update")
return "advanced"
def _adv_updatenow(self):
executil.system("cd /var/www/chitanka; echo UPDATING... check http://$(ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}')/manual.log for details; echo $(date) > web/manual.log; git stash 2>> web/manual.log 1>> web/manual.log; git pull 2>> web/manual.log 1>> web/manual.log; bin/update 2>> web/manual.log 1>> web/manual.log")
return "advanced"
def _adv_share(self):
executil.system("echo SHARING...; cp /var/www/shared /etc/samba/smb.conf > /dev/null 2>&1; service samba restart > /dev/null 2>&1")
return "advanced"
def _adv_noshare(self):
executil.system("echo REMOVING SHARE...; cp /var/www/noshared /etc/samba/smb.conf > /dev/null 2>&1; service samba restart > /dev/null 2>&1")
return "advanced"
def _adv_clearcache(self):
executil.system("echo Clearing chitanka cache, please wait...; sync; echo 3 > /proc/sys/vm/drop_caches; rm -fr /var/www/chitanka/web/cache/*")
return "advanced"
def _adv_clearspace(self):
executil.system("echo Clearing empty space, please wait...; dd if=/dev/zero of=big bs=1M; rm big")
return "advanced"
_adv_networking = networking
quit = _adv_quit
def loop(self, dialog="usage"):
self.running = True
prev_dialog = dialog
while dialog and self.running:
try:
try:
method = getattr(self, dialog)
except AttributeError:
raise Error("dialog not supported: " + dialog)
new_dialog = method()
prev_dialog = dialog
dialog = new_dialog
except Exception, e:
sio = StringIO()
traceback.print_exc(file=sio)
self.console.msgbox("Caught exception", sio.getvalue())
dialog = prev_dialog
def main():
advanced_enabled = True
args = sys.argv[1:]
if args:
if args[0] == '--usage':
advanced_enabled = False
else:
usage()
if os.geteuid() != 0:
fatal("confconsole needs root privileges to run")
tc = TurnkeyConsole(advanced_enabled)
tc.loop()
if __name__ == "__main__":
main()