Class: Yast::NetworkInterfacesClass

Inherits:
Module
  • Object
show all
Includes:
Logger
Defined in:
library/network/src/modules/NetworkInterfaces.rb

Overview

Reads and writes the ifcfg files (/etc/sysconfig/network/ifcfg-*). Categorizes the configurations according to type. Presents them one ifcfg at a time through the #Current hash.

Constant Summary

ALIAS_SEPARATOR =

A single character used to separate alias id

"#".freeze
TYPE_REGEX =
"(ip6tnl|mip6mnha|[#{String.CAlpha}]+)".freeze
ID_REGEX =
"([^#{ALIAS_SEPARATOR}]*)".freeze
ALIAS_REGEX =
"(.*)".freeze
DEVNAME_REGEX =
"#{TYPE_REGEX}-?#{ID_REGEX}".freeze
LOCALS =

Variables which could be suffixed and thus duplicated

[
  "IPADDR",
  "REMOTE_IPADDR",
  "NETMASK",
  "PREFIXLEN",
  "BROADCAST",
  "SCOPE",
  "LABEL",
  "IP_OPTIONS"
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#CurrentHash<String>

Current device information like { “BOOTPROTO”=>“dhcp”, “STARTMODE”=>“auto” }

#Add, #Edit and #Delete copy the requested device info (via #Select) to #Name and #Current, #Commit puts it back.

Returns:



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
# File 'library/network/src/modules/NetworkInterfaces.rb', line 62

def main
  textdomain "base"

  Yast.import "Arch"
  Yast.import "Map"
  Yast.import "Mode"
  Yast.import "Netmask"
  Yast.import "FileUtils"
  Yast.import "IP"

  @Name = ""

  @Current = {}

  # Interface information:
  # Devices[string type, string id] is a map with the contents of
  # ifcfg-<i>type</i>-<i>id</i>. Separating type from id is useful because
  # the type determines the fields of the interface file.
  # Multiple addresses for an interface are nested maps
  # [type, id, "_aliases", aid]
  # @see #Read
  @Devices = {}

  # Devices information
  # @see #Read
  @OriginalDevices = {}

  # Deleted devices
  @Deleted = []

  # True if devices are already read
  @initialized = false

  # Which operation is pending?
  # global
  @operation = nil
  # FIXME: used in lan/address.ycp (#17346) -> "global"

  # Predefined network card regular expressions
  @CardRegex =
    # other: irlan|lo|plip|...
    {
      "netcard" => "arc|ath|bnep|ci|ctc|slc|dummy|bond|escon|eth|fddi|ficon|hsi|qeth|lcs|iucv|myri|tr|usb|wlan|xp|vlan|br|tun|tap|ib|em|p|p[0-9]+p",
      "modem"   => "ppp|modem",
      "isdn"    => "isdn|ippp",
      "dsl"     => "dsl"
    }

  # Predefined network device regular expressions
  @DeviceRegex = {
    # device types
    "netcard" => @CardRegex["netcard"],
    "modem"   => @CardRegex["modem"],
    "isdn"    => @CardRegex["isdn"],
    "dsl"     => @CardRegex["dsl"],
    # device groups
    "dialup"  => @CardRegex["modem"] + "|" + @CardRegex["dsl"] + "|" + @CardRegex["isdn"]
  }

  # Types in order from fastest to slowest.
  # @see #FastestRegexps
  @FastestTypes = { 1 => "dsl", 2 => "isdn", 3 => "modem", 4 => "netcard" }

  # -------------------- components of configuration names --------------------

  # ifcfg name = type + id + alias_id
  # If id is numeric, it is not separated from type, otherwise separated by "-"
  # Id may be empty
  # Alias_id, if nonempty, is separated by alias_separator
  @ifcfg_name_regex = "^#{DEVNAME_REGEX}#{ALIAS_SEPARATOR}?#{ALIAS_REGEX}$"

  # Translates type code exposed by kernel in sysfs onto internaly used dev types.
  @TypeBySysfs = {
    "1"     => "eth",
    "24"    => "eth",
    "32"    => "ib",
    "512"   => "ppp",
    "768"   => "ipip",
    "769"   => "ip6tnl",
    "772"   => "lo",
    "776"   => "sit",
    "778"   => "gre",
    "783"   => "irda",
    "801"   => "wlan_aux",
    "65534" => "tun"
  }

  @TypeByKeyValue = ["INTERFACETYPE"]
  @TypeByKeyExistence = [
    ["ETHERDEVICE", "vlan"],
    ["WIRELESS_MODE", "wlan"],
    ["MODEM_DEVICE", "ppp"]
  ]
  @TypeByValueMatch = [
    ["BONDING_MASTER", "yes", "bond"],
    ["BRIDGE", "yes", "br"],
    ["WIRELESS", "yes", "wlan"],
    ["TUNNEL", "tap", "tap"],
    ["TUNNEL", "tun", "tun"],
    ["TUNNEL", "sit", "sit"],
    ["TUNNEL", "gre", "gre"],
    ["TUNNEL", "ipip", "ipip"],
    ["PPPMODE", "pppoe", "ppp"],
    ["PPPMODE", "pppoatm", "ppp"],
    ["PPPMODE", "capi-adsl", "ppp"],
    ["PPPMODE", "pptp", "ppp"],
    ["ENCAP", "syncppp", "isdn"],
    ["ENCAP", "rawip", "isdn"]
  ]

  @SensitiveFields = [
    "WIRELESS_WPA_PASSWORD",
    "WIRELESS_WPA_PSK",
    # the unnumbered one should be empty but just in case
    "WIRELESS_KEY",
    "WIRELESS_KEY_0",
    "WIRELESS_KEY_1",
    "WIRELESS_KEY_2",
    "WIRELESS_KEY_3"
  ]
end

#DevicesObject (readonly)

Returns the value of attribute Devices



32
33
34
# File 'library/network/src/modules/NetworkInterfaces.rb', line 32

def Devices
  @Devices
end

#NameString

Current device identifier, like eth0, eth1:blah, lo, …

#Add, #Edit and #Delete copy the requested device info (via #Select) to #Name and #Current, #Commit puts it back.

Returns:



# File 'library/network/src/modules/NetworkInterfaces.rb', line 45


Instance Method Details

#adapt_old_config!Object

Adapts the interface configuration used during many year for enslaved interfaces (IPADDR == 0.0.0.0 and BOOTPROTO == 'static').

Sets the BOOTPROTO as none, empties the IPADDR, and also empties the NETMASK and the PREFIXLEN if exist.



702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
# File 'library/network/src/modules/NetworkInterfaces.rb', line 702

def adapt_old_config!
  @Devices.each do |devtype, devices|
    devices.each do |device, config|
      bootproto = config["BOOTPROTO"] || "static"
      next unless bootproto == "static" && config["IPADDR"] == "0.0.0.0"

      config["BOOTPROTO"] = "none"
      config["IPADDR"]    = ""
      config["NETMASK"]   = "" if config.key? "NETMASK"
      config["PREFIXLEN"] = "" if config.key? "PREFIXLEN"

      @Devices[devtype][device] = config
    end
  end

  @Devices
end

#AddObject

Add a new device

Returns:

  • true if success



1417
1418
1419
1420
1421
1422
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1417

def Add
  @operation = nil
  return false if Select("") != true
  @operation = :add
  true
end

#add_device(device, ifcfg) ⇒ Object

The device is added to @Devices hash using the device name as key and the ifconfg hash as value

Parameters:

  • device (String)

    name

  • ifcfg (Hash)

    a map with netconfig (ifcfg) configuration



725
726
727
728
729
730
731
# File 'library/network/src/modules/NetworkInterfaces.rb', line 725

def add_device(device, ifcfg)
  # if possible use dev type as available in /sys otherwise use ifcfg config
  # as a fallback for device type detection
  devtype = GetTypeFromIfcfgOrName(device, ifcfg)
  @Devices[devtype] ||= {}
  @Devices[devtype][device] = ifcfg
end

#alias_name(typ, num, anum) ⇒ Object

Create a alias name from its type and numbers

Examples:

alias_name(“eth”, “1”, “2”) -> “eth1#2”


Parameters:

  • typ (String)

    device type

  • num (String)

    device number

  • anum (String)

    alias number

Returns:

  • alias name



458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'library/network/src/modules/NetworkInterfaces.rb', line 458

def alias_name(typ, num, anum)
  if typ.nil? || typ == ""
    Builtins.y2error("wrong type: %1", typ)
    return nil
  end
  if num.nil? # || num < 0
    Builtins.y2error("wrong number: %1", num)
    return nil
  end
  if anum.nil? || anum == ""
    Builtins.y2error("wrong alias number: %1", anum)
    return nil
  end
  Builtins.sformat("%1#%2", device_name(typ, num), anum)
end

#alias_num(dev) ⇒ Object

Return a device alias number

Examples:

alias_num(“eth1#2”) -> “2”


alias_num(“eth1#blah”) -> “blah”


Parameters:

Returns:

  • alias number



420
421
422
# File 'library/network/src/modules/NetworkInterfaces.rb', line 420

def alias_num(dev)
  ifcfg_part(dev, "3")
end

#canonicalize_config(config) ⇒ Hash

Canonicalize IPADDR and STARTMODE of given config and nested _aliases

Parameters:

  • config (Hash)

    a map with netconfig (ifcfg) configuration

Returns:

  • (Hash)

    ifcfg with canonicalized IP addresses



635
636
637
638
639
640
641
642
643
644
# File 'library/network/src/modules/NetworkInterfaces.rb', line 635

def canonicalize_config(config)
  config = deep_copy(config)
  # canonicalize, #46885
  (config["_aliases"] || {}).tap do |aliases|
    aliases.each { |a, c| aliases[a] = CanonicalizeIP(c) }
  end

  config = CanonicalizeIP(config)
  CanonicalizeStartmode(config)
end

#CanonicalizeIP(ifcfg) ⇒ Object

Canonicalize static ip configuration obtained from sysconfig. (suse#46885)

Static ip configuration formats supported by sysconfig: 1) IPADDR=10.0.0.1/8 2) IPADDR=10.0.0.1 PREFIXLEN=8 3) IPADDR=10.0.0.1 NETMASK=255.0.0.0

Features:

  • IPADDR (in form <ip>/<prefix>) overrides PREFIXLEN,

  • NETMASK is used only if prefix length unspecified)

  • If prefix length and NETMASK are unspecified, 32 is implied.

