Source

raa / scripts / rapa-console

Full commit
  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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
#!/usr/bin/env python
#
# Copyright (c) 2008-2009 rPath, Inc.
# All rights reserved
#

from snack import *
import socket
import sys
import xmlrpclib
from raa.lib import validate
import os
import pwd, grp
import time
import re

class BackException(Exception):

    pass

def ErrorWindow(screen, txt):
    ButtonChoiceWindow(screen, 'Error', txt, buttons = [ 'OK' ])

def HelpWindow(screen, txt):
    ButtonChoiceWindow(screen, 'Help', txt, buttons = [ 'OK' ], width = 55)

def MessageWindow(screen, txt):
    ButtonChoiceWindow(screen, 'Success', txt, buttons = [ 'OK' ])

def helpCallback(screen, klass):
    if klass.help:
        HelpWindow(screen, klass.help)

def ListboxChoiceWindow(screen, title, text, items,
            width = 40, scroll = 0, height = -1, default = None,
            help = None):
    """
    - ListboxChoiceWindow(screen, title, text, items, 
            width = 40, scroll = 0, height = -1, default = None,
            help = None):
    """
    if (height == -1): height = len(items)

    t = TextboxReflowed(width, text)
    l = Listbox(height, scroll = scroll, returnExit = 1)
    count = 0
    for item in items:
        if (type(item) == types.TupleType):
            (text, key) = item
        else:
            text = item
            key = count

        if (default == count):
            default = key
        elif (default == item):
            default = key

        l.append(text, key)
        count = count + 1

    if (default != None):
        l.setCurrent (default)

    g = GridFormHelp(screen, title, help, 1, 3)
    g.add(t, 0, 0)
    g.add(l, 0, 1, padding = (0, 1, 0, 1))

    rc = g.runOnce()

    return (l.current())

class StageRunner(object):
    def __init__(self, stage):
        self.stage = stage

    def runOnce(self, stage):
        """
        Run the stage.
        Return a new stage to run, or None if nothing else is to be run.
        """
        try:
            nextStage = stage.getResult()
        except socket.error, e:
            ButtonChoiceWindow(self.stage.screen, 'Error',
                               'Cannot contact the configuration server:'
                               + str(e), buttons = [ 'OK' ])
            return None
        except BackException:
            return None
        except xmlrpclib.ProtocolError, e:
            if e.errcode == 403:
                ButtonChoiceWindow(self.stage.screen, 'Insufficient Permission',
                                   'The credentials you supplied were not '
                                   'correct or did not grant access to '
                                   'this resource.',
                                   buttons = [ 'OK' ])
            else:
                ButtonChoiceWindow(self.stage.screen, 'Unknown Error',
                                   'Error:' + str(e), buttons = [ 'OK' ])
            return None
        except Exception, e:
            ButtonChoiceWindow(self.stage.screen, 'Unknown Error',
                               'Error:' + str(e), buttons = [ 'OK' ])
            return None
        return nextStage

    def run(self):
        """
        Infinite run loop
        """
        stage = self.stage
        while True:
            nextStage = self.runOnce(stage)
            stage = nextStage or self.stage

class Stage(object):

    help = None

    def __init__(self, screen):
        self.screen = screen

    @staticmethod
    def _cbCallback((cb, entries)):
        if cb.selected():
            flag = FLAGS_SET
        else:
            flag = FLAGS_RESET

        [ x.setFlags(FLAG_DISABLED, flag) for x in entries ]

    def getResult(self):
        """
        Return the next stage to run, or None if nothing else is to be run.
        """
        raise NotImplementedError()

class Splash(Stage):
    def parseEtcIssue(self):
        u = os.uname()
        ltime = time.localtime()
        users = len(os.popen("/usr/bin/users").readlines())
        message = []

        # See the mingetty man page for an explanation of these values
        trans = { 'd': time.strftime("%Y-%m-%d", ltime),
                  'l': os.ttyname(sys.stdin.fileno()),
                  'm': u[4],
                  'n': u[1],
                  'o': "".join(open("/proc/sys/kernel/domainname", "r").readlines()).rstrip(),
                  'r': u[2],
                  's': u[0],
                  't': time.strftime("%H:%M:%S", ltime),
                  'u': str(users),
                  'U': "%d users" % users,
                  'v': u[3] }

        def _txtsub(s):
            for c in trans.keys():
                s = s.replace('\\%s' % c, trans[c])
            return s

        for line in open("/etc/issue").readlines():
            message.append("\\".join([_txtsub(x) for x in line.split(r'\\')]).rstrip())
        return message

    def getResult(self):

        message = []
        try:
            message.extend(self.parseEtcIssue())
        except:
            pass
        if message:
            # Add newline between /etc/issue and our own message
            message.append("")
        if os.access('/etc/raa/console.msg', os.R_OK):
            message.extend(open('/etc/raa/console.msg', 'r').readlines())
        else:
            message.append("To access a login console, press control-alt-f2")
        # Try to center the message as much as we can.
        width = 70
        splashText = '\n'.join(x.strip().center(width - 4) for x in message)

        g = ButtonChoiceWindow(self.screen, 'Welcome', splashText,
            width=width, buttons = [ 'Sign in' ], help = None) 
	return SignIn(self.screen)

