summaryrefslogtreecommitdiffstats
path: root/ipsilon/admin
diff options
context:
space:
mode:
authorRob Crittenden <rcritten@redhat.com>2015-03-16 16:31:55 -0400
committerRob Crittenden <rcritten@redhat.com>2015-03-19 16:57:55 -0400
commit83ec7148841303516fe31e76116b70c8a5f73aab (patch)
tree7e7e2b09526abc607ca31c4432379edad7f12703 /ipsilon/admin
parentb5730c293fc532fffd3f3300a14813027c4242ae (diff)
downloadipsilon-83ec7148841303516fe31e76116b70c8a5f73aab.tar.gz
ipsilon-83ec7148841303516fe31e76116b70c8a5f73aab.tar.xz
ipsilon-83ec7148841303516fe31e76116b70c8a5f73aab.zip
Set Cache-control on all generated pages, centralize in Endpoint
See "Bindings for the OASIS Security Assertion Markup Language (SAML) V2.0" section 3.2.3.2. https://fedorahosted.org/ipsilon/ticket/7 Signed-off-by: Rob Crittenden <rcritten@redhat.com> Reviewed-by: Nathan Kinder <nkinder@redhat.com>
Diffstat (limited to 'ipsilon/admin')
-rw-r--r--ipsilon/admin/common.py5
1 files changed, 0 insertions, 5 deletions
diff --git a/ipsilon/admin/common.py b/ipsilon/admin/common.py
index fd20077..b371fe9 100644
--- a/ipsilon/admin/common.py
+++ b/ipsilon/admin/common.py
@@ -39,11 +39,6 @@ class AdminPage(Page):
def __init__(self, *args, **kwargs):
super(AdminPage, self).__init__(*args, **kwargs)
- self.default_headers.update({
- 'Cache-Control': 'no-cache, must-revalidate',
- 'Pragma': 'no-cache',
- 'Expires': 'Thu, 01 Dec 1994 16:00:00 GMT',
- })
self.auth_protect = True
id='n190' href='#n190'>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 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
#
# network.py - network configuration install data
#
# Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007  Red Hat, Inc.
#               2008, 2009
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author(s): Matt Wilson <ewt@redhat.com>
#            Erik Troan <ewt@redhat.com>
#            Mike Fulbright <msf@redhat.com>
#            Brent Fox <bfox@redhat.com>
#            David Cantrell <dcantrell@redhat.com>
#            Radek Vykydal <rvykydal@redhat.com>

import string
import shutil
import iutil
import socket
import struct
import os
import time
import dbus
import tempfile
import simpleconfig
import re
from flags import flags
from simpleconfig import IfcfgFile
import urlgrabber.grabber
from blivet.devices import FcoeDiskDevice, iScsiDiskDevice
import blivet.arch

from pyanaconda import nm

import gettext
_ = lambda x: gettext.ldgettext("anaconda", x)

import logging
log = logging.getLogger("anaconda")

sysconfigDir = "/etc/sysconfig"
netscriptsDir = "%s/network-scripts" % (sysconfigDir)
networkConfFile = "%s/network" % (sysconfigDir)
hostnameFile = "/etc/hostname"
ipv6ConfFile = "/etc/sysctl.d/anaconda.conf"
ifcfgLogFile = "/tmp/ifcfg.log"
CONNECTION_TIMEOUT = 45
DEFAULT_HOSTNAME = "localhost.localdomain"

NM_SERVICE = "org.freedesktop.NetworkManager"
NM_MANAGER_PATH = "/org/freedesktop/NetworkManager"
NM_SETTINGS_PATH = "/org/freedesktop/NetworkManager/Settings"
NM_MANAGER_IFACE = "org.freedesktop.NetworkManager"
NM_ACTIVE_CONNECTION_IFACE = "org.freedesktop.NetworkManager.Connection.Active"
NM_DEVICE_IFACE = "org.freedesktop.NetworkManager.Device"
NM_DEVICE_WIRED_IFACE = "org.freedesktop.NetworkManager.Device.Wired"
NM_IP4CONFIG_IFACE = "org.freedesktop.NetworkManager.IP4Config"
NM_IP6CONFIG_IFACE = "org.freedesktop.NetworkManager.IP6Config"
NM_ACCESS_POINT_IFACE = "org.freedesktop.NetworkManager.AccessPoint"

