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 collapse

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:


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'library/network/src/modules/NetworkInterfaces.rb', line 61

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" => "ath|ci|ctc|slc|dummy|bond|eth|ficon|hsi|qeth|lcs|wlan|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"],
    ["IPOIB_MODE", "ib"]
  ]
  @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


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

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 44

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.


668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
# File 'library/network/src/modules/NetworkInterfaces.rb', line 668

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


1246
1247
1248
1249
1250
1251
1252
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1246

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

  @operation = :add
  true
end

#add_device(device, ifcfg) ⇒ Object

The device is added to @Devices[devtype] 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


691
692
693
694
695
696
697
# File 'library/network/src/modules/NetworkInterfaces.rb', line 691

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


422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'library/network/src/modules/NetworkInterfaces.rb', line 422

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

#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


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

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 /) overrides PREFIXLEN,
  • NETMASK is used only if prefix length unspecified)
  • If prefix length and NETMASK are unspecified, 32 is implied.

Canonicalize it to:

  • IPADDR="" PREFIXLEN="" NETMASK="") in case of IPv4 config E.g. IPADDR=10.0.0.1 PREFIXLEN=8 NETMASK=255.0.0.0
  • IPADDR="" PREFIXLEN="" 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.


517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# File 'library/network/src/modules/NetworkInterfaces.rb', line 517

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


477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'library/network/src/modules/NetworkInterfaces.rb', line 477

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


1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1281

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
  Builtins.y2debug("ChangeDevice(%1)", name)

  # newdev is already a deep_copy created above
  @Devices[t] = @Devices.fetch(t, {}).merge(name => newdev)

  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


1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1209

def Check(dev)
  Builtins.y2debug("Check(%1)", dev)
  typ = GetType(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)


729
730
731
732
# File 'library/network/src/modules/NetworkInterfaces.rb', line 729

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

No longer needed

Returns true.

Returns:

  • true


1414
1415
1416
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1414

def CleanHotplugSymlink
  true
end

#CommitObject


1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1342

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


576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'library/network/src/modules/NetworkInterfaces.rb', line 576

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


562
563
564
565
566
567
568
569
570
# File 'library/network/src/modules/NetworkInterfaces.rb', line 562

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


1268
1269
1270
1271
1272
1273
1274
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1268

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

  @operation = :delete
  true
end

#Delete2(name) ⇒ Object


1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1310

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

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

  devsmap = Builtins.remove(devsmap, name)

  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


1335
1336
1337
1338
1339
1340
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1335

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


395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'library/network/src/modules/NetworkInterfaces.rb', line 395

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
  return Builtins.sformat("%1%2", typ, num) if Builtins.regexpmatch(num, "^[0-9]*$")

  Builtins.sformat("%1-%2", typ, num)
end

#device_name_from_alias(alias_name) ⇒ Object

Extracts device name from alias name

alias_name := ALIAS_SEPARATOR


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

def device_name_from_alias(alias_name)
  alias_name.sub(/#{ALIAS_SEPARATOR}.*/, "")
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


742
743
744
# File 'library/network/src/modules/NetworkInterfaces.rb', line 742

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


1257
1258
1259
1260
1261
1262
1263
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1257

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())


1190
1191
1192
1193
1194
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1190

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

#FastestObject

Find the fastest available device


1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1462

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


1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1484

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


751
752
753
754
755
756
757
758
759
760
# File 'library/network/src/modules/NetworkInterfaces.rb', line 751

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

553
554
555
556
# File 'library/network/src/modules/NetworkInterfaces.rb', line 553

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


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

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


