Search in sources :

Example 26 with IP4Address

use of org.eclipse.kura.net.IP4Address in project kura by eclipse.

the class LinuxNamed method init.

private void init() throws KuraException {
    // TODO
    File configFile = new File(s_persistentConfigFileName);
    if (configFile.exists()) {
        s_logger.debug("initing DNS Server configuration");
        try {
            Set<IP4Address> forwarders = new HashSet<IP4Address>();
            Set<NetworkPair<IP4Address>> allowedNetworks = new HashSet<NetworkPair<IP4Address>>();
            BufferedReader br = new BufferedReader(new FileReader(configFile));
            boolean forwardingConfig = true;
            String line = null;
            while ((line = br.readLine()) != null) {
                if (line.trim().equals("forward only;")) {
                    forwardingConfig = true;
                    break;
                }
            }
            br.close();
            br = null;
            if (forwardingConfig) {
                br = new BufferedReader(new FileReader(configFile));
                while ((line = br.readLine()) != null) {
                    // TODO - really simple for now
                    StringTokenizer st = new StringTokenizer(line);
                    while (st.hasMoreTokens()) {
                        String token = st.nextToken();
                        if (token.equals("forwarders")) {
                            // get the forwarders 'forwarders {192.168.1.1;192.168.2.1;};'
                            StringTokenizer st2 = new StringTokenizer(st.nextToken(), "{} ;");
                            while (st2.hasMoreTokens()) {
                                String forwarder = st2.nextToken();
                                if (forwarder != null && !forwarder.trim().equals("")) {
                                    s_logger.debug("found forwarder: {}", forwarder);
                                    forwarders.add((IP4Address) IPAddress.parseHostAddress(forwarder));
                                }
                            }
                        } else if (token.equals("allow-query")) {
                            // get the networks 'allow-query {192.168.2.0/24;192.168.3.0/24};'
                            StringTokenizer st2 = new StringTokenizer(st.nextToken(), "{} ;");
                            while (st2.hasMoreTokens()) {
                                String allowedNetwork = st2.nextToken();
                                if (allowedNetwork != null && !allowedNetwork.trim().equals("")) {
                                    String[] splitNetwork = allowedNetwork.split("/");
                                    allowedNetworks.add(new NetworkPair<IP4Address>((IP4Address) IPAddress.parseHostAddress(splitNetwork[0]), Short.parseShort(splitNetwork[1])));
                                }
                            }
                        }
                    }
                }
                br.close();
                br = null;
                // set the configuration and return
                this.m_dnsServerConfigIP4 = new DnsServerConfigIP4(forwarders, allowedNetworks);
                return;
            }
        } catch (FileNotFoundException e) {
            throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR, e);
        } catch (IOException e) {
            throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR, e);
        }
    } else {
        s_logger.debug("There is no current DNS server configuration that allows forwarding");
    }
}
Also used : IP4Address(org.eclipse.kura.net.IP4Address) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) DnsServerConfigIP4(org.eclipse.kura.net.dns.DnsServerConfigIP4) StringTokenizer(java.util.StringTokenizer) NetworkPair(org.eclipse.kura.net.NetworkPair) KuraException(org.eclipse.kura.KuraException) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) File(java.io.File) HashSet(java.util.HashSet)

Example 27 with IP4Address

use of org.eclipse.kura.net.IP4Address in project kura by eclipse.

the class DnsMonitorServiceImpl method getConfiguredDnsServers.

