Class: WifiWand::Platforms::Ubuntu::Model

Inherits:
BaseModel
  • Object
show all
Defined in:
lib/wifi_wand/platforms/ubuntu/model.rb

Defined Under Namespace

Classes: SavedWifiProfile

Constant Summary collapse

PREFERRED_NETWORK_SECRET_FIELDS =
%w[
  802-11-wireless-security.psk
  802-11-wireless-security.wep-key0
].freeze
PREFERRED_NETWORK_SECRET_PLACEHOLDERS =
%w[--].freeze
ACTIVE_CONNECTION_PROFILE_PLACEHOLDERS =
%w[--].freeze
SAVED_WIFI_PROFILE_SUMMARY_FIELDS =
'NAME,TYPE,TIMESTAMP'
SAVED_WIFI_PROFILE_SSID_FIELD =
'802-11-wireless.ssid'
SAVED_WIFI_PROFILE_SSID_LOOKUP_WORKERS =
8
SAVED_WIFI_PROFILE_SUMMARY_TIMEOUT_SECONDS =
5
DNS_CONNECTION_FIELDS =
%w[
  ipv4.dns
  ipv4.ignore-auto-dns
  ipv6.dns
  ipv6.ignore-auto-dns
].freeze

Instance Attribute Summary

Attributes inherited from BaseModel

#command_executor, #connection_manager, #connectivity_tester, #disconnect_manager, #runtime_config, #state_manager, #status_waiter, #wifi_interface

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseModel

#associated?, #available_network_names, #available_network_scan, #available_resources_help, #captive_portal_login_required, #capture_network_state, #command_available?, #connected_network_name, create_model, current_os_matches_this_model?, #cycle_network, #disassociated_stable?, #disconnect, #disconnect_stability_window_in_secs, #dns_working?, #err_stream, #err_stream=, #generate_qr_code, inherited, #init, #init_wifi_interface, #internet_connectivity_state, #internet_tcp_connectivity?, #ipv4_addresses, #ipv6_addresses, #last_connection_used_saved_password?, #mac?, #open_resources_by_codes, #os, #out_stream, #out_stream=, #print_qr_code, #public_ip_address, #public_ip_country, #public_ip_info, #public_ip_lookup, #qr_code_generator, #random_mac_address, #render_qr_code, #resource_manager, #restore_network_state, #run_command, #till, #ubuntu?, #verbose=, #verbose?, #wifi_info, #wifi_info_builder

Methods included from Timing

monotonic_now, status_deadline, status_timeout_for

Methods included from StringPredicates

string_nil_or_blank?, string_nil_or_empty?

Constructor Details

#initialize(options = {}) ⇒ Model

Returns a new instance of Model.



35
36
37
38
39
40
41
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 35

def initialize(options = {})
  super
  @saved_wifi_profiles_cache_mutex = Mutex.new
  @saved_wifi_profiles_cache_refcount = 0
  @saved_wifi_profiles_cache_loading = false
  @saved_wifi_profiles_cache_cond = ConditionVariable.new
end

Class Method Details

.os_idObject



43
44
45
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 43

def self.os_id
  :ubuntu
end

Instance Method Details

#_available_network_namesObject



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 173

def _available_network_names
  debug_method_entry(__method__)

  output = run_command(['nmcli', '-t', '-f', 'SSID,SIGNAL', 'dev', 'wifi', 'list']).stdout
  networks_with_signal = output.split("\n").map(&:strip).reject(&:empty?)

  # Parse SSID and signal strength, then sort by signal (descending)
  networks = networks_with_signal.map do |line|
    ssid, signal = nmcli_split(line, 2)
    [ssid, signal.to_i]
  end
  networks = networks.sort_by { |_, signal| -signal }
  networks = networks.map { |ssid, _| ssid }.reject(&:empty?)

  networks.uniq
end

#_connect(network_name, password = nil) ⇒ Object



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 255