NM_STATE_UNKNOWN = 0
NM_STATE_ASLEEP = 10
NM_STATE_DISCONNECTED = 20
NM_STATE_DISCONNECTING = 30
NM_STATE_CONNECTING = 40
NM_STATE_CONNECTED_LOCAL = 50
NM_STATE_CONNECTED_SITE = 60
NM_STATE_CONNECTED_GLOBAL = 70
NM_DEVICE_STATE_ACTIVATED = 100
NM_DEVICE_TYPE_WIFI = 2
NM_DEVICE_TYPE_ETHERNET = 1

DBUS_PROPS_IFACE = "org.freedesktop.DBus.Properties"

# part of a valid hostname between two periods (cannot start nor end with '-')
# for more info about '(?!-)' and '(?<!-)' see 're' module documentation
HOSTNAME_PART_RE = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)

ifcfglog = None
def setup_ifcfg_log():
    # Setup special logging for ifcfg NM interface
    from pyanaconda import anaconda_log
    global ifcfglog
    logger = logging.getLogger("ifcfg")
    logger.setLevel(logging.DEBUG)
    anaconda_log.logger.addFileHandler(ifcfgLogFile, logger, logging.DEBUG)
    if os.access("/dev/tty3", os.W_OK):
        anaconda_log.logger.addFileHandler("/dev/tty3", logger,
                                           anaconda_log.DEFAULT_TTY_LEVEL,
                                           anaconda_log.TTY_FORMAT,
                                           autoLevel=True)
    anaconda_log.logger.forwardToSyslog(logger)

    ifcfglog = logging.getLogger("ifcfg")

# Get a D-Bus interface for the specified device's (e.g., eth0) properties.
# If dev=None, return a hash of the form 'hash[dev] = props_iface' that
# contains all device properties for all interfaces that NetworkManager knows
# about.
def getDeviceProperties(dev=None):
    bus = dbus.SystemBus()
    nm = bus.get_object(NM_SERVICE, NM_MANAGER_PATH)
    devlist = nm.get_dbus_method("GetDevices")()
    all = {}

    for path in devlist:
        device = bus.get_object(NM_SERVICE, path)
        device_props_iface = dbus.Interface(device, DBUS_PROPS_IFACE)

        device_interface = str(device_props_iface.Get(NM_DEVICE_IFACE, "Interface"))

        if dev is None:
            all[device_interface] = device_props_iface
        elif device_interface == dev:
            return device_props_iface

    if dev is None:
        return all
    else:
        return None

# Get IP addresses for a network device.
# Returns list of ipv4 or ipv6 addresses, depending
# on version parameter. ipv4 is default.
def getIPAddresses(dev, version=4):
    if dev == '' or dev is None:
       return None

    device_props_iface = getDeviceProperties(dev=dev)
    if device_props_iface is None:
        return None

    bus = dbus.SystemBus()

    addresses = []

    if version == 4:
        ip4_config_path = device_props_iface.Get(NM_DEVICE_IFACE, 'Ip4Config')
        if ip4_config_path != '/':
            ip4_config_obj = bus.get_object(NM_SERVICE, ip4_config_path)
            ip4_config_props = dbus.Interface(ip4_config_obj, DBUS_PROPS_IFACE)

            # addresses (3-element list:  ipaddr, netmask, gateway)
            addrs = ip4_config_props.Get(NM_IP4CONFIG_IFACE, "Addresses")
            for addr in addrs:
                try:
                    tmp = struct.pack('I', addr[0])
                    ipaddr = socket.inet_ntop(socket.AF_INET, tmp)
                    addresses.append(ipaddr)
                except ValueError as e:
                    log.debug("Exception caught trying to convert IP address %s: %s" %
                    (addr, e))
    elif version == 6:
        ip6_config_path = device_props_iface.Get(NM_DEVICE_IFACE, 'Ip6Config')
        if ip6_config_path != '/':
            ip6_config_obj = bus.get_object(NM_SERVICE, ip6_config_path)
            ip6_config_props = dbus.Interface(ip6_config_obj, DBUS_PROPS_IFACE)

            addrs = ip6_config_props.Get(NM_IP6CONFIG_IFACE, "Addresses")
            for addr in addrs:
                try:
                    addrstr = "".join(str(byte) for byte in addr[0])
                    ipaddr = socket.inet_ntop(socket.AF_INET6, addrstr)
                    # XXX - should we prefer Global or Site-Local types?
                    #       does NM prefer them?
                    addresses.append(ipaddr)
                except ValueError as e:
                    log.debug("Exception caught trying to convert IP address %s: %s" %
                    (addr, e))
    else:
        raise ValueError, "invalid IP version %d" % version

    return addresses