class SignIn(Stage):

    def getResult(self):
        self.usernameEntry = Entry(20)
        self.passwordEntry = Entry(20, password = True)
        g = GridFormHelp(self.screen, 'rPath Platform Agent Sign In', self, 1, 2)
        sg = Grid(2, 2)

        sg.setField(Label('User Name'), 0, 0, padding = (0, 0, 1, 0),
                    anchorLeft = 1)
        sg.setField(self.usernameEntry, 1, 0, anchorLeft = 1)
        sg.setField(Label('Password'), 0, 1, padding = (0, 0, 1, 0),
                    anchorLeft = 1)
        sg.setField(self.passwordEntry, 1, 1, anchorLeft = 1)
        g.add(sg, 0, 0, padding = (0, 0, 0, 1))

        buttons = ButtonBar(self.screen, [ 'Sign in', 'Cancel' ])
        g.add(buttons, 0, 1, growx = True)

        rc = g.runOnce()
	
	if buttons.buttonPressed(rc) == 'cancel':
	    raise BackException

        (user, password) = (self.usernameEntry.value(),
                            self.passwordEntry.value())

        url = 'http://%s:%s@localhost:8004/xmlrpc/' % (user, password)
        rapaServer = xmlrpclib.ServerProxy(url)
	# check to see if we can sign in
        rc = rapaServer.reboot.Reboot.index()

	if password == 'password':
            next = ChangePassword(self.screen, user, password, rapaServer)
	else:
            next = LandingScreen(self.screen, rapaServer)
        return next

class ChangePassword(Stage):

    def __init__(self, screen, user, password, rapaServer):
        Stage.__init__(self, screen)
        self.rapaServer = rapaServer
	self.user = user
	self.oldPassword = password

    def _makeGrid(self):
        self.passwordEntry = Entry(20, password = True)
        self.password2Entry = Entry(20, password = True)

        g = GridFormHelp(self.screen, 'Change Password', self, 1, 2)
        sg = Grid(2, 2)
        sg.setField(Label('New Password'), 0, 0, padding = (0, 0, 1, 0),
                    anchorLeft = 1)
        sg.setField(self.passwordEntry, 1, 0, anchorLeft = 1)
        sg.setField(Label('Confirm Password'), 0, 1, padding = (0, 0, 1, 0),
                    anchorLeft = 1)
        sg.setField(self.password2Entry, 1, 1, anchorLeft = 1)
        g.add(sg, 0, 0, padding = (0, 0, 0, 1))

        b = Button('Change')
        g.add(b, 0, 1)
        return g


    def getResult(self):
        g = self._makeGrid()
        while 1:
            g.runOnce()

            (password, password2) = (self.passwordEntry.value(),
                                     self.password2Entry.value())

            rc = self.rapaServer.changepassword.ChangePassword.changePassword(
                 self.oldPassword, password, password2)

            if 'errors' not in rc:
                self.rapaServer._ServerProxy__host = re.sub('(:.*@)', ':%s@' % password, 
                                                            self.rapaServer._ServerProxy__host)
                return LandingScreen(self.screen, self.rapaServer)

            ErrorWindow(self.screen, rc['errors'][0])

            # screen.popWindow (from runOnce) has destroyed the old Grid. We need
            # to create a new one and re-populate it.
            g = self._makeGrid()

class LandingScreen(Stage):

    def __init__(self, screen, rapaServer):
        Stage.__init__(self, screen)
        self.rapaServer = rapaServer

    def getResult(self):
        rc = ListboxChoiceWindow(screen, 'Choose an operation',
                                'Choose from the operations available below:',
                                [ ('Network Configuration', 'networking'), 
                                  ('Reboot', 'reboot'),
                                  ('Shut down', 'shutdown'),
                                  ('Log out', 'logout')])
        if rc == 'logout':
            return None
        elif rc == 'shutdown':
            return Shutdown(self.screen, self.rapaServer)
        elif rc == 'reboot':
            return Reboot(self.screen, self.rapaServer)
        elif rc== 'networking':
            return NetworkDevices(self.screen, self.rapaServer)
        return None

class Reboot(Stage):

    def __init__(self, screen, rapaServer):
        Stage.__init__(self, screen)
        self.rapaServer = rapaServer

    def getResult(self):
        while True:
            rc = ButtonChoiceWindow(screen, 'Confirm',
                 'Confirm that you want to reboot.',
                 buttons = [ 'Reboot', 'Do not reboot' ])

            if rc == 'do not reboot':
                return LandingScreen(self.screen, self.rapaServer)
            elif rc == 'reboot':
                rc = self.rapaServer.reboot.Reboot.rebootNow()

class Shutdown(Stage):

    def __init__(self, screen, rapaServer):
        Stage.__init__(self, screen)
        self.rapaServer = rapaServer

    def getResult(self):
        while True:
            rc = ButtonChoiceWindow(screen, 'Confirm',
                 'Confirm that you want to shut down.',
                 buttons = [ 'Shut down', 'Do not shut down' ])

            if rc == 'do not shut down':
                return LandingScreen(self.screen, self.rapaServer)
            elif rc == 'shut down':
                rc = self.rapaServer.reboot.Reboot.shutdownNow()

