Source

vasm / src / vasm / backend / NETWORKING.py

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
#!/usr/bin/env python

#    This file is part of VASM.
#
#    VASM is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License v3 as published by
#    the Free Software Foundation.
#
#    VASM is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with VASM.  If not, see <http://www.gnu.org/licenses/>.

#   Thanks to Jason Pierce (rxMokka) for the research that went into this.

__author__ = "Moises Henriquez"
__author_email__ = "moc.liamg@xnl.E0M"[::-1]
__contributors__ = ["Uel Archuletta", 
    "Jason Pierce",
    "Rodrigo Bistolfi"]

""" NETWORKING.py
Interact with network interfaces and general system networking settings. """
import netinfo
import os
import logging
import shutil
from utils import get_popen
import SERVICES
logger = logging.getLogger('vasm')

# Networking Constants
NET_NONE = -1
NET_DAEMON = -2
NET_INET = -3
NET_INET_DHCP = -4
NET_INET_STATIC = -5
DHCP = NET_INET_DHCP
STATIC = NET_INET_STATIC

class MissingDaemonError(Exception):
    def __init__(self, message):
        self.message = message
    
    def __str__(self):
        return repr(self.message)

class NDaemon(object):
    """ Class representing a networking daemon available on the system. 
    Allows us to interact with this daemon, and perform tasks such as
    enabling it and disabling it. 
    Arguments:
        bin_path    -   Path to the executable.
        init_script -   Path to the rc.daemon file in /etc/rc.d
        service_script - Path to the service handler for this daemon. 
                        Usually somewhere in /etc/rc.d/init.d """
        
    def __init__(self, name=None, bin_path=None, init_script=None, 
            service_script=None, sessionscript = None):
        self.name = name
        self.bin_path = bin_path
        self.init_script = init_script
        self.service_script = service_script
        self.sessionscript = sessionscript
        
        self.enabled_autostart = '/etc/xdg/autostart'
        self.disabled_autostart = '/etc/xdg/autostart-disabled'
        self.sessionfile = os.path.split(self.sessionscript)[-1]
    
    def _run_command(self, cmd):
        proc = get_popen(cmd)
        stdout, stderr = proc.communicate()
        code = proc.returncode
        assert code == 0, stderr.strip()    
    
    def enable(self):
        """ Make the init_script executable """
        self.enable_session_script()
        return self._run_command(['chmod','+x', self.init_stript])
    
    def disable(self):
        """ Make the init_script not executable """
        self.disable_session_script()
        return self._run_command(['chmod', '-x', self.init_stript])
    
    def enable_session_script(self):
        """ Enable the session startup script.  This will allow the desktop
            to automatically start this daemons panel applets."""
        dpath = os.path.join(self.disabled_autostart, self.sessionfile)
        epath = os.path.join(self.enabled_autostart, self.sessionfile)
        if os.path.exists(dpath):
            shutil.move(dpath, epath)
        return
    
    def disable_session_script(self):
        """ Disable the session startup scripts.  This will avoid the desktop
            showing error messages about not being able to connect to this
            daemons backend."""
        # Make sure the disabled dir exists
        if not os.path.isdir(self.disabled_autostart):
            os.makedirs(self.disabled_autostart)
        dpath = os.path.join(self.disabled_autostart, self.sessionfile)
        epath = os.path.join(self.enabled_autostart, self.sessionfile)
        if os.path.exists(epath):
            return shutil.move(epath, dpath)
        return
    
    def check_status(self):
        """ Return the status of the daemon. 
        True = Daemon is enabled.
        False = Daemon is disabled."""
        if self._get_rcfile_status() or \
            os.path.exists(os.path.join(self.enabled_autostart, self.sessionfile)):
            return True
        return False
    
    def _get_rcfile_status(self):
        """ Returns True if self.init_script is executable.  False otherwise """
        return os.access(self.init_script, os.X_OK)
    
    def disable_service(self):
        """ disable the service for all runlevels """
        assert self.service_script is not None, \
            "No service script available for %s."% self.bin_path
        svcmodel = SERVICES.ServiceModel()
        assert svcmodel.hasService(self.service_script), \
            "No such service %s on the system."% self.service_script
        for x in range(3,5):
            svcmodel.disable_service(self.service_script, x)        
        return
    
    def enable_service(self):
        """ enable service for runlevels 3-5 """
        assert self.service_script is not None, \
            "No service script available available for %s."% self.bin_path
        svcmodel = SERVICES.ServiceModel()
        assert svcmodel.hasService(self.service_script), \
            "No such service %s on the system."% self.service_script
        
        for x in range(3, 5):
            svcmodel.enable_service(self.service_script, x)
        return

