Skip to content

Conversation

@add-uos
Copy link
Contributor

@add-uos add-uos commented Nov 28, 2025

add network full support

pick from: 1c81683

Log: add network full support
Bug: https://pms.uniontech.com/bug-view-286267.html

Summary by Sourcery

Improve network device generation to better validate and discover network interfaces from system information.

New Features:

  • Add support for discovering additional wired and wireless network interfaces based on hwinfo data when not present in lshw output.

Bug Fixes:

  • Ignore invalid logical interface names and MAC addresses to avoid creating bogus network devices.
  • Use permanent hardware address from hwinfo when available to correctly match network devices.

Enhancements:

  • Refactor MAC and logical name validation into reusable helper functions for network device generation.

add network full support

pick from: linuxdeepin@1c81683

Log:  add network full support
Bug: https://pms.uniontech.com/bug-view-286267.html
@sourcery-ai
Copy link

sourcery-ai bot commented Nov 28, 2025

Reviewer's Guide

Refactors network device generation to centralize validation of logical names and MAC addresses, rely on /sys/class/net existence checks, and enhance merging of lshw/hwinfo data so that additional wired/wireless interfaces are discovered and represented correctly.

Sequence diagram for updated network device generation

sequenceDiagram
    participant DeviceGenerator
    participant LshwResult
    participant HwinfoResult
    participant SysClassNet
    participant DeviceNetwork

    DeviceGenerator->>LshwResult: read lshwNetworkList
    loop for each lshwEntry
        LshwResult-->>DeviceGenerator: logicalNameLshw, macAddressLshw
        DeviceGenerator->>DeviceGenerator: isValidLogicalName(logicalNameLshw)
        alt logicalName invalid
            DeviceGenerator-->>DeviceGenerator: skip lshwEntry
        else logicalName valid
            DeviceGenerator->>DeviceGenerator: isValidMAC(macAddressLshw)
            alt MAC invalid
                DeviceGenerator-->>DeviceGenerator: skip lshwEntry
            else MAC valid
                alt logicalNameLshw contains wlan and hasWlan
                    DeviceGenerator-->>DeviceGenerator: skip extra wlan
                else first wlan or wired
                    DeviceGenerator->>DeviceNetwork: new DeviceNetwork
                    DeviceGenerator->>DeviceNetwork: setInfoFromLshw(lshwEntry)
                    DeviceGenerator->>DeviceGenerator: lstDevice.append(device)
                    alt logicalNameLshw contains wlan
                        DeviceGenerator-->>DeviceGenerator: hasWlan = true
                    end
                end
            end
        end
    end

    DeviceGenerator->>HwinfoResult: read hwinfoNetworkList
    loop for each hwinfoEntry
        HwinfoResult-->>DeviceGenerator: permanentHwAddress, hwAddress, deviceFile
        DeviceGenerator-->>DeviceGenerator: macHwinfo = permanentHwAddress if not empty else hwAddress
        DeviceGenerator-->>DeviceGenerator: hasMatchLogicalName = false
        loop for each device in lstDevice
            DeviceNetwork-->>DeviceGenerator: logicalNameLst, hwAddress
            alt logicalNameHwinfo is empty or contains p2p
                DeviceGenerator->>DeviceNetwork: setEnableValue(false)
            else macHwinfo == hwAddress or logicalNameHwinfo == logicalNameLst
                DeviceGenerator->>DeviceNetwork: setInfoFromHwinfo(hwinfoEntry)
                DeviceGenerator-->>DeviceGenerator: hasMatchLogicalName = true
            else no match
                DeviceGenerator->>DeviceNetwork: setCanUninstall(false)
                DeviceGenerator->>DeviceNetwork: setForcedDisplay(true)
            end
        end
        alt not hasMatchLogicalName
            DeviceGenerator->>DeviceGenerator: isValidMAC(macHwinfo)
            DeviceGenerator->>DeviceGenerator: isValidLogicalName(logicalNameHwinfo)
            alt MAC and logicalName valid
                alt logicalNameHwinfo does not contain wlan
                    DeviceGenerator->>DeviceNetwork: new DeviceNetwork
                    DeviceGenerator->>DeviceNetwork: setInfoFromHwinfo(hwinfoEntry)
                    DeviceGenerator->>DeviceGenerator: lstDevice.append(device)
                    DeviceGenerator-->>DeviceGenerator: hasMatchLogicalName = true
                else logicalNameHwinfo contains wlan
                    alt hasWlan is false
                        DeviceGenerator->>DeviceNetwork: new DeviceNetwork
                        DeviceGenerator->>DeviceNetwork: setInfoFromHwinfo(hwinfoEntry)
                        DeviceGenerator->>DeviceGenerator: lstDevice.append(device)
                        DeviceGenerator-->>DeviceGenerator: hasMatchLogicalName = true
                        DeviceGenerator-->>DeviceGenerator: hasWlan = true
                    else hasWlan is true
                        DeviceGenerator-->>DeviceGenerator: skip extra wlan
                    end
                end
            else invalid MAC or logicalName
                DeviceGenerator-->>DeviceGenerator: skip hwinfoEntry
            end
        end
    end

    DeviceGenerator->>DeviceNetwork: finalize lstDevice for UI/output