// Get a list of dns servers for the specified NetInterfaceConfig
private Set<IPAddress> getConfiguredDnsServers(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) throws KuraException {
    String interfaceName = netInterfaceConfig.getName();
    s_logger.trace("Getting dns servers for {}", interfaceName);
    LinuxDns linuxDns = LinuxDns.getInstance();
    LinkedHashSet<IPAddress> serverList = new LinkedHashSet<IPAddress>();
    for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceConfig.getNetInterfaceAddresses()) {
        for (NetConfig netConfig : netInterfaceAddressConfig.getConfigs()) {
            if (netConfig instanceof NetConfigIP4) {
                NetConfigIP4 netConfigIP4 = (NetConfigIP4) netConfig;
                List<IP4Address> userServers = netConfigIP4.getDnsServers();
                if (netConfigIP4.isDhcp()) {
                    // If DHCP but there are user defined entries, use those instead
                    if (userServers != null && !userServers.isEmpty()) {
                        s_logger.debug("Configured for DHCP with user-defined servers - adding: {}", userServers);
                        serverList.addAll(userServers);
                    } else {
                        if (netInterfaceConfig.getType().equals(NetInterfaceType.MODEM)) {
                            // FIXME - don't like this
                            // cannot use interfaceName here because it one config behind
                            int pppNo = ((ModemInterfaceConfigImpl) netInterfaceConfig).getPppNum();
                            if (LinuxNetworkUtil.hasAddress("ppp" + pppNo)) {
                                List<IPAddress> servers = linuxDns.getPppDnServers();
                                if (servers != null) {
                                    s_logger.debug("Adding PPP dns servers: {}", servers);
                                    serverList.addAll(servers);
                                }
                            }
                        } else {
                            String currentAddress = LinuxNetworkUtil.getCurrentIpAddress(interfaceName);
                            List<IPAddress> servers = linuxDns.getDhcpDnsServers(interfaceName, currentAddress);
                            if (servers != null) {
                                s_logger.debug("Configured for DHCP - adding DHCP servers: {}", servers);
                                serverList.addAll(servers);
                            }
                        }
                    }
                } else {
                    // If static, use the user defined entries
                    s_logger.debug("Configured for static - adding user-defined servers: {}", userServers);
                    serverList.addAll(userServers);
                }
            }
        }
    }
    return serverList;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) IP4Address(org.eclipse.kura.net.IP4Address) NetConfigIP4(org.eclipse.kura.net.NetConfigIP4) LinuxDns(org.eclipse.kura.linux.net.dns.LinuxDns) ModemInterfaceConfigImpl(org.eclipse.kura.core.net.modem.ModemInterfaceConfigImpl) NetConfig(org.eclipse.kura.net.NetConfig) IPAddress(org.eclipse.kura.net.IPAddress) NetInterfaceAddressConfig(org.eclipse.kura.net.NetInterfaceAddressConfig)

Example 28 with IP4Address

use of org.eclipse.kura.net.IP4Address in project kura by eclipse.

the class EthernetMonitorServiceImpl method monitor.