class Nic(object):
    """ Class representing a network interface. 
    By using this class, we can access information about the network
    
    Arguments:
        devname - Device name. ie, 'eth0'
        ip_addr - IP Address for the adaptor.
        netmask - netmask address.
        bcast -   broadcast address.
        macaddr - hardware MAC address
    """
    def __init__(self, devname=None,
            ip_addr = '127.0.0.1',
            netmask = '255.255.255.0',
            bcast = '',
            macaddr = None,
            scripts_loc = '/etc/rc.d'):
        self.devname = devname
        self.ip_addr = ip_addr
        self.netmask = netmask
        self.broadcast = bcast
        self.macaddr = macaddr
        self.livedata = self._get_live_data()
        self.scripts_location = scripts_loc
        self.inet = Inet(
            fpath = self.findConfig(), nic = self)
    
    def _get_live_data(self):
        """ Returns a dictionary of the current information on this nic """
        ldata = netinfo.get_routes(self.devname)
        data = {
            'IPADDR': netinfo.get_ip(self.devname),
            'NETMASK': netinfo.get_netmask(self.devname),
            'BROADCAST': netinfo.get_broadcast(self.devname)}
        gw = None
        for part in ldata:
            if part['dest'] == '0.0.0.0' and \
                    part['dev'] == self.devname and \
                    part['netmask'] == '0.0.0.0':
                gw = part['gateway']
                break
        if gw:
            data['GATEWAY'] = gw
        else:
            data['GATEWAY'] = ''
        return data

    def _get_next_available_config_file(self):
        """ Return a path to the next available config file """
        for x in range(1,10):
            initpath = os.path.join(self.scripts_location,
                'rc.inet%s'% x)
            if not os.path.exists(initpath):
                return initpath
        # Should never return None unless the box has a ridiculous
        # number of network adaptors.
        return None
    
    def findConfig(self):
        """ Locate the configuration file that configures this adaptor"""
        for file in os.listdir(self.scripts_location):
            if file.startswith('rc.inet') and \
                '.conf' not in file and not file.endswith('.new'):
                fpath = os.path.join(self.scripts_location, file)
                #file.endswith('.conf') or file.endswith('.new'):
                #fpath = os.path.join(self.scripts_location, file)
                with open(fpath) as data:
                    for line in data:
                        if self.devname in line:
                            return fpath
        return self._get_next_available_config_file()
    
    def enable(self):
        """ Enable this nic so it can be brought up automatically on boot """
        return self.inet.enable()
    
    def disable(self):
        """ Keep this nic from being brought up on boot """
        return self.inet.disable()
    
    def check_status(self):
        """ Check wether this Nic is being loaded @ startup """
        return self.inet.check_status()