def _connect(network_name, password = nil)
  #
  # CONNECTION LOGIC
  #
  # This logic is designed to be robust and handle the nuances of nmcli,
  # including the common problem of duplicate connection profiles (e.g.,
  # "MySSID", "MySSID 1").
  #
  # 1. CHECK IF ALREADY CONNECTED:
  #    The first step is to check if we are already connected to the target
  #    network. If so, there's nothing to do.
  #
  # 2. HANDLE CONNECTION REQUESTS WITH A PASSWORD:
  #    If a password is provided, we first check if it's different from the
  #    stored password. We only run a disruptive `modify` command if the
  #    password has actually changed. This prevents unnecessary modifications
  #    during test suite cleanup phases, which can cause system instability.
  #    a. Find the best existing profile for the SSID (by most recent timestamp).
  #    b. If a profile exists and the password differs, query its security type
  #       to use the correct parameter (e.g. .psk, .wep-key0) and modify it.
  #    c. If no profile is found, create a new one from scratch.
  #
  # 3. HANDLE CONNECTION REQUESTS WITHOUT A PASSWORD:
  #    If no password is provided, the user's intent is to connect to a
  #    network that is either open or already saved.
  #    a. Find the best existing profile for the SSID.
  #    b. If a profile is found, attempt to activate it using its stored settings.
  #    c. If no profile is found, assume it's an open network and attempt to connect.

  debug_method_entry(__method__)

  if connected? && _connected_network_name == network_name
    return
  end

  begin
    profile = find_best_profile_for_ssid(network_name)
    if password
      # Case 2: Password is provided.
      if profile
        activate_existing_profile_with_password(network_name, password, profile)
      else
        # No profile exists, create a new one.
        # Intentionally pass the caller-supplied password through to nmcli.
        # WifiWand is designed for single-user machines under the operator
        # control, and showing the exact supplied credential is useful when
        # troubleshooting failed joins in verbose mode.
        run_command(['nmcli', 'dev', 'wifi', 'connect', network_name, 'password', password])
      end
    elsif profile
      # Case 3a: No password provided and a profile exists.
      # Try to bring it up with stored settings.
      run_command(['nmcli', 'connection', 'up', profile])
    else
      # Case 3b: No password provided and no profile exists.
      # Try to connect to it as an open network.
      run_command(['nmcli', 'dev', 'wifi', 'connect', network_name])
    end
  rescue WifiWand::CommandExecutor::OsCommandError => e
    # The nmcli command failed. Determine the specific failure reason.
    error_text = e.text || e.message || ''

    # Check for network not found errors
    if error_text.match?(/No network with SSID/i)
      raise(WifiWand::NetworkNotFoundError.new(network_name: network_name))
    end

    # Check for authentication/password errors
    # These patterns indicate wrong password or missing credentials
    if [
      /Secrets were required/i,
      /802-11-wireless-security.*No secrets/i,
      /authentication.*failed/i,
      /Connection activation failed.*\(7\)/i,
    ].any? { |pattern| error_text.match?(pattern) }
      raise(WifiWand::NetworkAuthenticationError.new(network_name: network_name))
    end

    # Check for device-related errors
    if [
      /No suitable device found/i,
      /Device.*not found/i,
    ].any? { |pattern| error_text.match?(pattern) }
      raise WifiWand::WifiInterfaceError, wifi_interface
    end

    # Generic connection activation failed - could indicate network out of range
    # or temporarily unavailable (not the same as "not found")
    if error_text.match?(/Connection activation failed/i)
      raise(WifiWand::NetworkConnectionError.new(
        network_name: network_name,
        reason:       'Network may be out of range or temporarily unavailable'
      ))
    end

    # Re-raise the original error if it doesn't match known patterns
    raise e
  end
end

#_connected_network_nameObject



190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 190