Canonicalize it to:

  • IPADDR=“<ipv4>” PREFIXLEN=“<prefix>” NETMASK=“<netmask>”) in case of IPv4 config

E.g. IPADDR=10.0.0.1 PREFIXLEN=8 NETMASK=255.0.0.0

  • IPADDR=“<ipv6>” PREFIXLEN=“<prefix>” NETMASK=“”) in case of IPv6 config

E.g. IPADDR=2001:15c0:668e::5 PREFIXLEN=48 NETMASK=“”

Parameters:

  • ifcfg

    a map with netconfig (ifcfg) configuration for a one device

Returns:

  • a map with IPADDR, NETMASK and PREFIXLEN adjusted if IPADDR is present. Returns original ifcfg if IPADDR is not present. In case of error, returns nil.



553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# File 'library/network/src/modules/NetworkInterfaces.rb', line 553

def CanonicalizeIP(ifcfg)
  ifcfg = deep_copy(ifcfg)
  return nil if ifcfg.nil?

  ipaddr, prefixlen = ifcfg["IPADDR"].to_s.split("/")

  return ifcfg if ipaddr.to_s == "" # DHCP or inconsistent

  prefixlen = ifcfg["PREFIXLEN"].to_s if prefixlen.to_s == ""

  prefixlen = Netmask.ToBits(ifcfg["NETMASK"].to_s).to_s if prefixlen == ""

  # Now we have ipaddr and prefixlen
  # Let's compute the rest
  netmask = IP.Check4(ipaddr) ? Netmask.FromBits(prefixlen.to_i) : ""

  ifcfg["IPADDR"] = ipaddr
  ifcfg["PREFIXLEN"] = prefixlen
  ifcfg["NETMASK"] = netmask

  ifcfg
end

#CanonicalizeStartmode(ifcfg) ⇒ Object

STARTMODE: onboot, on and boot are aliases for auto



513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# File 'library/network/src/modules/NetworkInterfaces.rb', line 513

def CanonicalizeStartmode(ifcfg)
  ifcfg = deep_copy(ifcfg)
  canonicalize_startmode = {
    "on"     => "auto",
    "boot"   => "auto",
    "onboot" => "auto"
  }
  startmode = Ops.get_string(ifcfg, "STARTMODE", "")
  Ops.set(
    ifcfg,
    "STARTMODE",
    Ops.get(canonicalize_startmode, startmode, startmode)
  )
  deep_copy(ifcfg)
end

#Change2(name, newdev, check) ⇒ Object

Update Devices map

Parameters:

  • name (String)

    device identifier

  • newdev (Hash<String, Object>)

    new device map

  • check (true, false)

    if check if device already exists

Returns:

  • true if success



1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1449

def Change2(name, newdev, check)
  newdev = deep_copy(newdev)
  Builtins.y2debug("Change(%1,%2,%3)", name, newdev, check)
  Builtins.y2debug("Devices=%1", @Devices)
  if Check(name) && check
    Builtins.y2error("Device already present: %1", name)
    return false
  end

  t = if !IsEmpty(newdev)
    GetTypeFromIfcfgOrName(name, newdev)
  else
    GetType(name)
  end

  if name == @Name
    int_type = Ops.get_string(@Current, "INTERFACETYPE", "")

    t = int_type if Ops.greater_than(Builtins.size(int_type), 0)
  end
  a = alias_num(name)
  Builtins.y2debug("ChangeDevice(%1)", name)

  devsmap = Ops.get(@Devices, t, {})
  devmap = Ops.get(devsmap, name, {})
  amap = Ops.get_map(devmap, "_aliases", {})

  if a != ""
    Ops.set(amap, a, newdev)
    Ops.set(devmap, "_aliases", amap)
  else
    devmap = deep_copy(newdev)
  end

  Ops.set(devsmap, name, devmap)
  Ops.set(@Devices, t, devsmap)

  Builtins.y2debug("Devices=%1", @Devices)
  true
end

#Check(dev) ⇒ Object

Check presence of the device (alias)

Parameters:

  • dev (String)

    device identifier

Returns:

  • true if device is present



1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1367

def Check(dev)
  Builtins.y2debug("Check(%1)", dev)
  typ = GetType(dev)
  #    string num = device_num(dev);
  #    string anum = alias_num(dev);
  return false if !Builtins.haskey(@Devices, typ)

  devsmap = Ops.get(@Devices, typ, {})
  return false if !Builtins.haskey(devsmap, dev)

  Builtins.y2debug("Check passed")
  true
end

#CleanCacheReadObject