private void monitor(String interfaceName) {
    synchronized (s_lock) {
        try {
            List<? extends NetInterfaceAddressConfig> new_niacs = null;
            List<? extends NetInterfaceAddressConfig> cur_niacs = null;
            InterfaceState currentInterfaceState = null;
            boolean interfaceEnabled = false;
            boolean isDhcpClient = false;
            IP4Address staticGateway = null;
            boolean dhcpServerEnabled = false;
            // IPAddress dhcpServerSubnet = null;
            // short dhcpServerPrefix = -1;
            boolean postStatusChangeEvent = false;
            EthernetInterfaceConfigImpl currentInterfaceConfig = this.m_networkConfiguration.get(interfaceName);
            EthernetInterfaceConfigImpl newInterfaceConfig = this.m_newNetworkConfiguration.get(interfaceName);
            // FIXME:MC it should be possible to refactor this under the InterfaceState to avoid dual checks
            if (!LinuxNetworkUtil.isUp(interfaceName)) {
                LinuxNetworkUtil.bringUpDeletingAddress(interfaceName);
            }
            // If a new configuration exists, compare it to the existing configuration
            if (newInterfaceConfig != null) {
                // Get all configurations for the interface
                new_niacs = newInterfaceConfig.getNetInterfaceAddresses();
                if (currentInterfaceConfig != null) {
                    cur_niacs = currentInterfaceConfig.getNetInterfaceAddresses();
                }
                if (isConfigChanged(new_niacs, cur_niacs)) {
                    s_logger.info("Found a new Ethernet network configuration for {}", interfaceName);
                    // Disable the interface to be reconfigured below
                    disableInterface(interfaceName);
                    // Set the current config to the new config
                    this.m_networkConfiguration.put(interfaceName, newInterfaceConfig);
                    currentInterfaceConfig = newInterfaceConfig;
                    // Post a status change event - not to be confusd with the Config Change that I am consuming
                    postStatusChangeEvent = true;
                }
                this.m_newNetworkConfiguration.remove(interfaceName);
            }
            // Monitor for status changes and ensure dhcp server is running when enabled
            interfaceEnabled = isEthernetEnabled(currentInterfaceConfig);
            InterfaceState prevInterfaceState = this.m_interfaceState.get(interfaceName);
            // FIXME:MC Deprecate this constructor and prefer the one with the explicit parameters
            // (String interfaceName, boolean up, boolean link, IPAddress ipAddress)
            // It will save a call to determine the iface type and it will keep InterfaceState
            // as a state object as it should be. Maybe introduce an InterfaceStateBuilder.
            currentInterfaceState = new InterfaceState(NetInterfaceType.ETHERNET, interfaceName);
            if (!currentInterfaceState.equals(prevInterfaceState)) {
                postStatusChangeEvent = true;
            }
            // Find if DHCP server or DHCP client mode is enabled
            if (currentInterfaceConfig != null) {
                NetInterfaceStatus netInterfaceStatus = getStatus(currentInterfaceConfig);
                cur_niacs = currentInterfaceConfig.getNetInterfaceAddresses();
                if (cur_niacs != null && cur_niacs.size() > 0) {
                    for (NetInterfaceAddressConfig niac : cur_niacs) {
                        List<NetConfig> netConfigs = niac.getConfigs();
                        if (netConfigs != null && netConfigs.size() > 0) {
                            for (NetConfig netConfig : netConfigs) {
                                if (netConfig instanceof DhcpServerConfig4) {
                                    // only enable if Enabled for LAN
                                    if (netInterfaceStatus.equals(NetInterfaceStatus.netIPv4StatusEnabledLAN)) {
                                        dhcpServerEnabled = ((DhcpServerConfig4) netConfig).isEnabled();
                                    // dhcpServerSubnet = ((DhcpServerConfig4) netConfig).getSubnet();
                                    // dhcpServerPrefix = ((DhcpServerConfig4) netConfig).getPrefix();
                                    } else {
                                        s_logger.trace("Not enabling DHCP server for {} since it is set to {}", interfaceName, netInterfaceStatus);
                                    }
                                } else if (netConfig instanceof NetConfigIP4) {
                                    isDhcpClient = ((NetConfigIP4) netConfig).isDhcp();
                                    staticGateway = ((NetConfigIP4) netConfig).getGateway();
                                }
                            }
                        }
                    }
                } else {
                    s_logger.debug("No current net interface addresses for {}", interfaceName);
                }
            } else {
                s_logger.debug("Current interface config is null for {}", interfaceName);
            }
            // Enable/disable based on configuration and current status
            boolean interfaceStateChanged = false;
            if (interfaceEnabled) {
                if (currentInterfaceState.isUp()) {
                    if (!currentInterfaceState.isLinkUp()) {
                        s_logger.debug("link is down - disabling {}", interfaceName);
                        disableInterface(interfaceName);
                        interfaceStateChanged = true;
                    }
                } else {
                    // State is currently down
                    if (currentInterfaceState.isLinkUp()) {
                        s_logger.debug("link is up - enabling {}", interfaceName);
                        this.m_netAdminService.enableInterface(interfaceName, isDhcpClient);
                        interfaceStateChanged = true;
                    }
                }
            } else {
                if (currentInterfaceState.isUp()) {
                    s_logger.debug("{} is currently up - disable interface", interfaceName);
                    disableInterface(interfaceName);
                    interfaceStateChanged = true;
                }
            }
            // FIXME: reload the configuration IFF one of above enable/disable happened
            if (interfaceStateChanged) {
                currentInterfaceState = new InterfaceState(NetInterfaceType.ETHERNET, interfaceName);
            }
            // Manage the DHCP server and validate routes
            if (currentInterfaceState != null && currentInterfaceState.isUp() && currentInterfaceState.isLinkUp()) {
                NetInterfaceStatus netInterfaceStatus = getStatus(currentInterfaceConfig);
                if (netInterfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN) {
                    // This should be the default gateway - make sure it is
                    boolean found = false;
                    RouteConfig[] routes = this.m_routeService.getRoutes();
                    if (routes != null && routes.length > 0) {
                        for (RouteConfig route : routes) {
                            if (route.getInterfaceName().equals(interfaceName) && route.getDestination().equals(IPAddress.parseHostAddress("0.0.0.0")) && !route.getGateway().equals(IPAddress.parseHostAddress("0.0.0.0"))) {
                                found = true;
                                break;
                            }
                        }
                    }
                    if (!found) {
                        if (isDhcpClient || staticGateway != null) {
                            // disable the interface and reenable - something didn't happen at initialization as it
                            // was supposed to
                            s_logger.error("WAN interface " + interfaceName + " did not have a route setting it as the default gateway, restarting it");
                            this.m_netAdminService.disableInterface(interfaceName);
                            this.m_netAdminService.enableInterface(interfaceName, isDhcpClient);
                        }
                    }
                } else if (netInterfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledLAN) {
                    if (isDhcpClient) {
                        RouteService rs = RouteServiceImpl.getInstance();
                        RouteConfig rconf = rs.getDefaultRoute(interfaceName);
                        if (rconf != null) {
                            s_logger.debug("{} is configured for LAN/DHCP - removing GATEWAY route ...", rconf.getInterfaceName());
                            rs.removeStaticRoute(rconf.getDestination(), rconf.getGateway(), rconf.getNetmask(), rconf.getInterfaceName());
                        }
                    }
                }
                if (dhcpServerEnabled && !DhcpServerManager.isRunning(interfaceName)) {
                    s_logger.debug("Starting DHCP server for {}", interfaceName);
                    this.m_netAdminService.manageDhcpServer(interfaceName, true);
                }
            } else if (DhcpServerManager.isRunning(interfaceName)) {
                s_logger.debug("Stopping DHCP server for {}", interfaceName);
                this.m_netAdminService.manageDhcpServer(interfaceName, false);
            }
            // post event if there were any changes
            if (postStatusChangeEvent) {
                s_logger.debug("Posting NetworkStatusChangeEvent for {}: {}", interfaceName, currentInterfaceState);
                this.m_eventAdmin.postEvent(new NetworkStatusChangeEvent(interfaceName, currentInterfaceState, null));
                this.m_interfaceState.put(interfaceName, currentInterfaceState);
            }
            // If the interface is disabled in Denali, stop the monitor
            if (!interfaceEnabled) {
                s_logger.debug("{} is disabled - stopping monitor", interfaceName);
                stopMonitor(interfaceName);
            }
        } catch (Exception e) {
            s_logger.warn("Error during Ethernet Monitor", e);
        }
    }
}
Also used : IP4Address(org.eclipse.kura.net.IP4Address) NetInterfaceStatus(org.eclipse.kura.net.NetInterfaceStatus) RouteConfig(org.eclipse.kura.net.route.RouteConfig) DhcpServerConfig4(org.eclipse.kura.net.dhcp.DhcpServerConfig4) KuraException(org.eclipse.kura.KuraException) NetConfigIP4(org.eclipse.kura.net.NetConfigIP4) EthernetInterfaceConfigImpl(org.eclipse.kura.core.net.EthernetInterfaceConfigImpl) NetworkStatusChangeEvent(org.eclipse.kura.net.admin.event.NetworkStatusChangeEvent) NetConfig(org.eclipse.kura.net.NetConfig) RouteService(org.eclipse.kura.linux.net.route.RouteService) NetInterfaceAddressConfig(org.eclipse.kura.net.NetInterfaceAddressConfig)