772
773
774
775
776
777
778
779
780
781
782
783
784
# File 'library/network/src/modules/NetworkInterfaces.rb', line 772

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.reject! { |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


631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
# File 'library/network/src/modules/NetworkInterfaces.rb', line 631

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


362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'library/network/src/modules/NetworkInterfaces.rb', line 362

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

#GetDeviceTypesObject

Deprecated.

Not longer needed

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


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

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

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

  # device types which cannot be present on s390 arch
  s390_unknown_dev_types = [
    "dummy",
    "wlan",
    "ib"
  ]

  dev_types = common_dev_types + (Arch.s390 ? s390_dev_types : s390_unknown_dev_types)

  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

Deprecated.

Not longer needed

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


1057
1058
1059
1060
1061
1062
1063
1064
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
1125
1126
1127
1128
1129
1130
1131
1132
1133
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
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1057

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
    "atm"   => [
      _("ATM"),
      _("Asynchronous Transfer Mode (ATM)")
    ],
    # Device type label
    "bond"  => [_("Bond"), _("Bond Network")],
    # Device type label
    "ci"    => [
      _("CLAW"),
      _("Common Link Access for Workstation (CLAW)")
    ],
    # 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
    "eth"   => [
      _("Ethernet"),
      _("Ethernet 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
    "lcs"   => [_("OSA LCS"), _("OSA LCS Network Card")],
    # Device type label
    "lo"    => [_("Loopback"), _("Loopback Device")],
    # Device type label
    "modem" => [_("Modem"), _("Modem")],
    # 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
    "vmnet" => [_("VMWare"), _("VMWare Network Device")],
    # Device type label
    "wlan"  => [
      _("Wireless"),
      _("Wireless Network Card")
    ],
    # 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:


196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'library/network/src/modules/NetworkInterfaces.rb', line 196

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

#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:


227
228
229
230
231
232
233
234
235
236
237
# File 'library/network/src/modules/NetworkInterfaces.rb', line 227

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


1386
1387
1388
1389
1390
1391
1392
1393
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1386

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


346
347
348
349
350
351
352
353
354
355
# File 'library/network/src/modules/NetworkInterfaces.rb', line 346

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


289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'library/network/src/modules/NetworkInterfaces.rb', line 289

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 (ifcfg[rule_key] || "").casecmp?(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


321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'library/network/src/modules/NetworkInterfaces.rb', line 321

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

  type = GetTypeFromSysfs(dev)

  type = GetTypeFromIfcfg(ifcfg) if IsEmpty(type)

  # last instance - no record in sysfs, no configuration, device
  # name is not bounded to a type -> use fallbac "eth" as wicked already does
  type = "eth" if type.nil?

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

  type
end

#GetTypeFromSysfs(dev) ⇒ Object

Determines device type according /sys/class/net//type value

Firstly, it uses /sys/class/net//type for basic decision. Obtained values are translated to device type according /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


248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'library/network/src/modules/NetworkInterfaces.rb', line 248

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


1368
1369
1370
1371
1372
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1368

def GetValue(name, key)
  return nil if !Select(name)

  Ops.get_string(@Current, key, "")
end

#Import(devregex, devices) ⇒ Object

Import data

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

Parameters:

  • devregex (String)

    filter for devices

  • devices (Array)

    devices to replace filtered ones

Returns:

  • true on success


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

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


448
449
450
451
452
453
454
455
456
457
458
# File 'library/network/src/modules/NetworkInterfaces.rb', line 448

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

  cmd = "/usr/bin/cat /sys/class/net/#{dev.shellescape}/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


440
441
442
# File 'library/network/src/modules/NetworkInterfaces.rb', line 440

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


1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1421

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

#Locate(key, val) ⇒ Array

Locate devices which attributes match given key and value

Parameters:

Returns:

  • (Array)

    of devices with key=val


1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1400

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

#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:


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'library/network/src/modules/NetworkInterfaces.rb', line 61

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" => "ath|ci|ctc|slc|dummy|bond|eth|ficon|hsi|qeth|lcs|wlan|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"],
    ["IPOIB_MODE", "ib"]
  ]
  @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


1198
1199
1200
1201
1202
1203
1204
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1198

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


701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
# File 'library/network/src/modules/NetworkInterfaces.rb', line 701

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


466
467
468
469
470
471
472
# File 'library/network/src/modules/NetworkInterfaces.rb', line 466

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


1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1224

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], {})

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

  true
end

#SetValue(name, key, value) ⇒ Object


1374
1375
1376
1377
1378
1379
1380
1381
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1374

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)


1498
1499
1500
# File 'library/network/src/modules/NetworkInterfaces.rb', line 1498

def ValidCharsIfcfg
  String.ValidCharsFilename
end

#Write(devregex) ⇒ Object


786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
# File 'library/network/src/modules/NetworkInterfaces.rb', line 786

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}")
  @Deleted.each do |d|
    iface, alias_num = d.split("#")
    alias_num ? delete_alias(original_devs, iface, alias_num) : delete_device(iface)
  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
      # 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?
      Ops.set(@OriginalDevices, typ, {}) if Ops.get(@OriginalDevices, typ).nil?
      Ops.set(
        @OriginalDevices,
        [typ, config],
        Ops.get(@Devices, [typ, config], {})
      )
    end
  end

  # Finish him
  SCR.Write(path(".network"), nil)
  # Reread all settings to avoid wrong values when reopen the network
  # dialog during installation (bsc#1166778)
  CleanCacheRead()

  true
end