class NetworkDevices(Stage):

    help = ("Configure network host name, domain name service, and network "
            "interface settings, such as IP address and default gateway, "
            "using the controls below. Changes to host name and other DNS "
            "settings take effect immediately; changes to network interfaces "
            "take effect if you choose 'Apply' when prompted for confirmation, "
            "or if you choose 'Restart' after saving. Otherwise, saved changes "
            "take effect on the next appliance boot.")

    def __init__(self, screen, rapaServer):
        Stage.__init__(self, screen)
        self.rapaServer = rapaServer

    @staticmethod
    def formatDevLine(devName, cfg):
        if 'BOOTPROTO' not in cfg.keys():
            cfg['BOOTPROTO'] = 'static'

        ipcfg = ''
        if cfg['BOOTPROTO'] == 'dhcp':
            ipcfg = 'DHCP'
        elif 'IPADDR' in cfg:
            ipcfg = cfg['IPADDR']
        else:
            ipcfg = '0.0.0.0'

        enabled = cfg['ONBOOT'] == 'yes' and 'enabled' or 'disabled'

        return '%-15s | %-15s | %-8s' % (devName, ipcfg, enabled)

    def getResult(self):
        networkConfig = self.rapaServer.configure.Network.index()

        devList = []
        for devName, cfg in sorted(networkConfig['devs'].items()):
            txt = self.formatDevLine(devName, cfg)
            if txt:
                devList.append((txt, devName))

        if not devList:
            rc = ButtonChoiceWindow(self.screen, 'Error',
                 'There are no network devices available.',
                 buttons = [ 'Back' ])
            return LandingScreen(self.screen, self.rapaServer)

        li = Listbox(min(3, len(devList)), width = 40,
                     scroll = (len(devList) > 3), returnExit = True)
        [ li.append(*x) for x in devList ]

        buttons = ButtonBar(self.screen, [ 'Save', 'Help', 'Cancel' ])

        hostDhcp = Checkbox('Obtain host configuration from DHCP:',
                            isOn = networkConfig['host_usesdhcp'])
        hostGrid = Grid(2, 1)
        hostEntry = Entry(20, networkConfig['host_hostName'])
        hostGrid.setField(Label('Host name:'), 0, 0, anchorLeft = 1,
                          padding = (0, 0, 1, 0))
        hostGrid.setField(hostEntry, 1, 0, anchorRight = True)
        self._cbCallback((hostDhcp, (hostEntry, )))
        hostDhcp.setCallback(self._cbCallback,
                             (hostDhcp, (hostEntry, )))

        dnsDhcp = Checkbox('Obtain DNS servers from DHCP:',
                           isOn = networkConfig['dns_dnsdhcp'])
        dnsGrid = Grid(2, 2)
        dnsEntry = Entry(20, " ".join(networkConfig['dns_dnsServer']))
        searchEntry = Entry(20, networkConfig['dns_dnsDomain'])
        dnsGrid.setField(Label('DNS Servers:'), 0, 0, anchorLeft = 1,
                          padding = (0, 0, 1, 0))
        dnsGrid.setField(dnsEntry, 1, 0, anchorRight = True)
        dnsGrid.setField(Label('Search domain:'), 0, 1, anchorLeft = 1,
                          padding = (0, 0, 1, 0))
        dnsGrid.setField(searchEntry, 1, 1, anchorRight = True)
        self._cbCallback((dnsDhcp, (dnsEntry, searchEntry)))
        dnsDhcp.setCallback(self._cbCallback,
                             (dnsDhcp, (dnsEntry, searchEntry)))


        # If a gateway is present, gateway info is not driven by DHCP
        currentGatewayDev = networkConfig['host_gatewaydev']
        currentGateway = networkConfig['host_gateway']
        gatewayDhcp = Checkbox('Obtain default gateway from DHCP:',
                               isOn = not bool(currentGateway))
        gatewayGrid = Grid(2, 2)
        gatewayEntry = Entry(20, networkConfig['host_gateway'])
        gatewayGrid.setField(Label('Default Gateway:'), 0, 0, anchorLeft = 1,
                          padding = (0, 0, 1, 0))
        gatewayGrid.setField(gatewayEntry, 1, 0, anchorRight = True)
        width = max(len(x[1]) for x in devList)
        gatewayDevList = Listbox(min(3, len(devList)), width = width,
                         scroll = (len(devList) > 2), returnExit = False)
        for x in devList:
            gatewayDevList.append(x[1], x[1])
        if currentGatewayDev in gatewayDevList.item2key:
            gatewayDevList.setCurrent(currentGatewayDev)

        gatewayGrid.setField(Label('Gateway Device:'), 0, 1, anchorLeft = 1,
                          padding = (0, 0, 1, 0))
        gatewayGrid.setField(gatewayDevList, 1, 1, anchorLeft = True)
        self._cbCallback((gatewayDhcp, (gatewayEntry, )))
        gatewayDhcp.setCallback(self._cbCallback,
                             (gatewayDhcp, (gatewayEntry, )))

        g = GridFormHelp(self.screen, 'Configure Networking',
                         self, 1, 9)
        self._populateGrid(g, hostDhcp, hostGrid, dnsDhcp, dnsGrid,
                gatewayDhcp, gatewayGrid, li, buttons)
        while True:
            rc = g.run()
            if rc == li:
                dev = li.current()
                cfgDev = ConfigureDevice(self.screen, self.rapaServer,
                                       dev, networkConfig['devs'][dev])
                StageRunner(cfgDev).runOnce(cfgDev)
                networkConfig['devs'][dev] = cfgDev.getConfig()
                li.replace(self.formatDevLine(dev, networkConfig['devs'][dev]),
                           dev)
                li.setCurrent(dev)
                continue

            # Process button events first, if a cancel button was hit we don't
            # want to validate the changes (possibly invalid anyway)
            if buttons.buttonPressed(rc) == 'help':
                HelpWindow(self.screen, self.help)
                continue
            if buttons.buttonPressed(rc) == 'cancel':
                rc = ButtonChoiceWindow(self.screen, 'Confirm',
                    'Choose OK to exit without saving any changes.',
                    buttons = [ 'OK', 'Cancel' ])

                if rc == 'cancel':
                    continue
                self.screen.popWindow()
                return LandingScreen(self.screen, self.rapaServer)

            if hostDhcp.selected():
                useHostDhcp = True
                hostName = 'localhost.localdomain'
            else:
                useHostDhcp = False
                hostName = hostEntry.value()

            if dnsDhcp.selected():
                useDnsDhcp = True
                dnsServer = []
                searchPath = ''
            else:
                useDnsDhcp = False
                dnsServer = dnsEntry.value().split()
                searchPath = searchEntry.value()

            useGatewayDhcp = gatewayDhcp.selected()
            gatewaydev = gatewayDevList.current()
            gateway = gatewayEntry.value()

            if buttons.buttonPressed(rc) == 'save':
                rc = ButtonChoiceWindow(self.screen, 'Configure Networking',
                    'Choose Save to save the networking '
                    'information.\n\n'
                    'Choose Restart to save and imediately restart '
                    'all your network devices.',
                    buttons = [ 'Cancel', 'Save', 'Restart' ])
                if rc == 'cancel':
                    continue

                restart = (rc == 'restart')
            self.screen.popWindow()

            # The gateway is not set here but in the interface
            general = { 
                        'host': { 
                                  'usesdhcp': useHostDhcp,
                                  'gatewaydhcp': useGatewayDhcp,
                                  'gateway': gateway,
                                  'gatewaydev': gatewaydev,
                                  'hostName': hostName,
                                },
                        'dns':  {
                                  'dnsdhcp': useDnsDhcp,
                                  'dnsDomain': searchPath,
                                  'dnsServer': dnsServer,
                                }
                       }
            devices = {} 
            for d, devName in devList:
                cfg = networkConfig['devs'][devName]
                if cfg['BOOTPROTO'] == 'dhcp':
                    devices[devName] = {
                                         'dhcp': 'on',
                                         'ipaddress': '',
                                         'netmask': '', 
                                         'enabled': cfg['ONBOOT']
                                       }  
                else:
                    devices[devName] = {
                                         'dhcp': 'off',
                                         'ipaddress': cfg.get('IPADDR', ''),
                                         'netmask': cfg.get('NETMASK', ''), 
                                         'enabled': cfg['ONBOOT']
                                       }  
                       
            ret = self.rapaServer.configure.Network.saveAll2(
                    devices, general, restart)
            if 'errors' in ret:
                if isinstance(ret['errors'], list):
                    ErrorWindow(self.screen, ret['errors'][0])
                else:
                    ErrorWindow(self.screen, ret['errors'])

                # screen.popWindow above has destroyed the old Grid. We need
                # to create a new one and re-populate it.
                g = GridFormHelp(self.screen, 'Configure Networking',
                                 self, 1, 9)
                self._populateGrid(g, hostDhcp, hostGrid, dnsDhcp, dnsGrid,
                        gatewayDhcp, gatewayGrid, li, buttons)
                continue
            else:
                MessageWindow(self.screen, ret['message'][0])
            return LandingScreen(self.screen, self.rapaServer)

    def _populateGrid(self, g, hostDhcp, hostGrid, dnsDhcp, dnsGrid,
            gatewayDhcp, gatewayGrid, devList, buttons):
        g.add(hostDhcp, 0, 0, anchorLeft = 1)
        g.add(hostGrid, 0, 1, padding = (5, 0, 1, 0), anchorLeft = 1,
              growx = True)
        g.add(dnsDhcp, 0, 2, padding = (0, 1, 0, 0), anchorLeft = 1)
        g.add(dnsGrid, 0, 3, padding = (5, 0, 1, 0), anchorLeft = 1,
              growx = True)
        g.add(gatewayDhcp, 0, 4, padding = (0, 1, 0, 0), anchorLeft = True)
        g.add(gatewayGrid, 0, 5, padding = (5, 0, 1, 0), anchorLeft = True,
              growx = True)
        g.add(Label('Configure device:'), 0, 6, padding = (0, 1, 0, 0),
              anchorLeft = True)
        g.add(devList, 0, 7, padding = (5, 0, 0, 0), anchorLeft = True)
        g.add(buttons, 0, 8, padding = (0, 1, 0, 0), growx = True)
        return g


class ConfigureDevice(Stage):

    help = NetworkDevices.help

    def __init__(self, screen, rapaServer, devName, devInfo):
        self.screen = screen
        self.rapaServer = rapaServer
        self.devName = devName
        self.devInfo = devInfo

    def getConfig(self):
        return self.devInfo

    def getResult(self):
        g = GridFormHelp(self.screen, 'Configure Device %s' % self.devName,
                         self, 1, 4)
        enabled = Checkbox('Enable this device:',
                        isOn = self.devInfo['ONBOOT'] == 'yes')

        dhcp = Checkbox('Obtain device configuration from DHCP:',
                        isOn = self.devInfo['BOOTPROTO'] == 'dhcp')

        sg = Grid(2, 3)

        ipEntry = Entry(20, self.devInfo.get('IPADDR', ''))
        sg.setField(Label('IP Address'), 0, 0, padding = (0, 0, 1, 0),
                    anchorLeft = 1)
        sg.setField(ipEntry, 1, 0, anchorLeft = 1)

        nmEntry = Entry(20, self.devInfo.get('NETMASK', ''))
        sg.setField(Label('Netmask'), 0, 1, padding = (0, 0, 1, 0),
                    anchorLeft = 1)
        sg.setField(nmEntry, 1, 1, anchorLeft = 1)

        sg.setField(Label('MAC Address'), 0, 2, padding = (0, 0, 1, 0),
                    anchorLeft = 1)
        sg.setField(Label(self.devInfo['HWADDR']), 1, 2,
                    anchorLeft = 1)

        buttons = ButtonBar(self.screen, [ 'Save', 'Cancel' ])

        g.add(enabled, 0, 0, padding = (0, 0, 0, 1))
        g.add(dhcp, 0, 1, padding = (0, 0, 0, 1))
        g.add(sg, 0, 2)
        g.add(buttons, 0, 3, padding = (0, 1, 0, 0), growx = True)

        self._cbCallback((dhcp, (ipEntry, nmEntry)))
        dhcp.setCallback(self._cbCallback, (dhcp, (ipEntry, nmEntry)))

        while True:
            rc = g.run()
            if (buttons.buttonPressed(rc) == 'cancel'):
                self.screen.popWindow()
                raise BackException

            newDev = { 'HWADDR' : self.devInfo['HWADDR'] }

            if enabled.selected():
                newDev['ONBOOT'] = 'yes'
            else:
                newDev['ONBOOT'] = 'no'

            if dhcp.selected():
                newDev['BOOTPROTO'] = 'dhcp'
            else:
                newDev['BOOTPROTO'] = 'static'
                ip = ipEntry.value()
                nm = nmEntry.value()
                if len(ip) > 0 and not validate.validateIP(ip):
                    ErrorWindow(self.screen,
                                "'%s' is not a valid numeric IP address." % ip)
                    continue
                elif len(nm) > 0 and not validate.validateIP(nm):
                    ErrorWindow(self.screen,
                                "'%s' is not a valid netmask.'" % nm)
                    continue

                newDev['IPADDR'] = ip
                newDev['NETMASK'] = nm

            screen.popWindow()
            self.devInfo = newDev
            raise BackException

        return None