Example 29 with IP4Address

use of org.eclipse.kura.net.IP4Address in project kura by eclipse.

the class IfcfgConfigReader method getConfig.

private void getConfig(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig, Properties kuraExtendedProps) throws KuraException {
    String interfaceName = netInterfaceConfig.getName();
    s_logger.debug("Getting config for {}", interfaceName);
    NetInterfaceType type = netInterfaceConfig.getType();
    if (type == NetInterfaceType.ETHERNET || type == NetInterfaceType.WIFI || type == NetInterfaceType.LOOPBACK) {
        NetInterfaceStatus netInterfaceStatus = null;
        StringBuilder sb = new StringBuilder().append("net.interface.").append(netInterfaceConfig.getName()).append(".config.ip4.status");
        if (kuraExtendedProps != null && kuraExtendedProps.getProperty(sb.toString()) != null) {
            netInterfaceStatus = NetInterfaceStatus.valueOf(kuraExtendedProps.getProperty(sb.toString()));
        } else {
            netInterfaceStatus = NetInterfaceStatus.netIPv4StatusDisabled;
        }
        s_logger.debug("Setting NetInterfaceStatus to " + netInterfaceStatus + " for " + netInterfaceConfig.getName());
        boolean autoConnect = false;
        // int mtu = -1; // MTU is not currently used
        boolean dhcp = false;
        IP4Address address = null;
        String ipAddress = null;
        String prefixString = null;
        String netmask = null;
        String gateway = null;
        File ifcfgFile = null;
        if (OS_VERSION.equals(KuraConstants.Mini_Gateway.getImageName() + "_" + KuraConstants.Mini_Gateway.getImageVersion()) || OS_VERSION.equals(KuraConstants.Raspberry_Pi.getImageName()) || OS_VERSION.equals(KuraConstants.BeagleBone.getImageName()) || OS_VERSION.equals(KuraConstants.Intel_Edison.getImageName() + "_" + KuraConstants.Intel_Edison.getImageVersion() + "_" + KuraConstants.Intel_Edison.getTargetName()) || OS_VERSION.equals(KuraConstants.ReliaGATE_50_21_Ubuntu.getImageName() + "_" + KuraConstants.ReliaGATE_50_21_Ubuntu.getImageVersion())) {
            ifcfgFile = new File(DEBIAN_NET_CONFIGURATION_DIRECTORY + "interfaces");
        } else {
            ifcfgFile = new File(REDHAT_NET_CONFIGURATION_DIRECTORY + "ifcfg-" + interfaceName);
        }
        if (ifcfgFile.exists()) {
            Properties kuraProps;
            // found our match so load the properties
            if (OS_VERSION.equals(KuraConstants.Mini_Gateway.getImageName() + "_" + KuraConstants.Mini_Gateway.getImageVersion()) || OS_VERSION.equals(KuraConstants.Raspberry_Pi.getImageName()) || OS_VERSION.equals(KuraConstants.BeagleBone.getImageName()) || OS_VERSION.equals(KuraConstants.Intel_Edison.getImageName() + "_" + KuraConstants.Intel_Edison.getImageVersion() + "_" + KuraConstants.Intel_Edison.getTargetName()) || OS_VERSION.equals(KuraConstants.ReliaGATE_50_21_Ubuntu.getImageName() + "_" + KuraConstants.ReliaGATE_50_21_Ubuntu.getImageVersion())) {
                kuraProps = parseDebianConfigFile(ifcfgFile, interfaceName);
            } else {
                kuraProps = parseRedhatConfigFile(ifcfgFile, interfaceName);
            }
            if (kuraProps != null) {
                String onBoot = kuraProps.getProperty("ONBOOT");
                if ("yes".equals(onBoot)) {
                    s_logger.debug("Setting autoConnect to true");
                    autoConnect = true;
                } else {
                    s_logger.debug("Setting autoConnect to false");
                    autoConnect = false;
                }
                // override MTU with what is in config if it is present
                /*
                     * IAB: MTU is not currently used
                     * String stringMtu = kuraProps.getProperty("MTU");
                     * if (stringMtu == null) {
                     * try {
                     * mtu = LinuxNetworkUtil.getCurrentMtu(interfaceName);
                     * } catch (KuraException e) {
                     * // just assume ???
                     * if (interfaceName.equals("lo")) {
                     * mtu = 16436;
                     * } else {
                     * mtu = 1500;
                     * }
                     * }
                     * } else {
                     * mtu = Short.parseShort(stringMtu);
                     * }
                     */
                // get the bootproto
                String bootproto = kuraProps.getProperty("BOOTPROTO");
                if (bootproto == null) {
                    bootproto = "static";
                }
                // get the defroute
                String defroute = kuraProps.getProperty("DEFROUTE");
                if (defroute == null) {
                    defroute = "no";
                }
                // actual properties
                if (netInterfaceStatus == NetInterfaceStatus.netIPv4StatusDisabled) {
                    if (autoConnect) {
                        if (defroute.equals("no")) {
                            netInterfaceStatus = NetInterfaceStatus.netIPv4StatusEnabledLAN;
                        } else {
                            netInterfaceStatus = NetInterfaceStatus.netIPv4StatusEnabledWAN;
                        }
                    }
                }
                // check for dhcp or static configuration
                try {
                    ipAddress = kuraProps.getProperty("IPADDR");
                    prefixString = kuraProps.getProperty("PREFIX");
                    netmask = kuraProps.getProperty("NETMASK");
                    kuraProps.getProperty("BROADCAST");
                    try {
                        gateway = kuraProps.getProperty("GATEWAY");
                        s_logger.debug("got gateway for " + interfaceName + ": " + gateway);
                    } catch (Exception e) {
                        s_logger.warn("missing gateway stanza for " + interfaceName);
                    }
                    if (bootproto.equals("dhcp")) {
                        s_logger.debug("currently set for DHCP");
                        dhcp = true;
                        ipAddress = null;
                        netmask = null;
                    } else {
                        s_logger.debug("currently set for static address");
                        dhcp = false;
                    }
                } catch (Exception e) {
                    throw new KuraException(KuraErrorCode.INTERNAL_ERROR, "malformatted config file: " + ifcfgFile.toString(), e);
                }
                if (ipAddress != null && !ipAddress.isEmpty()) {
                    try {
                        address = (IP4Address) IPAddress.parseHostAddress(ipAddress);
                    } catch (UnknownHostException e) {
                        s_logger.warn("Error parsing address: " + ipAddress, e);
                    }
                }
                // make sure at least prefix or netmask is present if static
                if (autoConnect && !dhcp && prefixString == null && netmask == null) {
                    throw new KuraException(KuraErrorCode.INTERNAL_ERROR, "malformatted config file: " + ifcfgFile.toString() + " must contain NETMASK and/or PREFIX");
                }
            }
            List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = netInterfaceConfig.getNetInterfaceAddresses();
            if (netInterfaceAddressConfigs == null) {
                throw new KuraException(KuraErrorCode.INTERNAL_ERROR, "InterfaceAddressConfig list is null");
            } else if (netInterfaceAddressConfigs.size() == 0) {
                throw new KuraException(KuraErrorCode.INTERNAL_ERROR, "InterfaceAddressConfig list has no entries");
            }
            for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) {
                List<NetConfig> netConfigs = netInterfaceAddressConfig.getConfigs();
                if (netConfigs == null) {
                    netConfigs = new ArrayList<NetConfig>();
                    if (netInterfaceAddressConfig instanceof NetInterfaceAddressConfigImpl) {
                        ((NetInterfaceAddressConfigImpl) netInterfaceAddressConfig).setNetConfigs(netConfigs);
                        if (dhcp) {
                            // Replace with DNS provided by DHCP server
                            // (displayed as read-only in Denali)
                            List<? extends IPAddress> dhcpDnsServers = getDhcpDnsServers(interfaceName, netInterfaceAddressConfig.getAddress());
                            if (dhcpDnsServers != null) {
                                ((NetInterfaceAddressConfigImpl) netInterfaceAddressConfig).setDnsServers(dhcpDnsServers);
                            }
                        }
                    } else if (netInterfaceAddressConfig instanceof WifiInterfaceAddressConfigImpl) {
                        ((WifiInterfaceAddressConfigImpl) netInterfaceAddressConfig).setNetConfigs(netConfigs);
                        if (dhcp) {
                            // Replace with DNS provided by DHCP server
                            // (displayed as read-only in Denali)
                            List<? extends IPAddress> dhcpDnsServers = getDhcpDnsServers(interfaceName, netInterfaceAddressConfig.getAddress());
                            if (dhcpDnsServers != null) {
                                ((WifiInterfaceAddressConfigImpl) netInterfaceAddressConfig).setDnsServers(dhcpDnsServers);
                            }
                        }
                    }
                }
                NetConfigIP4 netConfig = new NetConfigIP4(netInterfaceStatus, autoConnect);
                setNetConfigIP4(netConfig, autoConnect, dhcp, address, gateway, prefixString, netmask, kuraProps);
                s_logger.debug("NetConfig: {}", netConfig);
                netConfigs.add(netConfig);
            }
        }
    }
}
Also used : NetInterfaceAddressConfigImpl(org.eclipse.kura.core.net.NetInterfaceAddressConfigImpl) UnknownHostException(java.net.UnknownHostException) NetInterfaceStatus(org.eclipse.kura.net.NetInterfaceStatus) IP4Address(org.eclipse.kura.net.IP4Address) Properties(java.util.Properties) KuraException(org.eclipse.kura.KuraException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException) NetConfigIP4(org.eclipse.kura.net.NetConfigIP4) NetInterfaceType(org.eclipse.kura.net.NetInterfaceType) KuraException(org.eclipse.kura.KuraException) NetConfig(org.eclipse.kura.net.NetConfig) ArrayList(java.util.ArrayList) List(java.util.List) IPAddress(org.eclipse.kura.net.IPAddress) File(java.io.File) NetInterfaceAddressConfig(org.eclipse.kura.net.NetInterfaceAddressConfig) WifiInterfaceAddressConfigImpl(org.eclipse.kura.core.net.WifiInterfaceAddressConfigImpl)