re-read all settings again from system for creating new proposal from scratch (#170558)



763
764
765
766
# File 'library/network/src/modules/NetworkInterfaces.rb', line 763

def CleanCacheRead
  @initialized = false
  Read()
end
Deprecated.

No longer needed

Returns true

Returns:

  • true



1617
1618
1619
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1617

def CleanHotplugSymlink
  true
end

#CommitObject



1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1529

def Commit
  Builtins.y2debug("Name=%1", @Name)
  Builtins.y2debug("Current=%1", @Current)
  Builtins.y2debug("Devices=%1", @Devices)
  Builtins.y2debug("Deleted=%1", @Deleted)
  Builtins.y2debug("operation=%1", @operation)

  if @operation == :add || @operation == :edit
    Change2(@Name, @Current, @operation == :add)
  elsif @operation == :delete
    Delete2(@Name)
  else
    Builtins.y2error("Unknown operation: %1 (%2)", @operation, @Name)
    return false
  end

  Builtins.y2debug("Devices=%1", @Devices)
  Builtins.y2debug("Deleted=%1", @Deleted)

  @Name = ""
  @Current = {}
  @operation = nil

  true
end

#ConcealSecrets(devs) ⇒ Object

Conceal secret information, such as WEP keys, so that the output can be passed to y2log and bugzilla. (#65741)

Parameters:

  • devs (Hash)

    a two-level map of ifcfgs like Devices

Returns:

  • ifcfgs with secret fields masked out



612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# File 'library/network/src/modules/NetworkInterfaces.rb', line 612

def ConcealSecrets(devs)
  devs = deep_copy(devs)
  return nil if devs.nil?
  out = Builtins.mapmap(
    Convert.convert(
      devs,
      from: "map",
      to:   "map <string, map <string, map <string, any>>>"
    )
  ) do |t, tdevs|
    tout = Builtins.mapmap(tdevs) do |id, ifcfg|
      { id => ConcealSecrets1(ifcfg) }
    end
    { t => tout }
  end
  deep_copy(out)
end

#ConcealSecrets1(ifcfg) ⇒ Object

Conceal secret information, such as WEP keys, so that the output can be passed to y2log and bugzilla.

Parameters:

  • ifcfg (Hash{String => Object})

    one ifcfg

Returns:

  • ifcfg with secret fields masked out



598
599
600
601
602
603
604
605
606
# File 'library/network/src/modules/NetworkInterfaces.rb', line 598

def ConcealSecrets1(ifcfg)
  ifcfg = deep_copy(ifcfg)
  return nil if ifcfg.nil?

  secret_fields = ifcfg.select { |k, v| @SensitiveFields.include?(k) && v != "" }
  secret_fields.map { |k, _v| ifcfg[k] = "CONCEALED" }

  ifcfg
end

#Delete(name) ⇒ Object

Delete the given device

Parameters:

  • name (String)

    device to delete

Returns:

  • true if success



1437
1438
1439
1440
1441
1442
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1437

def Delete(name)
  @operation = nil
  return false if Select(name) != true
  @operation = :delete
  true
end

#Delete2(name) ⇒ Object



1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1490

def Delete2(name)
  if !Check(name)
    Builtins.y2error("Device not found: %1", name)
    return false
  end

  t = GetType(name)
  a = alias_num(name)
  devsmap = Ops.get(@Devices, t, {})

  if a != ""
    amap = Ops.get_map(devsmap, [name, "_aliases"], {})
    amap = Builtins.remove(amap, a)
    Ops.set(devsmap, [name, "_aliases"], amap)
  else
    devsmap = Builtins.remove(devsmap, name)
  end

  Ops.set(@Devices, t, devsmap)

  # Originally this avoided errors in the log when deleting an
  # interface that was not present at Read (had no ifcfg file).
  # #115448: OriginalDevices is not updated after Write so
  # returning to the network proposal and deleting a card would not work.
  Builtins.y2milestone("Deleting file: #{name}")
  @Deleted << name
  true
end

#DeleteAlias(device, aid) ⇒ Object

Add the alias to the list of deleted items. Called when exiting from the aliases-of-device dialog. #48191



1522
1523
1524
1525
1526
1527
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1522

def DeleteAlias(device, aid)
  alias_ = Builtins.sformat("%1#%2", device, aid)
  Builtins.y2milestone("Deleting alias: %1", alias_)
  @Deleted << alias_
  true
end

#device_name(typ, num) ⇒ Object

Create a device name from its type and number

Examples:

device_name(“eth”, “1”) -> “eth1”


device_name(“lo”, “”) -> “lo”


Parameters:

  • typ (String)

    device type

  • num (String)

    device number

Returns:

  • device name



430
431
432
433
434
435
436
437
438
439
440
441
442
443
# File 'library/network/src/modules/NetworkInterfaces.rb', line 430

def device_name(typ, num)
  if typ.nil? || typ == ""
    Builtins.y2error("wrong type: %1", typ)
    return nil
  end
  if num.nil?
    Builtins.y2error("wrong number: %1", num)
    return nil
  end
  if Builtins.regexpmatch(num, "^[0-9]*$")
    return Builtins.sformat("%1%2", typ, num)
  end
  Builtins.sformat("%1-%2", typ, num)
end

#device_name_from_alias(alias_name) ⇒ Object

Extracts device name from alias name

alias_name := <device_name>ALIAS_SEPARATOR<alias_name>



448
449
450
# File 'library/network/src/modules/NetworkInterfaces.rb', line 448

def device_name_from_alias(alias_name)
  alias_name.sub(/#{ALIAS_SEPARATOR}.*/, "")
end

#device_num(dev) ⇒ Object

Return a device number Obsolete: It is incompatible with new device naming scheme.

Examples:

device_num(“eth1”) -> “1”


device_num(“lo”) -> “”


Parameters:

Returns:

  • device number



410
411
412
413
# File 'library/network/src/modules/NetworkInterfaces.rb', line 410

def device_num(dev)
  log.warn("Do not use device_num.")
  ifcfg_part(dev, "2")
end

#device_type(dev) ⇒ Object

Return a device type

Examples:

device_type(“eth1”) -> “eth”


device_type(“eth-pcmcia-0”) -> “eth”


Parameters:

Returns:

  • device type



199
200
201
# File 'library/network/src/modules/NetworkInterfaces.rb', line 199

def device_type(dev)
  ifcfg_part(dev, "1")
end

#devmap(name) ⇒ Hash

Returns a hash with configuration for particular device

Hash map is direct maping of sysconfig file into hash. Keys are sysconfig options (e.g. { 'IPADDR' => '1.1.1.1' }

Parameters:

  • name (String)

    is device name as provided by the system (e.g. eth0)

Returns:

  • (Hash)

    device configuration or nil in case of error



776
777
778
# File 'library/network/src/modules/NetworkInterfaces.rb', line 776

def devmap(name)
  Devices().fetch(GetType(name), {})[name]
end

#Edit(name) ⇒ Object

Edit the given device

Parameters:

  • name (String)

    device to edit

Returns:

  • true if success



1427
1428
1429
1430
1431
1432
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1427

def Edit(name)
  @operation = nil
  return false if Select(name) != true
  @operation = :edit
  true
end

#Export(devregex) ⇒ Object

Export data

Returns:

  • dumped settings (later acceptable by Import())



1299
1300
1301
1302
1303
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1299

def Export(devregex)
  devs = Filter(@Devices, devregex)
  log.debug("Devs=#{devs}")
  devs
end

#FastestObject

Find the fastest available device



1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1664

def Fastest
  ret = ""
  devices = List("")

  # Find the fastest device
  Builtins.foreach(@FastestTypes) do |_num, type|
    Builtins.foreach(devices) do |dev|
      if ret == "" &&
          Builtins.regexpmatch(
            dev,
            Ops.add(Ops.add("^", Ops.get(@DeviceRegex, type, "")), "[0-9]*$")
          ) &&
          IsConnected(dev)
        ret = dev
      end
    end
  end

  Builtins.y2milestone("ret=%1", ret)
  ret
end

#FastestType(name) ⇒ Object



1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1686

def FastestType(name)
  ret = ""
  Builtins.maplist(@FastestTypes) do |_num, type|
    regex = Ops.get(@DeviceRegex, type, "")
    if ret == "" &&
        Builtins.regexpmatch(name, Ops.add(Ops.add("^", regex), "[0-9]*$"))
      ret = type
    end
  end

  ret
end

#Filter(devices, devregex) ⇒ Array

Returns all the devices which device name matchs given devregex

Parameters:

  • devices (Array)

    of Devices

  • devregex (String)

    regex to filter by

Returns:

  • (Array)

    of Devices that match the given regex



785
786
787
788
789
790
791
792
793
794
# File 'library/network/src/modules/NetworkInterfaces.rb', line 785

def Filter(devices, devregex)
  devices = deep_copy(devices)
  return devices if devices.nil? || devregex.nil? || devregex == ""

  regex = "^(#{@DeviceRegex[devregex] || devregex})[0-9]*$"
  log.debug("regex=#{regex}")
  devices.select! { |f, _d| f =~ /#{regex}/ }
  log.debug("devices=#{devices}")
  devices
end

#filter_interfacetype(devmap) ⇒ Object

Filters out INTERFACETYPE option from ifcfg config when it is not needed.

INTERFACETYPE has big impact on wicked even yast behavior. It was overused by yast in the past. According wicked team it makes sense to use it only in two cases 1) lo device (when it's name is changed - very strongly discouraged) 2) dummy device

This function silently modifies user's config files. However, it should make sense because:

  • INTERFACETYPE is usually not needed

  • other functions in this module modifies the config as well (see Canonicalize* functions)

  • using INTERFACETYPE is reported as a warning by wicked (it asks for reporting a bug)

  • it is often ignored by wicked



589
590
591
592
# File 'library/network/src/modules/NetworkInterfaces.rb', line 589

def filter_interfacetype(devmap)
  ret = deep_copy(devmap)
  ret.delete_if { |k, v| k == "INTERFACETYPE" && !["lo", "dummy"].include?(v) }
end

#FilterDevices(devregex) ⇒ Object

Used in BuildSummary, BuildOverview



797
798
799
# File 'library/network/src/modules/NetworkInterfaces.rb', line 797

def FilterDevices(devregex)
  Filter(@Devices, devregex)
end

#FilterNOT(devices, devregex) ⇒ Array

Returns all the devices that does not match the given devregex

Parameters:

  • devices (Array)

    of Devices

  • devregex (String)

    regex to filter by

Returns:

  • (Array)

    of Devices that match the given regex



806
807
808
809
810
811
812
813
814
815
816
817
# File 'library/network/src/modules/NetworkInterfaces.rb', line 806

def FilterNOT(devices, devregex)
  return {} if devices.nil? || devregex.nil? || devregex == ""
  devices = deep_copy(devices)

  regex = "^(#{@DeviceRegex[devregex] || devregex})[0-9]*$"

  log.debug("regex=#{regex}")
  devices.select! { |f, _d| f !~ /#{regex}/ }

  log.debug("devices=#{devices}")
  devices
end

#generate_config(pth, values) ⇒ Hash{String => Object}

It reads, parses and transforms the given attributes from the given device config path returning a hash with the transformed device config

Parameters:

  • pth (String)

    path of the device config to read from

  • values (Hash<String, Object>)

    new device map

Returns:

  • (Hash{String => Object})

    parsed configuration



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
# File 'library/network/src/modules/NetworkInterfaces.rb', line 666

def generate_config(pth, values)
  config = {}
  values.each do |val|
    item = SCR.Read(path("#{pth}.#{val}"))
    log.debug("item=#{item}")
    next if item.nil?
    # No underscore '_' -> global
    # Also temporarily standard globals
    if !val.include?("_") || LOCALS.include?(val)
      config[val] = item
      next
    end

    # Try to strip _suffix
    # @example "IP_OPTIONS_1".rpartition("_") => ["IP_OPTIONS", "_", "1"]
    v, _j, s = val.rpartition("_")
    log.info("#{val}:#{v}:#{s}")
    # Global
    if !LOCALS.include?(v)
      config[val] = item
    else
      config["_aliases"] ||= {}
      config["_aliases"][s] ||= {}
      config["_aliases"][s][v] = item
    end
  end
  log.info("config=#{ConcealSecrets1(config)}")
  config = canonicalize_config(config)
  filter_interfacetype(config)
end

#GetDeviceTypeName(dev) ⇒ Object

Return device type in human readable form :-)

Examples:

GetDeviceTypeName(eth-bus-pci-0000:01:07.0) -> “Network Card”


GetDeviceTypeName(modem0) -> “Modem”


Parameters:

Returns:

  • device type



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
# File 'library/network/src/modules/NetworkInterfaces.rb', line 376

def GetDeviceTypeName(dev)
  # pppN must be tried before pN, modem before netcard
  if Builtins.regexpmatch(
    dev,
    Ops.add("^", Ops.get(@DeviceRegex, "modem", ""))
  )
    return _("Modem")
  elsif Builtins.regexpmatch(
    dev,
    Ops.add("^", Ops.get(@DeviceRegex, "netcard", ""))
  )
    return _("Network Card")
  elsif Builtins.regexpmatch(
    dev,
    Ops.add("^", Ops.get(@DeviceRegex, "isdn", ""))
  )
    return _("ISDN")
  elsif Builtins.regexpmatch(
    dev,
    Ops.add("^", Ops.get(@DeviceRegex, "dsl", ""))
  )
    return _("DSL")
  else
    return _("Unknown")
  end
end

#GetDeviceTypesObject

Return supported network device types (for type netcard) for this hardware



1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1065

def GetDeviceTypes
  # common linux device types available on all architectures
  common_dev_types = ["eth", "tr", "vlan", "br", "tun", "tap", "bond"]

  # s390 specific device types
  s390_dev_types = ["hsi", "ctc", "escon", "ficon", "iucv", "qeth", "lcs"]

  # device types which cannot be present on s390 arch
  s390_unknown_dev_types = [
    "arc",
    "bnep",
    "dummy",
    "fddi",
    "myri",
    "usb",
    "wlan",
    "ib"
  ]

  # ia64 specific device types
  ia64_dev_types = ["xp"]

  dev_types = deep_copy(common_dev_types)

  if Arch.s390
    dev_types = Convert.convert(
      Builtins.merge(dev_types, s390_dev_types),
      from: "list",
      to:   "list <string>"
    )
  else
    if Arch.ia64
      dev_types = Convert.convert(
        Builtins.merge(dev_types, ia64_dev_types),
        from: "list",
        to:   "list <string>"
      )
    end

    dev_types = Convert.convert(
      Builtins.merge(dev_types, s390_unknown_dev_types),
      from: "list",
      to:   "list <string>"
    )
  end

  Builtins.foreach(dev_types) do |device|
    if !Builtins.contains(
      Builtins.splitstring(Ops.get(@DeviceRegex, "netcard", ""), "|"),
      device
    )
      Builtins.y2error(
        "%1 is not contained in DeviceRegex[\"netcard\"]",
        device
      )
    end
  end

  deep_copy(dev_types)
end

#GetDevTypeDescription(type, longdescr) ⇒ Object

Return textual device type

Examples:

GetDevTypeDescription("eth", false) -> "Ethernet"
GetDevTypeDescription("eth", true)  -> "Ethernet Network Card"

Parameters:

  • type (String)

    device type

  • longdescr (String)

    description type

Returns:

  • textual form of device type



1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1134

def GetDevTypeDescription(type, longdescr)
  if Builtins.issubstring(type, "#")
    # Device type label
    # This is what used to be Virtual Interface (eth0:1).
    # In our data model, additional addresses for an interface
    # are represented as its sub-interfaces.
    # And also we frequently confuse "device" and "interface"
    # :-(
    return _("Additional Address")
  end

  device_types = {
    # Device type label
    "arc"   => [_("ARCnet"), _("ARCnet Network Card")],
    # Device type label
    "atm"   => [
      _("ATM"),
      _("Asynchronous Transfer Mode (ATM)")
    ],
    # Device type label
    "bnep"  => [
      _("Bluetooth"),
      _("Bluetooth Connection")
    ],
    # Device type label
    "bond"  => [_("Bond"), _("Bond Network")],
    # Device type label
    "ci"    => [
      _("CLAW"),
      _("Common Link Access for Workstation (CLAW)")
    ],
    # Device type label
    "contr" => [_("ISDN"), _("ISDN Card")],
    # Device type label
    "ctc"   => [
      _("CTC"),
      _("Channel to Channel Interface (CTC)")
    ],
    # Device type label
    "dsl"   => [_("DSL"), _("DSL Connection")],
    # Device type label
    "dummy" => [_("Dummy"), _("Dummy Network Device")],
    # Device type label
    "escon" => [
      _("ESCON"),
      _("Enterprise System Connector (ESCON)")
    ],
    # Device type label
    "eth"   => [
      _("Ethernet"),
      _("Ethernet Network Card")
    ],
    # Device type label
    "fddi"  => [_("FDDI"), _("FDDI Network Card")],
    # Device type label
    "ficon" => [
      _("FICON"),
      _("Fiberchannel System Connector (FICON)")
    ],
    # Device type label
    "hippi" => [
      _("HIPPI"),
      _("HIgh Performance Parallel Interface (HIPPI)")
    ],
    # Device type label
    "hsi"   => [
      _("Hipersockets"),
      _("Hipersockets Interface (HSI)")
    ],
    # Device type label
    "ippp"  => [_("ISDN"), _("ISDN Connection")],
    # Device type label
    "irlan" => [_("IrDA"), _("Infrared Network Device")],
    # Device type label
    "irda"  => [_("IrDA"), _("Infrared Device")],
    # Device type label
    "isdn"  => [_("ISDN"), _("ISDN Connection")],
    # Device type label
    "iucv"  => [
      _("IUCV"),
      _("Inter User Communication Vehicle (IUCV)")
    ],
    # Device type label
    "lcs"   => [_("OSA LCS"), _("OSA LCS Network Card")],
    # Device type label
    "lo"    => [_("Loopback"), _("Loopback Device")],
    # Device type label
    "modem" => [_("Modem"), _("Modem")],
    # Device type label
    "myri"  => [_("Myrinet"), _("Myrinet Network Card")],
    # Device type label
    "net"   => [_("ISDN"), _("ISDN Connection")],
    # Device type label
    "plip"  => [
      _("Parallel Line"),
      _("Parallel Line Connection")
    ],
    # Device type label
    "ppp"   => [_("Modem"), _("Modem")],
    # Device type label
    "qeth"  => [
      _("QETH"),
      _("OSA-Express or QDIO Device (QETH)")
    ],
    # Device type label
    "sit"   => [
      _("IPv6-in-IPv4"),
      _("IPv6-in-IPv4 Encapsulation Device")
    ],
    # Device type label
    "slip"  => [
      _("Serial Line"),
      _("Serial Line Connection")
    ],
    # Device type label
    "tr"    => [
      _("Token Ring"),
      _("Token Ring Network Card")
    ],
    # Device type label
    "usb"   => [_("USB"), _("USB Network Device")],
    # Device type label
    "vmnet" => [_("VMWare"), _("VMWare Network Device")],
    # Device type label
    "wlan"  => [
      _("Wireless"),
      _("Wireless Network Card")
    ],
    # Device type label
    "xp"    => [_("XPNET"), _("XP Network")],
    # Device type label
    "vlan"  => [_("VLAN"), _("Virtual LAN")],
    # Device type label
    "br"    => [_("Bridge"), _("Network Bridge")],
    # Device type label
    "tun"   => [_("TUN"), _("Network TUNnel")],
    # Device type label
    "tap"   => [_("TAP"), _("Network TAP")],
    # Device type label
    "ib"    => [_("InfiniBand"), _("InfiniBand Device")]
  }

  if Builtins.haskey(device_types, type)
    return Ops.get_string(
      device_types,
      [type, longdescr == true ? 1 : 0],
      ""
    )
  end

  type1 = String.FirstChunk(type, "-")
  if Builtins.haskey(device_types, type1)
    return Ops.get_string(
      device_types,
      [type1, longdescr == true ? 1 : 0],
      ""
    )
  end

  Builtins.y2error("Unknown type: %1", type)
  type
end

#GetEthTypeFromSysfs(dev) ⇒ String

Detects a subtype of Ethernet device type according /sys or /proc content

Examples:

GetEthTypeFromSysfs("eth0") -> "eth"
GetEthTypeFromSysfs("bond0") -> "bon"

Parameters:

  • dev (String)

    interface name

Returns:



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'library/network/src/modules/NetworkInterfaces.rb', line 211

def GetEthTypeFromSysfs(dev)
  sys_dir_path = "/sys/class/net/#{dev}"

  if FileUtils.Exists("#{sys_dir_path}/wireless")
    "wlan"
  elsif FileUtils.Exists("#{sys_dir_path}/phy80211")
    "wlan"
  elsif FileUtils.Exists("#{sys_dir_path}/bridge")
    "br"
  elsif FileUtils.Exists("#{sys_dir_path}/bonding")
    "bond"
  elsif FileUtils.Exists("#{sys_dir_path}/tun_flags")
    "tap"
  elsif FileUtils.Exists("/proc/net/vlan/#{dev}")
    "vlan"
  elsif FileUtils.Exists("/sys/devices/virtual/net/#{dev}") && dev =~ /dummy/
    "dummy"
  else
    "eth"
  end
end

#GetFreeDevice(type) ⇒ Object

Return free device

Examples:

GetFreeDevice(“eth”) -&gt; “1”


Parameters:

  • type (String)

    device type

Returns:

  • free device



1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1353

def GetFreeDevice(type)
  log.debug("type=#{type}")

  free_dev = GetFreeDevices(type, 1).first

  log.error("Free device location error: #{free_dev}") if free_dev.nil?
  log.debug("Free device=#{free_dev}")

  free_dev
end

#GetFreeDevices(type, num) ⇒ Array

It returns an array of <num> elements corresponding to the integer part of the free device names available for the given device type.

Examples:

GetFreeDevices(“eth”, 2) -> [1, 2]


Parameters:

  • type (String)

    device type

  • num (String)

    number of free devices to return

Returns:

  • (Array)

    of free devices for given type



1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1323

def GetFreeDevices(type, num)
  log.debug("Devices=#{@Devices}")
  log.debug("type,num=#{type},#{num}")
  log.debug("Devices[#{type}]=#{@Devices[type]}")

  curdevs = @Devices.fetch(type, {}).keys
  curdevs.map! { |d| d.include?(type) ? device_num(d) : d }

  i = 0
  count = 0
  ret = []

  # Remaining numbered devices
  while count < num
    if !curdevs.include?(i.to_s)
      ret << i.to_s
      count += 1
    end
    i += 1
  end

  log.debug("Free devices=#{ret}")

  ret
end

#GetIbTypeFromSysfs(dev) ⇒ String

Detects a subtype of InfiniBand device type according /sys

Examples:

GetEthTypeFromSysfs("ib0") -> "ib"
GetEthTypeFromSysfs("bond0") -> "bon"
GetEthTypeFromSysfs("ib0.8001") -> "ibchild"

Parameters:

  • dev (String)

    interface name

Returns:



242
243
244
245
246
247
248
249
250
251
252
# File 'library/network/src/modules/NetworkInterfaces.rb', line 242

def GetIbTypeFromSysfs(dev)
  sys_dir_path = "/sys/class/net/#{dev}"

  if FileUtils.Exists("#{sys_dir_path}/bonding")
    "bond"
  elsif FileUtils.Exists("#{sys_dir_path}/create_child")
    "ib"
  else
    "ibchild"
  end
end

#GetIP(device) ⇒ Array

get IP addres + additional IP addresses

Parameters:

  • device (String)

    identifier for network interface

Returns:

  • (Array)

    of IP addresses of selected interface



1572
1573
1574
1575
1576
1577
1578
1579
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1572

def GetIP(device)
  Select(device)
  ips = [GetValue(device, "IPADDR")]
  Builtins.foreach(Ops.get_map(@Current, "_aliases", {})) do |_key, value|
    ips = Builtins.add(ips, Ops.get_string(value, "IPADDR", ""))
  end
  deep_copy(ips)
end

#GetType(dev) ⇒ Object

Detects device type according cached data

If cached ifcfg for given device is found it is used as parameter for GetTypeFromIfcfgOrName( dev, ifcfg). Otherwise is device handled as unconfigured and result is equal to GetTypeFromIfcfgOrName( dev, nil)

Parameters:

  • dev

    device name

Returns:

  • detected device type



360
361
362
363
364
365
366
367
368
369
# File 'library/network/src/modules/NetworkInterfaces.rb', line 360

def GetType(dev)
  type = GetTypeFromIfcfgOrName(dev, nil)

  Builtins.foreach(@Devices) do |_dev_type, confs|
    ifcfg = Ops.get(confs, dev, {})
    type = GetTypeFromIfcfgOrName(dev, ifcfg) if !IsEmpty(ifcfg)
  end

  type
end

#GetTypeFromIfcfg(ifcfg) ⇒ Object

Detects device type according given ifcfg configuration

Returns:

  • device type or nil if type cannot be recognized from ifcfg config



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
# File 'library/network/src/modules/NetworkInterfaces.rb', line 305

def GetTypeFromIfcfg(ifcfg)
  ifcfg = deep_copy(ifcfg)
  type = nil

  return nil if IsEmpty(ifcfg)

  Builtins.foreach(@TypeByValueMatch) do |key_type|
    rule_key = Ops.get(key_type, 0, "")
    rule_value = Ops.get(key_type, 1, "")
    rule_type = Ops.get(key_type, 2, "")
    type = rule_type if Ops.get_string(ifcfg, rule_key, "") == rule_value
  end

  Builtins.foreach(@TypeByKeyExistence) do |key_type|
    rule_key = Ops.get(key_type, 0, "")
    rule_type = Ops.get(key_type, 1, "")
    type = rule_type if Ops.get_string(ifcfg, rule_key, "") != ""
  end

  Builtins.foreach(@TypeByKeyValue) do |rule_key|
    rule_type = Ops.get_string(ifcfg, rule_key, "")
    type = rule_type if rule_type != ""
  end

  type
end

#GetTypeFromIfcfgOrName(dev, ifcfg) ⇒ Object

Detects device type according its name and ifcfg configuration.

Parameters:

  • dev

    device name

  • ifcfg

    device's ifcfg configuration

Returns:

  • device type



337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'library/network/src/modules/NetworkInterfaces.rb', line 337

def GetTypeFromIfcfgOrName(dev, ifcfg)
  ifcfg = deep_copy(ifcfg)
  return nil if IsEmpty(dev)

  type = GetTypeFromSysfs(dev)

  type = GetTypeFromIfcfg(ifcfg) if IsEmpty(type)

  type = device_type(dev) if type.nil?

  log.debug("GetTypeFromIfcfgOrName: device='#{dev}' type='#{type}'")

  type
end

#GetTypeFromSysfs(dev) ⇒ Object

Determines device type according /sys/class/net/<dev>/type value

Firstly, it uses /sys/class/net/<dev>/type for basic decision. Obtained values are translated to device type according <kernel src>/include/uapi/linux/if_arp.h. Sometimes it uses some other checks to specify a “subtype”. E.g. in case of “eth” it checks for presence of “wireless” subdir to determine “wlan” device.

Parameters:

  • dev (String)

    interface name

Returns:

  • return device type or nil if nothing known found



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
# File 'library/network/src/modules/NetworkInterfaces.rb', line 263

def GetTypeFromSysfs(dev)
  sys_dir_path = Builtins.sformat("/sys/class/net/%1", dev)
  sys_type_path = Builtins.sformat("%1/type", sys_dir_path)

  return nil if IsEmpty(dev) || !FileUtils.Exists(sys_type_path)

  sys_type = Convert.to_string(
    SCR.Read(path(".target.string"), sys_type_path)
  )

  sys_type = if sys_type
    Builtins.regexpsub(sys_type, "(.*)\n", "\\1")
  else
    ""
  end

  sys_type = String.CutBlanks(sys_type)

  type = case sys_type
  when "1"
    GetEthTypeFromSysfs(dev)
  when "32"
    GetIbTypeFromSysfs(dev)
  else
    Ops.get(@TypeBySysfs, sys_type)
  end

  Builtins.y2debug(
    "GetTypeFromSysFs: device='%1', sysfs type='%2', type='%3'",
    dev,
    sys_type,
    type
  )

  return nil if IsEmpty(type)

  type
end

#GetValue(name, key) ⇒ Object



1555
1556
1557
1558
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1555

def GetValue(name, key)
  return nil if !Select(name)
  Ops.get_string(@Current, key, "")
end

#ifcfg_part(ifcfg, part) ⇒ Object



188
189
190
191
192
# File 'library/network/src/modules/NetworkInterfaces.rb', line 188

def ifcfg_part(ifcfg, part)
  return "" if Builtins.regexpmatch(ifcfg, @ifcfg_name_regex) != true
  ret = Builtins.regexpsub(ifcfg, @ifcfg_name_regex, "\\#{part}")
  ret.nil? ? "" : ret
end

#Import(devregex, devices) ⇒ Object

Import data

All devices which confirms to <devregex> are silently removed from Devices and replaced by those supplied by <devices>.

Parameters:

  • devregex (String)

    filter for devices

  • devices (Array)

    devices to replace filtered ones

Returns:

  • true on success



1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1020

def Import(devregex, devices)
  devices = deep_copy(devices)
  devs = FilterNOT(@Devices, devregex)
  Builtins.y2debug("Devs=%1", devs)

  devices = Builtins.mapmap(devices) do |typ, devsmap|
    {
      typ => Builtins.mapmap(
        Convert.convert(
          devsmap,
          from: "map",
          to:   "map <string, map <string, any>>"
        )
      ) do |num, config|
        config = CanonicalizeIP(config)
        config = CanonicalizeStartmode(config)
        { num => config }
      end
    }
  end

  @Devices = Convert.convert(
    Builtins.union(devs, devices),
    from: "map",
    to:   "map <string, map <string, map <string, any>>>"
  )

  @initialized = if devices.nil? || devices == {}
    # devices == $[] is used in lan_auto "Reset" as a way how to
    # rollback changes imported from AY
    false
  else
    true
  end

  Builtins.y2milestone(
    "NetworkInterfaces::Import - done, cache content: %1",
    @Devices
  )

  true
end

#IsConnected(dev) ⇒ Object

Test whether device is connected (Link:up) The info is taken from sysfs

Parameters:

  • dev (String)

    unique device string

Returns:

  • true if connected



484
485
486
487
488
489
490
491
492
493
494
# File 'library/network/src/modules/NetworkInterfaces.rb', line 484

def IsConnected(dev)
  # Assume all devices are connected in testsuite mode
  return true if Mode.testsuite

  cmd = "cat /sys/class/net/#{dev}/carrier"

  ret = Convert.to_map(SCR.Execute(path(".target.bash_output"), cmd))
  Builtins.y2milestone("Sysfs returned %1", ret)

  Builtins.deletechars(Ops.get_string(ret, "stdout", ""), "\n") == "1"
end

#IsEmpty(value) ⇒ Object



184
185
186
# File 'library/network/src/modules/NetworkInterfaces.rb', line 184

def IsEmpty(value)
  value.nil? ? true : value.empty?
end

#IsHotplug(_type) ⇒ Object

Deprecated.

Formerly hotpluggable devices required a special ifcfg name

Returns false

Returns:

  • false



476
477
478
# File 'library/network/src/modules/NetworkInterfaces.rb', line 476

def IsHotplug(_type)
  false
end

#List(devregex) ⇒ Array

Get devices of the given type

Parameters:

  • devregex (String)

    devices type (“” for all)

Returns:

  • (Array)

    of found devices



1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1624

def List(devregex)
  ret = []
  if devregex == "" || devregex.nil?
    Builtins.maplist(@Devices) do |_t, d|
      Builtins.maplist(
        Convert.convert(
          Map.Keys(d),
          from: "list",
          to:   "list <string>"
        )
      ) { |device| Ops.set(ret, Builtins.size(ret), device) }
    end
  else
    # it's a regex for type, not the whole name
    regex = Ops.add(
      Ops.add("^(", Ops.get(@DeviceRegex, devregex, devregex)),
      ")$"
    )
    Builtins.maplist(@Devices) do |t, d|
      if Builtins.regexpmatch(t, regex)
        Builtins.maplist(
          Convert.convert(
            Map.Keys(d),
            from: "list",
            to:   "list <string>"
          )
        ) { |device| Ops.set(ret, Builtins.size(ret), device) }
      end
    end
  end
  ret = Builtins.filter(ret) do |row|
    next true if !row.nil?
    Builtins.y2error("Filtering out : %1", row)
    false
  end
  Builtins.y2debug("List(%1) = %2", devregex, ret)
  deep_copy(ret)
end

#ListDevicesExcept(dev) ⇒ Object

list of all devices except given one by parameter dev also loopback is ommited



1707
1708
1709
1710
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1707

def ListDevicesExcept(dev)
  devices = Builtins.filter(LocateNOT("DEVICE", dev)) { |s| s != "lo" }
  deep_copy(devices)
end

#Locate(key, val) ⇒ Array

Locate devices which attributes match given key and value

Parameters:

Returns:

  • (Array)

    of devices with key=val



1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1586

def Locate(key, val)
  ret = []

  @Devices.values.each do |devsmap|
    devsmap.each do |device, conf|
      ret << device if conf[key] == val
    end
  end

  ret
end

#LocateNOT(key, val) ⇒ Array

Locate devices which attributes doesn't match given key and value

Parameters:

Returns:

  • (Array)

    of devices with key!=val



1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1603

def LocateNOT(key, val)
  ret = []

  @Devices.values.each do |devsmap|
    devsmap.each do |device, conf|
      ret << device if conf[key] != val
    end
  end

  ret
end

#mainHash<String>

Current device information like { “BOOTPROTO”=>“dhcp”, “STARTMODE”=>“auto” }

#Add, #Edit and #Delete copy the requested device info (via #Select) to #Name and #Current, #Commit puts it back.

Returns:



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
# File 'library/network/src/modules/NetworkInterfaces.rb', line 62

def main
  textdomain "base"

  Yast.import "Arch"
  Yast.import "Map"
  Yast.import "Mode"
  Yast.import "Netmask"
  Yast.import "FileUtils"
  Yast.import "IP"

  @Name = ""

  @Current = {}

  # Interface information:
  # Devices[string type, string id] is a map with the contents of
  # ifcfg-<i>type</i>-<i>id</i>. Separating type from id is useful because
  # the type determines the fields of the interface file.
  # Multiple addresses for an interface are nested maps
  # [type, id, "_aliases", aid]
  # @see #Read
  @Devices = {}

  # Devices information
  # @see #Read
  @OriginalDevices = {}

  # Deleted devices
  @Deleted = []

  # True if devices are already read
  @initialized = false

  # Which operation is pending?
  # global
  @operation = nil
  # FIXME: used in lan/address.ycp (#17346) -> "global"

  # Predefined network card regular expressions
  @CardRegex =
    # other: irlan|lo|plip|...
    {
      "netcard" => "arc|ath|bnep|ci|ctc|slc|dummy|bond|escon|eth|fddi|ficon|hsi|qeth|lcs|iucv|myri|tr|usb|wlan|xp|vlan|br|tun|tap|ib|em|p|p[0-9]+p",
      "modem"   => "ppp|modem",
      "isdn"    => "isdn|ippp",
      "dsl"     => "dsl"
    }

  # Predefined network device regular expressions
  @DeviceRegex = {
    # device types
    "netcard" => @CardRegex["netcard"],
    "modem"   => @CardRegex["modem"],
    "isdn"    => @CardRegex["isdn"],
    "dsl"     => @CardRegex["dsl"],
    # device groups
    "dialup"  => @CardRegex["modem"] + "|" + @CardRegex["dsl"] + "|" + @CardRegex["isdn"]
  }

  # Types in order from fastest to slowest.
  # @see #FastestRegexps
  @FastestTypes = { 1 => "dsl", 2 => "isdn", 3 => "modem", 4 => "netcard" }

  # -------------------- components of configuration names --------------------

  # ifcfg name = type + id + alias_id
  # If id is numeric, it is not separated from type, otherwise separated by "-"
  # Id may be empty
  # Alias_id, if nonempty, is separated by alias_separator
  @ifcfg_name_regex = "^#{DEVNAME_REGEX}#{ALIAS_SEPARATOR}?#{ALIAS_REGEX}$"

  # Translates type code exposed by kernel in sysfs onto internaly used dev types.
  @TypeBySysfs = {
    "1"     => "eth",
    "24"    => "eth",
    "32"    => "ib",
    "512"   => "ppp",
    "768"   => "ipip",
    "769"   => "ip6tnl",
    "772"   => "lo",
    "776"   => "sit",
    "778"   => "gre",
    "783"   => "irda",
    "801"   => "wlan_aux",
    "65534" => "tun"
  }

  @TypeByKeyValue = ["INTERFACETYPE"]
  @TypeByKeyExistence = [
    ["ETHERDEVICE", "vlan"],
    ["WIRELESS_MODE", "wlan"],
    ["MODEM_DEVICE", "ppp"]
  ]
  @TypeByValueMatch = [
    ["BONDING_MASTER", "yes", "bond"],
    ["BRIDGE", "yes", "br"],
    ["WIRELESS", "yes", "wlan"],
    ["TUNNEL", "tap", "tap"],
    ["TUNNEL", "tun", "tun"],
    ["TUNNEL", "sit", "sit"],
    ["TUNNEL", "gre", "gre"],
    ["TUNNEL", "ipip", "ipip"],
    ["PPPMODE", "pppoe", "ppp"],
    ["PPPMODE", "pppoatm", "ppp"],
    ["PPPMODE", "capi-adsl", "ppp"],
    ["PPPMODE", "pptp", "ppp"],
    ["ENCAP", "syncppp", "isdn"],
    ["ENCAP", "rawip", "isdn"]
  ]

  @SensitiveFields = [
    "WIRELESS_WPA_PASSWORD",
    "WIRELESS_WPA_PSK",
    # the unnumbered one should be empty but just in case
    "WIRELESS_KEY",
    "WIRELESS_KEY_0",
    "WIRELESS_KEY_1",
    "WIRELESS_KEY_2",
    "WIRELESS_KEY_3"
  ]
end

#Modified(devregex) ⇒ Object

Were the devices changed?

Returns:

  • true if modified



1307
1308
1309
1310
1311
1312
1313
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1307

def Modified(devregex)
  devs = Filter(@Devices, devregex)
  original_devs = Filter(@OriginalDevices, devregex)
  log.debug("OriginalDevs=#{original_devs}")
  log.debug("Devs=#{devs}")
  devs == original_devs
end

#ReadObject

Read devices from files and cache it

Returns:

  • true if sucess



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
# File 'library/network/src/modules/NetworkInterfaces.rb', line 735

def Read
  return true if @initialized == true

  @Devices = {}

  # preparation
  devices = get_devices(ignore_confs_regex)

  # Read devices
  devices.each do |device|
    pth = ".network.value.\"#{device}\""
    log.debug("pth=#{pth}")

    values = SCR.Dir(path(pth))
    log.debug("values=#{values}")

    config = generate_config(pth, values)

    add_device(device, config)
  end
  log.debug("Devices=#{@Devices}")

  @OriginalDevices = deep_copy(@Devices)
  @initialized = true
end

#RealType(type, _hotplug) ⇒ Object

Deprecated.

hotpluggable devices no longer need a special type

Return real type of the device (incl. PCMCIA, USB, …)

Examples:

RealType(“eth”, “usb”) -> “eth”


Parameters:

  • type (String)

    basic device type

  • hotplug (String)

    hot plug type

Returns:

  • real type



502
503
504
505
506
507
508
# File 'library/network/src/modules/NetworkInterfaces.rb', line 502

def RealType(type, _hotplug)
  if type == "" || type.nil?
    Builtins.y2error("Wrong type: %1", type)
    return "eth"
  end
  type
end

#Select(name) ⇒ Object

Select the given device

Parameters:

  • name (String)

    device to select (“” for new device, default values)

Returns:

  • true if success



1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1384

def Select(name)
  @Name = ""
  @Current = {}

  Builtins.y2debug("name=%1", name)
  if name != "" && !Check(name)
    Builtins.y2error("No such device: %1", name)
    return false
  end

  @Name = name
  t = GetType(@Name)
  @Current = Ops.get(@Devices, [t, @Name], {})
  a = alias_num(@Name)
  if !a.nil? && a != ""
    @Current = Ops.get_map(@Current, ["_aliases", a], {})
  end

  if @Current == {}
    # Default device map
    @Current =
      # FIXME: remaining items
      {}
  end

  Builtins.y2debug("Name=%1", @Name)
  Builtins.y2debug("Current=%1", @Current)

  true
end

#SetValue(name, key, value) ⇒ Object



1560
1561
1562
1563
1564
1565
1566
1567
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1560

def SetValue(name, key, value)
  return nil unless Edit(name)
  return false if key.nil? || key == "" || value.nil?

  @Current[key] = value

  Commit()
end

#ValidCharsIfcfgObject

#46803: forbid “/” (filename), maybe also “-” (separator) “_” (escape)



1700
1701
1702
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1700

def ValidCharsIfcfg
  String.ValidCharsFilename
end

#Write(devregex) ⇒ Object



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
# File 'library/network/src/modules/NetworkInterfaces.rb', line 819

def Write(devregex)
  log.info("Writing configuration")
  log.debug("Devices=#{@Devices}")
  log.debug("Deleted=#{@Deleted}")

  devs = Filter(@Devices, devregex)
  original_devs = Filter(@OriginalDevices, devregex)
  log.info("OriginalDevs=#{ConcealSecrets(original_devs)}")
  log.info("Devs=#{ConcealSecrets(devs)}")

  # Check for changes
  if devs == original_devs
    log.info("No changes to #{devregex} devices -> nothing to write")
    return true
  end

  # remove deleted devices
  log.info("Deleted=#{@Deleted}")
  Builtins.foreach(@Deleted) do |d|
    anum = alias_num(d)
    if anum == ""
      # delete config file
      p = Builtins.add(path(".network.section"), d)
      log.debug("deleting: #{p}")
      SCR.Write(p, nil)
    else
      dev = device_name_from_alias(d)
      typ = GetType(dev)
      base = Builtins.add(path(".network.value"), dev)
      # look in OriginalDevs because we need to catch all variables
      # of the alias

      dev_aliases = original_devs[typ][dev]["_aliases"][anum] || {}
      dev_aliases.keys.each do |key|
        p = base + "#{key}_#{anum}"
        log.debug("deleting: #{p}")
        SCR.Write(p, nil)
      end
    end
  end
  @Deleted = []

  # write all devices
  Builtins.maplist(
    Convert.convert(
      devs,
      from: "map",
      to:   "map <string, map <string, map <string, any>>>"
    )
  ) do |typ, devsmap|
    Builtins.maplist(devsmap) do |config, devmap|
      next if devmap == Ops.get_map(original_devs, [typ, config], {})
      # write sysconfig
      p = Ops.add(Ops.add(".network.value.\"", config), "\".")
      if Ops.greater_than(
        Builtins.size(Ops.get_string(devmap, "IPADDR", "")),
        0
      ) &&
          Builtins.find(Ops.get_string(devmap, "IPADDR", ""), "/") == -1
        if Ops.greater_than(
          Builtins.size(Ops.get_string(devmap, "IPADDR", "")),
          0
        ) &&
            Ops.greater_than(
              Builtins.size(Ops.get_string(devmap, "NETMASK", "")),
              0
            )
          Ops.set(
            devmap,
            "IPADDR",
            Builtins.sformat(
              "%1/%2",
              Ops.get_string(devmap, "IPADDR", ""),
              Netmask.ToBits(Ops.get_string(devmap, "NETMASK", ""))
            )
          )
          devmap = Builtins.remove(devmap, "NETMASK")
          # TODO : delete NETMASK from config file
        elsif Ops.greater_than(
          Builtins.size(Ops.get_string(devmap, "IPADDR", "")),
          0
        ) &&
            Ops.greater_than(
              Builtins.size(Ops.get_string(devmap, "PREFIXLEN", "")),
              0
            )
          Ops.set(
            devmap,
            "IPADDR",
            Builtins.sformat(
              "%1/%2",
              Ops.get_string(devmap, "IPADDR", ""),
              Ops.get_string(devmap, "PREFIXLEN", "")
            )
          )
          devmap = Builtins.remove(devmap, "PREFIXLEN")
          # TODO : delete PREFIXLEN from config file
        end
      end
      devmap["ZONE"] = nil if devmap["ZONE"] && devmap["ZONE"].empty?
      # write all keys to config
      Builtins.maplist(
        Convert.convert(
          Map.Keys(devmap),
          from: "list",
          to:   "list <string>"
        )
      ) do |k|
        # Write aliases
        if k == "_aliases"
          Builtins.maplist(Ops.get_map(devmap, k, {})) do |anum, amap|
            # Normally defaulting the label would be done
            # when creating the map, not here when
            # writing, but we create it in 2 ways so it's
            # better here. Actually it does not work because
            # the edit dialog nukes LABEL :-(
            if Ops.greater_than(Builtins.size(Ops.get(amap, "IPADDR", "")), 0) &&
                Ops.greater_than(
                  Builtins.size(Ops.get(amap, "NETMASK", "")),
                  0
                )
              Ops.set(
                amap,
                "IPADDR",
                Builtins.sformat(
                  "%1/%2",
                  Ops.get(amap, "IPADDR", ""),
                  Netmask.ToBits(Ops.get(amap, "NETMASK", ""))
                )
              )
              amap = Builtins.remove(amap, "NETMASK")
              # TODO : delete NETMASK from config file
            elsif Ops.greater_than(
              Builtins.size(Ops.get(amap, "IPADDR", "")),
              0
            ) &&
                Ops.greater_than(
                  Builtins.size(Ops.get(amap, "PREFIXLEN", "")),
                  0
                )
              Ops.set(
                amap,
                "IPADDR",
                Builtins.sformat(
                  "%1/%2",
                  Ops.get(amap, "IPADDR", ""),
                  Ops.get(amap, "PREFIXLEN", "")
                )
              )
              amap = Builtins.remove(amap, "PREFIXLEN")
              # TODO : delete PREFIXLEN from config file
            end
            Builtins.maplist(amap) do |ak, av|
              akk = Ops.add(Ops.add(ak, "_"), anum)
              SCR.Write(Builtins.topath(Ops.add(p, akk)), av) #         seen_label = seen_label || ak == "LABEL";
            end
          end
        else
          # Write regular keys
          SCR.Write(
            Builtins.topath(Ops.add(p, k)),
            Ops.get_string(devmap, k, "")
          )
        end
      end

      # 0600 if contains encryption key (#24842)
      has_key = @SensitiveFields.any? { |k| devmap[k] && !devmap[k].empty? }
      if has_key
        log.debug("Permission change: #{config}")
        SCR.Write(
          Builtins.add(path(".network.section_private"), config),
          true
        )
      end
      @OriginalDevices = {} if @OriginalDevices.nil?
      if Ops.get(@OriginalDevices, typ).nil?
        Ops.set(@OriginalDevices, typ, {})
      end
      Ops.set(
        @OriginalDevices,
        [typ, config],
        Ops.get(@Devices, [typ, config], {})
      )
    end
  end

  # Finish him
  SCR.Write(path(".network"), nil)

  true
end