def setLang():
    if os.getenv('LANG') is None:
        # first, a reasonable fallback
        os.environ['LANG'] = 'en_US.utf8'
        # then try to find the system setting
        try:
            LangEnv = [
                  x.strip().split('=', 1)
                  for x in file('/etc/sysconfig/i18n').readlines() 
                  if x.startswith('LANG=') ][-1][1]
            os.environ['LANG'] = LangEnv.strip('"').strip("'")
        except:
            pass

# LANG must be set for slang to work
setLang()

if os.geteuid() == 0:
    if len(sys.argv) > 1:
        # this should only be used by init; it assumes we're already the
        # session leader
        tty = sys.argv[-1]
        if tty[0] != '/':
            tty = '/dev/' + tty

        fd = os.open(tty, os.O_RDWR)
        os.dup2(fd, 7)
        newtty = 7
        os.close(fd)

        # disassociate from the tty
        try:
            os.close(0)
            os.close(1)
            os.close(2)
        except:
            pass

        # this open sets the controlling tty for this process
        inF = os.dup(newtty)
        assert(inF == 0)
        outF = os.dup(newtty)
        assert(outF == 1)
        outF = os.dup(newtty)
        assert(outF == 2)
        os.close(newtty)

    try:
        nobodyUid = pwd.getpwnam('nobody').pw_uid

        try:
            nobodyGid = grp.getgrnam('nobody').gr_gid
        except KeyError, e:
            # On Ubuntu, nobody is a member of nogroup
            nobodyGid = grp.getgrnam('nogroup').gr_gid

        os.setgid(nobodyGid)
        os.setuid(nobodyUid)
    except Exception, e:
        sys.stderr.write('Cannot switch to user/group nobody: %s\n' % str(e))
        sys.exit(1)
elif len(sys.argv) > 1:
    sys.stderr.write('Arguments only supported when run as root.\n')
    sys.exit(1)

screen = SnackScreen()
screen.helpCallback(helpCallback)
screen.pushHelpLine('   <Tab>/<Alt-Tab> between elements  |  <Space> selects')
try:
    f = open('/etc/sysconfig/appliance-name', "r")
    for i, l in enumerate(f.readlines()):
        l = l[:-1]
        screen.drawRootText(0, i, l)
    f.close()
except OSError:
    pass

try:
    while True:
        try:
            StageRunner(Splash(screen)).run()
        except BackException:
            pass
except:
    screen.finish()
    raise

screen.finish()