Example 30 with IP4Address

use of org.eclipse.kura.net.IP4Address in project kura by eclipse.

the class PppConfigWriter method writeConfig.

private void writeConfig(ModemInterfaceConfigImpl modemInterfaceConfig) throws KuraException {
    String oldInterfaceName = modemInterfaceConfig.getName();
    String newInterfaceName = modemInterfaceConfig.getName();
    // Get the configs
    ModemConfig modemConfig = null;
    NetConfigIP4 netConfigIP4 = null;
    for (ModemInterfaceAddressConfig modemInterfaceAddressConfig : modemInterfaceConfig.getNetInterfaceAddresses()) {
        for (NetConfig netConfig : modemInterfaceAddressConfig.getConfigs()) {
            if (netConfig instanceof ModemConfig) {
                modemConfig = (ModemConfig) netConfig;
            } else if (netConfig instanceof NetConfigIP4) {
                netConfigIP4 = (NetConfigIP4) netConfig;
            }
        }
    }
    // Use the ppp number for the interface name, if configured
    int pppNum = -1;
    if (modemConfig != null) {
        pppNum = modemConfig.getPppNumber();
        if (pppNum >= 0) {
            newInterfaceName = "ppp" + pppNum;
            modemInterfaceConfig.setName(newInterfaceName);
        }
    }
    // Save the status and priority
    IfcfgConfigWriter.writeKuraExtendedConfig(modemInterfaceConfig);
    Class<? extends ModemPppConfigGenerator> configClass = null;
    UsbDevice usbDevice = modemInterfaceConfig.getUsbDevice();
    int baudRate = -1;
    if (usbDevice != null) {
        SupportedUsbModemInfo modemInfo = SupportedUsbModemsInfo.getModem(usbDevice);
        UsbModemFactoryInfo usbFactoryInfo = SupportedUsbModemsFactoryInfo.getModem(modemInfo);
        if (usbFactoryInfo != null) {
            configClass = usbFactoryInfo.getConfigGeneratorClass();
        }
        baudRate = 921600;
    } else {
        SupportedSerialModemInfo serialModemInfo = SupportedSerialModemsInfo.getModem();
        SerialModemFactoryInfo serialFactoryInfo = SupportedSerialModemsFactoryInfo.getModem(serialModemInfo);
        configClass = serialFactoryInfo.getConfigGeneratorClass();
        baudRate = serialModemInfo.getDriver().getComm().getBaudRate();
    }
    String pppPeerFilename = formPeerFilename(usbDevice);
    String pppLogfile = formPppLogFilename(usbDevice);
    String chatFilename = formChatFilename(usbDevice);
    String disconnectFilename = formDisconnectFilename(usbDevice);
    // Cleanup values associated with the old name if the interface name has changed
    if (!oldInterfaceName.equals(newInterfaceName)) {
        try {
            // Remove the old ppp peers symlink
            s_logger.debug("Removing old symlinks to {}", pppPeerFilename);
            removeSymbolicLinks(pppPeerFilename, OS_PEERS_DIRECTORY);
            // Remove the old modem identifier
            StringBuilder key = new StringBuilder("net.interface.").append(oldInterfaceName).append(".modem.identifier");
            s_logger.debug("Removing modem identifier for {}", oldInterfaceName);
            KuranetConfig.deleteProperty(key.toString());
            // Remove custom dns servers
            key = new StringBuilder("net.interface.").append(oldInterfaceName).append(".config.dnsServers");
            s_logger.debug("Removing dns servers for {}", oldInterfaceName);
            KuranetConfig.deleteProperty(key.toString());
            // Remove gpsEnabled
            key = new StringBuilder().append("net.interface.").append(oldInterfaceName).append(".config.gpsEnabled");
            s_logger.debug("Removing gpsEnabled for {}", oldInterfaceName);
            KuranetConfig.deleteProperty(key.toString());
            // Remove status
            IfcfgConfigWriter.removeKuraExtendedConfig(oldInterfaceName);
        } catch (IOException e) {
            throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
        }
    }
    if (configClass != null) {
        try {
            ModemPppConfigGenerator scriptGenerator = configClass.newInstance();
            if (modemConfig != null) {
                s_logger.debug("Writing connect scripts for " + modemInterfaceConfig.getName() + " using " + configClass.toString());
                s_logger.debug("Writing {}", pppPeerFilename);
                PppPeer pppPeer = scriptGenerator.getPppPeer(getDeviceId(usbDevice), modemConfig, pppLogfile, chatFilename, disconnectFilename);
                pppPeer.setBaudRate(baudRate);
                pppPeer.write(pppPeerFilename);
                s_logger.debug("Writing {}", chatFilename);
                ModemXchangeScript connectScript = scriptGenerator.getConnectScript(modemConfig);
                connectScript.writeScript(chatFilename);
                s_logger.debug("Writing {}", disconnectFilename);
                ModemXchangeScript disconnectScript = scriptGenerator.getDisconnectScript(modemConfig);
                disconnectScript.writeScript(disconnectFilename);
                if (pppNum >= 0) {
                    s_logger.debug("Linking peer file using ppp number: {}", pppNum);
                    String symlinkFilename = formPeerLinkAbsoluteName(pppNum);
                    LinuxFileUtil.createSymbolicLink(pppPeerFilename, symlinkFilename);
                } else {
                    s_logger.error("Can't create symbolic link to " + pppPeerFilename + ", invalid ppp number: " + pppNum);
                }
                String modemIdentifier = modemInterfaceConfig.getModemIdentifier();
                if (modemIdentifier != null) {
                    StringBuilder key = new StringBuilder("net.interface.").append(modemInterfaceConfig.getName()).append(".modem.identifier");
                    s_logger.debug("Storing modem identifier " + modemIdentifier + " using key: " + key);
                    KuranetConfig.setProperty(key.toString(), modemIdentifier);
                }
                // Custom dns servers
                if (netConfigIP4 != null) {
                    StringBuilder key = new StringBuilder("net.interface.").append(modemInterfaceConfig.getName()).append(".config.dnsServers");
                    List<IP4Address> dnsServers = netConfigIP4.getDnsServers();
                    if (dnsServers != null && !dnsServers.isEmpty()) {
                        StringBuilder serversSB = new StringBuilder();
                        Iterator<IP4Address> it = dnsServers.iterator();
                        serversSB.append(it.next().getHostAddress());
                        while (it.hasNext()) {
                            serversSB.append(DNS_DELIM).append(it.next().getHostAddress());
                        }
                        s_logger.debug("Storing DNS servers " + serversSB + " using key: " + key);
                        KuranetConfig.setProperty(key.toString(), serversSB.toString());
                    } else {
                        KuranetConfig.deleteProperty(key.toString());
                    }
                }
                StringBuilder key = new StringBuilder().append("net.interface.").append(newInterfaceName).append(".config.gpsEnabled");
                s_logger.debug("Setting gpsEnabled for {}", newInterfaceName);
                KuranetConfig.setProperty(key.toString(), Boolean.toString(modemConfig.isGpsEnabled()));
                key = new StringBuilder().append("net.interface.").append(newInterfaceName).append(".config.resetTimeout");
                s_logger.debug("Setting modem resetTimeout for {}", newInterfaceName);
                KuranetConfig.setProperty(key.toString(), Integer.toString(modemConfig.getResetTimeout()));
            } else {
                s_logger.error("Error writing connect scripts - modemConfig is null");
            }
        } catch (Exception e) {
            s_logger.error("Could not write modem config", e);
        }
    }
}
Also used : IP4Address(org.eclipse.kura.net.IP4Address) UsbDevice(org.eclipse.kura.usb.UsbDevice) SupportedSerialModemInfo(org.eclipse.kura.linux.net.modem.SupportedSerialModemInfo) IOException(java.io.IOException) KuraException(org.eclipse.kura.KuraException) IOException(java.io.IOException) NetConfigIP4(org.eclipse.kura.net.NetConfigIP4) UsbModemFactoryInfo(org.eclipse.kura.net.admin.modem.SupportedUsbModemsFactoryInfo.UsbModemFactoryInfo) ModemConfig(org.eclipse.kura.net.modem.ModemConfig) PppPeer(org.eclipse.kura.net.admin.modem.PppPeer) SerialModemFactoryInfo(org.eclipse.kura.net.admin.modem.SupportedSerialModemsFactoryInfo.SerialModemFactoryInfo) ModemXchangeScript(org.eclipse.kura.net.admin.visitor.linux.util.ModemXchangeScript) KuraException(org.eclipse.kura.KuraException) ModemInterfaceAddressConfig(org.eclipse.kura.net.modem.ModemInterfaceAddressConfig) NetConfig(org.eclipse.kura.net.NetConfig) ModemPppConfigGenerator(org.eclipse.kura.net.admin.modem.ModemPppConfigGenerator) SupportedUsbModemInfo(org.eclipse.kura.linux.net.modem.SupportedUsbModemInfo)