class Inet(object):
    """ Class used to represend an rc.inet configuration file
        in a vectorlinux system.
        Arguments:
            fpath    -   Absolute path to the file we are working with
            nmethod  -   Networking method. Must be one of DHCP or STATIC
    
    DO NOT USE THIS CLASS DIRECTLY.
    Each Nic object gets an object of this class. It can be accessed
    as the .inet attribute of the Nic object.
    """
    def __init__(self, fpath=None, nmethod=DHCP, nic=None):
        self.fpath = fpath
        self.nmethod = nmethod
        self.nic = nic
        try:
            self.config = self._read_config_data()
        except:
            self.config = self._generate_new_config_data()
    
    def _run_command(self, cmd):
        proc = get_popen(cmd)
        stdout, stderr = proc.communicate()
        code = proc.returncode
        assert code == 0, stderr.strip()
    
    def enable(self):
        """ Enable this inet by setting it's config file executable """
        # First check to make sure the file exists
        assert os.path.exists(self.fpath), \
            "No such file %s in the system.  " % self.fpath + \
            "  Has the configuration been saved yet?"
        return self._run_command(['chmod', '+x', self.fpath])
    
    def disable(self):
        """ Disable this inet by etting it's config file NOT executable """
        assert os.path.exists(self.fpath), \
            "No such file %s in the system."% self.fpath
        return self._run_command(['chmod', '-x', self.fpath])
    
    def check_status(self):
        """ Return True if inet is enabled.  False otherwise """
        assert os.path.exists(self.fpath), \
            "No such file %s in the system.  Cannot check its status"% self.fpath
        return os.access(self.fpath, os.X_OK)

    def _generate_new_config_data(self):
        """ Generates new data for a config file.  Only
        the config dictionary is generated here.  The header comments
        and the script call are generated later. """
        if self.nmethod is DHCP:
            dhcpval = 'yes'
        else:
            dhcpval = 'no'
        ret = {
            'DEVICE':self.nic.devname,
            'DHCP': dhcpval,
            'IPADDR': '127.0.0.1',
            'NETMASK': '255.255.255.0',
            'GATEWAY': '',
            'PROBE':'no'}
        return ret
    
    def _generate_complete_config_file(self):
        """ Returns a list with the data necessary to
            write a complete new config file to the sysetem """
        HEADER = [
            "#!/bin/sh",
            "# This file is created by vasm",
            "# Avoid modifying it by hand.",
            "# ",
            "##################################",
            "## The Settings. ",
            ]
        FOOTER = [
            "# ",
            "##################################",
            "# ## The Script ## ",
            "# Source the standard networking script.",
            ". /etc/rc.d/functions-network \"$@\"","#",]
        COMPLETE = []
        # Add the header comments.
        COMPLETE.extend(HEADER)
        # Add the important data 
        for comp in self.config:
            _line = "%s='%s'"% (comp, self.config[comp])
            COMPLETE.append(_line)
        # Add the footer
        COMPLETE.extend(FOOTER)
        return COMPLETE

    def _read_config_data(self):
        """ Return a dictionary with the different options on
            the config file. """
        assert os.path.exists(self.fpath), \
            "No such file %s.  %s represents a NEW unsaved rc.inet config file" % (
                self.fpath, self.fpath)
        ret = {}
        with open(self.fpath) as data:
            for line in data:
                if self._line_sets_value(line):
                    key, value = self._get_line_key_value(line)
                    ret[key] = value
        return ret
    
    def save_config(self):
        """ Write the cofiguration to the filesystem.
            Call this method after the differnt settings have
            been modified """
        # If the file doesn't exist, then we must write a new one
        if not os.path.exists(self.fpath):
            data = self._generate_complete_config_file()
            f = open(self.fpath, 'w')
            f.writelines('\n'.join(data))
            f.close()
            return
        # The file already exists in the filesytem.  We must
        # update it.
        return self._do_write_changes()
        
    def _do_write_changes(self):
        """ Only update the configuration data.  Leave the
            file's comments alone """
        ndata = []
        with open(self.fpath) as data:
            for line in data:
                if self._line_sets_value(line):
                    key, val = self._get_line_key_value(line)
                    line = "%s='%s'"% (key, self.config[key])
                ndata.append(line.strip())
        # write the modified data to the filesystem
        f = open(self.fpath, 'w')
        f.writelines('\n'.join(ndata))
        f.close()
        return

    def _line_sets_value(self, line):
        """ Returns True if line sets a value.  False otherwise """
        return "=" in line
    
    def _get_line_key_value(self, line):
        """ Returns a tuple of (key, value) set by line """
        key, val = line.split('=')
        val = val.strip().replace("\'","").replace("\"","").strip()
        return key, val