def _connected_network_name
  interface = wifi_interface
  return nil unless interface

  output = run_command(['iw', 'dev', interface, 'link'], raise_on_error: false).stdout
  return nil if output.strip.start_with?('Not connected')

  ssid_line = output.split("\n").find { |line| line.strip.start_with?('SSID:') }
  return nil unless ssid_line

  ssid = ssid_line.strip.delete_prefix('SSID:').strip
  ssid.empty? ? nil : ssid
end

#_disconnectObject



622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 622

public def _disconnect
  debug_method_entry(__method__)

  interface = wifi_interface
  begin
    run_command(['nmcli', 'dev', 'disconnect', interface])
  rescue WifiWand::CommandExecutor::OsCommandError => e
    # It's normal for disconnect to fail if there's no active connection
    # Common scenarios: device not active, not connected to any network
    return nil if e.exitstatus == 6

    raise e
  end
  nil
end

#_ipv4_addressesObject



534
535
536
537
538
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 534

public def _ipv4_addresses
  debug_method_entry(__method__)

  interface_ip_addresses(command_ip_version: '-4', line_type: 'inet', family: :ipv4)
end

#_ipv6_addressesObject



540
541
542
543
544
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 540

public def _ipv6_addresses
  debug_method_entry(__method__)

  interface_ip_addresses(command_ip_version: '-6', line_type: 'inet6', family: :ipv6)
end

#_preferred_network_password(preferred_network_name, timeout_in_secs: :default) ⇒ Object



498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 498

public def _preferred_network_password(preferred_network_name, timeout_in_secs: :default)
  debug_method_entry(__method__, binding, :preferred_network_name)

  command_options = { raise_on_error: false }
  if timeout_in_secs && timeout_in_secs != :default
    command_options[:timeout_in_secs] =
      timeout_in_secs
  end
  output = run_command(
    ['nmcli', '--show-secrets', 'connection', 'show', preferred_network_name], **command_options
  ).stdout
  extract_preferred_network_secret(output)
end

#active_connection_profile_nameObject



712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 712

public def active_connection_profile_name
  debug_method_entry(__method__)

  interface = wifi_interface
  return nil unless interface

  begin
    output = run_command(['nmcli', '-t', '-f', 'GENERAL.CONNECTION', 'dev', 'show', interface],
      raise_on_error: false).stdout
  rescue *WifiWand::NetworkErrorConstants::NETWORK_OPERATION_COMMAND_ERRORS
    return nil
  end

  line = output.split("\n").find { |row| nmcli_split(row, 2).first == 'GENERAL.CONNECTION' }
  return nil unless line

  profile = nmcli_split(line, 2).last
  normalize_active_connection_profile_name(profile)
end

#bssidObject



566
567
568
569
570
571
572
573
574
575
576
577
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 566

public def bssid
  debug_method_entry(__method__)

  output = run_command(['iw', 'dev', wifi_interface, 'link'], raise_on_error: false).stdout
  return nil if output.strip.start_with?('Not connected')

  connected_line = output.split("\n").find { |line| line.strip.start_with?('Connected to ') }
  return nil unless connected_line

  match = connected_line.strip.match(/\AConnected to (?<bssid>[0-9a-f]{2}(?::[0-9a-f]{2}){5})\b/i)
  match ? match[:bssid] : nil
end

#connect(network_name, password = nil, skip_saved_password_lookup: false) ⇒ Object



355
356
357
358
359
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 355

public def connect(network_name, password = nil, skip_saved_password_lookup: false)
  with_saved_wifi_profiles_cache do
    super
  end
end

#connected?Boolean

Returns:

  • (Boolean)


101
102
103
104
105
106
107
108
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 101

def connected?
  return false unless wifi_on?

  output = run_command(
    ['nmcli', '-t', '-f', 'DEVICE', 'connection', 'show', '--active'], raise_on_error: false
  ).stdout
  output.split("\n").any? { |line| line.strip == wifi_interface }
end

#connection_property_value(connection_name, field_name) ⇒ Object



839
840
841
842
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 839

public def connection_property_value(connection_name, field_name)
  run_command(['nmcli', '--get-values', field_name, 'connection', 'show',
    connection_name]).stdout.strip
end

#connection_ready?(network_name) ⇒ Boolean

Returns:

  • (Boolean)


142
143
144
145
146
147
148
149
150
151
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 142

def connection_ready?(network_name)
  return false unless _connected_network_name == network_name
  return false if active_connection_profile_name.nil?
  return false unless connected?

  true
rescue WifiWand::Error => e
  err_stream.puts("connection_ready? check failed: #{e.class}: #{e.message}") if verbose?
  false
end

#connection_security_typeString?

Gets the security type of the currently connected network.

Returns:

  • (String, nil)

    The security type: "WPA", "WPA2", "WPA3", "WEP", "NONE" for open networks, or nil if not connected/not found



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
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 1060

public def connection_security_type
  debug_method_entry(__method__)

  network_name = _connected_network_name
  return nil unless network_name

  begin
    output = run_command(
      ['nmcli', '-t', '-f', 'IN-USE,SSID,SECURITY', 'dev', 'wifi', 'list'], raise_on_error: false
    ).stdout
  rescue *WifiWand::NetworkErrorConstants::NETWORK_OPERATION_COMMAND_ERRORS
    return nil # Can't scan, return nil
  end

  # Match NetworkManager's active BSS row, not just SSID, because duplicate SSIDs can
  # advertise different security modes.
  network_line = output.split("\n").find do |line|
    in_use, ssid, = nmcli_split(line, 3)
    in_use == '*' && ssid == network_name
  end
  return nil unless network_line

  # The output can be like "*:SSID:WPA2" or "*:SSID:WPA1 WPA2"
  security_type = nmcli_split(network_line, 3).last&.strip

  # nmcli reports open networks with an empty SECURITY field or a "--" placeholder.
  if security_type.to_s.empty? || security_type == '--'
    'NONE'
  else
    WifiWand::Models::Helpers::SecurityTypeNormalizer.canonical_security_type_from(security_type)
  end
end

#default_interfaceObject

Returns the network interface used for default internet route on Linux



733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 733

public def default_interface
  debug_method_entry(__method__)

  begin
    output = run_command(%w[ip route show default], raise_on_error: false).stdout
    return nil if output.empty?

    # Extract interface name (5th field in: "default via 192.168.1.1 dev wlp0s20f3 ...")
    tokens = output.split("\n").first&.split
    dev_index = tokens&.index('dev')
    dev_index ? tokens[dev_index + 1] : nil
  rescue *WifiWand::NetworkErrorConstants::NETWORK_OPERATION_COMMAND_ERRORS
    nil
  end
end

#desired_dns_configuration(nameservers) ⇒ Object



783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 783

public def desired_dns_configuration(nameservers)
  if nameservers == :clear
    return {
      'ipv4.dns'             => '',
      'ipv4.ignore-auto-dns' => 'no',
      'ipv6.dns'             => '',
      'ipv6.ignore-auto-dns' => 'no',
    }
  end

  # Validate IP addresses (accept both IPv4 and IPv6)
  bad_addresses = nameservers.reject do |ns|
    IPAddr.new(ns) # Valid if IPAddr can parse it (IPv4 or IPv6)
    true
  rescue IPAddr::InvalidAddressError, IPAddr::AddressFamilyError
    false
  end

  unless bad_addresses.empty?
    raise InvalidIPAddressError, bad_addresses
  end

  ipv4_servers, ipv6_servers = nameservers.partition { |ns| IPAddr.new(ns).ipv4? }

  {
    'ipv4.dns'             => ipv4_servers.join(' '),
    'ipv4.ignore-auto-dns' => ipv4_servers.any? ? 'yes' : 'no',
    'ipv6.dns'             => ipv6_servers.join(' '),
    'ipv6.ignore-auto-dns' => ipv6_servers.any? ? 'yes' : 'no',
  }
end

#disconnect_associated?Boolean

Returns:

  • (Boolean)

Raises:



110
111
112
113
114
115
116
117
118
119
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 110

def disconnect_associated?
  return false unless wifi_on?

  result = run_command(
    ['nmcli', '-t', '-f', 'DEVICE', 'connection', 'show', '--active'], raise_on_error: false
  )
  raise WifiWand::CommandExecutor::OsCommandError.new(result: result) unless result.success?

  result.stdout.split("\n").any? { |line| line.strip == wifi_interface }
end

#dns_configuration_modify_commands(connection_name, dns_configuration) ⇒ Object



823
824
825
826
827
828
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 823

public def dns_configuration_modify_commands(connection_name, dns_configuration)
  DNS_CONNECTION_FIELDS.map do |field_name|
    ['nmcli', 'connection', 'modify', connection_name, field_name,
      dns_configuration.fetch(field_name)]
  end
end

#dns_configuration_snapshot(connection_name) ⇒ Object

Reads the current profile values up front so rollback can restore the exact pre-transaction state instead of inferring defaults.



817
818
819
820
821
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 817

public def dns_configuration_snapshot(connection_name)
  DNS_CONNECTION_FIELDS.to_h do |field_name|
    [field_name, connection_property_value(connection_name, field_name)]
  end
end

#extract_preferred_network_secret(connection_output) ⇒ Object



512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 512

public def extract_preferred_network_secret(connection_output)
  connection_lines = connection_output.split("\n")

  PREFERRED_NETWORK_SECRET_FIELDS.each do |field_name|
    secret_line = connection_lines.find { |line| line.include?("#{field_name}:") }
    next unless secret_line

    secret = secret_line.split(':', 2).last&.strip
    next unless preferred_network_secret_value?(secret)

    return secret
  end

  nil
end

#has_preferred_network?(network_name) ⇒ Boolean

Returns:

  • (Boolean)


471
472
473
474
475
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 471

public def has_preferred_network?(network_name)
  with_saved_wifi_profiles_cache do
    preferred_networks_matching_ssid(network_name.to_s).any?
  end
end

#is_wifi_interface?(interface, timeout_in_secs: nil) ⇒ Boolean

Returns:

  • (Boolean)


91
92
93
94
95
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 91

def is_wifi_interface?(interface, timeout_in_secs: nil)
  result = run_command(['iw', 'dev', interface, 'info'],
    raise_on_error: false, timeout_in_secs: timeout_in_secs)
  result.success?
end

#mac_addressObject



546
547
548
549
550
551
552
553
554
555
556
557
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 546

public def mac_address
  debug_method_entry(__method__)

  output = run_command(['ip', 'link', 'show', wifi_interface], raise_on_error: false).stdout
  ether_line = output.split("\n").find { |line| line.include?('ether') }
  return nil unless ether_line

  # Extract MAC address (field after 'link/ether')
  tokens = ether_line.split
  ether_index = tokens.index('link/ether')
  ether_index ? tokens[ether_index + 1] : nil
end

#nameserversObject



638
639
640
641
642
643
644
645
646
647
648
649
650
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 638

public def nameservers
  debug_method_entry(__method__)

  # Prefer the active NetworkManager profile when querying DNS
  current_connection = active_connection_profile_name || _connected_network_name
  if current_connection
    connection_nameservers = nameservers_from_connection(current_connection)
    return connection_nameservers unless connection_nameservers.empty?
  end

  # Fallback to system resolver if no connection-specific DNS
  nameservers_using_resolv_conf || []
end

#nameservers_from_connection(connection_name) ⇒ Object

Gets DNS nameservers configured for a specific connection profile This is the NetworkManager connection-based approach for getting DNS



751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 751

public def nameservers_from_connection(connection_name)
  debug_method_entry(__method__, binding, :connection_name)

  begin
    output = run_command(['nmcli', 'connection', 'show', connection_name],
      raise_on_error: false).stdout

    # Extract DNS servers from connection configuration
    # Look for both configured DNS (ipv4.dns[1]:) and runtime DNS (IP4.DNS[1]:)
    # Format examples:
    #   ipv4.dns[1]:                        1.1.1.1    (static configuration)
    #   IP4.DNS[1]:                         192.168.3.1 (active/runtime state)
    # Note: ipv4.dns is documented in NetworkManager official docs, IP4.DNS observed in practice

    ip_version_pattern = /(?i)ip(?:v?[46])/    # Matches 'ipv4', 'ip4', 'ipv6', 'ip6'
    dns_field_pattern = /\.dns\[\d+\]:/       # Matches '.dns[N]:'

    # Use .source to get the raw pattern, ensuring flags apply uniformly to the new regex.
    dns_line_pattern = /#{ip_version_pattern.source}#{dns_field_pattern.source}/i

    dns_lines = output.split("\n").grep(dns_line_pattern)

    dns_lines.map do |line|
      # Split only on the first colon so IPv6 addresses (which contain colons) are preserved
      line.split(':', 2).last.strip
    end.reject(&:empty?).uniq
  rescue *WifiWand::NetworkErrorConstants::NETWORK_OPERATION_COMMAND_ERRORS
    # If we can't get connection info, return empty array
    []
  end
end

#network_hidden?Boolean

Checks if the currently connected network is a hidden network. A hidden network does not broadcast its SSID.

Returns:

  • (Boolean)

    true if connected to a hidden network, false otherwise

  • (Boolean)


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
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 1096

public def network_hidden?
  debug_method_entry(__method__)

  network_name = _connected_network_name
  return false unless network_name

  # Get the active connection profile name
  profile_name = active_connection_profile_name || network_name

  begin
    # Query the connection profile to check if it's marked as hidden
    output = run_command(
      ['nmcli', '-t', '-f', '802-11-wireless.hidden', 'connection', 'show', profile_name],
      raise_on_error: false
    ).stdout

    # The output will be like "802-11-wireless.hidden:yes" or "802-11-wireless.hidden:no"
    hidden_line = output.split("\n").find { |line| line.include?('802-11-wireless.hidden:') }
    return false unless hidden_line

    # Extract the value after the colon
    hidden_value = hidden_line.split(':', 2).last&.strip
    hidden_value == 'yes'
  rescue *WifiWand::NetworkErrorConstants::NETWORK_OPERATION_COMMAND_ERRORS
    # If we can't get the connection info, assume it's not hidden
    false
  end
end

#nmcli_split(line, limit = nil) ⇒ Array<String>

Splits a line of nmcli terse (-t) output on unescaped field separators. nmcli escapes literal colons as : and literal backslashes as \.

Parameters:

  • line (String)

    A line of nmcli -t terse output

  • limit (Integer, nil) (defaults to: nil)

    Maximum number of parts to produce

Returns:

  • (Array<String>)

    Unescaped field values



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
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 851

public def nmcli_split(line, limit = nil)
  parts = []
  field = +''
  escaped = false

  line.each_char do |char|
    if escaped
      unescaped_char = if [':', '\\'].include?(char)
        char
      else
        "\\#{char}"
      end
      field << unescaped_char
      escaped = false
    elsif char == '\\'
      escaped = true
    elsif char == ':' && (limit.nil? || parts.length < limit - 1)
      parts << field
      field = +''
    else
      field << char
    end
  end

  field << '\\' if escaped
  parts << field
end

#open_resource(resource_url) ⇒ Object



706
707
708
709
710
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 706

public def open_resource(resource_url)
  debug_method_entry(__method__, binding, :resource_url)

  run_command(['xdg-open', resource_url])
end

#preferred_network_password(preferred_network_name, timeout_in_secs: :default) ⇒ Object



477
478
479
480
481
482
483
484
485
486
487
488
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 477

public def preferred_network_password(preferred_network_name, timeout_in_secs: :default)
  debug_method_entry(__method__, binding, :preferred_network_name)

  with_saved_wifi_profiles_cache do
    preferred_network_name = preferred_network_name.to_s
    if (resolved_profile_name = find_best_profile_for_ssid(preferred_network_name))
      _preferred_network_password(resolved_profile_name, timeout_in_secs: timeout_in_secs)
    else
      raise PreferredNetworkNotFoundError, preferred_network_name
    end
  end
end

#preferred_networksObject



490
491
492
493
494
495
496
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 490

public def preferred_networks
  debug_method_entry(__method__)

  with_saved_wifi_profiles_cache do
    saved_wifi_profiles.map(&:ssid).reject(&:empty?).uniq.sort
  end
end

#preferred_networks_matching_ssid(ssid) ⇒ Object



1049
1050
1051
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 1049

public def preferred_networks_matching_ssid(ssid)
  saved_wifi_profiles_matching_ssid(ssid).map(&:name)
end

#probe_wifi_interface(timeout_in_secs: nil) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 74

def probe_wifi_interface(timeout_in_secs: nil)
  debug_method_entry(__method__)
  lines = run_command(
    %w[iw dev],
    timeout_in_secs: timeout_in_secs
  ).stdout.lines.map(&:strip)
  current_interface = nil
  lines.each do |line|
    if line.start_with?('Interface ')
      current_interface = line.split[1]
    elsif line.start_with?('type managed') && current_interface
      return current_interface
    end
  end
  nil
end

#remove_preferred_network(network_name) ⇒ Object



457
458
459
460
461
462
463
464
465
466
467
468
469
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 457

public def remove_preferred_network(network_name)
  debug_method_entry(__method__, binding, :network_name)

  matching_profiles = preferred_networks_matching_ssid(network_name)
  if matching_profiles.empty?
    []
  else
    matching_profiles.each do |profile_name|
      run_command(['nmcli', 'connection', 'delete', profile_name])
    end
    matching_profiles
  end
end

#remove_preferred_networks(*network_names) ⇒ Object



361
362
363
364
365
366
367
368
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 361

public def remove_preferred_networks(*network_names)
  network_names = network_names.first if network_names.first.is_a?(Array) && network_names.size == 1
  network_names = network_names.map(&:to_s).uniq

  with_saved_wifi_profiles_cache do
    super(*network_names)
  end
end

#resolve_saved_profile_name(network_name) ⇒ Object



1053
1054
1055
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 1053

public def resolve_saved_profile_name(network_name)
  find_best_profile_for_ssid(network_name) || network_name
end

#restore_dns_configuration(connection_name, original_dns_configuration) ⇒ Object

Replays the captured DNS fields and reactivates the profile so callers are not left with a partially applied DNS configuration.



832
833
834
835
836
837
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 832

public def restore_dns_configuration(connection_name, original_dns_configuration)
  dns_configuration_modify_commands(connection_name, original_dns_configuration).each do |command|
    run_command(command)
  end
  run_command(['nmcli', 'connection', 'up', connection_name])
end

#set_nameservers(nameservers) ⇒ Object

rubocop:disable Naming/AccessorMethodName



663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 663

public def set_nameservers(nameservers) # rubocop:disable Naming/AccessorMethodName
  # Use NetworkManager connection-based DNS configuration
  # This is the correct approach for Ubuntu - we modify the connection profile,
  # not the interface directly. Each Wi-Fi network has its own connection profile
  # which can have different DNS settings.

  debug_method_entry(__method__, binding, :nameservers)

  # Get the current active Wi-Fi connection name
  current_connection = active_connection_profile_name || _connected_network_name
  unless current_connection
    raise WifiInterfaceError, 'No active Wi-Fi connection to configure DNS for.'
  end

  desired_dns_configuration = desired_dns_configuration(nameservers)
  original_dns_configuration = dns_configuration_snapshot(current_connection)
  configuration_changed = false

  dns_configuration_modify_commands(current_connection, desired_dns_configuration).each do |command|
    run_command(command)
    configuration_changed = true
  end
  run_command(['nmcli', 'connection', 'up', current_connection])

  nameservers
rescue WifiWand::CommandExecutor::OsCommandError => e
  step = e.command.include?('connection up') ? :activate : :modify
  if configuration_changed
    begin
      restore_dns_configuration(current_connection, original_dns_configuration)
    rescue WifiWand::CommandExecutor::OsCommandError => rollback_error
      raise(DnsConfigurationError.new(
        connection_name: current_connection,
        step:            step,
        cause_error:     e,
        rollback_error:  rollback_error
      ))
    end
  end

  raise(DnsConfigurationError.new(connection_name: current_connection, step: step, cause_error: e))
end

#signal_qualityObject



579
580
581
582
583
584
585
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 579

public def signal_quality
  return nil unless connected?

  signal_quality_from_nmcli_scan
rescue WifiWand::Error
  nil
end

#status_line_data(progress_callback: nil) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 47

def status_line_data(progress_callback: nil)
  StatusLineDataBuilder.call(
    self,
    progress_callback:                          progress_callback,
    runtime_config:                             runtime_config,
    expected_network_errors:                    NetworkErrorConstants::EXPECTED_NETWORK_ERRORS,
    connectivity_worker_result_timeout_seconds: TimingConstants::OVERALL_CONNECTIVITY_TIMEOUT
  )
end

#status_network_identity(timeout_in_secs: nil) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 121

def status_network_identity(timeout_in_secs: nil)
  deadline = status_deadline(timeout_in_secs)
  validate_os_preconditions unless @wifi_interface
  connected = status_connected?(deadline)
  network_name = connected ? status_connected_network_name(deadline) : nil
  sq = connected ? status_signal_quality(deadline) : nil

  {
    connected:      connected,
    network_name:   network_name,
    signal_quality: sq,
  }
end

#status_wifi_on?(timeout_in_secs: nil) ⇒ Boolean

Returns:

  • (Boolean)


135
136
137
138
139
140
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 135

def status_wifi_on?(timeout_in_secs: nil)
  deadline = status_deadline(timeout_in_secs)
  validate_os_preconditions unless @wifi_interface

  wifi_on_before_deadline?(deadline)
end

#validate_os_preconditionsObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 57

def validate_os_preconditions
  missing_commands = []

  # Check for critical commands
  missing_commands << 'iw (install: sudo apt install iw)' unless command_available?('iw')
  unless command_available?('nmcli')
    missing_commands << 'nmcli (install: sudo apt install network-manager)'
  end
  missing_commands << 'ip (install: sudo apt install iproute2)' unless command_available?('ip')

  unless missing_commands.empty?
    raise CommandNotFoundError, missing_commands
  end

  :ok
end

#wifi_offObject



163
164
165
166
167
168
169
170
171
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 163

def wifi_off
  return unless wifi_on?

  run_command(%w[nmcli radio wifi off])
  till(:wifi_off, timeout_in_secs: WifiWand::TimingConstants::STATUS_WAIT_TIMEOUT_SHORT)
  wifi_on? ? raise(WifiDisableError) : nil
rescue WifiWand::WaitTimeoutError
  raise WifiDisableError
end

#wifi_onObject



153
154
155
156
157
158
159
160
161
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 153

def wifi_on
  return if wifi_on?

  run_command(%w[nmcli radio wifi on])
  till(:wifi_on, timeout_in_secs: WifiWand::TimingConstants::STATUS_WAIT_TIMEOUT_SHORT)
  wifi_on? ? nil : raise(WifiEnableError)
rescue WifiWand::WaitTimeoutError
  raise WifiEnableError
end

#wifi_on?Boolean

Returns:

  • (Boolean)


97
98
99
# File 'lib/wifi_wand/platforms/ubuntu/model.rb', line 97

def wifi_on?
  nmcli_wifi_radio_enabled?
end