def sanityCheckHostname(hostname):
    """
    Check if the given string is (syntactically) a valid hostname.

    @param hostname: a string to check
    @returns: a pair containing boolean value (valid or invalid) and
              an error message (if applicable)
    @rtype: (bool, str)

    """

    if not hostname:
        return (False, _("Hostname cannot be None or an empty string."))

    if len(hostname) > 255:
        return (False, _("Hostname must be 255 or fewer characters in length."))

    validStart = string.ascii_letters + string.digits
    validAll = validStart + ".-"

    if hostname[0] not in validStart:
        return (False, _("Hostname must start with a valid character in the "
                         "ranges 'a-z', 'A-Z', or '0-9'"))

    if hostname.endswith("."):
        # hostname can end with '.', but the regexp used below would not match
        hostname = hostname[:-1]

    if not all(HOSTNAME_PART_RE.match(part) for part in hostname.split(".")):
        return (False, _("Hostnames can only contain the characters 'a-z', "
                         "'A-Z', '0-9', '-', or '.', parts between periods "
                         "must contain something and cannot start or end with "
                         "'-'."))

    return (True, "")

# Return a list of IP addresses for all active devices.
def getIPs():
    ips = []
    for devname in nm.nm_activated_devices():
        try:
            ips += (getIPAddresses(devname, version=4) +
                    getIPAddresses(devname, version=6))
        except Exception as e:
            log.warning("Got an exception trying to get the ip addr "
                        "of %s: %s" % (devname, e))
    return ips

# Return the first real non-local IP we find
def getFirstRealIP():
    for ip in getIPs():
        if ip not in ("127.0.0.1", "::1"):
            return ip
    return None

def netmask2prefix(netmask):
    prefix = 0

    while prefix < 33:
        if (prefix2netmask(prefix) == netmask):
            return prefix

        prefix += 1

    return prefix

def prefix2netmask(prefix):
    """ Convert prefix (CIDR bits) to netmask """
    bytes = []
    for i in range(4):
        if prefix >= 8:
            bytes.append(255)
            prefix -= 8
        else:
            bytes.append(256 - 2**(8-prefix))
            prefix = 0
    netmask = ".".join(str(byte) for byte in bytes)
    return netmask

# Try to determine what the hostname should be for this system
def getHostname():

    hn = None

    # First address (we prefer ipv4) of last device (as it used to be) wins
    for dev in nm.nm_activated_devices():
        addrs = (getIPAddresses(dev, version=4) +
                 getIPAddresses(dev, version=6))
        for ipaddr in addrs:
            try:
                hinfo = socket.gethostbyaddr(ipaddr)
            except Exception as e:
                log.debug("Exception caught trying to get host name of %s: %s" %
                          (ipaddr, e))
            else:
                if len(hinfo) == 3:
                    hn = hinfo[0]
                    break

    if not hn or hn in ('(none)', 'localhost', 'localhost.localdomain'):
        hn = socket.gethostname()

    if not hn or hn in ('(none)', 'localhost', 'localhost.localdomain'):
        hn = DEFAULT_HOSTNAME

    return hn

def nmIsConnected(state):
    return state in (NM_STATE_CONNECTED_LOCAL,
                     NM_STATE_CONNECTED_SITE,
                     NM_STATE_CONNECTED_GLOBAL)

def hasActiveNetDev():
    try:
        bus = dbus.SystemBus()
        nm = bus.get_object(NM_SERVICE, NM_MANAGER_PATH)
        props = dbus.Interface(nm, DBUS_PROPS_IFACE)
        state = props.Get(NM_SERVICE, "State")

        return nmIsConnected(state)
    except:
        return flags.testing

def logIfcfgFile(path, message=""):
    content = ""
    if os.access(path, os.R_OK):
        f = open(path, 'r')
        content = f.read()
        f.close()
    else:
        content = "file not found"
    ifcfglog.debug("%s%s:\n%s" % (message, path, content))

def logIfcfgFiles(message=""):
    ifcfglog.debug("content of files (%s):" % message)
    for name in os.listdir(netscriptsDir):
        if name.startswith("ifcfg-"):
            if name == 'ifcfg-lo':
                continue
            path = os.path.join(netscriptsDir, name)
            f = open(path, 'r')
            content = f.read()
            f.close()
            ifcfglog.debug("%s:\n%s" % (path, content))

class NetworkDevice(IfcfgFile):

    def __init__(self, dir, iface):
        IfcfgFile.__init__(self, dir, iface)
        if iface.startswith('ctc'):
            self.info["TYPE"] = "CTC"
        self.wepkey = ""
        self._dirty = False

    def clear(self):
        IfcfgFile.clear(self)
        if self.iface.startswith('ctc'):
            self.info["TYPE"] = "CTC"
        self.wepkey = ""

    def __str__(self):
        s = ""
        keys = self.info.keys()
        if blivet.arch.isS390() and ("HWADDR" in keys):
            keys.remove("HWADDR")
        # make sure we include autoneg in the ethtool line
        if 'ETHTOOL_OPTS' in keys:
            eopts = self.get('ETHTOOL_OPTS')
            if "autoneg" not in eopts:
                self.set(('ETHTOOL_OPTS', "autoneg off %s" % eopts))

        for key in keys:
            if self.info[key] is not None:
                s = s + key + '="' + self.info[key] + '"\n'

        return s

    def loadIfcfgFile(self):
        ifcfglog.debug("loadIfcfFile %s" % self.path)

        self.clear()
        IfcfgFile.read(self)
        self._dirty = False

    def writeIfcfgFile(self):
        # Write out the file only if there is a key whose
        # value has been changed since last load of ifcfg file.
        ifcfglog.debug("writeIfcfgFile %s to %s%s" % (self.iface, self.path,
                                                  ("" if self._dirty else " not needed")))
        if self._dirty:
            ifcfglog.debug("old %s:\n%s" % (self.path, self.fileContent()))
            ifcfglog.debug("writing NetworkDevice %s:\n%s" % (self.iface, self.__str__()))
            IfcfgFile.write(self)
            self._dirty = False

        # We can't read the file right now racing with ifcfg-rh update
        #ifcfglog.debug("%s:\n%s" % (device.path, device.fileContent()))

    def set(self, *args):
        # If we are changing value of a key set _dirty flag
        # informing that ifcfg file needs to be synced.
        s = " ".join(["%s=%s" % key_val for key_val in args])
        ifcfglog.debug("NetworkDevice %s set: %s" %
                       (self.iface, s))
        for (key, data) in args:
            if self.get(key) != data:
                break
        else:
            return
        IfcfgFile.set(self, *args)
        self._dirty = True

    @property
    def keyfilePath(self):
        return os.path.join(self.dir, "keys-%s" % self.iface)

    def fileContent(self):
        if not os.path.exists(self.path):
            return ""
        f = open(self.path, 'r')
        content = f.read()
        f.close()
        return content


def get_NM_object(path):
    return dbus.SystemBus().get_object(NM_SERVICE, path)

def createMissingDefaultIfcfgs():
    """
    Create or dump missing default ifcfg file for wired devices.
    For default auto connections created by NM upon start - which happens
    in case of missing ifcfg file - rename the connection using device name
    and dump its ifcfg file. (For server, default auto connections will
    be turned off in NetworkManager.conf.)
    If there is no default auto connection for a device, create default
    ifcfg file.
    Returns True if any ifcfg file was created or dumped.

    """
    rv = False
    nm = get_NM_object(NM_MANAGER_PATH)
    dev_paths = nm.GetDevices()
    for devpath in dev_paths:

        # for each ethernet device
        device = get_NM_object(devpath)
        device_props_iface = dbus.Interface(device, DBUS_PROPS_IFACE)
        devicetype = device_props_iface.Get(NM_DEVICE_IFACE, "DeviceType")
        if devicetype != NM_DEVICE_TYPE_ETHERNET:
            continue

        # if there is no ifcfg file for the device
        interface = str(device_props_iface.Get(NM_DEVICE_IFACE, "Interface"))
        device_cfg = NetworkDevice(netscriptsDir, interface)
        if os.access(device_cfg.path, os.R_OK):
            continue

        # check if there is a connection for the device (default autoconnection)
        hwaddr = device_props_iface.Get(NM_DEVICE_WIRED_IFACE, "HwAddress")
        con = get_NM_connection(hwaddr)
        if con:
            log.debug("network: dumping ifcfg file for default autoconnection on %s" % interface)
            settings = con.GetSettings()
            settings['connection']['id'] = interface
            con.Update(settings)
        else:
            log.debug("network: no ifcfg file for %s" % interface)
        rv = True

    return rv

def get_NM_connection(connection_spec, spec_type="hwaddr"):

    if spec_type == "iface":
        nm = get_NM_object(NM_MANAGER_PATH)
        dev_paths = nm.GetDevices()
        for devpath in dev_paths:
            device = get_NM_object(devpath)
            device_props_iface = dbus.Interface(device, DBUS_PROPS_IFACE)
            interface = str(device_props_iface.Get(NM_DEVICE_IFACE, "Interface"))
            if interface == connection_spec:
                try:
                    connection_spec = str(device_props_iface.Get(NM_DEVICE_WIRED_IFACE, "HwAddress"))
                    spec_type = "hwaddr"
                except dbus.DBusException as e:
                    log.debug("get_NM_settings (interface %s) %s" % (interface, e))
                    return None
                break

    if spec_type == "hwaddr":
        settings = get_NM_object(NM_SETTINGS_PATH)
        con_paths = settings.ListConnections()
        for con_path in con_paths:
            con = get_NM_object(con_path)
            setting = con.GetSettings()
            try:
                con_hwaddr_bytearray = setting['802-3-ethernet']['mac-address']
            except KeyError:
                log.debug("no mac-address setting found for %s" % con_path)
                continue
            con_hwaddr = ":".join("%02X" % byte for byte in
                                  con_hwaddr_bytearray)
            if con_hwaddr.upper() == connection_spec.upper():
                return con

    return None

# get a kernel cmdline string for dracut needed for access to storage host
def dracutSetupArgs(networkStorageDevice):

    if networkStorageDevice.nic == "default" or ":" in networkStorageDevice.nic:
        nic = ifaceForHostIP(networkStorageDevice.host_address)
        if not nic:
            return ""
    else:
        nic = networkStorageDevice.nic

    if nic not in nm.nm_devices():
        log.error('Unknown network interface: %s' % nic)
        return ""

    ifcfg = NetworkDevice(netscriptsDir, nic)
    ifcfg.loadIfcfgFile()
    return dracutBootArguments(ifcfg,
                               networkStorageDevice.host_address,
                               getHostname())