Aggregations

IP4Address (org.eclipse.kura.net.IP4Address)33 KuraException (org.eclipse.kura.KuraException)20 ArrayList (java.util.ArrayList)15 IOException (java.io.IOException)12 NetConfigIP4 (org.eclipse.kura.net.NetConfigIP4)11 IPAddress (org.eclipse.kura.net.IPAddress)10 NetConfig (org.eclipse.kura.net.NetConfig)10 UnknownHostException (java.net.UnknownHostException)9 NetInterfaceAddressConfig (org.eclipse.kura.net.NetInterfaceAddressConfig)9 IP6Address (org.eclipse.kura.net.IP6Address)8 RouteConfig (org.eclipse.kura.net.route.RouteConfig)7 RouteConfigIP4 (org.eclipse.kura.net.route.RouteConfigIP4)6 RouteConfigIP6 (org.eclipse.kura.net.route.RouteConfigIP6)6 FileNotFoundException (java.io.FileNotFoundException)5 List (java.util.List)5 StringTokenizer (java.util.StringTokenizer)5 DhcpServerConfigIP4 (org.eclipse.kura.net.dhcp.DhcpServerConfigIP4)5 WifiConfig (org.eclipse.kura.net.wifi.WifiConfig)5 BufferedReader (java.io.BufferedReader)4 FileReader (java.io.FileReader)4