class NetConfModel(object):
    """ Global networking model. """
    def __init__(self, host_file='/etc/HOSTNAME',
        dns_file='/etc/resolve.conf',
        hostname=None):
        self.host_file = host_file
        self.dns_file = dns_file
        self.hostname = hostname
    
    def set_hostname(self):
        """ Set the machine hostname to the value specified in self.hostname"""
        assert self.hostname not in ('',None), \
            "Empty hostname is not accepted.  Please set the .hostname attribute first"
        f = open(self.host_file, 'w')
        f.writelines("\n".join([self.hostname,]))
        f.close()
    
    def get_hostname(self):
        """ read the hostname from the file """
        f = open(self.host_file, 'r')
        data = f.readline()
        f.close
        return data.strip()

    def listNetworkingDaemons(self):
        """ Returns a list of known networking daemons available on 
        the system.  list contents are NDaemon objects """
        ret = []
        # Define some known daemons in a dictionary where the key
        # is the name of the daemon, and the key is another dictionary with
        # a 'path', 'initscript', and 'service' keys.
        DAEMONS = {'networkmanager':
            {'path': '/usr/sbin/NetworkManager',
                'name': 'NetworkManager',
                'initscript' : '/etc/rc.d/rc.networkmanager',
                'service' : None,
                'sessionscript' : '/etc/xdg/autostart/nm-applet.desktop'},
            'wicd' : {
                'name': 'Wicd',
                'path': '/usr/sbin/wicd',
                'initscript' : '/etc/rc.d/rc.wicd',
                'service': None,
                'sessionscript' : '/etc/xdg/autostart/wicd-tray.desktop'}}
        for netapp in DAEMONS:
            if os.path.exists(DAEMONS[netapp]['path']):
                ndaemon = NDaemon(
                    name = DAEMONS[netapp]['name'],
                    bin_path = DAEMONS[netapp]['path'],
                    init_script = DAEMONS[netapp]['initscript'],
                    service_script = DAEMONS[netapp]['service'],
                    sessionscript = DAEMONS[netapp]['sessionscript'])
                ret.append(ndaemon)
        return ret
    
    def hasDaemon(self, daemon_name):
        """ Check if the system has daemon_name available """
        options = self.listNetworkingDaemons()
        for item in options:
            if item.name == daemon:
                return True
        return False
    
    def useDaemon(self, daemon):
        """ Configure the system to use the specified networking daemon """
        assert self.hasDaemon(daemon) is True, \
            "The %s daemon is not available on this system."% daemon
        # FIXME: Do we want to disable the manual setup? ie, run nic.disable()
        #       on all of the system's adaptors?
        options = self.lietNetworkingDaemons()
        valid = False
        for bin in options:
            if bin.lower() == daemon.lower():
                valid = True
        if not valid:
            raise MissingDaemonException(
            "Specified daemon is not available on this system.")

    def useManualSetup(self, nic):
        """ Do not use daemon for networking, but rather automatically 
        bring up an interface as configured. """
        # Turn off all daemons
        for program in self.listNetworkingDaemons():
            program.disable()
        # Disable all interfaces except for the one specified
        for iface in self.listNetworkAddapters():
            if iface != nic:
                iface.disable()        
        return
    
    def useNoNetworking(self):
        """ Disable all kinds of automatic networking configuration """
        # Disable all kinds of automatic network configuration.
        # Disable daemons
        for program in self.listNetworkingDaemons():
            program.disable()
        # Disable adaptors
        for _nic in self.listNetworkAddapters():
            _nic.disable()
        return

    def listNetworkAdapters(self):
        """ Return a list of Nic objects """
        ret = []
        for nic in netinfo.list_devs():
            if nic == 'lo':
                continue
            ip = netinfo.get_ip(nic)
            broadcast = netinfo.get_broadcast(nic)
            nmask = netinfo.get_netmask(nic)
            macaddr = netinfo.get_hwaddr(nic)
            # Create the Nic object.
            # The new Nic object will get its own inet object
            _NIC = Nic(devname = nic,
                netmask = nmask,
                bcast = broadcast,
                macaddr = macaddr,
                ip_addr = ip)
            ret.append(_NIC)
        return ret
    
    def getNic(self, devname):
        """ Return a Nic object for the device name provided """
        all = self.listNetworkAddapters()
        for item in all:
            if item.devname == devname:
                return item
        return None
    
    def getCurrentMethod(self):
        """ Returns which networking method is currently being used. """
        # look for active daemons
        for app in self.listNetworkingDaemons():
            if app.check_status():
                return (NET_DAEMON, app.name)
        # look for active inets
        for inet in self.listNetworkAdapters():
            if inet.check_status():
                return (NET_INET, inet.devname)
        # Nothig was found
        return (NET_NONE, None)
    
    def getActiveNics(self):
        """ Returns a list of active network interfaces """
        ret = []
        for inet in self.listNetworkAdapters():
            if inet.check_status():
                ret.append(inet)
        return ret