Loading

Class diagram for DeviceGenerator network support changes

classDiagram
    class DeviceGenerator {
        +generatorMonitorDevice() void
        +generatorNetworkDevice() void
    }

    class DeviceNetwork {
        +setInfoFromLshw(lshwEntry) void
        +setInfoFromHwinfo(hwinfoEntry) void
        +setEnableValue(enable) void
        +setCanUninstall(canUninstall) void
        +setForcedDisplay(forcedDisplay) void
        +hwAddress() QString
        +logicalName() QString
    }

    class NetworkValidation {
        +isValidLogicalName(logicalName QString) bool
        +isValidMAC(macAddress QString) bool
    }

    DeviceGenerator --> DeviceNetwork : creates_and_updates
    DeviceGenerator ..> NetworkValidation : uses
    NetworkValidation <.. DeviceNetwork : validated_by
Loading

File-Level Changes

Change Details Files
Centralize and harden validation of network interface logical names and MAC addresses.
  • Introduce isValidLogicalName helper to filter out p2p interfaces and require presence in /sys/class/net.
  • Introduce isValidMAC helper to reject empty, all-zero, all-FF, or malformed MAC addresses via regex.
  • Reuse these helpers in the network generation logic instead of inline checks.
deepin-devicemanager/src/GenerateDevice/DeviceGenerator.cpp
Adjust lshw-based network device creation to trust sysfs presence checks and track WLAN uniqueness.
  • Remove in-loop /sys/class/net existence checks and let isValidLogicalName gate device creation.
  • Create DeviceNetwork objects directly after passing validation and append to lstDevice.
  • Maintain hasWlan flag when discovering WLAN devices to enforce a single wireless device assumption.
deepin-devicemanager/src/GenerateDevice/DeviceGenerator.cpp
Improve hwinfo-based merging and backfill of network devices to achieve full network support.
  • Prefer 'Permanent HW Address' over 'HW Address' when available for matching.
  • Match hwinfo entries against existing devices by MAC or logical name and update them via setInfoFromHwinfo.
  • Track whether any existing device matched; if none matched but MAC and logical name are valid, create new DeviceNetwork entries, distinguishing wired from wireless and respecting the single-WLAN constraint.
  • Ensure newly created devices from hwinfo are added to lstDevice with appropriate flags and hasWlan updates.
deepin-devicemanager/src/GenerateDevice/DeviceGenerator.cpp

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@deepin-ci-robot
Copy link

deepin pr auto review

我来对这段代码进行审查,并提出改进建议:

  1. 代码结构优化:
  • 新增的 isValidLogicalNameisValidMAC 函数提高了代码复用性,这是好的做法。
  • 建议将这两个辅助函数移到类的私有成员函数中,或者放在单独的工具类中,以保持更好的封装性。
  1. 逻辑改进:
  • isValidLogicalName 函数中,建议先检查目录是否存在,再检查是否包含 "p2p",这样更符合逻辑顺序。
  • MAC 地址验证正则表达式可以更严格一些,确保不会匹配到无效的 MAC 地址。
  1. 性能优化:
  • 在循环中频繁创建 QDir 对象可能影响性能,建议在 isValidLogicalName 函数中使用 QFileInfo::exists() 替代 QDir::exists()。
  1. 安全性改进:
  • 在访问文件系统路径时,应该进行路径验证,防止路径遍历攻击。
  • 建议在 isValidLogicalName 中添加对 logicalName 的合法性检查,确保它不包含 ".." 等危险字符。
  1. 错误处理:
  • isValidLogicalName 中的日志输出使用了 qCInfo,建议使用 qCWarning 更合适,因为这实际上是一个错误情况。