def dracutBootArguments(ifcfg, storage_ipaddr, hostname=None):

    netargs = set()
    devname = ifcfg.iface

    if ifcfg.get('BOOTPROTO') == 'ibft':
        netargs.add("ip=ibft")
    elif storage_ipaddr:
        if hostname is None:
            hostname = ""
        # if using ipv6
        if ':' in storage_ipaddr:
            if ifcfg.get('DHCPV6C') == "yes":
                # XXX combination with autoconf not yet clear,
                # support for dhcpv6 is not yet implemented in NM/ifcfg-rh
                netargs.add("ip=%s:dhcp6" % devname)
            elif ifcfg.get('IPV6_AUTOCONF') == "yes":
                netargs.add("ip=%s:auto6" % devname)
            elif ifcfg.get('IPV6ADDR'):
                ipaddr = "[%s]" % ifcfg.get('IPV6ADDR')
                if ifcfg.get('IPV6_DEFAULTGW'):
                    gateway = "[%s]" % ifcfg.get('IPV6_DEFAULTGW')
                else:
                    gateway = ""
                netargs.add("ip=%s::%s:%s:%s:%s:none" % (ipaddr, gateway,
                           ifcfg.get('PREFIX'), hostname, devname))
        else:
            if ifcfg.get('bootproto').lower() == 'dhcp':
                netargs.add("ip=%s:dhcp" % devname)
            else:
                if ifcfg.get('GATEWAY'):
                    gateway = ifcfg.get('GATEWAY')
                else:
                    gateway = ""

                netmask = ifcfg.get('netmask')
                prefix  = ifcfg.get('prefix')
                if not netmask and prefix:
                    netmask = prefix2netmask(int(prefix))

                netargs.add("ip=%s::%s:%s:%s:%s:none" % (ifcfg.get('ipaddr'),
                           gateway, netmask, hostname, devname))

    hwaddr = ifcfg.get("HWADDR")
    if hwaddr:
        netargs.add("ifname=%s:%s" % (devname, hwaddr.lower()))

    nettype = ifcfg.get("NETTYPE")
    subchannels = ifcfg.get("SUBCHANNELS")
    if blivet.arch.isS390() and nettype and subchannels:
        znet = "rd.znet=%s,%s" % (nettype, subchannels)
        options = ifcfg.get("OPTIONS").strip("'\"")
        if options:
            options = filter(lambda x: x != '', options.split(' '))
            znet += ",%s" % (','.join(options))
        netargs.add(znet)

    return netargs

def kickstartNetworkData(ifcfg=None, hostname=None):

    from pyanaconda.kickstart import AnacondaKSHandler
    handler = AnacondaKSHandler()
    kwargs = {}

    if not ifcfg and hostname:
        return handler.NetworkData(hostname=hostname, bootProto="")

    # ipv4 and ipv6
    if not ifcfg.get("ESSID"):
        kwargs["device"] = ifcfg.iface
    if ifcfg.get("ONBOOT") and ifcfg.get("ONBOOT" ) == "no":
        kwargs["onboot"] = False
    if ifcfg.get('MTU') and ifcfg.get('MTU') != "0":
        kwargs["mtu"] = ifcfg.get('MTU')

    # ipv4
    if not ifcfg.get('BOOTPROTO'):
        kwargs["noipv4"] = True
    else:
        if ifcfg.get('BOOTPROTO').lower() == 'dhcp':
            kwargs["bootProto"] = "dhcp"
            if ifcfg.get('DHCPCLASS'):
                kwargs["dhcpclass"] = ifcfg.get('DHCPCLASS')
        elif ifcfg.get('IPADDR'):
            kwargs["bootProto"] = "static"
            kwargs["ip"] = ifcfg.get('IPADDR')
            netmask = ifcfg.get('NETMASK')
            prefix  = ifcfg.get('PREFIX')
            if not netmask and prefix:
                netmask = prefix2netmask(int(prefix))
            if netmask:
                kwargs["netmask"] = netmask
            # note that --gateway is common for ipv4 and ipv6
            if ifcfg.get('GATEWAY'):
                kwargs["gateway"] = ifcfg.get('GATEWAY')
        elif ifcfg.get('IPADDR0'):
            kwargs["bootProto"] = "static"
            kwargs["ip"] = ifcfg.get('IPADDR0')
            prefix  = ifcfg.get('PREFIX0')
            if prefix:
                netmask = prefix2netmask(int(prefix))
                kwargs["netmask"] = netmask
            # note that --gateway is common for ipv4 and ipv6
            if ifcfg.get('GATEWAY0'):
                kwargs["gateway"] = ifcfg.get('GATEWAY0')


    # ipv6
    if (not ifcfg.get('IPV6INIT') or
        ifcfg.get('IPV6INIT') == "no"):
        kwargs["noipv6"] = True
    else:
        if ifcfg.get('IPV6_AUTOCONF') in ("yes", ""):
            kwargs["ipv6"] = "auto"
        else:
            if ifcfg.get('IPV6ADDR'):
                kwargs["ipv6"] = ifcfg.get('IPV6ADDR')
                if ifcfg.get('IPV6_DEFAULTGW'):
                    kwargs["gateway"] = ifcfg.get('IPV6_DEFAULTGW')
            if ifcfg.get('DHCPV6C') == "yes":
                kwargs["ipv6"] = "dhcp"

    # ipv4 and ipv6
    dnsline = ''
    for key in ifcfg.info.keys():
        if key.upper().startswith('DNS'):
            if dnsline == '':
                dnsline = ifcfg.get(key)
            else:
                dnsline += "," + ifcfg.get(key)
    if dnsline:
        kwargs["nameserver"] = dnsline

    if ifcfg.get("ETHTOOL_OPTS"):
        kwargs["ethtool"] = ifcfg.get("ETHTOOL_OPTS")

    if ifcfg.get("ESSID"):
        kwargs["essid"] = ifcfg.get("ESSID")

    # hostname
    if ifcfg.get("DHCP_HOSTNAME"):
        kwargs["hostname"] = ifcfg.get("DHCP_HOSTNAME")
    elif ifcfg.get("BOOTPROTO").lower != "dhcp":
        if (hostname and
            hostname != DEFAULT_HOSTNAME):
            kwargs["hostname"] = hostname

    return handler.NetworkData(**kwargs)

def ifaceForHostIP(host):
    route = iutil.execWithCapture("ip", [ "route", "get", "to", host ])
    if not route:
        log.error("Could not get interface for route to %s" % host)
        return ""

    routeInfo = route.split()
    if routeInfo[0] != host or len(routeInfo) < 5 or \
       "dev" not in routeInfo or routeInfo.index("dev") > 3:
        log.error('Unexpected "ip route get to %s" reply: %s' %
                  (host, routeInfo))
        return ""

    return routeInfo[routeInfo.index("dev") + 1]

def copyFileToPath(file, destPath='', overwrite=False):
    if not os.path.isfile(file):
        return False
    destfile = os.path.join(destPath, file.lstrip('/'))
    if (os.path.isfile(destfile) and not overwrite):
        return False
    if not os.path.isdir(os.path.dirname(destfile)):
        iutil.mkdirChain(os.path.dirname(destfile))
    shutil.copy(file, destfile)
    return True

# /etc/sysconfig/network-scripts/ifcfg-*
# /etc/sysconfig/network-scripts/keys-*
# TODO: routing info from /etc/sysconfig/network-scripts?
def copyIfcfgFiles(destPath):
    files = os.listdir(netscriptsDir)
    for cfgFile in files:
        if cfgFile.startswith(("ifcfg-","keys-")):
            srcfile = os.path.join(netscriptsDir, cfgFile)
            copyFileToPath(srcfile, destPath)

# /etc/dhcp/dhclient-DEVICE.conf
# TODORV: do we really don't want overwrite on live cd?
def copyDhclientConfFiles(destPath):
    for devName in nm.nm_devices():
        dhclientfile = os.path.join("/etc/dhcp/dhclient-%s.conf" % devName)
        copyFileToPath(dhclientfile, destPath)

def get_ksdevice_name(ksspec=""):

    if not ksspec:
        ksspec = flags.cmdline.get('ksdevice', "")
    ksdevice = ksspec

    bootif_mac = None
    if ksdevice == 'bootif' and "BOOTIF" in flags.cmdline:
        bootif_mac = flags.cmdline["BOOTIF"][3:].replace("-", ":").upper()
    for dev in sorted(nm.nm_devices()):
        # "eth0"
        if ksdevice == dev:
            break
        # "link"
        elif ksdevice == 'link':
            try:
                link_up = nm.nm_device_carrier(dev)
            except ValueError as e:
                log.debug("get_ksdevice_name: %s" % e)
                continue
            if link_up:
                ksdevice = dev
                break
        # "XX:XX:XX:XX:XX:XX" (mac address)
        elif ':' in ksdevice:
            try:
                hwaddr = nm.nm_device_hwaddress(dev)
            except ValueError as e:
                log.debug("get_ksdevice_name: %s" % e)
                continue
            if ksdevice.lower() == hwaddr.lower():
                ksdevice = dev
                break
        # "bootif" and BOOTIF==XX:XX:XX:XX:XX:XX