以下是改进后的代码建议:

bool DeviceGenerator::isValidLogicalName(const QString& logicalName)
{
    // 安全检查:防止路径遍历
    if (logicalName.contains("..") || logicalName.contains('/') || logicalName.contains('\\')) {
        qCWarning(appLog) << "Invalid logical name:" << logicalName;
        return false;
    }

    // 检查是否为p2p设备
    if (logicalName.contains("p2p", Qt::CaseInsensitive)) {
        return false;
    }

    // 使用QFileInfo替代QDir提高性能
    QString addressFilePath = "/sys/class/net/" + logicalName;
    if (!QFileInfo::exists(addressFilePath)) {
        qCWarning(appLog) << "Network interface path not exist:" << addressFilePath;
        return false;
    }

    return true;
}

bool DeviceGenerator::isValidMAC(const QString& macAddress)
{
    // 更严格的MAC地址验证
    if (macAddress.isEmpty() ||
        macAddress.compare("00:00:00:00:00:00", Qt::CaseInsensitive) == 0 ||
        macAddress.compare("ff:ff:ff:ff:ff:ff", Qt::CaseInsensitive) == 0) {
        return false;
    }

    // 更严格的MAC地址正则表达式
    static const QRegularExpression macRegex("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$");
    return macRegex.match(macAddress).hasMatch();
}

其他建议:

  1. 考虑使用智能指针(如 QScopedPointer)来管理 DeviceNetwork 对象的生命周期,避免内存泄漏。
  2. 在 generatorNetworkDevice 函数中,可以考虑使用 C++11 的范围循环(range-based for)来简化代码。
  3. 建议添加更多的注释来解释复杂的逻辑,特别是关于 wlan 设备限制的部分。
  4. 考虑将 hasWlan 变量改为类成员变量,以便在多个方法中共享使用。

这些改进将使代码更加健壮、安全和可维护。

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • Consider moving isValidLogicalName and isValidMAC into an anonymous namespace or making them static to limit their visibility to this translation unit and avoid potential name clashes.
  • In isValidLogicalName, the log statement prints the QDir object instead of the actual path string; logging dir.path() (or the constructed path) would make the message clearer.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider moving `isValidLogicalName` and `isValidMAC` into an anonymous namespace or making them `static` to limit their visibility to this translation unit and avoid potential name clashes.
- In `isValidLogicalName`, the log statement prints the `QDir` object instead of the actual path string; logging `dir.path()` (or the constructed path) would make the message clearer.

## Individual Comments

### Comment 1
<location> `deepin-devicemanager/src/GenerateDevice/DeviceGenerator.cpp:297-303` </location>
<code_context>
     qCDebug(appLog) << "DeviceGenerator::generatorMonitorDevice end";
 }

+bool isValidLogicalName(const QString& logicalName)
+{
+    if (logicalName.contains("p2p", Qt::CaseInsensitive))
+        return false;
+
+    QString addressFilePath = "/sys/class/net/" + logicalName;
+    QDir dir(addressFilePath);
+    if (dir.exists())
+        return true;
</code_context>

<issue_to_address>
**issue (bug_risk):** Empty logical names are treated as valid due to `/sys/class/net/` existing.

When `logicalName` is empty (which can happen in the hwinfo path), `addressFilePath` becomes `/sys/class/net/`, and `QDir("/sys/class/net/").exists()` will almost always be true. As a result, `isValidLogicalName("")` returns `true`, which conflicts with the later intent to only add devices when the logical name exists and is valid, and can result in phantom devices with no logical name. Add an explicit guard such as `if (logicalName.isEmpty()) return false;` before constructing `addressFilePath`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@deepin-ci-robot
Copy link

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: add-uos, lzwind

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@add-uos
Copy link
Contributor Author

add-uos commented Nov 28, 2025

/merge

@deepin-bot deepin-bot bot merged commit 6743411 into linuxdeepin:master Nov 28, 2025
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants