libkylin-nm-base/0000775000175000017500000000000015160517573012647 5ustar fengfenglibkylin-nm-base/kylin-nm.pro0000664000175000017500000000074015160517205015120 0ustar fengfengTEMPLATE = subdirs CONFIG += ordered \ qt SUBDIRS = \ # plugins/plugin.pro \ libnm-kylin \ kylin-keyring/kylin-keyring.pro\ # kylin-nm-gui \ # kylin-nm-server \ tests #默认不编译测试用例,仅自测时打开 SUBDIRS -= tests #kylin-nm-gui.depends = libnm-kylin #kylin-nm-server.depends = libnm-kylin #TRANSLATIONS += \ # translations/kylin-nm_zh_CN.ts \ # translations/kylin-nm_tr.ts \ # translations/kylin-nm_bo.ts libkylin-nm-base/README.md0000664000175000017500000000155615160517167014134 0ustar fengfeng# NAME kylin-nm - kylin network monitor used in ubuntu-kylin operation system # DESCRIPTION kylin-nm is a Qt based applet and uses some interface provided by NetworkManager. It provides a GUI for users to connect or disconnect wired or wireless network which managed by NetworkManager. Users can also create new wired network and configure a old network. By click button at left bottom in the main window, a network configure window of NetworkManager will show in the screen. Users can get some information about network directly by clicking one item in the network list, these information shown in extension area. # BUILD KYLIN-NM down the source sode install dependency packages(see cntrol files in the debian directory) execute debuild command in the root directory of project execute sudo dpkg -i packagename.deb to install libkylin-nm-base/AUTHORS0000664000175000017500000000004315160517167013713 0ustar fengfengshine libkylin-nm-base/man/0000775000175000017500000000000015160517167013421 5ustar fengfenglibkylin-nm-base/man/kylin-nm-dev.10000664000175000017500000000140215160517167016012 0ustar fengfeng.\" Man page for Kylin-nm .TH KYLIN-NM 1 "20 September 2019" "UKUI Desktop Environment" .\" Please adjust this date when revising the manpage. .\" .SH "NAME" kylin-nm \- The tool for the UKUI Desktop Environment .SH "SYNOPSIS" .B kylin-nm .SH "DESCRIPTION" The \fBkylin-nm\fR program is a part of the ukui-indicators, It provides network manager for the the UKUI Desktop Environment. Detect the system disk automatically, Can pop up and open the device. .PP This manual page documents the \fBkylin-nm\fR command. .P .SH "BUGS" .SS Should you encounter any bugs, they may be reported at: https://github.com/ukui/kylin-nm/issues .SH "AUTHORS" .SS This Man Page has been written for the UKUI Desktop Environment by: shine (2019) .SH "SEE ALSO"libkylin-nm-base/COPYING0000664000175000017500000004310015160517564013700 0ustar fengfeng GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see . Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Moe Ghoul, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. libkylin-nm-base/libnm-kylin/0000775000175000017500000000000015160517205015064 5ustar fengfenglibkylin-nm-base/libnm-kylin/libnm-base-kylin/0000775000175000017500000000000015160517205020221 5ustar fengfenglibkylin-nm-base/libnm-kylin/libnm-base-kylin/kylin-nm-interface.h0000664000175000017500000000356515160517205024077 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINNMINTERFACE_H #define KYLINNMINTERFACE_H #include "libnm-base-kylin_global.h" #include class QWidget; enum PluginType { SIMPLE = 0, //锁屏 && 登录 COMPLEX, //托盘 OOBE, //oobe }; class LIBNMBASEKYLIN_EXPORT Interface : public QObject{ Q_OBJECT public: virtual ~Interface(){} virtual QWidget * pluginUi() = 0; // 插件主界面---setPluginType后调用 virtual void setPluginType(PluginType type, bool useSwitch = true) = 0; // 设置插件类型 virtual void setParentWidget(QWidget* widget) = 0; virtual void setWidgetVisable(bool) = 0; virtual bool checkInputStauts() { return false; } virtual void setInputStauts() { return; } virtual bool checkPluginIsHidden() { return false; } virtual void updatePluginHidden(bool) = 0; Q_SIGNALS: void needShowVirtualKeyboard(); }; #define Interface_iid "org.kylin.network" Q_DECLARE_INTERFACE(Interface, Interface_iid) #endif // KYLINNMINTERFACE_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/kylinnetworkmanger.cpp0000664000175000017500000004242415160517205024665 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinnetworkmanager.h" #define WAIT_US 1000 KyNetworkManager::KyNetworkManager(QObject *parent) : QObject(parent) { // kylinNetworkManagerInit(); m_init = false; } KyNetworkManager::~KyNetworkManager() { m_networkResource = nullptr; } void KyNetworkManager::kylinNetworkManagerInit() { if (!m_init) { qDebug() << "kylinNetworkManagerInit"; m_networkResource = KyNetworkResourceManager::getInstance(); if (!m_networkResource->NetworkManagerIsInited()) { m_networkResource->onInitNetwork(); } m_activeConnectResource = new KyActiveConnectResourse(this); m_deviceResource = new KyNetworkDeviceResourse(this); m_general = new KylinGeneralOpration(this); m_wiredConnectResourse = new KyWiredConnectResourse(this); m_wirelessNetResource = new KyWirelessNetResource(this); m_apNetResource = new KyApNetResource(this); initConnect(); Q_EMIT initFinished(); } m_init = true; } void KyNetworkManager::initConnect() { connect(m_activeConnectResource, &KyActiveConnectResourse::wiredStateChange, this, &KyNetworkManager::wiredStateChange); connect(m_activeConnectResource, &KyActiveConnectResourse::wirelessStateChange, this, &KyNetworkManager::wirelessStateChange); connect(m_deviceResource, &KyNetworkDeviceResourse::carrierChange, this, &KyNetworkManager::carrierChange); connect(m_deviceResource, &KyNetworkDeviceResourse::deviceStateChange, this, &KyNetworkManager::deviceStateChange); connect(m_deviceResource, &KyNetworkDeviceResourse::deviceManagedChange, this, &KyNetworkManager::deviceManagedChange); connect(m_general, &KylinGeneralOpration::connectStatusChanged, this, &KyNetworkManager::connectStatusChanged); connect(m_general, &KylinGeneralOpration::networkingEnabledChanged, this, &KyNetworkManager::networkingEnabledChanged); connect(m_general, &KylinGeneralOpration::wifiEnabledChanged, this, &KyNetworkManager::wifiEnabledChanged); connect(m_general, &KylinGeneralOpration::wiredEnabledChanged, this, &KyNetworkManager::wiredEnabledChanged); connect(m_apNetResource, &KyApNetResource::wirelessApConnectStateChange, this, &KyNetworkManager::wirelessApConnectStateChange); connect(m_wiredConnectResourse, &KyWiredConnectResourse::wiredConnectionAdd, this, &KyNetworkManager::wiredConnectionAdd); connect(m_wiredConnectResourse, &KyWiredConnectResourse::wiredConnectionUpdate, this, &KyNetworkManager::wiredConnectionUpdate); connect(m_wiredConnectResourse, &KyWiredConnectResourse::connectionRemove, this, &KyNetworkManager::connectionRemove); connect(m_wiredConnectResourse, &KyWiredConnectResourse::wiredDeviceAdd, this, &KyNetworkManager::wiredDeviceAdd); connect(m_wiredConnectResourse, &KyWiredConnectResourse::wiredDeviceUpdate, this, &KyNetworkManager::wiredDeviceUpdate); connect(m_wiredConnectResourse, &KyWiredConnectResourse::deviceRemove, this, &KyNetworkManager::deviceRemove); connect(m_wirelessNetResource, &KyWirelessNetResource::signalStrengthChange, this, &KyNetworkManager::signalStrengthChange); connect(m_wirelessNetResource, &KyWirelessNetResource::secuTypeChange, this, &KyNetworkManager::secuTypeChange); connect(m_wirelessNetResource, &KyWirelessNetResource::wirelessConnectionRemove, this, &KyNetworkManager::wirelessConnectionRemove); connect(m_wirelessNetResource, &KyWirelessNetResource::wirelessConnectionAdd, this, &KyNetworkManager::wirelessConnectionAdd); connect(m_wirelessNetResource, &KyWirelessNetResource::wirelessConnectionUpdate, this, &KyNetworkManager::wirelessConnectionUpdate); connect(m_wirelessNetResource, &KyWirelessNetResource::wifiNetworkUpdate, this, &KyNetworkManager::wifiNetworkUpdate); connect(m_wirelessNetResource, &KyWirelessNetResource::wifiNetworkAdd, this, &KyNetworkManager::wifiNetworkAdd); connect(m_wirelessNetResource, &KyWirelessNetResource::wifiNetworkRemove, this, &KyNetworkManager::wifiNetworkRemove); connect(m_wirelessNetResource, &KyWirelessNetResource::wirelessDeviceAdd, this, &KyNetworkManager::wirelessDeviceAdd); connect(m_wirelessNetResource, &KyWirelessNetResource::wirelessDeviceNameUpdate, this, &KyNetworkManager::wirelessDeviceNameUpdate); connect(m_wirelessNetResource, &KyWirelessNetResource::updateWifiList, this, &KyNetworkManager::updateWifiList); } //同步方法 //有线 无线 移动热点界面 void KyNetworkManager::getActiveConnectionList(QString deviceName, KyConnectionType connectionType, QList &connectItemList) { m_activeConnectResource->getActiveConnectionList(deviceName, connectionType, connectItemList); } int KyNetworkManager::getAcivateWifiSignal() { return m_activeConnectResource->getAcivateWifiSignal(); } void KyNetworkManager::getNetworkDeviceList(KyDeviceType deviceType, QStringList &networkDeviceList) { m_deviceResource->getNetworkDeviceList(deviceType, networkDeviceList); } bool KyNetworkManager::getDeviceManaged(QString devName) { return m_deviceResource->getDeviceManaged(devName); } KyDeviceState KyNetworkManager::getDeviceState(QString deviceName) { return m_deviceResource->getDeviceState(deviceName); } void KyNetworkManager::getDeviceConnectivity(const QString deviceName, KyConnectivity &connectivity) { m_deviceResource->getDeviceConnectivity(deviceName, connectivity); } void KyNetworkManager::getConnectStatus(KyConnectStatus &connectType) { m_general->getConnectStatus(connectType); } bool KyNetworkManager::getWirelessEnabled() { return m_general->getWirelessEnabled(); } bool KyNetworkManager::getWiredEnabled() { return m_general->getWiredEnabled(); } bool KyNetworkManager::getNetworkingEnabled() { return m_general->getNetworkingEnabled(); } void KyNetworkManager::getWiredList(QMap> &map) { m_wiredConnectResourse->getWiredList(map); } void KyNetworkManager::getWifiNetworkList(QString devName, QList &list) { m_wirelessNetResource->getWifiNetworkList(devName, list); } void KyNetworkManager::getApConnections(QList &apConnectItemList) { m_apNetResource->getApConnections(apConnectItemList); } //详情页 //共有ipv4 ipv6 包括autoconnect void KyNetworkManager::getConnectIpInfo(QString uuid, KyConnectSetting &connectSetting) { KyNetResource resource; resource.getConnectionSetting(uuid, connectSetting); } //详情页-->有线连接detail void KyNetworkManager::getWiredConnectDetail(QString interface, QString uuid, KyDetailInfo &connectSetting) { KyWiredConnectResourse resource; resource.getWiredConnectDetail(interface, uuid, connectSetting); } //详情页-->无线连接detail void KyNetworkManager::getWirelessConnectDetail(QString interface, QString ssid, QString uuid, KyDetailInfo &connectSetting) { KyWirelessNetResource resource; resource.getWirelessConnectDetail(interface, ssid, uuid, connectSetting); } //无线连接-->安全 bool KyNetworkManager::getNormalWifiConnectSecuInfo(QString &uuid, KyWpaPasswordInfo &info) { KyWirelessNetResource resource; return resource.getNormalWifiConnectSecuInfo(uuid, info); } bool KyNetworkManager::getEnterPriseInfoTls(QString &uuid, KyEapMethodTlsInfo &info) { KyWirelessNetResource resource; return resource.getEnterPriseInfoTls(uuid, info); } bool KyNetworkManager::getEnterPriseInfoPeap(QString &uuid, KyEapMethodPeapInfo &info) { KyWirelessNetResource resource; return resource.getEnterPriseInfoPeap(uuid, info); } bool KyNetworkManager::getEnterPriseInfoTtls(QString &uuid, KyEapMethodTtlsInfo &info) { KyWirelessNetResource resource; return resource.getEnterPriseInfoTtls(uuid, info); } bool KyNetworkManager::getEnterPriseInfoLeap(QString &uuid, KyEapMethodLeapInfo &info) { KyWirelessNetResource resource; return resource.getEnterPriseInfoLeap(uuid, info); } bool KyNetworkManager::getEnterPriseInfoPwd(QString &uuid, KyEapMethodPwdInfo &info) { KyWirelessNetResource resource; return resource.getEnterPriseInfoPwd(uuid, info); } bool KyNetworkManager::getEnterPriseInfoFast(QString &uuid, KyEapMethodFastInfo &info) { KyWirelessNetResource resource; return resource.getEnterPriseInfoFast(uuid, info); } //获取企业网类型 bool KyNetworkManager::getEnterpiseEapMethod(const QString &uuid, KyEapMethodType &type) { KyWirelessNetResource resource; return resource.getEnterpiseEapMethod(uuid, type); } bool KyNetworkManager::wiredConnectIsActived() { return m_activeConnectResource->wiredConnectIsActived(); } bool KyNetworkManager::wirelessConnectIsActived() { return m_activeConnectResource->wirelessConnectIsActived(); } bool KyNetworkManager::getWiredDeviceIsCarriered(QString wiredDevName) { return m_deviceResource->wiredDeviceIsCarriered(wiredDevName); } //异步槽 void KyNetworkManager::onSetWirelessNetworkEnabled(bool enabled) { m_general->setWirelessNetworkEnabled(enabled); } void KyNetworkManager::onSetNetworkingEnabled(bool enabled) { m_general->setNetworkingEnabled(enabled); } void KyNetworkManager::onSetWiredEnabled(bool enabled) { m_general->setWiredEnabled(enabled); } void KyNetworkManager::onSetDeviceManaged(QString devName, bool managed) { m_deviceResource->setDeviceManaged(devName, managed); } void KyNetworkManager::onSetWiredDeviceEnable(QString devName, bool enable) { m_deviceResource->setDeviceManaged(devName, enable); } void KyNetworkManager::onDeleteConnect(const QString &connectUuid) { KyConnectOperation operate; operate.deleteConnect(connectUuid); } void KyNetworkManager::onActivateConnection(const QString connectUuid, const QString deviceName) { KyConnectOperation operate; operate.activateConnection(connectUuid, deviceName); } void KyNetworkManager::onDeactivateConnection(const QString &activeConnectUuid) { KyConnectOperation operate; operate.deactivateConnection(activeConnectUuid); } void KyNetworkManager::onCreateWiredConnect(KyConnectSetting connectSettingsInfo) { KyWiredConnectOperation operate; operate.createWiredConnect(connectSettingsInfo); } //=====================申请无线扫描=================== void KyNetworkManager::onRequestWirelessScan() { KyWirelessConnectOperation operate; operate.requestWirelessScan(); } //=======================连接操作==================== //连接无本地配置的非企业网热点 void KyNetworkManager::onAddAndActivateNormalWifi(KyWirelessConnectSetting connSettingInfo, KySecuType type) { KyWirelessConnectOperation operate; operate.addAndActiveWirelessConnect(connSettingInfo, type); } //连接无本地配置的企业网热点 void KyNetworkManager::onAddAndActiveWirelessEnterPriseTlsConnect(KyEapMethodTlsInfo info, KyWirelessConnectSetting connSettingInfo) { KyWirelessConnectOperation operate; operate.addAndActiveWirelessEnterPriseTlsConnect(info, connSettingInfo); } void KyNetworkManager::onAddAndActiveWirelessEnterPrisePeapConnect(KyEapMethodPeapInfo info, KyWirelessConnectSetting connSettingInfo) { KyWirelessConnectOperation operate; operate.addAndActiveWirelessEnterPrisePeapConnect(info, connSettingInfo); } void KyNetworkManager::onAddAndActiveWirelessEnterPriseTtlsConnect(KyEapMethodTtlsInfo info, KyWirelessConnectSetting connSettingInfo) { KyWirelessConnectOperation operate; operate.addAndActiveWirelessEnterPriseTtlsConnect(info, connSettingInfo); } void KyNetworkManager::onAddAndActiveWirelessEnterPriseLeapConnect(KyEapMethodLeapInfo info, KyWirelessConnectSetting connSettingInfo) { KyWirelessConnectOperation operate; operate.addAndActiveWirelessEnterPriseLeapConnect(info, connSettingInfo); } void KyNetworkManager::onAddAndActiveWirelessEnterPrisePwdConnect(KyEapMethodPwdInfo info, KyWirelessConnectSetting connSettingInfo) { KyWirelessConnectOperation operate; operate.addAndActiveWirelessEnterPrisePwdConnect(info, connSettingInfo); } void KyNetworkManager::onAddAndActiveWirelessEnterPriseFastConnect(KyEapMethodFastInfo info, KyWirelessConnectSetting connSettingInfo) { KyWirelessConnectOperation operate; operate.addAndActiveWirelessEnterPriseFastConnect(info, connSettingInfo); } //=====================新增配置操作==================== //新增普通连接 void KyNetworkManager::onAddNormalConnect(const KyWirelessConnectSetting &connSettingInfo, KySecuType &type) { KyWirelessConnectOperation operate; operate.addConnect(connSettingInfo, type); } //新增TLS连接 void KyNetworkManager::onAddTlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTlsInfo &tlsinfo) { KyWirelessConnectOperation operate; operate.addTlsConnect(connSettingInfo, tlsinfo); } //新增PEAP连接 void KyNetworkManager::onAddPeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPeapInfo &peapInfo) { KyWirelessConnectOperation operate; operate.addPeapConnect(connSettingInfo, peapInfo); } //新增TTLS连接 void KyNetworkManager::onAddTtlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTtlsInfo &ttlsInfo) { KyWirelessConnectOperation operate; operate.addTtlsConnect(connSettingInfo, ttlsInfo); } //=====================更新配置操作==================== void KyNetworkManager::onUpdateIpv4AndIpv6SettingInfo(const QString &uuid, const KyConnectSetting &connectSettingsInfo) { KyWirelessConnectOperation operate; operate.updateIpv4AndIpv6SettingInfo(uuid, connectSettingsInfo); } //连接修改(安全改为个人/None) void KyNetworkManager::onUpdateWirelessPersonalConnect(const QString &uuid, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange) { KyWirelessConnectOperation operate; operate.updateWirelessPersonalConnect(uuid, connSettingInfo, bPwdChange); } //连接修改(安全改为改为企业) void KyNetworkManager::onUpdateWirelessEnterPriseTlsConnect(const QString &uuid, const KyEapMethodTlsInfo &tlsinfo) { KyWirelessConnectOperation operate; operate.updateWirelessEnterPriseTlsConnect(uuid, tlsinfo); } void KyNetworkManager::onUpdateWirelessEnterPrisePeapConnect(const QString &uuid, const KyEapMethodPeapInfo &peapInfo) { KyWirelessConnectOperation operate; operate.updateWirelessEnterPrisePeapConnect(uuid, peapInfo); } void KyNetworkManager::onUpdateWirelessEnterPriseTtlsConnect(const QString &uuid, const KyEapMethodTtlsInfo &ttlsInfo) { KyWirelessConnectOperation operate; operate.updateWirelessEnterPriseTtlsConnect(uuid, ttlsInfo); } void KyNetworkManager::onUpdateWirelessEnterPriseLeapConnect(const QString &uuid, const KyEapMethodLeapInfo &leapInfo) { KyWirelessConnectOperation operate; operate.updateWirelessEnterPriseLeapConnect(uuid, leapInfo); } void KyNetworkManager::onUpdateWirelessEnterPrisePwdConnect(const QString &uuid, const KyEapMethodPwdInfo &pwdInfo) { KyWirelessConnectOperation operate; operate.updateWirelessEnterPrisePwdConnect(uuid, pwdInfo); } void KyNetworkManager::onUpdateWirelessEnterPriseFastConnect(const QString &uuid, const KyEapMethodFastInfo &fastInfo) { KyWirelessConnectOperation operate; operate.updateWirelessEnterPriseFastConnect(uuid, fastInfo); } void KyNetworkManager::onUpdateWirelessAutoConnectState(const QString &uuid, bool bAutoConnect) { KyWirelessConnectOperation operate; operate.setWirelessAutoConnect(uuid, bAutoConnect); } libkylin-nm-base/libnm-kylin/libnm-base-kylin/libnm-base-kylin.pro0000664000175000017500000000737715160517205024116 0ustar fengfeng#QT -= gui #QT += core gui x11extras dbus KWindowSystem svg concurrent network QT += core dbus network TARGET = kylin-nm-base TEMPLATE = lib DEFINES += LIBNMBASEKYLIN_LIBRARY CONFIG += c++11 qt warn_on link_pkgconfig no_keywords CONFIG += create_pc create_prl no_install_prl PKGCONFIG +=libnm gsettings-qt6 gtk+-3.0 #PKGCONFIG += gio-2.0 glib-2.0 gio-unix-2.0 libnm libnma libsecret-1 gsettings-qt INCLUDEPATH += /usr/include/KF6/NetworkManagerQt INCLUDEPATH += /usr/include/dbus-1.0/dbus LIBS += -L/usr/lib/ -lKF6NetworkManagerQt # The following define makes your compiler emit warnings if you use # any Qt feature that has been marked deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if it uses deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ depend/kyapnetresource.cpp \ depend/kyenterpricesettinginfo.cpp \ depend/kylinactiveconnectresource.cpp \ depend/kylinconnectoperation.cpp \ depend/kylinconnectsetting.cpp \ depend/kylingeneral.cpp \ depend/kylinnetresource.cpp \ depend/kylinnetworkdeviceresource.cpp \ depend/kylinnetworkmanagerutil.cpp \ depend/kynetloadratethread.cpp \ kylinnetworkmanger.cpp \ depend/kylinnetworkresourcemanager.cpp \ depend/kylinwiredconnectoperation.cpp \ depend/kylinwirednetresource.cpp \ depend/kywirelessconnectoperation.cpp \ depend/kywirelessnetresource.cpp kylinnetworkmanger.cpp \ HEADERS += \ depend/kynetloadratethread.h \ libnm-base-kylin_global.h \ kylin-nm-interface.h \ kylinnetworkmanager.h \ depend/kyapnetresource.h \ depend/kyenterpricesettinginfo.h \ depend/kylinactiveconnectresource.h \ depend/kylinapconnectitem.h \ depend/kylinconnectitem.h \ depend/kylinconnectoperation.h \ depend/kylinconnectsetting.h \ depend/kylingeneral.h \ depend/kylinnetresource.h \ depend/kylinnetworkdeviceresource.h \ depend/kylinnetworkmanagerutil.h \ depend/kylinnetworkresourcemanager.h \ depend/kylinnetworkresourcetype.h \ depend/kylinwiredconnectoperation.h \ depend/kylinwirednetresource.h \ depend/kywirelessconnectoperation.h \ depend/kywirelessnetitem.h \ depend/kywirelessnetresource.h DESTDIR += $$PWD # Default rules for deployment. unix { target.path = /usr/lib/ manager.path = /usr/include/kylin-nm manager.files = kylinnetworkmanager.h \ libnm-base-kylin_global.h \ kylin-nm-interface.h depend.path = /usr/include/kylin-nm/depend depend.files = depend/*.h pkg.path = /usr/share/pkgconfig pkg.files = pkgconfig/*.pc # gschema.files = org.ukui.kylin-nm.switch.gschema.xml # gschema.path = /usr/share/glib-2.0/schema QMAKE_PKGCONFIG_NAME = kylin-nm-base QMAKE_PKGCONFIG_DESCRIPTION = kylin-nm Header files QMAKE_PKGCONFIG_VERSION = $$VERSION QMAKE_PKGCONFIG_LIBDIR = $$target.path QMAKE_PKGCONFIG_DESTDIR = ../share/pkgconfig QMAKE_PKGCONFIG_INCDIR = $$INCLUDEPATH #/usr/include/kylin-nm /usr/include/KF5/NetworkManagerQt # QMAKE_PKGCONFIG_INCDIR += /usr/include/KF5/NetworkManagerQt QMAKE_PKGCONFIG_CFLAGS += -I/usr/include/kylin-nm QMAKE_PKGCONFIG_REQUIRES = gio-2.0 glib-2.0 libnm INSTALLS += manager \ depend \ gschema } !isEmpty(target.path): INSTALLS += target DISTFILES += \ org.ukui.kylin-nm.switch.gschema.xml libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/0000775000175000017500000000000015160517205021460 5ustar fengfenglibkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcemanager.h0000664000175000017500000002272415160517205027503 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINNETWORKRESOURCEMANAGER_H #define KYLINNETWORKRESOURCEMANAGER_H #include "NetworkManagerQt/Manager" #include "NetworkManagerQt/Settings" #include "NetworkManagerQt/WirelessDevice" #include "NetworkManagerQt/GenericTypes" #include "NetworkManagerQt/VpnConnection" #include "NetworkManagerQt/WirelessDevice" #include "NetworkManagerQt/AdslDevice" #include "NetworkManagerQt/WiredDevice" #include "NetworkManagerQt/WimaxDevice" #include "NetworkManagerQt/VlanDevice" #include "NetworkManagerQt/BondDevice" #include "NetworkManagerQt/BridgeDevice" #include "NetworkManagerQt/GenericDevice" #include "NetworkManagerQt/InfinibandDevice" #include "NetworkManagerQt/BluetoothDevice" #include "NetworkManagerQt/OlpcMeshDevice" #include "NetworkManagerQt/TeamDevice" #include "NetworkManagerQt/WirelessSetting" #include "NetworkManagerQt/WirelessSecuritySetting" #include "NetworkManagerQt/Utils" #include "NetworkManagerQt/ConnectionSettings" #include "NetworkManagerQt/Security8021xSetting" #include #include #include "kylinnetworkresourcetype.h" #define VIRTURAL_DEVICE_PATH "/sys/devices/virtual/net" class KyNetworkResourceManager : public QObject { Q_OBJECT public: static KyNetworkResourceManager* getInstance(); static void Release(); public: explicit KyNetworkResourceManager(QObject *parent = nullptr); ~KyNetworkResourceManager(); public: NetworkManager::ActiveConnection::Ptr findActiveConnectionByPath(QString const & path); NetworkManager::ActiveConnection::Ptr findActiveConnectByUuid(const QString activeConnectUuid); NetworkManager::Connection::Ptr findConnectByUuid(const QString uuid); NetworkManager::Device::Ptr findDeviceByUni(QString const &deviceUni); NetworkManager::Device::Ptr findDeviceByName(QString interfaceName); NetworkManager::WirelessNetwork::Ptr findWifiNetwork(QString const &ssid, QString const &deviceUni); NetworkManager::ActiveConnection::List getActiveConnectList(); NetworkManager::Connection::List getConnectList(); NetworkManager::Device::List getNetworkDeviceList(); NetworkManager::WirelessNetwork::List getWifiNetworkList(); bool isActiveConnection(QString uuid); bool isActivatingConnection(QString uuid); void getConnectivity(KyConnectivity &connectivity); bool NetworkManagerIsInited(); void requestScan(NetworkManager::WirelessDevice *p_wirelessDevice); bool isWiredConnect(QString connectPath); bool isApConnection(NetworkManager::Connection::Ptr connectPtr); private: void removeActiveConnection(int pos); void clearActiveConnections(); void insertActiveConnections(); void addActiveConnection(NetworkManager::ActiveConnection::Ptr conn); void removeConnection(int pos); void clearConnections(); void insertConnections(); void addConnection(NetworkManager::Connection::Ptr conn); void removeDevice(int pos); void clearDevices(); void insertDevices(); void addDevice(NetworkManager::Device::Ptr conn); void updateDeviceName(NetworkManager::Device *p_device); void removeWifiNetwork(int pos); void clearWifiNetworks(); void insertWifiNetworks(); void addWifiNetwork(NetworkManager::WirelessNetwork::Ptr net); void connectionDump(); void wifiNetworkAdd(NetworkManager::Device * dev, QString const & ssid); void wifiNetworkUpdate(NetworkManager::WirelessNetwork * net); void wifiNetworkRemove(NetworkManager::Device * dev, QString const & ssid); void wirelessActiveStateChange(NetworkManager::ConnectionSettings::Ptr connectSettingsPtr, QString deviceName, QString uuid, KyConnectState state); void wiredActiveStateChange(QString connectPath, QString deviceName, QString uuid, KyConnectState state); void connectActiveStateChange(NetworkManager::Connection::Ptr connectPtr, QString deviceName, KyConnectState state); private Q_SLOTS: void onServiceAppear(QString, QString, QString); void onPropertiesChanged(QVariantMap qvm); Q_SIGNALS: // wired connect void wiredConnectionAdd(QString devName, QString connectUuid, QString connectName, QString connectPath); void wiredConnectionUpdate(QString devName, QString connectUuid, QString connectName, QString connectPath); // void wiredConnectionRemove(QString path); void connectionAdd(QString connectUuid, QString connectName, QString connectPath); void connectionUpdate(QString connectUuid, QString connectName, QString connectPath); void connectionRemove(QString path); //device void wiredDeviceAdd(QString deviceName); void wiredDeviceUpdate(QString oldDeviceName, QString newDeviceName); void wirelessDeviceAdd(QString deviceName); void wirelessDeviceUpdate(QString oldDeviceName, QString newDeviceName); void deviceAdd(QString deviceName, KyDeviceType deviceType); void deviceUpdate(QString oldDeviceName, QString newDeviceName); void deviceRemove(QString deviceName); void deviceManagedChange(QString deviceName, bool managed); void deviceActiveChange(QString deviceName, bool deviceActive); void deviceCarrierChange(QString deviceName, bool pluged); void deviceBitRateChange(QString deviceName, int bitRate); void deviceMacAddressChange(QString deviceName, const QString &hwAddress); void deviceStateChange(QString deviceName, KyDeviceState newstate, KyDeviceState oldstate, NetworkManager::Device::StateChangeReason reason); //wireless void wifiNetworkRemoved(QString, QString); void wifiNetworkAdded(QString, QString); void wifiNetworkPropertyChange(NetworkManager::WirelessNetwork::Ptr net); void wifiNetworkDeviceDisappear(); void wirelessConnectionAdd(QString connectUuid, QString connectName, QString connectPath); void wirelessConnectionUpdate(QString devName,QString connectUuid, QString connectName, QString connectPath); // void wirelessConnectionRemove(QString path); // void wiredConnectionUpdate(QString connectUuid, QString connectName, QString connectPath); //activate connection void activeConnectionAdd(QString uuid); void activeConnectionRemove(QString uuid); void wiredConnectStateChange(QString deviceName, QString uuid, KyConnectState state); void wirelessConnectStateChange(QString deviceName, QString ssid, QString uuid, KyConnectState state); void wirelessApConnectStateChange(); //general void connectivityChanged(KyConnectivity connectivity); void wifiEnabledChanged(bool); void wiredEnabledChanged(bool); void networkingEnabledChanged(bool); void primaryConnectionTypeChanged(KyConnectionType type); public Q_SLOTS: void onInitNetwork(); //connection void onConnectionUpdated(); //void onConnectionRemoved(); //active connection void onActiveConnectionChanged(NetworkManager::ActiveConnection::State state); void onVpnActiveConnectChangedReason(NetworkManager::VpnConnection::State state, NetworkManager::VpnConnection::StateChangeReason reason); void onDeviceActiveChange(); void onDeviceCarrierChange(bool pluged); void onDeviceBitRateChange(int bitRate); void onDeviceMacAddressChange(const QString &hwAddress); void onDeviceStateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason); void onWifiNetworkAppeared(QString const & ssid); void onWifiNetworkDisappeared(QString const & ssid); //wifi network void onUpdateWirelessNet(); void onConnectivityChanged(NetworkManager::Connectivity connectivity); //notifier void onDeviceAdded(QString const & uni); void onDeviceRemoved(QString const & uni); void onDeviceUpdated(); void onDeviceManagedChange(); //active connection notifier void onActiveConnectionAdded(QString const & path); void onActiveConnectionRemoved(QString const & path); //settings notifier void onConnectionAdded(QString const & path); void onConnectionRemoved(QString const & path); void onPrimaryConnectionTypeChanged(NetworkManager::ConnectionSettings::ConnectionType); public: static KyNetworkResourceManager* m_pInstance; private: bool m_initFinished = false; NetworkManager::ActiveConnection::List m_activeConnectList; NetworkManager::Connection::List m_connectList; NetworkManager::Device::List m_deviceList; NetworkManager::WirelessNetwork::List m_wifiNetList; QMap m_deviceMap; }; #endif // KYLINNETWORKRESOURCEMANAGER_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectitem.h0000664000175000017500000000210715160517205025210 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINCONNECTITEM_H #define KYLINCONNECTITEM_H #include class KyWiredItem { public: QString m_connectName; QString m_connectUuid; QString m_connectPath; }; #endif // KYLINWIREDCONNECTITEM_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkmanagerutil.h0000664000175000017500000000340515160517205026624 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINUTIL_H #define KYLINUTIL_H #include #include #include #include #include #include #include #include #include #include "kylinnetworkresourcetype.h" #include "kywirelessconnectoperation.h" #define KEY_CONNECTION "connection" #define KEY_CONNECT_TYPE "type" #define ETHERNET_TYPE "802-3-ethernet" QString getConnectTypeByDbus(QString connectPath); QString getSsidFromByteArray(QByteArray &rawSsid); QString enumToQstring(NetworkManager::AccessPoint::Capabilities cap, NetworkManager::AccessPoint::WpaFlags wpa_flags,NetworkManager::AccessPoint::WpaFlags rsn_flags); void setWiredEnabledByGDbus(bool enabled); void setDeviceManagedByGDbus(QString dbusPath, bool managed); bool getWiredEnabledByGDbus(); #endif // KYLINUTIL_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylingeneral.cpp0000664000175000017500000000777115160517205024664 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylingeneral.h" #include "kylinnetworkdeviceresource.h" #include "kylinactiveconnectresource.h" #include "kylinnetworkmanagerutil.h" KylinGeneralOpration::KylinGeneralOpration(QObject *parent) : QObject(parent) { m_networkResourceInstance = KyNetworkResourceManager::getInstance(); connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiEnabledChanged, this, &KylinGeneralOpration::wifiEnabledChanged); connect(m_networkResourceInstance, &KyNetworkResourceManager::networkingEnabledChanged, this, &KylinGeneralOpration::networkingEnabledChanged); connect(m_networkResourceInstance, &KyNetworkResourceManager::primaryConnectionTypeChanged, this, &KylinGeneralOpration::updateConnectStatus); connect(m_networkResourceInstance, &KyNetworkResourceManager::connectivityChanged, this, &KylinGeneralOpration::updateConnectStatus); connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredEnabledChanged, this, &KylinGeneralOpration::wiredEnabledChanged); } KylinGeneralOpration::~KylinGeneralOpration() { m_networkResourceInstance = nullptr; } void KylinGeneralOpration::getConnectStatus(KyConnectStatus &status) { updateConnectStatus(); status = m_status; } void KylinGeneralOpration::updateConnectStatus() { KyConnectStatus status; KyConnectionType connectType; KyActiveConnectResourse activeResource; getPrimaryConnectionType(connectType); if (activeResource.wiredConnectIsActived()) { status = LAN_CONNECTED; } else if (activeResource.wirelessConnectIsActived()) { status = WLAN_CONNECTED; } else { status = NOT_CONNECTED; } KyConnectivity connecttivity; getConnectivity(connecttivity); if (connecttivity != CONNECTIVITY_FULL) { if (status == LAN_CONNECTED) { status = LAN_CONNECTED_LIMITED; } else if (status == WLAN_CONNECTED) { status = WLAN_CONNECTED_LIMITED; } } if (status != m_status) { m_status = status; Q_EMIT connectStatusChanged(m_status); } } void KylinGeneralOpration::getConnectivity(KyConnectivity &connectivity) { connectivity = (KyConnectivity)NetworkManager::connectivity(); } void KylinGeneralOpration::getPrimaryConnectionType(KyConnectionType &connectType) { connectType = (KyConnectionType)NetworkManager::primaryConnectionType(); } bool KylinGeneralOpration::getWirelessEnabled() { return NetworkManager::isWirelessEnabled(); } void KylinGeneralOpration::setWirelessNetworkEnabled(bool enabled) { NetworkManager::setWirelessEnabled(enabled); } bool KylinGeneralOpration::getNetworkingEnabled() { return NetworkManager::isNetworkingEnabled(); } void KylinGeneralOpration::setNetworkingEnabled(bool enabled) { NetworkManager::setNetworkingEnabled(enabled); } void KylinGeneralOpration::setWiredEnabled(bool enabled) { setWiredEnabledByGDbus(enabled); } bool KylinGeneralOpration::getWiredEnabled() { return getWiredEnabledByGDbus(); } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyapnetresource.cpp0000664000175000017500000001245615160517205025417 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kyapnetresource.h" #include "kylinnetworkdeviceresource.h" #include "kywirelessconnectoperation.h" #include "kylinnetworkmanagerutil.h" const QString str2GBand = "2.4Ghz"; const QString str5GBand = "5Ghz"; KyApNetResource::KyApNetResource(QObject *parent) : QObject(parent) { m_networkResourceInstance = KyNetworkResourceManager::getInstance(); connect(m_networkResourceInstance, &KyNetworkResourceManager::wirelessApConnectStateChange, this, &KyApNetResource::wirelessApConnectStateChange); } KyApNetResource::~KyApNetResource() { m_networkResourceInstance = nullptr; } KyApConnectItem KyApNetResource::getApConnectItem(NetworkManager::Connection::Ptr connectPtr) { if (nullptr == connectPtr) { qWarning()<<"[KyConnectResourse]"<<"get bluetooth connection item failed, the connect is empty"; return KyApConnectItem(); } NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); NetworkManager::WirelessSetting::Ptr wirelessSetting = settingPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); if (NetworkManager::WirelessSetting::NetworkMode::Ap != wirelessSetting->mode()) { qWarning() << "[KyConnectResourse]" <<"get ap item failed, the active connect mode is not ap."; return KyApConnectItem(); } KyNetworkDeviceResourse deviceResource; if (!deviceResource.wirelessDeviceIsExist(settingPtr->interfaceName())) { qWarning() << "[KyConnectResourse]" <<"get ap item failed, the ap device is not exist yet"; return KyApConnectItem(); } QByteArray rawSsid = wirelessSetting->ssid(); KyApConnectItem apConnectItem; apConnectItem.m_connectName = connectPtr->name(); apConnectItem.m_connectSsid = getSsidFromByteArray(rawSsid); apConnectItem.m_connectUuid = connectPtr->uuid(); if (wirelessSetting->band() == NetworkManager::WirelessSetting::FrequencyBand::A) { apConnectItem.m_band = str2GBand; } else if (wirelessSetting->band() == NetworkManager::WirelessSetting::FrequencyBand::Bg) { apConnectItem.m_band = str5GBand; } apConnectItem.m_ifaceName = settingPtr->interfaceName(); apConnectItem.m_isActivated = KyNetworkResourceManager::getInstance()->isActiveConnection(connectPtr->uuid()); //NetworkManager::WirelessSecuritySetting::Ptr wirelessSecuritySetting // = settingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); KyWirelessConnectOperation wirelessOperation; apConnectItem.m_password = wirelessOperation.getPsk(apConnectItem.m_connectUuid);// wirelessSecuritySetting->psk(); return apConnectItem; } KyApConnectItem KyApNetResource::getApConnectionByUuid(QString connectUuid) { NetworkManager::Connection::Ptr connectPtr = nullptr; connectPtr = KyNetworkResourceManager::getInstance()->findConnectByUuid(connectUuid); if (nullptr == connectPtr) { return KyApConnectItem(); } if (NetworkManager::ConnectionSettings::ConnectionType::Wireless != connectPtr->settings()->connectionType()) { return KyApConnectItem(); } KyApConnectItem connectItem = getApConnectItem(connectPtr); return connectItem; } void KyApNetResource::getApConnections(QList &apConnectItemList) { QList apActiveConnectItemList; QList apDeactiveConnectItemList; NetworkManager::Connection::List connectList; connectList.clear(); connectList = KyNetworkResourceManager::getInstance()->getConnectList(); if (connectList.empty()) { qWarning()<<"[KyConnectResourse]"<<"get ap connections failed, the connect list is empty"; return; } NetworkManager::Connection::Ptr connectPtr = nullptr; for (int index = 0; index < connectList.size(); index++) { connectPtr = connectList.at(index); if (NetworkManager::ConnectionSettings::ConnectionType::Wireless != connectPtr->settings()->connectionType()) { continue; } KyApConnectItem connectItem = getApConnectItem(connectPtr); if (connectItem.m_isActivated) { apActiveConnectItemList << connectItem; } else { apDeactiveConnectItemList << connectItem; } } apConnectItemList << apActiveConnectItemList << apDeactiveConnectItemList; return; } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinactiveconnectresource.cpp0000664000175000017500000002535315160517205027640 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinactiveconnectresource.h" #include "kywirelessconnectoperation.h" #include "kylinnetworkmanagerutil.h" #include "kylinnetworkdeviceresource.h" #include #include #include #define LOG_FLAG "[KyActiveConnectResourse]" KyActiveConnectResourse::KyActiveConnectResourse(QObject *parent) : QObject(parent) { m_networkResourceInstance = KyNetworkResourceManager::getInstance(); connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredConnectStateChange, this, &KyActiveConnectResourse::wiredStateChange); connect(m_networkResourceInstance, &KyNetworkResourceManager::wirelessConnectStateChange, this, &KyActiveConnectResourse::wirelessStateChange); } KyActiveConnectResourse::~KyActiveConnectResourse() { m_networkResourceInstance = nullptr; } KyActivateItem KyActiveConnectResourse::getActiveConnectionItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr) { if (nullptr == activeConnectPtr) { qWarning() << LOG_FLAG <<"the active connect is empty"; return KyActivateItem(); } if (NetworkManager::ActiveConnection::State::Activated != activeConnectPtr->state()) { return KyActivateItem(); } KyActivateItem activeConnectItem; activeConnectItem.m_uuid = activeConnectPtr->uuid(); NetworkManager::Connection::Ptr connectPtr = activeConnectPtr->connection(); activeConnectItem.m_connName = connectPtr->name(); activeConnectItem.m_dbusPath = connectPtr->path(); if (activeConnectPtr->type() == CONNECT_TYPE_WIRELESS) { NetworkManager::WirelessSetting::Ptr wireless_sett = connectPtr->settings()->setting(NetworkManager::Setting::Wireless).dynamicCast(); QByteArray rawSsid = wireless_sett->ssid(); activeConnectItem.m_ssid = getSsidFromByteArray(rawSsid); } activeConnectItem.m_connStatus = CONNECT_STATE_ACTIVATED; return activeConnectItem; } void KyActiveConnectResourse::getActiveConnectionList(QString deviceName, KyConnectionType connectionType, QList &activeConnectItemList) { NetworkManager::ActiveConnection::List activeConnectList = m_networkResourceInstance->getActiveConnectList(); if (activeConnectList.isEmpty()) { qWarning() << LOG_FLAG <<"the active connect list is empty"; return; } NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; for (int index = 0; index < activeConnectList.size(); index++) { activeConnectPtr = nullptr; activeConnectPtr = activeConnectList.at(index); if (activeConnectPtr.isNull()) { continue; } if (connectionType != activeConnectPtr->type()) { continue; } QStringList interfaces = activeConnectPtr->devices(); for (int index = 0; index < interfaces.size(); ++index) { QString ifaceUni = interfaces.at(index); NetworkManager::Device:: Ptr devicePtr = m_networkResourceInstance->findDeviceByUni(ifaceUni); if (devicePtr->interfaceName() == deviceName) { KyActivateItem activeConnectItem = getActiveConnectionItem(activeConnectPtr); activeConnectItem.m_interface = deviceName; activeConnectItemList << activeConnectItem; break; } } } } //动态ip地址 void KyActiveConnectResourse::getActiveConnectIpInfo( const QString &connectUuid, QString &ipv4Address, QString &ipv6Address) { ipv4Address.clear(); ipv6Address.clear(); NetworkManager::ActiveConnection::Ptr activeConnectPtr = m_networkResourceInstance->findActiveConnectByUuid(connectUuid); if (activeConnectPtr.isNull()) { qWarning() << LOG_FLAG <<"it can not find connect "<< connectUuid; return; } getActiveConnectIp(activeConnectPtr, ipv4Address, ipv6Address); } void KyActiveConnectResourse::getActiveConnectIp( NetworkManager::ActiveConnection::Ptr activeConnectPtr, QString &ipv4Address, QString &ipv6Address) { NetworkManager::IpConfig ipv4Config =activeConnectPtr->ipV4Config(); if (ipv4Config.isValid()) { if (!ipv4Config.addresses().isEmpty()) { NetworkManager::IpAddress address = ipv4Config.addresses().at(0); ipv4Address = address.ip().toString(); } else { qWarning()<<"[KyActiveConnectResourse]"<<"the ipv4 address is empty."; } } else { qWarning()<<"[KyActiveConnectResourse]"<<"ipv4 config is not valid"; } NetworkManager::IpConfig ipv6Config =activeConnectPtr->ipV6Config(); if (ipv6Config.isValid()) { if (!ipv6Config.addresses().isEmpty()) { NetworkManager::IpAddress address = ipv6Config.addresses().at(0); ipv6Address = address.ip().toString(); } else { qWarning()<<"[KyActiveConnectResourse]"<<"ipv6 address is empty"; } } else { qWarning()<<"[KyActiveConnectResourse]"<<"ipv6 config is not valid"; } } void KyActiveConnectResourse::getActiveConnectDnsInfo( const QString &connectUuid, QList &ipv4Dns, QList &ipv6Dns) { NetworkManager::ActiveConnection::Ptr activeConnectPtr = m_networkResourceInstance->findActiveConnectByUuid(connectUuid); if (activeConnectPtr.isNull()) { qWarning()<< "[KyActiveConnectResourse]" <<"it can not find connect "<< connectUuid; return; } getActiveConnectDns(activeConnectPtr, ipv4Dns, ipv6Dns); } void KyActiveConnectResourse::getActiveConnectDns( NetworkManager::ActiveConnection::Ptr activeConnectPtr, QList &ipv4Dns, QList &ipv6Dns) { NetworkManager::IpConfig ipv4Config = activeConnectPtr->ipV4Config(); if (ipv4Config.isValid()) { ipv4Dns = ipv4Config.nameservers(); } else { qWarning()<<"[KyActiveConnectResourse]"<<"ipv4 config is not valid"; } NetworkManager::IpConfig ipv6Config =activeConnectPtr->ipV6Config(); if (ipv6Config.isValid()) { ipv6Dns = ipv6Config.nameservers(); } else { qWarning()<<"[KyActiveConnectResourse]"<<"ipv6 config is not valid"; } return; } bool KyActiveConnectResourse::wiredConnectIsActived() { int index = 0; NetworkManager::ActiveConnection::List activeConnectList; activeConnectList.clear(); activeConnectList = m_networkResourceInstance->getActiveConnectList(); if (activeConnectList.empty()) { qWarning()<<"[KyActiveConnectResourse]" <<"get active connect failed, the active connect list is empty"; return false; } NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; for (index = 0; index < activeConnectList.size(); index++) { activeConnectPtr = activeConnectList.at(index); if (activeConnectPtr.isNull()) { continue; } if (NetworkManager::ConnectionSettings::ConnectionType::Wired != activeConnectPtr->type()) { continue; } QString path = activeConnectPtr->connection()->path(); if (!m_networkResourceInstance->isWiredConnect(path)) { continue; } if (activeConnectPtr->state() == NetworkManager::ActiveConnection::State::Activated) { return true; } } return false; } bool KyActiveConnectResourse::wirelessConnectIsActived() { int index = 0; NetworkManager::ActiveConnection::List activeConnectList; activeConnectList.clear(); activeConnectList = m_networkResourceInstance->getActiveConnectList(); if (activeConnectList.empty()) { qWarning()<<"[KyActiveConnectResourse]" <<"get active connect failed, the active connect list is empty"; return false; } NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; for (index = 0; index < activeConnectList.size(); index++) { activeConnectPtr = activeConnectList.at(index); if (activeConnectPtr.isNull()) { continue; } if (NetworkManager::ConnectionSettings::ConnectionType::Wireless != activeConnectPtr->type()) { continue; } if (activeConnectPtr->state() == NetworkManager::ActiveConnection::State::Activated) { return true; } } return false; } int KyActiveConnectResourse::getAcivateWifiSignal() { int signalStrength = 0; KyNetworkDeviceResourse devResource; QStringList devList; devResource.getNetworkDeviceList(DEVICE_TYPE_WIFI, devList); for (int i = 0; i < devList.size(); ++i) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceByName(devList.at(i)); if (nullptr == connectDevice || !connectDevice->isValid()) { qWarning()<< LOG_FLAG <<"getDeviceActiveAPInfo failed, the device" << devList.at(i) << "is not existed"; continue; } if (connectDevice->type() == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice *wirelessDevicePtr = qobject_cast(connectDevice.data()); NetworkManager::AccessPoint::Ptr apPtr = wirelessDevicePtr->activeAccessPoint(); if (apPtr.isNull()) { continue; } signalStrength = apPtr->signalStrength(); break; } } return signalStrength; } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetresource.h0000664000175000017500000000420615160517205025240 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYNETRESOURCE_H #define KYNETRESOURCE_H #include "kylinnetworkresourcemanager.h" #include "kylinconnectsetting.h" #include #include class KyDetailInfo { public: QString strSecType; QString strChan; QString strMac; QString strHz; QString strBandWidth; QString strDynamicIpv4; QString strDynamicIpv6; QString strDynamicIpv4Dns; bool isAutoConnect = false; }; class KyNetResource : public QObject { Q_OBJECT public: explicit KyNetResource(QObject *parent = nullptr); ~KyNetResource(); void getConnectionSetting(QString connectUuid, KyConnectSetting &connectSetting); protected: KyNetworkResourceManager *m_networkResourceInstance = nullptr; void getBaseInfo(QString devName,QString ssid, bool isWlan, bool isActive, KyDetailInfo &conInfo); void getDynamicIpInfo(QString uuid, KyDetailInfo &conInfo); private: void getIpv4ConnectSetting(NetworkManager::Ipv4Setting::Ptr &ipv4Setting, KyConnectSetting &connectSetting); void getIpv6ConnectSetting(NetworkManager::Ipv6Setting::Ptr &ipv6Setting, KyConnectSetting &connectSetting); }; #endif // KYNETRESOURCE_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetresource.cpp0000664000175000017500000001356415160517205025602 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinnetresource.h" #include "kylinnetworkdeviceresource.h" #include "kylinactiveconnectresource.h" #include "kywirelessnetresource.h" #include "kylinnetworkmanagerutil.h" KyNetResource::KyNetResource(QObject *parent) : QObject(parent) { m_networkResourceInstance = KyNetworkResourceManager::getInstance(); } KyNetResource::~KyNetResource() { m_networkResourceInstance = nullptr; } void KyNetResource::getIpv4ConnectSetting( NetworkManager::Ipv4Setting::Ptr &ipv4Setting, KyConnectSetting &connectSetting) { if (NetworkManager::Ipv4Setting::Automatic == ipv4Setting->method()) { connectSetting.m_ipv4ConfigIpType = CONFIG_IP_DHCP; return; } connectSetting.m_ipv4ConfigIpType = CONFIG_IP_MANUAL; connectSetting.m_ipv4Address = ipv4Setting->addresses(); connectSetting.m_ipv4Dns = ipv4Setting->dns(); } void KyNetResource::getIpv6ConnectSetting( NetworkManager::Ipv6Setting::Ptr &ipv6Setting, KyConnectSetting &connectSetting) { if (NetworkManager::Ipv6Setting::Automatic == ipv6Setting->method()) { connectSetting.m_ipv6ConfigIpType = CONFIG_IP_DHCP; return; } connectSetting.m_ipv6ConfigIpType = CONFIG_IP_MANUAL; connectSetting.m_ipv6Address = ipv6Setting->addresses(); connectSetting.m_ipv6Dns = ipv6Setting->dns(); } void KyNetResource::getConnectionSetting(QString connectUuid, KyConnectSetting &connectSetting) { NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->findConnectByUuid(connectUuid); if (nullptr == connectPtr || !connectPtr->isValid()) { qWarning() <<"[KyConnectResourse]" << "it can not find valid connection" << connectUuid; return; } connectSetting.m_connectName = connectPtr->name(); NetworkManager::ConnectionSettings::Ptr connectionSettings = connectPtr->settings(); connectSetting.m_ifaceName = connectionSettings->interfaceName(); connectSetting.m_isAutoConnect = connectionSettings->autoconnect(); NetworkManager::Ipv4Setting::Ptr ipv4Setting = connectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); getIpv4ConnectSetting(ipv4Setting, connectSetting); NetworkManager::Ipv6Setting::Ptr ipv6Setting = connectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); getIpv6ConnectSetting(ipv6Setting, connectSetting); } void KyNetResource::getBaseInfo(QString devName,QString ssid, bool isWlan, bool isActive, KyDetailInfo &conInfo) { //有线无线公有 KyNetworkDeviceResourse devResource; QString hardAddress; int bandWith; devResource.getHardwareInfo(devName, hardAddress, bandWith); if (!hardAddress.isEmpty()) { conInfo.strBandWidth = QString("%1").arg(bandWith/1000) + "Mbps"; conInfo.strMac = hardAddress; } if (isWlan) { if (!isActive) { NetworkManager::Device::Ptr devPtr = KyNetworkResourceManager::getInstance()->findDeviceByName(devName); if (devPtr.isNull()) { return; } NetworkManager::WirelessNetwork::Ptr netPtr = KyNetworkResourceManager::getInstance()->findWifiNetwork(ssid, devPtr->uni()); if (netPtr.isNull()) { return; } NetworkManager::AccessPoint::Ptr bestApPtr = netPtr->referenceAccessPoint(); conInfo.strHz = QString::number(bestApPtr->frequency()) + "MHz"; conInfo.strChan = QString::number(NetworkManager::findChannel(bestApPtr->frequency())); NetworkManager::AccessPoint::Capabilities cap = bestApPtr->capabilities(); NetworkManager::AccessPoint::WpaFlags wpaFlag = bestApPtr->wpaFlags(); NetworkManager::AccessPoint::WpaFlags rsnFlag = bestApPtr->rsnFlags(); conInfo.strSecType = enumToQstring(cap, wpaFlag, rsnFlag); } else { uint iHz,iChan; QString strMac; devResource.getDeviceActiveAPInfo(devName, strMac, iHz, iChan, conInfo.strSecType); conInfo.strHz = QString::number(iHz); conInfo.strChan = QString::number(iChan); } if (conInfo.strSecType.isEmpty()) { conInfo.strSecType = tr("None"); } } } //详情ipv4 ipv6 ipv4Dns void KyNetResource::getDynamicIpInfo(QString uuid, KyDetailInfo &conInfo) { //已激活的网络 详情页显示动态ipv4 ipv6 dns QString ipv4,ipv6; QList ipv4Dns,ipv6Dns; KyActiveConnectResourse activeResourse; activeResourse.getActiveConnectIpInfo(uuid,ipv4,ipv6); activeResourse.getActiveConnectDnsInfo(uuid,ipv4Dns,ipv6Dns); //Ipv6 if (!ipv6.isEmpty()) { conInfo.strDynamicIpv6 = ipv6; } //IPv4 if (!ipv4.isEmpty()) { conInfo.strDynamicIpv4 = ipv4; } if (!ipv4Dns.isEmpty()) { conInfo.strDynamicIpv4Dns = ipv4Dns.at(0).toString(); } } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyenterpricesettinginfo.cpp0000664000175000017500000003725615160517205027157 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kyenterpricesettinginfo.h" void assembleEapMethodTlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTlsInfo &info) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodTls); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setIdentity(info.identity); if (!info.domain.isEmpty()){ wifi_8021x_sett->setDomainSuffixMatch(info.domain); } if (info.bNeedCa) { QByteArray caCerEndWithNull("file://" + info.caCertPath.toUtf8() + '\0'); wifi_8021x_sett->setCaCertificate(caCerEndWithNull); } else { QByteArray caCerEndWithNull(""); wifi_8021x_sett->setCaCertificate(caCerEndWithNull); } QByteArray cliCertEndWithNull("file://" + info.clientCertPath.toUtf8() + '\0'); wifi_8021x_sett->setClientCertificate(cliCertEndWithNull); QByteArray cliPriKeyEndWithNull("file://" + info.clientPrivateKey.toUtf8() + '\0'); wifi_8021x_sett->setPrivateKey(cliPriKeyEndWithNull); wifi_8021x_sett->setPrivateKeyPassword(info.clientPrivateKeyPWD); wifi_8021x_sett->setPrivateKeyPasswordFlags(info.m_privateKeyPWDFlag); NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); return; } void assembleEapMethodPeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPeapInfo &info) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodPeap); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)info.phase2AuthMethod); wifi_8021x_sett->setIdentity(info.userName); wifi_8021x_sett->setPassword(info.userPWD); wifi_8021x_sett->setPasswordFlags(info.m_passwdFlag); NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); return; } void assembleEapMethodTtlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTtlsInfo &info) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodTtls); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); if (info.authType == KyTtlsAuthMethod::AUTH_EAP) { wifi_8021x_sett->setPhase2AuthEapMethod((NetworkManager::Security8021xSetting::AuthEapMethod)info.authEapMethod);//gtc md5 mschapv2 otp tls } else if (info.authType == KyTtlsAuthMethod::AUTH_NO_EAP) { wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)info.authNoEapMethod);//chap md5 mschapv2 pap gtc mschap otp tls } wifi_8021x_sett->setIdentity(info.userName); wifi_8021x_sett->setPassword(info.userPWD); wifi_8021x_sett->setPasswordFlags(info.m_passwdFlag); NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); return; } void modifyEapMethodTlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTlsInfo &tlsInfo) { NetworkManager::Security8021xSetting::Ptr setting = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); setting->setInitialized(true); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodTls); setting->setEapMethods(list); setting->setIdentity(tlsInfo.identity); if(!tlsInfo.domain.isEmpty()) { setting->setDomainSuffixMatch(tlsInfo.domain); } if (tlsInfo.bNeedCa) { QByteArray caCerEndWithNull("file://" + tlsInfo.caCertPath.toUtf8() + '\0'); setting->setCaCertificate(caCerEndWithNull); } else { QByteArray caCerEndWithNull(""); setting->setCaCertificate(caCerEndWithNull); } QByteArray cliCertEndWithNull("file://" + tlsInfo.clientCertPath.toUtf8() + '\0'); setting->setClientCertificate(cliCertEndWithNull); QByteArray cliPriKeyEndWithNull("file://" + tlsInfo.clientPrivateKey.toUtf8() + '\0'); setting->setPrivateKey(cliPriKeyEndWithNull); setting->setPrivateKeyPasswordFlags(tlsInfo.m_privateKeyPWDFlag); if(tlsInfo.bChanged) { setting->setPrivateKeyPassword(tlsInfo.clientPrivateKeyPWD); } return; } void modifyEapMethodPeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPeapInfo &peapInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); wifi_8021x_sett->setInitialized(true); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodPeap); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)peapInfo.phase2AuthMethod); wifi_8021x_sett->setIdentity(peapInfo.userName); if(peapInfo.bChanged) { wifi_8021x_sett->setPassword(peapInfo.userPWD); } wifi_8021x_sett->setPasswordFlags(peapInfo.m_passwdFlag); QByteArray caCerEndWithNull(""); wifi_8021x_sett->setCaCertificate(caCerEndWithNull); return; } void modifyEapMethodTtlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTtlsInfo &ttlsInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodTtls); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); if (ttlsInfo.authType == KyTtlsAuthMethod::AUTH_EAP) { wifi_8021x_sett->setPhase2AuthEapMethod((NetworkManager::Security8021xSetting::AuthEapMethod)ttlsInfo.authEapMethod);//gtc md5 mschapv2 otp tls } else if (ttlsInfo.authType == KyTtlsAuthMethod::AUTH_NO_EAP) { wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)ttlsInfo.authNoEapMethod);//chap md5 mschapv2 pap gtc mschap otp tls } wifi_8021x_sett->setIdentity(ttlsInfo.userName); if(ttlsInfo.bChanged) { wifi_8021x_sett->setPassword(ttlsInfo.userPWD); } wifi_8021x_sett->setPasswordFlags(ttlsInfo.m_passwdFlag); QByteArray caCerEndWithNull(""); wifi_8021x_sett->setCaCertificate(caCerEndWithNull); return; } void assembleEapMethodLeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodLeapInfo &leapInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodLeap); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setIdentity(leapInfo.m_userName); wifi_8021x_sett->setPassword(leapInfo.m_userPwd); wifi_8021x_sett->setPasswordFlags(leapInfo.m_passwdFlag); NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); return; } void assembleEapMethodPwdSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPwdInfo &pwdInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodPwd); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setIdentity(pwdInfo.m_userName); wifi_8021x_sett->setPassword(pwdInfo.m_userPwd); wifi_8021x_sett->setPasswordFlags(pwdInfo.m_passwdFlag); NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); return; } void assembleEapMethodFastSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodFastInfo &fastInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodFast); wifi_8021x_sett->setInitialized(true); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setAnonymousIdentity(fastInfo.m_anonIdentity); if (fastInfo.m_allowAutoPacFlag) { wifi_8021x_sett->setPhase1FastProvisioning((NetworkManager::Security8021xSetting::FastProvisioning)fastInfo.m_pacProvisioning); } else { wifi_8021x_sett->setPhase1FastProvisioning(NetworkManager::Security8021xSetting::FastProvisioning::FastProvisioningDisabled); } QByteArray pacEndWithNull("file://" + fastInfo.m_pacFilePath.toUtf8() + '\0'); wifi_8021x_sett->setPacFile(pacEndWithNull); wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)fastInfo.m_authMethod); wifi_8021x_sett->setIdentity(fastInfo.m_userName); wifi_8021x_sett->setPassword(fastInfo.m_userPwd); wifi_8021x_sett->setPasswordFlags(fastInfo.m_passwdFlag); NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); return; } void modifyEapMethodLeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodLeapInfo &leapInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); wifi_8021x_sett->setInitialized(true); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodLeap); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setIdentity(leapInfo.m_userName); if(leapInfo.bChanged) { wifi_8021x_sett->setPassword(leapInfo.m_userPwd); } wifi_8021x_sett->setPasswordFlags(leapInfo.m_passwdFlag); QByteArray caCerEndWithNull(""); wifi_8021x_sett->setCaCertificate(caCerEndWithNull); return; } void modifyEapMethodPwdSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPwdInfo &pwdInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); wifi_8021x_sett->setInitialized(true); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodPwd); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setIdentity(pwdInfo.m_userName); if(pwdInfo.bChanged) { wifi_8021x_sett->setPassword(pwdInfo.m_userPwd); } wifi_8021x_sett->setPasswordFlags(pwdInfo.m_passwdFlag); QByteArray caCerEndWithNull(""); wifi_8021x_sett->setCaCertificate(caCerEndWithNull); return; } void modifyEapMethodFastSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodFastInfo &fastInfo) { NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); wifi_8021x_sett->setInitialized(true); QList list; list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodFast); wifi_8021x_sett->setEapMethods(list); wifi_8021x_sett->setAnonymousIdentity(fastInfo.m_anonIdentity); if (fastInfo.m_allowAutoPacFlag) { wifi_8021x_sett->setPhase1FastProvisioning((NetworkManager::Security8021xSetting::FastProvisioning)fastInfo.m_pacProvisioning); } else { wifi_8021x_sett->setPhase1FastProvisioning(NetworkManager::Security8021xSetting::FastProvisioning::FastProvisioningDisabled); } QByteArray pacEndWithNull("file://" + fastInfo.m_pacFilePath.toUtf8() + '\0'); wifi_8021x_sett->setPacFile(pacEndWithNull); wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)fastInfo.m_authMethod); wifi_8021x_sett->setIdentity(fastInfo.m_userName); if(fastInfo.bChanged) { wifi_8021x_sett->setPassword(fastInfo.m_userPwd); } wifi_8021x_sett->setPasswordFlags(fastInfo.m_passwdFlag); return; } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyapnetresource.h0000664000175000017500000000300215160517205025047 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYAPNETRESOURCE_H #define KYAPNETRESOURCE_H #include #include "kylinapconnectitem.h" #include "kylinnetworkresourcemanager.h" class KyApNetResource : public QObject { Q_OBJECT public: explicit KyApNetResource(QObject *parent = nullptr); ~KyApNetResource(); void getApConnections(QList &apConnectItemList); Q_SIGNALS: void wirelessApConnectStateChange(); private: KyApConnectItem getApConnectItem(NetworkManager::Connection::Ptr connectPtr); KyApConnectItem getApConnectionByUuid(QString connectUuid); KyNetworkResourceManager *m_networkResourceInstance = nullptr; }; #endif // KYAPNETRESOURCE_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kynetloadratethread.cpp0000664000175000017500000001002015160517205026213 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kynetloadratethread.h" #include #define UPDATE_LOADRATE_TIMER 1000 KyNetLoadRateThread::KyNetLoadRateThread(QString dev, QObject *parent) :m_deviceName(dev), QThread(parent) { } KyNetLoadRateThread::~KyNetLoadRateThread() { } void KyNetLoadRateThread::run() { m_updateRatesTimer = new QTimer(this); m_updateRatesTimer->setTimerType(Qt::PreciseTimer); connect(m_updateRatesTimer, &QTimer::timeout, [&]() { updateLoadRate(); }); m_updateRatesTimer->start(UPDATE_LOADRATE_TIMER); exec(); } void KyNetLoadRateThread::updateLoadRate() { if (getCurrentLoadRate(m_deviceName, &m_startRcvRate, &m_startTxRate) == -1) { m_startRcvRate = m_endRcvRate; return; } m_deltaRcv = (m_startRcvRate - m_endRcvRate) / 1024; m_deltaTx = (m_startTxRate - m_endTxRate) / 1024; //简易滤波 if (m_deltaRcv < 0 || m_deltaTx < 0) { m_deltaRcv = 0; m_deltaTx = 0; } else if (m_endRcvRate == 0 || m_endTxRate == 0){ m_deltaRcv = 0; m_deltaTx = 0; } m_endRcvRate = m_startRcvRate; m_endTxRate = m_startTxRate; } int KyNetLoadRateThread::getCurrentLoadRate(QString dev, long *saveRate, long *txRate) { FILE * netDevFile; //文件指针 char buffer[1024]; //文件中的内容暂存在字符缓冲区里 //size_t bytes_read; //实际读取的内容大小 char * match; //用以保存所匹配字符串及之后的内容 char * device;//将QString转为Char * QByteArray ba = dev.toLatin1(); // must device = ba.data(); int counter = 0; unsigned int buffSize=0; char tmpValue[128]; if ((NULL == device) || (NULL == saveRate) || (NULL == txRate)) { qDebug() << "LOG_FLAG" << "parameter pass error" ; return -1; } if ((netDevFile = fopen("/proc/net/dev", "r")) == NULL) { //打开文件/pro/net/dev/,从中读取流量数据 qDebug() << "LOG_FLAG" << "error occurred when try to open file /proc/net/dev/"; return -1; } memset(buffer, 0, sizeof(buffer)); while (fgets(buffer, sizeof(buffer), netDevFile) != NULL) { match = strstr(buffer, device); if (NULL == match) { // qDebug()<<"No eth0 keyword to find!"; continue; } else { match = match + qstrnlen(device,1024) + qstrnlen(":",1024); //地址偏移到冒号 sscanf(match, "%ld ", saveRate); memset(tmpValue, 0, sizeof(tmpValue)); sscanf(match, "%s ", tmpValue); match = match + qstrnlen(tmpValue,128); buffSize=qstrnlen(buffer,1024); for (size_t i = 0; i < buffSize; ++i) { if (0x20 == *match) { match++; } else { if (8 == counter) { sscanf(match, "%ld ", txRate); } memset(tmpValue, 0, sizeof(tmpValue)); sscanf(match, "%s ", tmpValue); match = match + qstrnlen(tmpValue,128); counter++; } } } } fclose(netDevFile); netDevFile = nullptr; return 0; //返回成功 } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectsetting.h0000664000175000017500000000442715160517205025736 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINCONNECTSETTING_H #define KYLINCONNECTSETTING_H #include #include //#include #include #include #include #include #include typedef enum { CONFIG_IP_MANUAL, CONFIG_IP_DHCP, }KyIpConfigType; typedef enum { IPADDRESS_V4, IPADDRESS_V6, }KyIpAddressType; class KyConnectSetting/* : public QObject*/ { // Q_OBJECT public: /* explicit*/ KyConnectSetting(/*QObject *parent = nullptr*/); ~KyConnectSetting(); public: void setIfaceName(QString &ifaceName); void setConnectName(QString &connectName); int setIpConfigType(KyIpAddressType ipType, KyIpConfigType configType); void ipv4AddressConstruct(QString &ipv4Address, QString &ipv4NetMask, QString &ipv4GateWay, QStringList &ipv4Dns); void ipv6AddressConstruct(QString &ipv6Address, QString &ipv6NetMask, QString &ipv6GateWay, QStringList &ipv6Dns); void dumpInfo(); public: QString m_connectName; QString m_ifaceName; KyIpConfigType m_ipv4ConfigIpType; QList m_ipv4Address; QList m_ipv4Dns; KyIpConfigType m_ipv6ConfigIpType; QList m_ipv6Address; QList m_ipv6Dns; bool m_isAutoConnect = true; }; #endif // KYLINCONNECTSETTING_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwirednetresource.cpp0000664000175000017500000001252715160517205026633 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinwirednetresource.h" #include "kywirelessconnectoperation.h" #include "kylinnetworkmanagerutil.h" #include #include #include #include #include static bool subLanListSort(const KyWiredItem info1, const KyWiredItem info2) { QString name1 = info1.m_connectName; QString name2 = info2.m_connectName; bool result = true; if (QString::compare(name1, name2, Qt::CaseInsensitive) > 0) { result = false; } return result; } static void lanListSort(QList &list) { std::sort(list.begin(), list.end(), subLanListSort); } KyWiredConnectResourse::KyWiredConnectResourse(QObject *parent) : KyNetResource(parent) { connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredConnectionAdd, this, &KyWiredConnectResourse::wiredConnectionAdd); connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredConnectionUpdate, this, &KyWiredConnectResourse::wiredConnectionUpdate); connect(m_networkResourceInstance, &KyNetworkResourceManager::connectionRemove, this, &KyWiredConnectResourse::connectionRemove); connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredDeviceAdd, this, &KyWiredConnectResourse::wiredDeviceAdd); connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredDeviceUpdate, this, &KyWiredConnectResourse::wiredDeviceUpdate); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceRemove, this, &KyWiredConnectResourse::deviceRemove); } //配合activeconnection 此处未单独区分已连接的wifi void KyWiredConnectResourse::getWiredList(QMap> &map) { map.clear(); kyWirdNetItemListInit(); if (m_wiredNetworkMap.isEmpty()) { return; } else { QMap >::iterator iter = m_wiredNetworkMap.begin(); while (iter != m_wiredNetworkMap.end()) { lanListSort(m_wiredNetworkMap[iter.key()]); iter++; } map = m_wiredNetworkMap; } } void KyWiredConnectResourse::getWiredConnectDetail(QString interface, QString uuid, KyDetailInfo &connectSetting) { getBaseInfo(interface, "", false, false, connectSetting); getDynamicIpInfo(uuid, connectSetting); } KyWiredItem KyWiredConnectResourse::getConnectionItem(NetworkManager::Connection::Ptr connectPtr) { if (nullptr == connectPtr) { qWarning()<<"[KyConnectResourse]"<<"the connect is empty"; return KyWiredItem(); } KyWiredItem connectionItem; connectionItem.m_connectName = connectPtr->name(); connectionItem.m_connectUuid = connectPtr->uuid(); connectionItem.m_connectPath = connectPtr->path(); return connectionItem; } void KyWiredConnectResourse::kyWirdNetItemListInit() { m_wiredNetworkMap.clear(); NetworkManager::Connection::List connectList = m_networkResourceInstance->getConnectList(); if (connectList.empty()) { qWarning()<<"[KyConnectResourse]"<<"kyWirdNetItemListInit failed, the connect list is empty"; return; } KyNetworkDeviceResourse deviceResource; QStringList devList; deviceResource.getNetworkDeviceList(DEVICE_TYPE_ETHERNET, devList); if (devList.isEmpty()) { qWarning()<<"[KyConnectResourse]"<<"kyWirdNetItemListInit failed, the device list is empty"; return; } else { for (int i = 0; i < devList.size(); ++i) { m_wiredNetworkMap.insert(devList.at(i), QList()); } } NetworkManager::Connection::Ptr connectPtr = nullptr; for (int index = 0; index < connectList.size(); index++) { connectPtr = connectList.at(index); if (connectPtr.isNull()) { continue; } if (!m_networkResourceInstance->isWiredConnect(connectPtr->path())) { continue; } KyWiredItem connectItem = getConnectionItem(connectPtr); if (connectItem.m_connectUuid.isEmpty()) { continue; } QString connectInterface = connectPtr->settings()->interfaceName(); if (connectInterface.isEmpty()) { for (int i = 0; i < m_wiredNetworkMap.keys().size(); ++i) { m_wiredNetworkMap[m_wiredNetworkMap.keys().at(i)] << connectItem; } } else { if (m_wiredNetworkMap.contains(connectInterface)) { m_wiredNetworkMap[connectInterface] << connectItem; } } } } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinactiveconnectresource.h0000664000175000017500000000537015160517205027302 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINACTIVECONNECTRESOURCE_H #define KYLINACTIVECONNECTRESOURCE_H #include #include "kylinnetworkresourcemanager.h" #include "kylinconnectitem.h" #include "kylinnetworkdeviceresource.h" #include "kylinapconnectitem.h" #include "kylinnetworkresourcetype.h" class KyActivateItem { public: QString m_interface; QString m_uuid; QString m_ssid; QString m_connName; QString m_dbusPath; KyConnectState m_connStatus; }; class KyActiveConnectResourse : public QObject { Q_OBJECT public: explicit KyActiveConnectResourse(QObject *parent = nullptr); ~KyActiveConnectResourse(); public: void getActiveConnectionList(QString deviceName, KyConnectionType connectionType, QList &connectItemList); void getActiveConnectIpInfo(const QString &uuid, QString &ipv4Address, QString &ipv6Address); void getActiveConnectDnsInfo(const QString &uuid, QList &ipv4Dns, QList &ipv6Dns); bool wiredConnectIsActived(); bool wirelessConnectIsActived(); int getAcivateWifiSignal(); private: void getActiveConnectIp(NetworkManager::ActiveConnection::Ptr activeConnectPtr, QString &ipv4Address, QString &ipv6Address); void getActiveConnectDns(NetworkManager::ActiveConnection::Ptr activeConnectPtr, QList &ipv4Dns, QList &ipv6Dns); KyActivateItem getActiveConnectionItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr); Q_SIGNALS: void wiredStateChange(QString deviceName, QString uuid, KyConnectState state); void wirelessStateChange(QString deviceName, QString ssid, QString uuid, KyConnectState state); private: KyNetworkResourceManager *m_networkResourceInstance = nullptr; }; #endif // KYLINACTIVECONNECTRESOURCE_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkmanagerutil.cpp0000664000175000017500000002207015160517205027156 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include "kylinnetworkmanagerutil.h" #include "kylinnetworkdeviceresource.h" #define LOG_FLAG "[kylin-util]" const QString CONFIG_FILE_PATH = QDir::homePath() + "/.config/ukui/kylin-nm.conf"; QString getConnectTypeByDbus(QString connectPath) { QString connectType = ""; if (connectPath.isEmpty()) { qWarning() << LOG_FLAG << "connect path is empty, so can not get connect type"; return connectType; } QDBusInterface dbusInterface("org.freedesktop.NetworkManager", connectPath, "org.freedesktop.NetworkManager.Settings.Connection", QDBusConnection::systemBus()); QDBusMessage result = dbusInterface.call("GetSettings"); const QDBusArgument &dbusArg1st = result.arguments().at( 0 ).value(); QMap> map; dbusArg1st >> map; if (map.isEmpty()) { qWarning() << LOG_FLAG <<"get connection settings failed."; return connectType; } QMap connectMap = map.value(KEY_CONNECTION); if (connectMap.isEmpty()) { qWarning() << LOG_FLAG <<"threre is not connection settings"; return connectType; } connectType = connectMap.value(KEY_CONNECT_TYPE).toString(); return connectType; } QString getSsidFromByteArray(QByteArray &rawSsid) { QString wifiSsid = ""; if (rawSsid.isEmpty()) { qWarning() << LOG_FLAG << "wifi raw ssid is empty"; return wifiSsid; } /* * 由于区分GB2312和UTF-8的方法比较困难,加之会存在中英文混合的情况,所以暂时 * 不区分,统一经过gb2312转换,经过测试没有影响。 */ // QTextCodec *p_textGBK = QTextCodec::codecForName("GB2312"); // wifiSsid = p_textGBK->toUnicode(rawSsid); QStringDecoder utf8Decoder(QStringDecoder::Utf8); wifiSsid = utf8Decoder(rawSsid); // 如果解码出错或包含替换字符,尝试GBK if (utf8Decoder.hasError() || wifiSsid.contains(QChar::ReplacementCharacter)) { QStringDecoder gbkDecoder("GBK"); if(gbkDecoder.isValid()){ wifiSsid = gbkDecoder(rawSsid); } //gbk不行回退到latin if(gbkDecoder.hasError()){ return QString::fromLatin1(rawSsid); } } return wifiSsid; } QString enumToQstring(NetworkManager::AccessPoint::Capabilities apCapability, NetworkManager::AccessPoint::WpaFlags wpaFlags, NetworkManager::AccessPoint::WpaFlags rsnFlags) { QString out; if ((apCapability & AP_CAPABILITY_PRIVACY) && (wpaFlags == AP_SECURITY_NONE) && (rsnFlags == AP_SECURITY_NONE)) { out += "WEP "; } if (wpaFlags != AP_SECURITY_NONE) { out += "WPA1 "; } if ((rsnFlags & AP_SECURITY_KEY_MGMT_PSK) || (rsnFlags & AP_SECURITY_KEY_MGMT_802_1X)) { out += "WPA2 "; } if (rsnFlags & AP_SECURITY_KEY_MGMT_SAE) { out += "WPA3 "; } if ((wpaFlags & AP_SECURITY_KEY_MGMT_802_1X) || (rsnFlags & AP_SECURITY_KEY_MGMT_802_1X)) { out += "802.1X "; } return out; } void setWiredEnabledByGDbus(bool enabled) { GDBusProxy *props_proxy; GVariant *ret = NULL; GError *error = NULL; /* Create a D-Bus object proxy for the active connection object's properties */ props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", "org.freedesktop.DBus.Properties", NULL, NULL); g_assert (props_proxy); /* Get the object path of the Connection details */ ret = g_dbus_proxy_call_sync (props_proxy, "Set", g_variant_new ("(ssv)", "org.freedesktop.NetworkManager", "WiredEnabled", g_variant_new_boolean(enabled)), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (!ret) { g_dbus_error_strip_remote_error (error); qDebug() << "failed to setWiredEnabledByGDbus"; g_error_free (error); } out: if (ret) g_variant_unref (ret); g_object_unref (props_proxy); } bool getWiredEnabledByGDbus() { GDBusProxy *props_proxy; GVariant *ret = NULL, *path_value = NULL; GError *error = NULL; gboolean bRet = false; /* Create a D-Bus object proxy for the active connection object's properties */ props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", "org.freedesktop.DBus.Properties", NULL, NULL); g_assert (props_proxy); /* Get the object path of the Connection details */ ret = g_dbus_proxy_call_sync (props_proxy, "Get", g_variant_new ("(ss)", "org.freedesktop.NetworkManager", "WiredEnabled"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (!ret) { g_dbus_error_strip_remote_error (error); qDebug() << "failed to setWiredEnabledByGDbus"; g_error_free (error); } g_variant_get (ret, "(v)", &path_value); if (!g_variant_is_of_type (path_value, G_VARIANT_TYPE_BOOLEAN)) { g_warning ("Unexpected type returned getting Connection property: %s", g_variant_get_type_string (path_value)); goto out; } bRet = g_variant_get_boolean (path_value); out: if (path_value) g_variant_unref (path_value); if (ret) g_variant_unref (ret); g_object_unref (props_proxy); return bRet; } void setDeviceManagedByGDbus(QString dbusPath, bool managed) { GDBusProxy *props_proxy; GVariant *ret = NULL; GError *error = NULL; /* Create a D-Bus object proxy for the active connection object's properties */ props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.NetworkManager", dbusPath.toStdString().c_str(), "org.freedesktop.DBus.Properties", NULL, NULL); g_assert (props_proxy); /* Get the object path of the Connection details */ ret = g_dbus_proxy_call_sync (props_proxy, "Set", g_variant_new ("(ssv)", "org.freedesktop.NetworkManager.Device", "Managed", g_variant_new_boolean(managed)), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (!ret) { g_dbus_error_strip_remote_error (error); qDebug() << "failed to setWiredEnabledByGDbus"; g_error_free (error); } out: if (ret) g_variant_unref (ret); g_object_unref (props_proxy); } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylingeneral.h0000664000175000017500000000405115160517205024315 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINGENERAL_H #define KYLINGENERAL_H #include #include "kylinnetworkresourcemanager.h" enum KyConnectStatus { NOT_CONNECTED = 0, LAN_CONNECTED, WLAN_CONNECTED, LAN_CONNECTED_LIMITED, WLAN_CONNECTED_LIMITED, }; class KylinGeneralOpration : public QObject { Q_OBJECT public: explicit KylinGeneralOpration(QObject *parent = nullptr); ~KylinGeneralOpration(); void getConnectStatus(KyConnectStatus &status); bool getWirelessEnabled(); void setWirelessNetworkEnabled(bool enabled); bool getNetworkingEnabled(); void setNetworkingEnabled(bool enabled); void setWiredEnabled(bool enabled); bool getWiredEnabled(); Q_SIGNALS: void connectStatusChanged(KyConnectStatus); void wifiEnabledChanged(bool); void wiredEnabledChanged(bool); void networkingEnabledChanged(bool); private Q_SLOTS: void updateConnectStatus(); private: KyNetworkResourceManager *m_networkResourceInstance = nullptr; KyConnectStatus m_status = NOT_CONNECTED; void updateGsetting(bool); void getConnectivity(KyConnectivity &connectivity); void getPrimaryConnectionType(KyConnectionType &connectType); }; #endif // KYLINGENERAL_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinapconnectitem.h0000664000175000017500000000232615160517205025534 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINAPCONNECTITEM_H #define KYLINAPCONNECTITEM_H #include class KyApConnectItem { public: QString m_connectName = ""; QString m_connectSsid = ""; QString m_connectUuid = ""; QString m_ifaceName = ""; QString m_password = ""; QString m_band = ""; bool m_isActivated = false; }; #endif // KYLINAPCONNECTITEM_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetresource.h0000664000175000017500000001037115160517205026313 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYWIRELESSNETRESOURCE_H #define KYWIRELESSNETRESOURCE_H #include #include "kylinnetresource.h" #include "kywirelessnetitem.h" #include "kylinnetworkresourcemanager.h" #include "kyenterpricesettinginfo.h" #include "kywirelessconnectoperation.h" #include "kylinactiveconnectresource.h" class KyWpaPasswordInfo{ public: QString pwd; NetworkManager::Setting::SecretFlags flag; }; class KyWirelessNetResource : public KyNetResource { Q_OBJECT public: explicit KyWirelessNetResource(QObject *parent = nullptr); public: //初始化列表用到的接口 void getWifiNetworkList(QString devName, QList &list); //属性页---->安全 bool getNormalWifiConnectSecuInfo(QString &uuid, KyWpaPasswordInfo &info); bool getEnterPriseInfoTls(QString &uuid, KyEapMethodTlsInfo &info); bool getEnterPriseInfoPeap(QString &uuid, KyEapMethodPeapInfo &info); bool getEnterPriseInfoTtls(QString &uuid, KyEapMethodTtlsInfo &info); bool getEnterPriseInfoLeap(QString &uuid, KyEapMethodLeapInfo &info); bool getEnterPriseInfoPwd(QString &uuid, KyEapMethodPwdInfo &info); bool getEnterPriseInfoFast(QString &uuid, KyEapMethodFastInfo &info); //获取企业网类型 bool getEnterpiseEapMethod(const QString &uuid, KyEapMethodType &type); void getWirelessConnectDetail(QString interface, QString ssid, QString uuid, KyDetailInfo &connectSetting); private: void kyWirelessNetItemListInit(); void wirelessNetItemInit(KyWirelessNetItem &wirelessItem, NetworkManager::WirelessNetwork::Ptr wirelessNetPtr); void getUuidBySsid(const QString &ssid, QString &deviceName, QString &uuid, QString &dbusPath); public Q_SLOTS: void onWifiNetworkAdded(QString devIfaceName, QString ssid); void onWifiNetworkRemoved(QString devIfaceName, QString ssid); void onWifiNetworkPropertyChange(NetworkManager::WirelessNetwork::Ptr net); void onWifiNetworkDeviceDisappear(); void onConnectionAdd(QString connectUuid, QString connectName, QString connectPath); void onConnectionRemove(QString); void onDeviceAdd(QString deviceName); void onDeviceRemove(QString deviceName); void onDeviceNameUpdate(QString oldName, QString newName); private Q_SLOTS: void updateList(); Q_SIGNALS: void signalStrengthChange(QString deviceName, QString ssid, int strength); void secuTypeChange(QString deviceName, QString ssid, QString securityType); void wirelessConnectionRemove(QString deviceName, QString ssid); void wirelessConnectionAdd(QString deviceName, QString ssid, QString uuid, QString dbusPath); void wirelessConnectionUpdate(QString deviceName, QString ssid, QString uuid, QString dbusPath, KySecuType connectSecuType); void wifiNetworkUpdate(QString, QString, KyWirelessNetItem); void wifiNetworkAdd(QString deviceName, KyWirelessNetItem &item); void wifiNetworkRemove(QString deviceName, QString ssid); void wirelessDeviceAdd(QString deviceName); void deviceRemove(QString deviceName); void wirelessDeviceNameUpdate(QString oldName, QString newName); void updateWifiList(QString, QList, QList); private: QMap> m_WifiNetworkList; QTimer * m_updateTimer = nullptr; QString getDeviceIFace(NetworkManager::WirelessNetwork::Ptr net); }; #endif // KYWIRELESSNETRESOURCE_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinapconnectitem.cpp0000664000175000017500000000215715160517205026071 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinapconnectitem.h" KyApConnectItem::KyApConnectItem(QObject *parent) : QObject(parent) { m_connectName = ""; m_connectUuid = ""; m_connectSsid = ""; m_ifaceName = ""; m_password = ""; m_band = ""; m_isActivated = false; } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkdeviceresource.cpp0000664000175000017500000002604415160517205027662 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinnetworkdeviceresource.h" #include "kylinnetworkmanagerutil.h" #include "kylinconnectoperation.h" #define VIRTURAL_DEVICE_PATH "/sys/devices/virtual/net" #define LOG_FLAG "KyNetworkDeviceResourse" KyNetworkDeviceResourse::KyNetworkDeviceResourse(QObject *parent) : QObject(parent) { m_networkResourceInstance = KyNetworkResourceManager::getInstance(); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceCarrierChange, this, &KyNetworkDeviceResourse::carrierChange); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceStateChange, this, &KyNetworkDeviceResourse::deviceStateChange); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceManagedChange, this, &KyNetworkDeviceResourse::deviceManagedChange); // connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceBitRateChange, // this, &KyNetworkDeviceResourse::deviceBitRateChange); // connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceMacAddressChange, // this, &KyNetworkDeviceResourse::deviceMacAddressChange); // connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceActiveChange, // this, &KyNetworkDeviceResourse::deviceActiveChange); } KyNetworkDeviceResourse::~KyNetworkDeviceResourse() { m_networkResourceInstance = nullptr; } void KyNetworkDeviceResourse::getNetworkDeviceList( KyDeviceType deviceType, QStringList &networkDeviceList) { NetworkManager::Device::List deviceList = m_networkResourceInstance->getNetworkDeviceList(); if (deviceList.isEmpty()) { qDebug() << LOG_FLAG <<"network device is not exist. device type" << deviceType; return; } NetworkManager::Device::Ptr devicePtr = nullptr; for (int index = 0; index < deviceList.size(); ++index) { devicePtr = deviceList.at(index); if (devicePtr.isNull()) { continue; } if (devicePtr->type() == deviceType) { if (DEVICE_TYPE_ETHERNET == deviceType) { //为了区分有线网卡和虚拟网卡 qDebug()<< LOG_FLAG << "device uni" << devicePtr->udi(); if (devicePtr->udi().startsWith(VIRTURAL_DEVICE_PATH)) { continue; } } networkDeviceList<interfaceName(); } } return; } void KyNetworkDeviceResourse::getHardwareInfo(QString ifaceName, QString &hardAddress, int &bandWith) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceByName(ifaceName); if (nullptr == connectDevice || !connectDevice->isValid()) { qWarning()<< LOG_FLAG <<"get hardware info failed, the device" << ifaceName << "is not existed"; hardAddress.clear(); bandWith = 0; return; } switch (connectDevice->type()) { case NetworkManager::Device::Ethernet: { NetworkManager::WiredDevice *wiredDevicePtr = qobject_cast(connectDevice.data()); hardAddress = wiredDevicePtr->hardwareAddress(); bandWith = wiredDevicePtr->bitRate(); break; } case NetworkManager::Device::Wifi: { NetworkManager::WirelessDevice *wirelessDevicePtr = qobject_cast(connectDevice.data()); hardAddress = wirelessDevicePtr->hardwareAddress(); bandWith = wirelessDevicePtr->bitRate(); break; } default: { hardAddress = ""; bandWith = 0; qWarning()<< LOG_FLAG << "the network device type is undefined" << connectDevice->type(); break; } } } KyDeviceState KyNetworkDeviceResourse::getDeviceState(QString deviceName) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceByName(deviceName); if (!connectDevice.isNull() && connectDevice->isValid()) { return (KyDeviceState)connectDevice->state(); } qWarning()<< LOG_FLAG <<"get device state failed, the device is " << deviceName; return DEVICE_STATE_UNKNOWN; } bool KyNetworkDeviceResourse::wiredDeviceIsCarriered(QString deviceName) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceByName(deviceName); if (connectDevice.isNull()) { qWarning()<< LOG_FLAG << "check device carriered failed."; return false; } if (connectDevice->isValid() && NetworkManager::Device::Type::Ethernet == connectDevice->type()) { NetworkManager::WiredDevice *wiredDevicePtr = qobject_cast(connectDevice.data()); return wiredDevicePtr->carrier(); } qWarning()<< LOG_FLAG << deviceName <<" can not get carrier state."; return false; } void KyNetworkDeviceResourse::getDeviceActiveAPInfo(const QString devName, QString &strMac, uint &iHz, uint &iChan, QString &secuType) { strMac.clear(); iHz = 0; iChan = 0; secuType.clear(); NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceByName(devName); if (nullptr == connectDevice || !connectDevice->isValid()) { qWarning()<< LOG_FLAG <<"getDeviceActiveAPInfo failed, the device" << devName << "is not existed"; return; } switch (connectDevice->type()) { case NetworkManager::Device::Wifi: { NetworkManager::WirelessDevice *wirelessDevicePtr = qobject_cast(connectDevice.data()); NetworkManager::AccessPoint::Ptr apPtr = wirelessDevicePtr->activeAccessPoint(); if (apPtr.isNull()) { break; } strMac = apPtr->hardwareAddress(); iHz = apPtr->frequency(); iChan = NetworkManager::findChannel(iHz); NetworkManager::AccessPoint::Capabilities capability = apPtr->capabilities(); NetworkManager::AccessPoint::WpaFlags wpaFlag = apPtr->wpaFlags(); NetworkManager::AccessPoint::WpaFlags rsnFlag = apPtr->rsnFlags(); secuType = enumToQstring(capability, wpaFlag, rsnFlag); break; } case NetworkManager::Device::Ethernet: break; default: break; } } int KyNetworkDeviceResourse::getWirelessDeviceCapability(const QString deviceName) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceByName(deviceName); if (!connectDevice.isNull() && connectDevice->isValid() && NetworkManager::Device::Type::Wifi == connectDevice->type()) { NetworkManager::WirelessDevice *wirelessDevicePtr = qobject_cast(connectDevice.data()); int cap = 0; if (wirelessDevicePtr->wirelessCapabilities() & NetworkManager::WirelessDevice::ApCap) { cap = cap | 0x01; } if (wirelessDevicePtr->wirelessCapabilities() & NetworkManager::WirelessDevice::Freq2Ghz) { cap = cap | 0x02; } if (wirelessDevicePtr->wirelessCapabilities() & NetworkManager::WirelessDevice::Freq5Ghz) { cap = cap | 0x04; } return cap; } else { qWarning()<<"[KyNetworkDeviceResourse]"<findDeviceByName(devName); if (!connectDevice.isNull() && connectDevice->isValid()) { dbusPath = connectDevice->uni(); } else { qWarning()<<"[KyNetworkDeviceResourse] can not find device " << devName; return; } setDeviceManagedByGDbus(dbusPath, managed); } bool KyNetworkDeviceResourse::getDeviceManaged(QString deviceName) { NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceByName(deviceName); if (connectDevice != nullptr && connectDevice->isValid()) { return connectDevice->managed(); } else { qWarning()<<"[KyNetworkDeviceResourse] can not find device " << deviceName; return false; } } void KyNetworkDeviceResourse::getDeviceConnectivity(const QString deviceName, KyConnectivity &connectivity) { connectivity = CONNECTIVITY_UNKNOWN; QString dbusPath; NetworkManager::Device::Ptr connectDevice = m_networkResourceInstance->findDeviceByName(deviceName); if (connectDevice != nullptr && connectDevice->isValid()) { dbusPath = connectDevice->uni(); } else { qWarning() << "[KyNetworkDeviceResourse] can not find device " << deviceName; return; } QDBusInterface *ip4ConnectivityDbus = new QDBusInterface("org.freedesktop.NetworkManager", dbusPath, "org.freedesktop.DBus.Properties", QDBusConnection::systemBus()); if (ip4ConnectivityDbus == nullptr || !ip4ConnectivityDbus->isValid()) { qWarning() << "[KyNetworkDeviceResourse] get device properties failed"; return; } QDBusReply reply = ip4ConnectivityDbus->call("Get", "org.freedesktop.NetworkManager.Device", "Ip4Connectivity"); if (reply.isValid()) { connectivity = (KyConnectivity) reply.value().toUInt(); } else { qWarning() << "[KyNetworkDeviceResourse] get device properties failed"; } delete ip4ConnectivityDbus; ip4ConnectivityDbus = nullptr; } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcetype.h0000664000175000017500000002476115160517205027055 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINNETWORKRESOURCETYPE_H #define KYLINNETWORKRESOURCETYPE_H typedef enum{ CONNECT_STATE_UNKONW = 0, /**< The active connection is in an unknown state */ CONNECT_STATE_ACTIVATING, /**< The connection is activating */ CONNECT_STATE_ACTIVATED, /**< The connection is activated */ CONNECT_STATE_DEACTIVATING, /**< The connection is being torn down and cleaned up */ CONNECT_STATE_DEACTIVATED, /**< The connection is no longer active */ CONNECT_STATE_COUNT }KyConnectState; typedef enum{ CHANGE_REASON_UNKNOWN = 0, /**< The reason for the active connection state change is unknown */ CHANGE_REASON_NONE, /**< No reason was given for the active connection state change */ CHANGE_REASON_USER_DISCONNECTED, /**< The active connection changed state because the user disconnected it */ CHANGE_REASON_DEVICE_DISCONNECTIED, /**< The active connection changed state because the device it was using was disconnected */ CHANGE_REASON_SERVICE_STOP, /**< The service providing the VPN connection was stopped */ CHANGE_REASON_IPCONFIG_INVALID = 5, /**< The IP config of the active connection was invalid */ CHANGE_REASON_CONNECT_TIMEOUT, /**< The connection attempt to the VPN service timed out */ CHANGE_REASON_SERVICE_START_TIMEOUT,/**< A timeout occurred while starting the service providing the VPN connection */ CHANGE_REASON_SERVICE_START_FAILED, /**< Starting the service providing the VPN connection failed */ CHANGE_REASON_NO_SECRET, /**< Necessary secrets for the connection were not provided */ CHANGE_REASON_LOGIN_FAILED = 10, /**< Authentication to the server failed */ CHANGE_REASON_CONNECT_REMOVED, /**< The connection was deleted from settings */ CHANGE_REASON_DEPENDENCY_FAILED, /**< Master connection of this connection failed to activate */ CHANGE_REASON_DEVICE_REALIZE_FAILED,/**< Could not create the software device link */ CHANGE_REASON_DEVICE_REMOVED, /**< The device this connection depended on disappeared */ CHANGE_REASON_COUNT }KyConnectChangeReason; typedef enum { CONNECT_TYPE_UNKNOWN = 0, CONNECT_TYPE_ADSL, CONNECT_TYPE_BLUETOOTH, CONNECT_TYPE_BOND, CONNECT_TYPE_BRIDGE, CONNECT_TYPE_CDMA = 5, CONNECT_TYPE_GSM, CONNECT_TYPE_INFINIBAND, CONNECT_TYPE_OLPCMESH, CONNECT_TYPE_PPPOE, CONNECT_TYPE_VLAN = 10, CONNECT_TYPE_VPN, CONNECT_TYPE_WIMAX, CONNECT_TYPE_WIRED, CONNECT_TYPE_WIRELESS, CONNECT_TYPE_TEAM = 15, CONNECT_TYPE_GENERIC, CONNECT_TYPE_TUN, CONNECT_TYPE_IPTUNNEL, CONNECT_TYPE_WIREDGUARD, CONNECT_TYPE_COUNT }KyConnectionType; typedef enum { CONNECTIVITY_UNKNOWN = 0, /**< Network connectivity is unknown. */ CONNECTIVITY_NO, /**< The host is not connected to any network. */ CONNECTIVITY_PORTAL, /**< The host is behind a captive portal and cannot reach the full Internet. */ CONNECTIVITY_LIMITED, /**< The host is connected to a network, but does not appear to be able to reach the full Internet. */ CONNECTIVITY_FULL, /**< The host is connected to a network, and appears to be able to reach the full Internet. */ CONNECTIVITY_COUNT }KyConnectivity; typedef enum { DEVICE_TYPE_UNKNOWN = 0, /**< Unknown device type */ DEVICE_TYPE_ETHERNET, /**< Ieee8023 wired ethernet */ DEVICE_TYPE_WIFI, /**< the Ieee80211 family of wireless networks */ DEVICE_TYPE_UNUSED1, /**< Currently unused */ DEVICE_TYPE_UNUSED2, /**< Currently unused */ DEVICE_TYPE_BLUETOOTH = 5, /**< network bluetooth device (usually a cell phone) */ DEVICE_TYPE_OLPCMESH, /**< OLPC Mesh networking device */ DEVICE_TYPE_WIMAX, /**< WiMax WWAN technology */ DEVICE_TYPE_MODEM, /**< POTS, GSM, CDMA or LTE modems */ DEVICE_TYPE_INFINIBAND, /**< Infiniband network device */ DEVICE_TYPE_BOND = 10, /**< Bond virtual device */ DEVICE_TYPE_VLAN, /**< Vlan virtual device */ DEVICE_TYPE_ADSL, /**< ADSL modem device */ DEVICE_TYPE_BRIDGE, /**< Bridge virtual device */ DEVICE_TYPE_GENERIC, /**< Generic device @since 1.0.0 */ DEVICE_TYPE_TEAM = 15, /**< Team master device @since 1.0.0 */ DEVICE_TYPE_GRE, /**< Gre virtual device @since 1.2.0, @deprecated use IpTunnel instead*/ DEVICE_TYPE_MACVLAN, /**< MacVlan virtual device @since 1.2.0 */ DEVICE_TYPE_TUN, /**< Tun virtual device @since 1.2.0 */ DEVICE_TYPE_VETH, /**< Veth virtual device @since 1.2.0 */ DEVICE_TYPE_IPTUNNEL = 20, /**< IP Tunneling Device @since 1.2.0 */ DEVICE_TYPE_VXLAN, /**< Vxlan Device @since 1.2.0 */ DEVICE_TYPE_MACSEC, /**< MacSec Device @since 1.6.0 */ DEVICE_TYPE_DUMMY, /**< Dummy Device @since 1.8.0 */ DEVICE_TYPE_PPP, /**< Ppp Device @since 1.10 */ DEVICE_TYPE_OVSINTERFACE = 25, /**< OvsInterface Device @since 1.10 */ DEVICE_TYPE_OVSPORT, /**< OvsPort Device @since 1.10 */ DEVICE_TYPE_OVSBRIDGE, /**< OvsBridge Device @since 1.10 */ DEVICE_TYPE_WPAN, /**< Wpan Device @since 1.14 */ DEVICE_TYPE_LOWPAN, /**< Lowpan Device @since 1.14 */ DEVICE_TYPE_WIREGUARD = 30, /**< WireGuard Device @since 1.14 */ DEVICE_TYPE_WIFIP2P, /**< WifiP2P Device @since 1.16 */ DEVICE_TYPE_COUNT }KyDeviceType; typedef enum { DEVICE_STATE_UNKNOWN = 0, /**< The device is in an unknown state */ DEVICE_STATE_UNMANAGED = 10, /**< The device is recognized but not managed by NetworkManager */ DEVICE_STATE_UNAVAILABLE = 20, /**< The device cannot be used (carrier off, rfkill, etc) */ DEVICE_STATE_DISCONNECTED = 30, /**< The device is not connected */ DEVICE_STATE_PREPARING = 40, /**< The device is preparing to connect */ DEVICE_STATE_CONFIGURINGHARDWARE = 50, /**< The device is being configured */ DEVICE_STATE_NEEDAUTH = 60, /**< The device is awaiting secrets necessary to continue connection */ DEVICE_STATE_CONFIGURINGIP = 70, /**< The IP settings of the device are being requested and configured */ DEVICE_STATE_CHECKINGIP = 80, /**< The device's IP connectivity ability is being determined */ DEVICE_STATE_WAITINGFORSECONDARIES = 90, /**< The device is waiting for secondary connections to be activated */ DEVICE_STATE_ACTIVATED = 100, /**< The device is active */ DEVICE_STATE_DEACTIVATING = 110, /**< The device's network connection is being torn down */ DEVICE_STATE_FAILED = 120 /**< The device is in a failure state following an attempt to activate it */ }KyDeviceState; /** * KyApSecurityFlags: * @AP_SEC_NONE: the access point has no special security requirements * @AP_SEC_PAIR_WEP40: 40/64-bit WEP is supported for * pairwise/unicast encryption * @AP_SEC_PAIR_WEP104: 104/128-bit WEP is supported for * pairwise/unicast encryption * @AP_SEC_PAIR_TKIP: TKIP is supported for pairwise/unicast encryption * @AP_SEC_PAIR_CCMP: AES/CCMP is supported for pairwise/unicast encryption * @AP_SEC_GROUP_WEP40: 40/64-bit WEP is supported for group/broadcast * encryption * @AP_SEC_GROUP_WEP104: 104/128-bit WEP is supported for * group/broadcast encryption * @AP_SEC_GROUP_TKIP: TKIP is supported for group/broadcast encryption * @AP_SEC_GROUP_CCMP: AES/CCMP is supported for group/broadcast * encryption * @AP_SEC_KEY_MGMT_PSK: WPA/RSN Pre-Shared Key encryption is * supported * @AP_SEC_KEY_MGMT_802_1X: 802.1x authentication and key management * is supported * @AP_SEC_KEY_MGMT_SAE: WPA/RSN Simultaneous Authentication of Equals is * supported * * 802.11 access point security and authentication flags. These flags describe * the current security requirements of an access point as determined from the * access point's beacon. **/ typedef enum { /*< underscore_name=nm_802_11_ap_security_flags, flags >*/ AP_SECURITY_NONE = 0x00000000, AP_SECURITY_PAIR_WEP40 = 0x00000001, AP_SECURITY_PAIR_WEP104 = 0x00000002, AP_SECURITY_PAIR_TKIP = 0x00000004, AP_SECURITY_PAIR_CCMP = 0x00000008, AP_SECURITY_GROUP_WEP40 = 0x00000010, AP_SECURITY_GROUP_WEP104 = 0x00000020, AP_SECURITY_GROUP_TKIP = 0x00000040, AP_SECURITY_GROUP_CCMP = 0x00000080, AP_SECURITY_KEY_MGMT_PSK = 0x00000100, AP_SECURITY_KEY_MGMT_802_1X = 0x00000200, AP_SECURITY_KEY_MGMT_SAE = 0x00000400, }KyApSecurityFlags; /** * KyApCapabilities: * @AP_FLAGS_NONE: access point has no special capabilities * @AP_FLAGS_PRIVACY: access point requires authentication and * encryption (usually means WEP) * @AP_FLAGS_WPS: access point supports some WPS method * @AP_FLAGS_WPS_PBC: access point supports push-button WPS * @AP_FLAGS_WPS_PIN: access point supports PIN-based WPS * * 802.11 access point fCapabilities. **/ typedef enum { AP_CAPABILITY_NONE = 0x00000000, AP_CAPABILITY_PRIVACY = 0x00000001, AP_CAPABILITY_WPS = 0x00000002, AP_CAPABILITY_WPS_PBC = 0x00000004, AP_CAPABILITY_WPS_PIN = 0x00000008, }KyApCapabilities; //class KySecretFlagType { //public: // enum KySecretFlag{ // SECRET_FLAG_NONE = 0, // SECRET_FLAG_AgentOWNED = 0x01, // SECRET_FLAG_NOTSAVED = 0x02, // SECRET_FLAG_NOTREQUIRED = 0x04 // }; // Q_DECLARE_FLAGS(kySecretFlags, KySecretFlag) //}; //Q_DECLARE_OPERATORS_FOR_FLAGS(KySecretFlagType::KySecretFlags) #endif // KYLINNETWORKRESOURCETYPE_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwiredconnectoperation.cpp0000664000175000017500000000543715160517205027651 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinnetworkdeviceresource.h" #include "kylinnetworkmanagerutil.h" #include #include #include #include #include KyWiredConnectOperation::KyWiredConnectOperation(QObject *parent) : KyConnectOperation(parent) { } void KyWiredConnectOperation::createWiredConnect(KyConnectSetting &connectSettingsInfo) { connectSettingsInfo.dumpInfo(); NetworkManager::ConnectionSettings::Ptr wiredConnectionSettings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(NetworkManager::ConnectionSettings::Wired)); connectSettingSet(wiredConnectionSettings, connectSettingsInfo); NetworkManager::Ipv4Setting::Ptr ipv4Setting = wiredConnectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); ipv4SettingSet(ipv4Setting, connectSettingsInfo); NetworkManager::Ipv6Setting::Ptr ipv6Setting = wiredConnectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); ipv6SettingSet(ipv6Setting, connectSettingsInfo); NetworkManager::WiredSetting::Ptr wiredSetting = wiredConnectionSettings->setting(NetworkManager::Setting::Wired).dynamicCast(); wiredSetting->setInitialized(true); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(wiredConnectionSettings->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wired connection failed: ") + watcher->error().message(); qWarning() << errorMessage; Q_EMIT this->createConnectionError(errorMessage); } watcher->deleteLater(); }); } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessconnectoperation.h0000664000175000017500000001544715160517205027340 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYWIRELESSCONNECTOPERATION_H #define KYWIRELESSCONNECTOPERATION_H #include #include #include "kyenterpricesettinginfo.h" #include "kylinconnectoperation.h" #include "kyenterpricesettinginfo.h" const QByteArray GSETTINGS_SCHEMA = "org.ukui.kylin-nm.switch"; const QString WIRELESS_SWITCH = "wirelessswitch"; const QString WIFI_BAND_2_4GHZ = "2.4Ghz"; const QString WIFI_BAND_5GHZ = "5Ghz"; enum KySecuType { UNKNOWN, NONE, WPA_AND_WPA2_PERSONAL, WPA_AND_WPA2_ENTERPRISE, WPA3_PERSONAL, }; enum KyKeyMgmt { Unknown = -1, Wep, Ieee8021x, WpaNone, WpaPsk, WpaEap, SAE }; class KyWirelessConnectSetting : public KyConnectSetting { public: QString m_ssid; QString m_psk; NetworkManager::Setting::SecretFlags m_secretFlag = NetworkManager::Setting::SecretFlagType::None; bool isHidden = false; }; class KyWirelessConnectOperation : public KyConnectOperation { Q_OBJECT public: explicit KyWirelessConnectOperation(QObject *parent = nullptr); public: void requestWirelessScan(); //获取密码保存策略 bool getConnSecretFlags(QString &connUuid, NetworkManager::Setting::SecretFlags &); //获取KeyMgmt KyKeyMgmt getConnectKeyMgmt(const QString &uuid); KySecuType getConnectSecuType(const QString &uuid); //激活连接 void activeWirelessConnect(QString , QString); //断开连接 void deActivateWirelessConnection(const QString activeConnectName, const QString &activeConnectUuid); //新增普通连接 void addConnect(const KyWirelessConnectSetting &connSettingInfo, KySecuType &type); //新增TLS连接 void addTlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTlsInfo &tlsinfo); //新增PEAP连接 void addPeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPeapInfo &peapInfo); //新增TTLS连接 void addTtlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTtlsInfo &ttlsInfo); //新增LEAP连接 void addLeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodLeapInfo &leapInfo); //新增PWD连接 void addPwdConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPwdInfo &pwdInfo); //新增FAST连接 void addFastConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodFastInfo &fastInfo); //新增连接并激活(普通wifi) void addAndActiveWirelessConnect(KyWirelessConnectSetting &connSettingInfo, KySecuType &type); //新增连接并激活(企业wifi) void addAndActiveWirelessEnterPriseTlsConnect(KyEapMethodTlsInfo &info, KyWirelessConnectSetting &connSettingInfo); void addAndActiveWirelessEnterPrisePeapConnect(KyEapMethodPeapInfo &info, KyWirelessConnectSetting &connSettingInfo); void addAndActiveWirelessEnterPriseTtlsConnect(KyEapMethodTtlsInfo &info, KyWirelessConnectSetting &connSettingInfo); void addAndActiveWirelessEnterPriseLeapConnect(KyEapMethodLeapInfo &info, KyWirelessConnectSetting &connSettingInfo); void addAndActiveWirelessEnterPrisePwdConnect(KyEapMethodPwdInfo &info, KyWirelessConnectSetting &connSettingInfo); void addAndActiveWirelessEnterPriseFastConnect(KyEapMethodFastInfo &info, KyWirelessConnectSetting &connSettingInfo); //属性页 page1 AutoConnect void setWirelessAutoConnect(const QString &uuid, bool bAutoConnect); //属性页 page2 page3 ipv6 void updateIpv4AndIpv6SettingInfo(const QString &uuid, const KyConnectSetting &connectSettingsInfo); //属性页 page4 wifi Security //连接修改(安全改为个人/None) void updateWirelessPersonalConnect(const QString &uuid, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange); //连接修改(安全改为改为企业) void updateWirelessEnterPriseTlsConnect(const QString &uuid, const KyEapMethodTlsInfo &tlsinfo); void updateWirelessEnterPrisePeapConnect(const QString &uuid, const KyEapMethodPeapInfo &peapInfo); void updateWirelessEnterPriseTtlsConnect(const QString &uuid, const KyEapMethodTtlsInfo &ttlsInfo); void updateWirelessEnterPriseLeapConnect(const QString &uuid, const KyEapMethodLeapInfo &leapInfo); void updateWirelessEnterPrisePwdConnect(const QString &uuid, const KyEapMethodPwdInfo &pwdInfo); void updateWirelessEnterPriseFastConnect(const QString &uuid, const KyEapMethodFastInfo &fastInfo); //忘记 void deleteWirelessConnect(const QString &connectUuid); //获取密码 QString getPsk(const QString &connectUuid); QString getPrivateKeyPassword(const QString &connectUuid); QString get8021xPassword(const QString &connectUuid); void activeWirelessAp(const QString apUuid, const QString apName, const QString apPassword, const QString apDevice, const QString wirelessBand); void deactiveWirelessAp(const QString apName, const QString apUuid); bool isApConnection(QString uuid); private: NetworkManager::ConnectionSettings::Ptr createWirelessApSetting(const QString apSsid, const QString apPassword, const QString apDevice, const QString wirelessBand); void updateWirelessApSetting(NetworkManager::Connection::Ptr apConnectPtr, const QString apName, const QString apPassword, const QString apDevice, const QString wirelessBand); NetworkManager::WirelessNetwork::Ptr checkWifiNetExist(QString ssid, QString devName); void updateWirelessSecu(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange = false); void setIpv4AndIpv6Setting(NetworkManager::ConnectionSettings::Ptr connSetting, const KyConnectSetting &connSettingInfo); void setWirelessSecuWpaXEap(NetworkManager::ConnectionSettings::Ptr connSettingPtr); void activateApConnectionByUuid(const QString apUuid, const QString apDevice); }; #endif // KYWIRELESSCONNECTOPERATION_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetitem.cpp0000664000175000017500000000206715160517205025760 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kywirelessnetitem.h" KyWirelessNetItem::KyWirelessNetItem() { m_NetSsid = ""; m_connectUuid = ""; m_connectSecuType = KySecuType::NONE; m_secuType = ""; m_signalStrength = 0; } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkdeviceresource.h0000664000175000017500000000545115160517205027326 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINNETORKDEVICERESOURCE_H #define KYLINNETORKDEVICERESOURCE_H #include #include "kylinnetworkresourcemanager.h" #include "kylinconnectitem.h" #include "kylinwiredconnectoperation.h" //设备操作和信息获取 class KyNetworkDeviceResourse : public QObject { Q_OBJECT public: explicit KyNetworkDeviceResourse(QObject *parent = nullptr); ~KyNetworkDeviceResourse(); public: void getNetworkDeviceList(KyDeviceType deviceType, QStringList &networkDeviceList); void getHardwareInfo(QString ifaceName, QString &hardAddress, int &bandWith); //移动热点有关 void getDeviceActiveAPInfo(const QString devName, QString &strMac, uint &iHz, uint &iChan, QString &secuType); int getWirelessDeviceCapability(const QString deviceName); KyDeviceState getDeviceState(QString deviceName); bool wiredDeviceIsCarriered(QString deviceName); bool wirelessDeviceIsExist(const QString devName); void setDeviceManaged(QString devName, bool managed); bool getDeviceManaged(QString devName); void getDeviceConnectivity(const QString deviceName, KyConnectivity &connectivity); private: void getActiveConnection(QString &deviceName, QString &connectUuid); void saveActiveConnection(QString &deviceName, QString &connectUuid); Q_SIGNALS: void deviceStateChange(QString deviceName, KyDeviceState newstate, KyDeviceState oldstate, NetworkManager::Device::StateChangeReason reason); void carrierChange(QString deviceName, bool pluged); void wiredDeviceEnableChange(QString, bool); void deviceManagedChange(QString deviceName, bool managed); // void deviceBitRateChanage(QString deviceName, int bitRate); // void deviceMacAddressChanage(QString deviceName, const QString &hwAddress); // void deviceActiveChanage(QString deviceName, bool deivceActive); private: KyNetworkResourceManager *m_networkResourceInstance = nullptr; }; #endif // KYLINNETORKDEVICERESOURCE_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyenterpricesettinginfo.h0000664000175000017500000002016715160517205026615 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYENTERPRICESETTINGINFO_H #define KYENTERPRICESETTINGINFO_H #include #include #include "kylinnetworkresourcemanager.h" #include enum KyEapMethodType { TLS = 0, PEAP, TTLS, LEAP, PWD, FAST, }; class KyEapMethodTlsInfo { public: QString identity; QString domain; QString devIfaceName; QString caCertPath; bool bNeedCa; QString clientCertPath; QString clientPrivateKey; QString clientPrivateKeyPWD; NetworkManager::Setting::SecretFlags m_privateKeyPWDFlag; // only valid when update bool bChanged; inline bool operator == (const KyEapMethodTlsInfo& info) const { if (this->identity == info.identity && this->domain == info.domain // && this->devIfaceName == info.devIfaceName && this->caCertPath == info.caCertPath && this->bNeedCa == info.bNeedCa && this->clientCertPath == info.clientCertPath && this->clientPrivateKey == info.clientPrivateKey && this->clientPrivateKeyPWD == info.clientPrivateKeyPWD && this->m_privateKeyPWDFlag == info.m_privateKeyPWDFlag) { return true; } else { return false; } } }; typedef enum { KyAuthEapMethodUnknown = 0, KyAuthEapMethodMd5, KyAuthEapMethodMschapv2, KyAuthEapMethodOtp, KyAuthEapMethodGtc, KyAuthEapMethodTls } KyEapMethodAuth; typedef enum{ KyAuthMethodUnknown = 0, KyAuthMethodPap, KyAuthMethodChap, KyAuthMethodMschap, KyAuthMethodMschapv2, KyAuthMethodGtc, KyAuthMethodOtp, KyAuthMethodMd5, KyAuthMethodTls } KyNoEapMethodAuth; class KyEapMethodPeapInfo { public: KyNoEapMethodAuth phase2AuthMethod; QString userName; QString userPWD; NetworkManager::Setting::SecretFlags m_passwdFlag; // only valid when update bool bChanged; inline bool operator == (const KyEapMethodPeapInfo& info) const { if (this->phase2AuthMethod == info.phase2AuthMethod && this->userName == info.userName && this->userPWD == info.userPWD && this->m_passwdFlag == info.m_passwdFlag) { return true; } else { return false; } } }; enum KyTtlsAuthMethod { AUTH_EAP, AUTH_NO_EAP }; class KyEapMethodTtlsInfo { public: KyTtlsAuthMethod authType; KyEapMethodAuth authEapMethod; KyNoEapMethodAuth authNoEapMethod; QString userName; QString userPWD; NetworkManager::Setting::SecretFlags m_passwdFlag; // only valid when update bool bChanged; inline bool operator == (const KyEapMethodTtlsInfo& info) const { if (this->authType == info.authType) { if (authType == AUTH_EAP) { if (this->authEapMethod == info.authEapMethod && this ->userName == info.userName && this->userPWD == info.userPWD && this->m_passwdFlag == info.m_passwdFlag) { return true; } } else { if (authType == AUTH_EAP) { if (this->authNoEapMethod == info.authNoEapMethod && this ->userName == info.userName && this->userPWD == info.userPWD && this->m_passwdFlag == info.m_passwdFlag) { return true; } } } } return false; } }; typedef enum { KyFastProvisioningUnknown = -1, KyFastProvisioningDisabled, KyFastProvisioningAllowUnauthenticated, KyFastProvisioningAllowAuthenticated, KyFastProvisioningAllowBoth }KyFastProvisioning; class KyEapMethodLeapInfo { public: QString m_userName; QString m_userPwd; NetworkManager::Setting::SecretFlags m_passwdFlag; // only valid when update bool bChanged; inline bool operator == (const KyEapMethodLeapInfo& info) const { if (this->m_userName == info.m_userName && this->m_userPwd == info.m_userPwd && this->m_passwdFlag == info.m_passwdFlag) { return true; } else { return false; } } }; class KyEapMethodPwdInfo { public: QString m_userName; QString m_userPwd; NetworkManager::Setting::SecretFlags m_passwdFlag; // only valid when update bool bChanged; inline bool operator == (const KyEapMethodPwdInfo& info) const { if (this->m_userName == info.m_userName && this->m_userPwd == info.m_userPwd && this->m_passwdFlag == info.m_passwdFlag) { return true; } else { return false; } } }; class KyEapMethodFastInfo { public: QString m_anonIdentity; KyFastProvisioning m_pacProvisioning; bool m_allowAutoPacFlag; QString m_pacFilePath; KyNoEapMethodAuth m_authMethod; QString m_userName; QString m_userPwd; NetworkManager::Setting::SecretFlags m_passwdFlag; // only valid when update bool bChanged; inline bool operator == (const KyEapMethodFastInfo& info) const { if (this->m_anonIdentity == info.m_anonIdentity && this->m_pacProvisioning == info.m_pacProvisioning && this->m_allowAutoPacFlag == info.m_allowAutoPacFlag && this->m_pacFilePath == info.m_pacFilePath && this->m_authMethod == info.m_authMethod && this->m_userName == info.m_userName && this->m_userPwd == info.m_userPwd && this->m_passwdFlag == info.m_passwdFlag) { return true; } else { return false; } } }; void assembleEapMethodTlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTlsInfo &tlsInfo); void assembleEapMethodPeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPeapInfo &peapInfo); void assembleEapMethodTtlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTtlsInfo &ttlsInfo); void assembleEapMethodLeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodLeapInfo &leapInfo); void assembleEapMethodPwdSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPwdInfo &pwdInfo); void assembleEapMethodFastSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodFastInfo &fastInfo); void modifyEapMethodTlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTlsInfo &tlsInfo); void modifyEapMethodPeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPeapInfo &peapInfo); void modifyEapMethodTtlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTtlsInfo &ttlsInfo); void modifyEapMethodLeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodLeapInfo &leapInfo); void modifyEapMethodPwdSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPwdInfo &pwdInfo); void modifyEapMethodFastSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodFastInfo &fastInfo); #endif // KYENTERPRICESETTINGINFO_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetresource.cpp0000664000175000017500000007303715160517205026656 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kywirelessnetresource.h" #include "kylinnetworkmanagerutil.h" #define LOG_FLAG "[KyWirelessNetResource]" #define PSK_SETTING_NAME "802-11-wireless-security" #define PRIVATE_PSK_SETTING_NAME "802-1x" #define FREQ_5GHZ 5000 static bool subWifiListSort(const KyWirelessNetItem info1, const KyWirelessNetItem info2) { if (info1.m_connectUuid.isEmpty() == info2.m_connectUuid.isEmpty()) { if (info1.m_signalStrength != info2.m_signalStrength) { return info1.m_signalStrength > info2.m_signalStrength; } else { if (QString::compare(info1.m_NetSsid, info2.m_NetSsid, Qt::CaseInsensitive) > 0) { return false; } else { return true; } } } return !info1.m_connectUuid.isEmpty(); } static void wifiListSort(QList &list) { std::sort(list.begin(), list.end(), subWifiListSort); } KyWirelessNetResource::KyWirelessNetResource(QObject *parent) : KyNetResource(parent) { qRegisterMetaType("KyWirelessNetItem&"); qRegisterMetaType("NetworkManager::WirelessNetwork::Ptr"); kyWirelessNetItemListInit(); //无线出现/消失-->item 增删 connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkAdded, this, &KyWirelessNetResource::onWifiNetworkAdded); connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkRemoved, this, &KyWirelessNetResource::onWifiNetworkRemoved); connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkPropertyChange, this, &KyWirelessNetResource::onWifiNetworkPropertyChange); connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkDeviceDisappear, this, &KyWirelessNetResource::onWifiNetworkDeviceDisappear); //无线配置变化-->item uuid变化 connect(m_networkResourceInstance, &KyNetworkResourceManager::wirelessConnectionAdd, this, &KyWirelessNetResource::onConnectionAdd); connect(m_networkResourceInstance, &KyNetworkResourceManager::connectionRemove, this, &KyWirelessNetResource::onConnectionRemove); //设备变化-->map key变化 connect(m_networkResourceInstance, &KyNetworkResourceManager::wirelessDeviceAdd, this, &KyWirelessNetResource::onDeviceAdd); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceRemove, this, &KyWirelessNetResource::onDeviceRemove); connect(m_networkResourceInstance, &KyNetworkResourceManager::wirelessDeviceUpdate, this, &KyWirelessNetResource::onDeviceNameUpdate); m_updateTimer = new QTimer(this); m_updateTimer->start(10*1000); connect(m_updateTimer, &QTimer::timeout, this, &KyWirelessNetResource::updateList); } //配合activeconnection 此处未单独区分已连接的wifi void KyWirelessNetResource::getWifiNetworkList(QString devName, QList &list) { list.clear(); if (m_WifiNetworkList.isEmpty() || !m_WifiNetworkList.contains(devName)) { return; } else { QMap >::iterator iter = m_WifiNetworkList.begin(); while (iter != m_WifiNetworkList.end()) { if (iter.key() == devName) { list = m_WifiNetworkList[iter.key()]; wifiListSort(list); return; } iter++; } } } void KyWirelessNetResource::kyWirelessNetItemListInit() { m_WifiNetworkList.clear(); NetworkManager::WirelessNetwork::List m_wifiNetList = m_networkResourceInstance->getWifiNetworkList(); for (auto const & net : m_wifiNetList) { QString devIface = getDeviceIFace(net); if (devIface.isEmpty()) { continue; } KyWirelessNetItem item; wirelessNetItemInit(item, net); if (!m_WifiNetworkList.contains(devIface)){ QList list; list.append(item); m_WifiNetworkList.insert(devIface,list); } else { m_WifiNetworkList[devIface].append(item); } } return; } void KyWirelessNetResource::wirelessNetItemInit(KyWirelessNetItem &wirelessItem, NetworkManager::WirelessNetwork::Ptr wirelessNetPtr) { if(wirelessNetPtr.isNull()) { return; } NetworkManager::AccessPoint::Ptr accessPointPtr = wirelessNetPtr->referenceAccessPoint(); QByteArray rawSsid = accessPointPtr->rawSsid(); wirelessItem.m_NetSsid = getSsidFromByteArray(rawSsid); wirelessItem.m_signalStrength = accessPointPtr->signalStrength(); wirelessItem.m_frequency = accessPointPtr->frequency(); NetworkManager::AccessPoint::Capabilities cap = accessPointPtr->capabilities(); NetworkManager::AccessPoint::WpaFlags wpaFlag = accessPointPtr->wpaFlags(); NetworkManager::AccessPoint::WpaFlags rsnFlag = accessPointPtr->rsnFlags(); wirelessItem.m_secuType = enumToQstring(cap, wpaFlag, rsnFlag); QString interface = getDeviceIFace(wirelessNetPtr); getUuidBySsid(wirelessItem.m_NetSsid, interface, wirelessItem.m_connectUuid, wirelessItem.m_dbusPath); KyWirelessConnectOperation operation; wirelessItem.m_connectSecuType = operation.getConnectSecuType(wirelessItem.m_connectUuid); wirelessItem.m_isApConnection = operation.isApConnection(wirelessItem.m_connectUuid); NetworkManager::Device::Ptr devicePtr = nullptr; devicePtr = m_networkResourceInstance->findDeviceByName(wirelessNetPtr->device()); if (!devicePtr.isNull()) { QString devUni = devicePtr->uni(); NetworkManager::WirelessNetwork::Ptr wirelessPtr = nullptr; wirelessPtr = m_networkResourceInstance->findWifiNetwork(wirelessItem.m_NetSsid, devUni); if (!wirelessPtr.isNull()) { NetworkManager::AccessPoint::List apList = wirelessPtr->accessPoints(); bool b2G = false; bool b5G = false; if (!apList.empty()) { for (int i = 0; i < apList.count(); ++i) { if (apList.at(i)->frequency() < FREQ_5GHZ) { b2G = true; } if (apList.at(i)->frequency() >= FREQ_5GHZ) { b5G = true; } if (b2G && b5G) { wirelessItem.m_isMix = true; break; } } } } } } void KyWirelessNetResource::getUuidBySsid(const QString &ssid, QString &deviceName, QString &uuid, QString &dbusPath) { uuid.clear(); dbusPath.clear(); NetworkManager::Connection::List connectList; connectList.clear(); connectList = m_networkResourceInstance->getConnectList(); if (connectList.empty()) { qWarning()<<"[KyConnectResourse]"<<"get connection failed, the connect list is empty"; return; } NetworkManager::Connection::Ptr connectPtr = nullptr; for (int index = 0; index < connectList.size(); index++) { connectPtr = connectList.at(index); if (connectPtr.isNull()) { continue; } if (NetworkManager::ConnectionSettings::Wireless != connectPtr->settings()->connectionType()) { continue; } QString connectInterface = connectPtr->settings()->interfaceName(); if (!connectInterface.isEmpty() && deviceName != connectInterface) { continue; } NetworkManager::WirelessSetting::Ptr wifi_sett = connectPtr->settings()->setting(NetworkManager::Setting::Wireless).dynamicCast(); if (wifi_sett->ssid() == ssid) { uuid = connectPtr->settings()->uuid(); dbusPath = connectPtr->path(); } } } void KyWirelessNetResource::onWifiNetworkAdded(QString devIfaceName, QString ssid) { NetworkManager::WirelessNetwork::Ptr wifi = nullptr; NetworkManager::WirelessNetwork::List m_wifiNetList = m_networkResourceInstance->getWifiNetworkList(); for (auto const & net : m_wifiNetList) { if (net.isNull()) { continue; } NetworkManager::AccessPoint::Ptr accessPointPtr = net->referenceAccessPoint(); QByteArray rawSsid = accessPointPtr->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); if (wifiSsid == ssid && m_networkResourceInstance->findDeviceByUni(net->device())->interfaceName() == devIfaceName) { wifi = net; } } if (wifi.isNull()) { return; } KyWirelessNetItem item; wirelessNetItemInit(item, wifi); if (m_WifiNetworkList.contains(devIfaceName)) { m_WifiNetworkList[devIfaceName].append(item); } else { QList list; list.append(item); m_WifiNetworkList.insert(devIfaceName,list); } Q_EMIT wifiNetworkAdd(devIfaceName, item); } void KyWirelessNetResource::onWifiNetworkRemoved(QString devIfaceName, QString ssid) { if (m_WifiNetworkList.contains(devIfaceName)) { int index = 0; for ( ; index < m_WifiNetworkList.value(devIfaceName).size(); index++) { if ( m_WifiNetworkList[devIfaceName].at(index).m_NetSsid == ssid) { m_WifiNetworkList[devIfaceName].removeAt(index); } } //remove后为空则删除 if (m_WifiNetworkList.value(devIfaceName).isEmpty()) { m_WifiNetworkList.remove(devIfaceName); } Q_EMIT wifiNetworkRemove(devIfaceName, ssid); } } void KyWirelessNetResource::onWifiNetworkPropertyChange(NetworkManager::WirelessNetwork::Ptr net) { if (nullptr == net) { return; } NetworkManager::AccessPoint::Ptr accessPointPtr = net->referenceAccessPoint(); QByteArray rawSsid = accessPointPtr->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceByUni(net->device()); if (devicePtr.isNull()) { return; } QString devIface = devicePtr->interfaceName(); if (m_WifiNetworkList.contains(devIface)) { QList::iterator iter = m_WifiNetworkList[devIface].begin(); while (iter != m_WifiNetworkList[devIface].end()) { if (iter->m_NetSsid == wifiSsid) { if (iter->m_signalStrength != net->signalStrength()) { iter->m_signalStrength = net->signalStrength(); } QString secuType = enumToQstring(accessPointPtr->capabilities(), accessPointPtr->wpaFlags(), accessPointPtr->rsnFlags()); if (iter->m_secuType != secuType) { iter->m_secuType = secuType; KyWirelessNetItem item = *iter; Q_EMIT wifiNetworkUpdate(devIface, wifiSsid, item); } break; } iter++; } } } void KyWirelessNetResource::onWifiNetworkDeviceDisappear() { qWarning() << "wifiNetworkDeviceDisappear!!!!!!!!!"; for (int i = 0; i < m_WifiNetworkList.keys().size(); ++i) { Q_EMIT deviceRemove(m_WifiNetworkList.keys().at(i)); } kyWirelessNetItemListInit(); } //对应属性页-->安全 bool KyWirelessNetResource::getNormalWifiConnectSecuInfo(QString &uuid, KyWpaPasswordInfo &info) { KyWirelessConnectOperation operation; info.pwd = operation.getPsk(uuid); return operation.getConnSecretFlags(uuid, info.flag); } bool KyWirelessNetResource::getEnterpiseEapMethod(const QString &uuid, KyEapMethodType &type) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (connectPtr.isNull()) { qWarning() << "getEnterpiseEapMethod faild.Can't find uuid = " << uuid; return false; } KyWirelessConnectOperation operation; KyKeyMgmt keyMgmt = operation.getConnectKeyMgmt(uuid); if (keyMgmt != WpaEap) { qWarning() << "getEnterpiseEapMethod but not WpaEap.it's " << keyMgmt; return false; } NetworkManager::ConnectionSettings::Ptr connectionSettings = connectPtr->settings(); NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connectionSettings->setting(NetworkManager::Setting::Security8021x).dynamicCast(); QList list = wifi_8021x_sett->eapMethods(); if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodTls)) { type = TLS; } else if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodPeap)) { type = PEAP; } else if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodTtls)) { type = TTLS; } else if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodLeap)) { type = LEAP; } else if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodPwd)) { type = PWD; } else if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodFast)) { type = FAST; } return true; } bool KyWirelessNetResource::getEnterPriseInfoTls(QString &uuid, KyEapMethodTlsInfo &info) { NetworkManager::Connection::Ptr conn = m_networkResourceInstance->findConnectByUuid(uuid); if (conn.isNull()) { qWarning() << LOG_FLAG << "modifyEnterPriseInfoTls connection missing"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (security_sett.isNull()) { qWarning()<< LOG_FLAG << "don't have WirelessSecurity connection"; return false; } if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { return false; } NetworkManager::Security8021xSetting::Ptr setting = conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); if (setting.isNull()) { qWarning()<< LOG_FLAG << "don't have Security8021x connection"; return false; } info.identity = setting->identity(); info.domain = setting->domainSuffixMatch(); info.caCertPath = setting->caCertificate(); if (info.caCertPath.left(7) == "file://") { info.caCertPath = info.caCertPath.mid(7); } info.clientCertPath = setting->clientCertificate(); if (info.clientCertPath.left(7) == "file://") { info.clientCertPath = info.clientCertPath.mid(7); } info.clientPrivateKey = QString(setting->privateKey()); if (info.clientPrivateKey.left(7) == "file://") { info.clientPrivateKey = info.clientPrivateKey.mid(7); } info.m_privateKeyPWDFlag = setting->privateKeyPasswordFlags(); if (!info.m_privateKeyPWDFlag) { KyWirelessConnectOperation operation; info.clientPrivateKeyPWD = operation.getPrivateKeyPassword(conn->uuid()); } return true; } bool KyWirelessNetResource::getEnterPriseInfoPeap(QString &uuid, KyEapMethodPeapInfo &info) { NetworkManager::Connection::Ptr conn = m_networkResourceInstance->findConnectByUuid(uuid); if (conn.isNull()) { qWarning() << LOG_FLAG << "getEnterPriseInfoPeap connection missing"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (security_sett.isNull()) { qWarning() << LOG_FLAG << "don't have WirelessSecurity connection"; return false; } if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { qWarning() << LOG_FLAG << "keyMgmt not WpaEap " << security_sett->keyMgmt(); return false; } NetworkManager::Security8021xSetting::Ptr setting = conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); if (setting.isNull() || !setting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodPeap)) { qWarning()<< LOG_FLAG << "don't have Security8021x connection"; return false; } info.phase2AuthMethod = (KyNoEapMethodAuth)setting->phase2AuthMethod(); info.userName = setting->identity(); info.m_passwdFlag = setting->passwordFlags(); if (!info.m_passwdFlag) { KyWirelessConnectOperation operation; info.userPWD = operation.get8021xPassword(conn->uuid()); } return true; } bool KyWirelessNetResource::getEnterPriseInfoTtls(QString &uuid, KyEapMethodTtlsInfo &info) { NetworkManager::Connection::Ptr conn = m_networkResourceInstance->findConnectByUuid(uuid); if (conn.isNull()) { qWarning() << LOG_FLAG << "modifyEnterPriseInfoTtls connection missing"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (security_sett.isNull()) { qWarning() << LOG_FLAG << "don't have WirelessSecurity connection"; return false; } if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { qWarning() << LOG_FLAG << "not wpaeap"<keyMgmt(); return false; } NetworkManager::Security8021xSetting::Ptr setting = conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); if (setting.isNull() || !setting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodTtls)) { qWarning() << LOG_FLAG << "don't have Security8021x connection"; return false; } info.authEapMethod = (KyEapMethodAuth)setting->phase2AuthEapMethod(); info.authNoEapMethod = (KyNoEapMethodAuth)setting->phase2AuthMethod(); info.authType = KyTtlsAuthMethod::AUTH_EAP; if (info.authEapMethod != KyAuthEapMethodUnknown) { info.authType = KyTtlsAuthMethod::AUTH_EAP; } else { info.authType = KyTtlsAuthMethod::AUTH_NO_EAP; } info.userName = setting->identity(); info.m_passwdFlag = setting->passwordFlags(); if (!info.m_passwdFlag) { KyWirelessConnectOperation operation; info.userPWD = operation.get8021xPassword(conn->uuid()); } return true; } bool KyWirelessNetResource::getEnterPriseInfoLeap(QString &uuid, KyEapMethodLeapInfo &info) { NetworkManager::Connection::Ptr conn = m_networkResourceInstance->findConnectByUuid(uuid); if (conn.isNull()) { qDebug()<< LOG_FLAG << "getEnterPriseInfoLeap connection missing"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (security_sett.isNull()) { qDebug()<< LOG_FLAG << "don't have WirelessSecurity connection"; return false; } if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { qDebug()<< LOG_FLAG << "keyMgmt not WpaEap " << security_sett->keyMgmt(); return false; } NetworkManager::Security8021xSetting::Ptr setting = conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); if (setting.isNull() || !setting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodLeap)) { qDebug()<< LOG_FLAG << "don't have Security8021x connection"; return false; } info.m_userName = setting->identity(); info.m_passwdFlag = setting->passwordFlags(); if (!info.m_passwdFlag) { KyWirelessConnectOperation operation; info.m_userPwd = operation.get8021xPassword(conn->uuid()); } return true; } bool KyWirelessNetResource::getEnterPriseInfoPwd(QString &uuid, KyEapMethodPwdInfo &info) { NetworkManager::Connection::Ptr conn = m_networkResourceInstance->findConnectByUuid(uuid); if (conn.isNull()) { qDebug()<< LOG_FLAG << "getEnterPriseInfoPwd connection missing"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (security_sett.isNull()) { qDebug()<< LOG_FLAG << "don't have WirelessSecurity connection"; return false; } if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { qDebug()<< LOG_FLAG << "keyMgmt not WpaEap " << security_sett->keyMgmt(); return false; } NetworkManager::Security8021xSetting::Ptr setting = conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); if (setting.isNull() || !setting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodPwd)) { qDebug()<< LOG_FLAG << "don't have Security8021x connection"; return false; } info.m_userName = setting->identity(); info.m_passwdFlag = setting->passwordFlags(); if (!info.m_passwdFlag) { KyWirelessConnectOperation operation; info.m_userPwd = operation.get8021xPassword(conn->uuid()); } return true; } bool KyWirelessNetResource::getEnterPriseInfoFast(QString &uuid, KyEapMethodFastInfo &info) { NetworkManager::Connection::Ptr conn = m_networkResourceInstance->findConnectByUuid(uuid); if (conn.isNull()) { qDebug()<< LOG_FLAG << "getEnterPriseInfoFast connection missing"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (security_sett.isNull()) { qDebug()<< LOG_FLAG << "don't have WirelessSecurity connection"; return false; } if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { qDebug()<< LOG_FLAG << "keyMgmt not WpaEap " << security_sett->keyMgmt(); return false; } NetworkManager::Security8021xSetting::Ptr setting = conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); if (setting.isNull() || !setting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodFast)) { qDebug()<< LOG_FLAG << "don't have Security8021x connection"; return false; } info.m_anonIdentity = setting->anonymousIdentity(); info.m_pacProvisioning = (KyFastProvisioning)setting->phase1FastProvisioning(); info.m_pacFilePath = setting->pacFile(); if (info.m_pacFilePath.left(7) == "file://") { info.m_pacFilePath = info.m_pacFilePath.mid(7); } info.m_authMethod = (KyNoEapMethodAuth)setting->phase2AuthMethod(); info.m_userName = setting->identity(); info.m_passwdFlag = setting->passwordFlags(); if (!info.m_passwdFlag) { KyWirelessConnectOperation operation; info.m_userPwd = operation.get8021xPassword(conn->uuid()); } return true; } void KyWirelessNetResource::getWirelessConnectDetail(QString interface, QString ssid, QString uuid, KyDetailInfo &connectSetting) { getBaseInfo(interface, ssid, true, !uuid.isEmpty(), connectSetting); if (!uuid.isEmpty()) { getDynamicIpInfo(uuid, connectSetting); } } void KyWirelessNetResource::onConnectionAdd(QString connectUuid, QString connectName, QString connectPath) { Q_UNUSED(connectName); NetworkManager::Connection::Ptr conn = m_networkResourceInstance->findConnectByUuid(connectUuid); if (conn.isNull()) { qWarning() << LOG_FLAG << "onConnectionAdd can not find connection" << connectUuid; return; } NetworkManager::ConnectionSettings::Ptr sett = conn->settings(); NetworkManager::WirelessSetting::Ptr wireless_sett = sett->setting(NetworkManager::Setting::Wireless).dynamicCast(); QByteArray rawSsid = wireless_sett->ssid(); QString wifiSsid = getSsidFromByteArray(rawSsid); QMap map; map.clear(); QMap >::iterator iter = m_WifiNetworkList.begin(); while (iter != m_WifiNetworkList.end()) { for(int i = 0; i < iter.value().size(); i++) { if (iter.value().at(i).m_NetSsid == wifiSsid && (sett->interfaceName() == iter.key() || sett->interfaceName().isEmpty())) { QString devIfaceName; QString ssid; KyWirelessConnectOperation operation; m_WifiNetworkList[iter.key()][i].m_connectUuid = conn->uuid(); m_WifiNetworkList[iter.key()][i].m_dbusPath = conn->path(); m_WifiNetworkList[iter.key()][i].m_connectSecuType = operation.getConnectSecuType(conn->uuid()); devIfaceName = iter.key(); ssid = iter.value().at(i).m_NetSsid; Q_EMIT wirelessConnectionAdd(devIfaceName, ssid, connectUuid, connectPath); map.insert(devIfaceName, ssid); break; } } iter++; } } void KyWirelessNetResource::onConnectionRemove(QString path) { QMap map; map.clear(); QMap >::iterator iter = m_WifiNetworkList.begin(); while (iter != m_WifiNetworkList.end()) { for(int i = 0; i < iter.value().size(); i++) { if (iter.value().at(i).m_dbusPath == path) { KyWirelessConnectOperation operation; QString devIfaceName = iter.key(); QString ssid = iter.value().at(i).m_NetSsid; getUuidBySsid(ssid, devIfaceName, m_WifiNetworkList[iter.key()][i].m_connectUuid, m_WifiNetworkList[iter.key()][i].m_dbusPath); if (m_WifiNetworkList[iter.key()][i].m_connectUuid.isEmpty()) { Q_EMIT wirelessConnectionRemove(devIfaceName, ssid); } else { Q_EMIT wirelessConnectionUpdate(devIfaceName, ssid, m_WifiNetworkList[iter.key()][i].m_connectUuid, m_WifiNetworkList[iter.key()][i].m_dbusPath, operation.getConnectSecuType(m_WifiNetworkList[iter.key()][i].m_connectUuid)); } map.insert(devIfaceName, ssid); break; } } iter++; } } void KyWirelessNetResource::onDeviceAdd(QString deviceName) { if (!m_WifiNetworkList.contains(deviceName)) { m_WifiNetworkList.insert(deviceName,QList()); Q_EMIT wirelessDeviceAdd(deviceName); } } void KyWirelessNetResource::onDeviceRemove(QString deviceName) { if (m_WifiNetworkList.contains(deviceName)) { m_WifiNetworkList.remove(deviceName); Q_EMIT deviceRemove(deviceName); } } void KyWirelessNetResource::onDeviceNameUpdate(QString oldName, QString newName) { if (m_WifiNetworkList.contains(oldName)) { QMap> newWifiNetworkList(m_WifiNetworkList); QList list = m_WifiNetworkList[oldName]; newWifiNetworkList.remove(oldName); newWifiNetworkList.insert(newName,list); m_WifiNetworkList = newWifiNetworkList; Q_EMIT wirelessDeviceNameUpdate(oldName, newName); } } void KyWirelessNetResource::updateList() { for (int i = 0; i< m_WifiNetworkList.keys().size(); ++i) { QString devName = m_WifiNetworkList.keys().at(i); QList connectItemList; KyActiveConnectResourse actResource; actResource.getActiveConnectionList(devName, CONNECT_TYPE_WIRELESS, connectItemList); QList list = m_WifiNetworkList[devName]; wifiListSort(list); Q_EMIT updateWifiList(devName, connectItemList, list); } } QString KyWirelessNetResource::getDeviceIFace(NetworkManager::WirelessNetwork::Ptr net) { if (net.isNull()) { return ""; } QString devUni = net->device(); NetworkManager::Device::Ptr dev = m_networkResourceInstance->findDeviceByUni(devUni); if (dev.isNull()) { qDebug()<< LOG_FLAG << "KyWirelessNetResource: can't find " << net->ssid() << " find in device list"; return ""; } return dev->interfaceName(); } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kynetloadratethread.h0000664000175000017500000000351615160517205025674 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYNETLOADRATETHREAD_H #define KYNETLOADRATETHREAD_H #include #include #include class KyNetLoadRateThread : public QThread { public: KyNetLoadRateThread(QString dev, QObject *parent = nullptr); ~KyNetLoadRateThread(); void getNetSpeed(long int &rcvRate, long int &txRate) { rcvRate = m_deltaRcv; txRate = m_deltaTx; } protected: virtual void run(); private: void updateLoadRate(); int getCurrentLoadRate(QString dev, long *saveRate, long *txRate); QString m_deviceName; QTimer * m_updateRatesTimer = nullptr; long int m_startRcvRate = 0; //保存开始时的流量计数 long int m_endRcvRate = 0; //保存结束时的流量计数 long int m_startTxRate = 0; //保存开始时的流量计数 long int m_endTxRate = 0; //保存结束时的流量计数 long int m_deltaRcv = 0; long int m_deltaTx = 0; Q_SIGNALS: void loadRateUpdate(); }; #endif // KYNETLOADRATETHREAD_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessconnectoperation.cpp0000664000175000017500000015357715160517205027702 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kywirelessconnectoperation.h" #include "kylinnetworkmanagerutil.h" #include #define PSK_SETTING_NAME "802-11-wireless-security" #define PRIVATE_PSK_SETTING_NAME "802-1x" NetworkManager::ConnectionSettings::Ptr assembleWpaXPskSettings(NetworkManager::AccessPoint::Ptr accessPoint, QString &psk, bool isAutoConnect) { QByteArray rawSsid = accessPoint->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); NetworkManager::ConnectionSettings::Ptr settings{new NetworkManager::ConnectionSettings{NetworkManager::ConnectionSettings::Wireless}}; settings->setId(wifiSsid); settings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); settings->setAutoconnect(isAutoConnect); //Note: workaround for wrongly (randomly) initialized gateway-ping-timeout settings->setGatewayPingTimeout(0); NetworkManager::WirelessSetting::Ptr wifi_sett = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); wifi_sett->setInitialized(true); wifi_sett->setSsid(rawSsid); wifi_sett->setSecurity("802-11-wireless-security"); NetworkManager::WirelessSecuritySetting::Ptr security_sett = settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); if (NetworkManager::AccessPoint::Adhoc == accessPoint->mode()) { wifi_sett->setMode(NetworkManager::WirelessSetting::Adhoc); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaNone); } else { security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaPsk); } if (!psk.isEmpty()) { security_sett->setPsk(psk); } return settings; } NetworkManager::ConnectionSettings::Ptr assembleSaeSettings(NetworkManager::AccessPoint::Ptr accessPoint, QString &psk, bool isAutoConnect) { QByteArray rawSsid = accessPoint->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); NetworkManager::ConnectionSettings::Ptr settings{new NetworkManager::ConnectionSettings{NetworkManager::ConnectionSettings::Wireless}}; settings->setId(wifiSsid); settings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); settings->setAutoconnect(isAutoConnect); //Note: workaround for wrongly (randomly) initialized gateway-ping-timeout settings->setGatewayPingTimeout(0); NetworkManager::WirelessSetting::Ptr wifi_sett = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); wifi_sett->setInitialized(true); wifi_sett->setSsid(rawSsid); wifi_sett->setSecurity("802-11-wireless-security"); NetworkManager::WirelessSecuritySetting::Ptr security_sett = settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); if (NetworkManager::AccessPoint::Adhoc == accessPoint->mode()) { wifi_sett->setMode(NetworkManager::WirelessSetting::Adhoc); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaNone); } else { security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::SAE); } if (!psk.isEmpty()) { security_sett->setPsk(psk); } return settings; } NetworkManager::ConnectionSettings::Ptr assembleWirelessSettings(const NetworkManager::AccessPoint::Ptr accessPointPtr, const KyWirelessConnectSetting &connSettingInfo, KyKeyMgmt type, bool isHidden) { QByteArray rawSsid; if (nullptr == accessPointPtr || accessPointPtr.isNull()) { rawSsid = connSettingInfo.m_ssid.toUtf8(); } else { rawSsid = accessPointPtr->rawSsid(); } NetworkManager::ConnectionSettings::Ptr settings{new NetworkManager::ConnectionSettings{NetworkManager::ConnectionSettings::Wireless}}; settings->setId(connSettingInfo.m_connectName); settings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); settings->setAutoconnect(connSettingInfo.m_isAutoConnect); //Note: workaround for wrongly (randomly) initialized gateway-ping-timeout settings->setGatewayPingTimeout(0); settings->setInterfaceName(connSettingInfo.m_ifaceName); NetworkManager::WirelessSetting::Ptr wifi_sett = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); wifi_sett->setInitialized(true); wifi_sett->setSsid(rawSsid); wifi_sett->setSecurity("802-11-wireless-security"); wifi_sett->setHidden(isHidden); if (type != KyKeyMgmt::WpaNone && type != KyKeyMgmt::Unknown) { NetworkManager::WirelessSecuritySetting::Ptr security_sett = settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt((NetworkManager::WirelessSecuritySetting::KeyMgmt)type); if (KyKeyMgmt::SAE == type || KyKeyMgmt::WpaPsk == type) { security_sett->setPsk(connSettingInfo.m_psk); } } return settings; } KyWirelessConnectOperation::KyWirelessConnectOperation(QObject *parent) : KyConnectOperation(parent) { } void KyWirelessConnectOperation::requestWirelessScan() { NetworkManager::Device::List deviceList = m_networkResourceInstance->getNetworkDeviceList(); for (auto const & dev : deviceList) { auto spec_dev = dev->as(); if (nullptr != spec_dev) { m_networkResourceInstance->requestScan(spec_dev); } } } //普通wifi void KyWirelessConnectOperation::addConnect(const KyWirelessConnectSetting &connSettingInfo, KySecuType &type) { KyKeyMgmt mgmt; if (type == NONE) { mgmt = WpaNone; } else if (type == WPA_AND_WPA2_PERSONAL) { mgmt = WpaPsk; } else if (type == WPA3_PERSONAL) { mgmt = WpaEap; } else { return; } NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning()<referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, mgmt, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } watcher->deleteLater(); }); } //tls void KyWirelessConnectOperation::addTlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTlsInfo &tlsInfo) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning() << errorMessage; Q_EMIT createConnectionError(errorMessage); return; } NetworkManager::AccessPoint::Ptr accessPointPtr = wifiNet->referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); assembleEapMethodTlsSettings(connSetting, tlsInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless tls connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } watcher->deleteLater(); }); } //peap void KyWirelessConnectOperation::addPeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPeapInfo &peapInfo) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning()<referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); assembleEapMethodPeapSettings(connSetting, peapInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless peap connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } watcher->deleteLater(); }); } void KyWirelessConnectOperation::addTtlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTtlsInfo &ttlsInfo) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning()<referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); assembleEapMethodTtlsSettings(connSetting, ttlsInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless ttls connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } watcher->deleteLater(); }); return; } void KyWirelessConnectOperation::addLeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodLeapInfo &leapInfo) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning() << errorMessage; Q_EMIT createConnectionError(errorMessage); return; } NetworkManager::AccessPoint::Ptr accessPointPtr = wifiNet->referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); assembleEapMethodLeapSettings(connSetting, leapInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless leap connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } watcher->deleteLater(); }); return; } void KyWirelessConnectOperation::addPwdConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPwdInfo &pwdInfo) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning() << errorMessage; Q_EMIT createConnectionError(errorMessage); return; } NetworkManager::AccessPoint::Ptr accessPointPtr = wifiNet->referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); assembleEapMethodPwdSettings(connSetting, pwdInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless pwd connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } watcher->deleteLater(); }); return; } void KyWirelessConnectOperation::addFastConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodFastInfo &fastInfo) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + connSettingInfo.m_ifaceName; qWarning() << errorMessage; Q_EMIT createConnectionError(errorMessage); return; } NetworkManager::AccessPoint::Ptr accessPointPtr = wifiNet->referenceAccessPoint(); NetworkManager::ConnectionSettings::Ptr connSetting = assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, false); setIpv4AndIpv6Setting(connSetting, connSettingInfo); assembleEapMethodFastSettings(connSetting, fastInfo); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless fast connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); } watcher->deleteLater(); }); return; } void KyWirelessConnectOperation::setWirelessAutoConnect(const QString &uuid, bool bAutoConnect) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setAutoConnect(connectionSettings, bAutoConnect); connectPtr->update(connectionSettings->toMap()); } QString KyWirelessConnectOperation::getPsk(const QString &connectUuid) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(connectUuid); if (connectPtr.isNull()) { QString errorMessage = tr("it can not find connection") + connectUuid; qWarning()< reply = connectPtr->secrets(PSK_SETTING_NAME); QMap map(reply.value()); if (map.contains("802-11-wireless-security") && map.value("802-11-wireless-security").contains("psk")) { QString psk = map.value("802-11-wireless-security").value("psk").toString(); return psk; } return ""; } QString KyWirelessConnectOperation::getPrivateKeyPassword(const QString &connectUuid) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(connectUuid); if (connectPtr.isNull()) { QString errorMessage = tr("it can not find connection") + connectUuid; qWarning()< reply = connectPtr->secrets(PRIVATE_PSK_SETTING_NAME); QMap map(reply.value()); if (map.contains("802-1x") && map.value("802-1x").contains("private-key-password")) { QString psk = map.value("802-1x").value("private-key-password").toString(); return psk; } return ""; } QString KyWirelessConnectOperation::get8021xPassword(const QString &connectUuid) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(connectUuid); if (connectPtr.isNull()) { QString errorMessage = tr("it can not find connection") + connectUuid; qWarning()< reply = connectPtr->secrets(PRIVATE_PSK_SETTING_NAME); QMap map(reply.value()); if (map.contains("802-1x") && map.value("802-1x").contains("password")) { QString psk = map.value("802-1x").value("password").toString(); return psk; } return ""; } void KyWirelessConnectOperation::updateIpv4AndIpv6SettingInfo(const QString &uuid, const KyConnectSetting &connectSettingsInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setIpv4AndIpv6Setting(connectionSettings,connectSettingsInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessPersonalConnect(const QString &uuid, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett = connectionSettings->setting(NetworkManager::Setting::Security8021x).dynamicCast(); wifi_8021x_sett->setInitialized(false); updateWirelessSecu(connectionSettings, connSettingInfo, bPwdChange); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessEnterPriseTlsConnect(const QString &uuid, const KyEapMethodTlsInfo &tlsInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (connectPtr.isNull()) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setWirelessSecuWpaXEap(connectionSettings); modifyEapMethodTlsSettings(connectionSettings, tlsInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessEnterPrisePeapConnect(const QString &uuid, const KyEapMethodPeapInfo &peapInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setWirelessSecuWpaXEap(connectionSettings); modifyEapMethodPeapSettings(connectionSettings, peapInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessEnterPriseTtlsConnect(const QString &uuid, const KyEapMethodTtlsInfo &ttlsInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setWirelessSecuWpaXEap(connectionSettings); modifyEapMethodTtlsSettings(connectionSettings, ttlsInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessEnterPriseLeapConnect(const QString &uuid, const KyEapMethodLeapInfo &leapInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setWirelessSecuWpaXEap(connectionSettings); modifyEapMethodLeapSettings(connectionSettings, leapInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessEnterPrisePwdConnect(const QString &uuid, const KyEapMethodPwdInfo &pwdInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setWirelessSecuWpaXEap(connectionSettings); modifyEapMethodPwdSettings(connectionSettings, pwdInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::updateWirelessEnterPriseFastConnect(const QString &uuid, const KyEapMethodFastInfo &fastInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); setWirelessSecuWpaXEap(connectionSettings); modifyEapMethodFastSettings(connectionSettings, fastInfo); connectPtr->update(connectionSettings->toMap()); return; } void KyWirelessConnectOperation::addAndActiveWirelessConnect(KyWirelessConnectSetting &connSettingInfo, KySecuType &type) { KyKeyMgmt mgmt; if (type == NONE) { mgmt = WpaNone; } else if (type == WPA_AND_WPA2_PERSONAL) { mgmt = WpaPsk; } else if (type == WPA3_PERSONAL) { mgmt = SAE; } else { return; } QString devIface = connSettingInfo.m_ifaceName; QString conn_uni, dev_uni, conn_name, spec_object; NMVariantMapMap map_settings; //检测wifi是否存在 NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); if (!connSettingInfo.isHidden && wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; qWarning() << errorMessage; Q_EMIT activateConnectionError(errorMessage); return; } //配置生成 auto dev = m_networkResourceInstance->findDeviceByName(devIface); if (dev.isNull()) { return; } dev_uni = dev->uni(); auto spec_dev = dev->as(); if (!connSettingInfo.isHidden) { //非隐藏wifi auto access_point = wifiNet->referenceAccessPoint(); conn_uni = access_point->uni(); conn_name = access_point->ssid(); spec_object = conn_uni; NetworkManager::WirelessSecurityType sec_type = NetworkManager::findBestWirelessSecurity(spec_dev->wirelessCapabilities() , true, (spec_dev->mode() == NetworkManager::WirelessDevice::Adhoc) , access_point->capabilities(), access_point->wpaFlags(), access_point->rsnFlags()); NetworkManager::ConnectionSettings::Ptr settings = nullptr; switch (sec_type) { case NetworkManager::UnknownSecurity: qWarning() << QStringLiteral("unknown security to use for '%1'").arg(conn_name); case NetworkManager::NoneSecurity: //nothing to do break; case NetworkManager::WpaPsk: case NetworkManager::Wpa2Psk: settings = assembleWpaXPskSettings(access_point, connSettingInfo.m_psk, connSettingInfo.m_isAutoConnect); if (nullptr != settings) { map_settings = settings->toMap(); } else { qWarning() << QStringLiteral("connection settings assembly for '%1' failed, abandoning activation...").arg(conn_name); return; } break; case NetworkManager::SAE: settings = assembleSaeSettings(access_point, connSettingInfo.m_psk, connSettingInfo.m_isAutoConnect); if (nullptr != settings) { map_settings = settings->toMap(); } else { qWarning() << QStringLiteral("connection settings assembly for '%1' failed, abandoning activation...").arg(conn_name); return; } break; //TODO:其他加密类型 default: qWarning() << "addAndActiveWirelessConnect not support"; return; } } else { //隐藏wifi map_settings = assembleWirelessSettings(nullptr, connSettingInfo, mgmt, connSettingInfo.isHidden)->toMap(); } //激活 QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qWarning() << "activation of connection failed " << errorMessage; } watcher->deleteLater(); }); } void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseTlsConnect(KyEapMethodTlsInfo &info, KyWirelessConnectSetting &connSettingInfo) { QString devIface = connSettingInfo.m_ifaceName; QString conn_uni, dev_uni, spec_object; NMVariantMapMap map_settings; NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; if (!connSettingInfo.isHidden) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; qWarning()<referenceAccessPoint(); conn_uni = accessPointPtr->uni(); spec_object = conn_uni; } auto dev = m_networkResourceInstance->findDeviceByName(devIface); if (dev.isNull()) { return; } dev_uni = dev->uni(); NetworkManager::ConnectionSettings::Ptr settings = assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, connSettingInfo.isHidden); assembleEapMethodTlsSettings(settings, info); if(settings.isNull()) { qWarning() << "assembleEapMethodTlsSettings failed"; return; } map_settings = settings->toMap(); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qWarning() << "addAndActiveWirelessEnterPriseTlsConnect failed " << errorMessage; } watcher->deleteLater(); }); } void KyWirelessConnectOperation::addAndActiveWirelessEnterPrisePeapConnect(KyEapMethodPeapInfo &info, KyWirelessConnectSetting &connSettingInfo) { qDebug() << "addAndActiveWirelessEnterPrisePeapConnect"; QString devIface = connSettingInfo.m_ifaceName; QString conn_uni, dev_uni, spec_object; NMVariantMapMap map_settings; NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; if (!connSettingInfo.isHidden) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; qWarning() << errorMessage; Q_EMIT activateConnectionError(errorMessage); return; } accessPointPtr = wifiNet->referenceAccessPoint(); conn_uni = accessPointPtr->uni(); spec_object = conn_uni; } auto dev = m_networkResourceInstance->findDeviceByName(devIface); if (dev.isNull()) { return; } dev_uni = dev->uni(); NetworkManager::ConnectionSettings::Ptr settings = assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, connSettingInfo.isHidden); assembleEapMethodPeapSettings(settings, info); if(settings.isNull()) { qWarning() << "assembleEapMethodPeapSettings failed"; return; } map_settings = settings->toMap(); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qWarning() << "addAndActiveWirelessEnterPrisePeapConnect failed " << errorMessage; } watcher->deleteLater(); }); } void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseTtlsConnect(KyEapMethodTtlsInfo &info, KyWirelessConnectSetting &connSettingInfo) { QString devIface = connSettingInfo.m_ifaceName; QString conn_uni, dev_uni, spec_object; NMVariantMapMap map_settings; NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; if (!connSettingInfo.isHidden) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; qWarning()<referenceAccessPoint(); conn_uni = accessPointPtr->uni(); spec_object = conn_uni; } auto dev = m_networkResourceInstance->findDeviceByName(devIface); if (dev.isNull()) { return; } dev_uni = dev->uni(); NetworkManager::ConnectionSettings::Ptr settings = assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, connSettingInfo.isHidden); assembleEapMethodTtlsSettings(settings, info); if(settings.isNull()) { qWarning() << "assembleEapMethodTtlsSettings failed"; return; } map_settings = settings->toMap(); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qWarning() << "addAndActiveWirelessEnterPriseTtlsConnect failed " << errorMessage; } watcher->deleteLater(); }); } void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseLeapConnect(KyEapMethodLeapInfo &info, KyWirelessConnectSetting &connSettingInfo) { QString devIface = connSettingInfo.m_ifaceName; QString conn_uni, dev_uni, spec_object; NMVariantMapMap map_settings; NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; if (!connSettingInfo.isHidden) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; qWarning()<referenceAccessPoint(); conn_uni = accessPointPtr->uni(); spec_object = conn_uni; } auto dev = m_networkResourceInstance->findDeviceByName(devIface); if (dev.isNull()) { return; } dev_uni = dev->uni(); NetworkManager::ConnectionSettings::Ptr settings = assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, connSettingInfo.isHidden); assembleEapMethodLeapSettings(settings, info); if(settings.isNull()) { qDebug() << "assembleEapMethodLeapSettings failed"; return; } map_settings = settings->toMap(); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "addAndActiveWirelessEnterPriseLeapConnect failed " << errorMessage; } watcher->deleteLater(); }); } void KyWirelessConnectOperation::addAndActiveWirelessEnterPrisePwdConnect(KyEapMethodPwdInfo &info, KyWirelessConnectSetting &connSettingInfo) { QString devIface = connSettingInfo.m_ifaceName; QString conn_uni, dev_uni, spec_object; NMVariantMapMap map_settings; NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; if (!connSettingInfo.isHidden) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; qWarning()<referenceAccessPoint(); conn_uni = accessPointPtr->uni(); spec_object = conn_uni; } auto dev = m_networkResourceInstance->findDeviceByName(devIface); if (dev.isNull()) { return; } dev_uni = dev->uni(); NetworkManager::ConnectionSettings::Ptr settings = assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, connSettingInfo.isHidden); assembleEapMethodPwdSettings(settings, info); if(settings.isNull()) { qDebug() << "assembleEapMethodPwdSettings failed"; return; } map_settings = settings->toMap(); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "addAndActiveWirelessEnterPrisePwdConnect failed " << errorMessage; } watcher->deleteLater(); }); } void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseFastConnect(KyEapMethodFastInfo &info, KyWirelessConnectSetting &connSettingInfo) { QString devIface = connSettingInfo.m_ifaceName; QString conn_uni, dev_uni, spec_object; NMVariantMapMap map_settings; NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; if (!connSettingInfo.isHidden) { NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); if (wifiNet.isNull()) { QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; qWarning()<referenceAccessPoint(); conn_uni = accessPointPtr->uni(); spec_object = conn_uni; } auto dev = m_networkResourceInstance->findDeviceByName(devIface); if (dev.isNull()) { return; } dev_uni = dev->uni(); NetworkManager::ConnectionSettings::Ptr settings = assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, connSettingInfo.isHidden); assembleEapMethodFastSettings(settings, info); if(settings.isNull()) { qDebug() << "assembleEapMethodFastSettings failed"; return; } map_settings = settings->toMap(); QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "addAndActiveWirelessEnterPriseFastConnect failed " << errorMessage; } watcher->deleteLater(); }); } bool KyWirelessConnectOperation::getConnSecretFlags(QString &connUuid, NetworkManager::Setting::SecretFlags &flag) { NetworkManager::Connection::Ptr conn; conn = m_networkResourceInstance->findConnectByUuid(connUuid); if (conn.isNull()) { qWarning() <<"get failed"; return false; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); flag = security_sett->pskFlags(); return true; } NetworkManager::ConnectionSettings::Ptr KyWirelessConnectOperation::createWirelessApSetting(const QString apSsid, const QString apPassword, const QString apDevice, const QString wirelessBand) { NetworkManager::ConnectionSettings::Ptr connectionSettings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(NetworkManager::ConnectionSettings::Wireless)); connectionSettings->setId(apSsid); connectionSettings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); connectionSettings->setAutoconnect(false); connectionSettings->setAutoconnectPriority(0); connectionSettings->setInterfaceName(apDevice); //Note: workaround for wrongly (randomly) initialized gateway-ping-timeout connectionSettings->setGatewayPingTimeout(0); NetworkManager::Ipv4Setting::Ptr ipv4Setting = connectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); ipv4Setting->setInitialized(true); ipv4Setting->setMethod(NetworkManager::Ipv4Setting::Shared); NetworkManager::Ipv6Setting::Ptr ipv6Setting = connectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); ipv6Setting->setInitialized(true); ipv6Setting->setMethod(NetworkManager::Ipv6Setting::Ignored); NetworkManager::WirelessSetting::Ptr wirelessSetting = connectionSettings->setting(NetworkManager::Setting::Wireless).dynamicCast(); wirelessSetting->setInitialized(true); wirelessSetting->setSsid(apSsid.toUtf8()); wirelessSetting->setMode(NetworkManager::WirelessSetting::NetworkMode::Ap); wirelessSetting->setSecurity("802-11-wireless-security"); if (wirelessBand == WIFI_BAND_2_4GHZ) { wirelessSetting->setBand(NetworkManager::WirelessSetting::FrequencyBand::Bg); } else if (wirelessBand == WIFI_BAND_5GHZ) { wirelessSetting->setBand(NetworkManager::WirelessSetting::FrequencyBand::A); } else { qWarning()<<"[KyWirelessConnectOperation] the band type undefined"<setBand(NetworkManager::WirelessSetting::FrequencyBand::Automatic); } NetworkManager::WirelessSecuritySetting::Ptr wirelessSecuritySetting = connectionSettings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (apPassword.isEmpty()) { wirelessSecuritySetting->setInitialized(false); } else { wirelessSecuritySetting->setInitialized(true); wirelessSecuritySetting->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaPsk); wirelessSecuritySetting->setPsk(apPassword); } return connectionSettings; } void KyWirelessConnectOperation::updateWirelessApSetting( NetworkManager::Connection::Ptr apConnectPtr, const QString apName, const QString apPassword, const QString apDevice, const QString wirelessBand) { NetworkManager::ConnectionSettings::Ptr apConnectSettingPtr = apConnectPtr->settings(); apConnectSettingPtr->setId(apName); apConnectSettingPtr->setInterfaceName(apDevice); apConnectSettingPtr->setAutoconnect(false); NetworkManager::WirelessSetting::Ptr wirelessSetting = apConnectSettingPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); wirelessSetting->setInitialized(true); wirelessSetting->setSsid(apName.toUtf8()); if (wirelessBand == WIFI_BAND_2_4GHZ) { wirelessSetting->setBand(NetworkManager::WirelessSetting::FrequencyBand::Bg); } else if (wirelessBand == WIFI_BAND_5GHZ) { wirelessSetting->setBand(NetworkManager::WirelessSetting::FrequencyBand::A); } else { qWarning()<<"[KyWirelessConnectOperation] the band type undefined"<setBand(NetworkManager::WirelessSetting::FrequencyBand::Automatic); } NetworkManager::WirelessSecuritySetting::Ptr wirelessSecuritySetting = apConnectSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (apPassword.isEmpty()) { wirelessSecuritySetting->setInitialized(false); } else { wirelessSecuritySetting->setInitialized(true); wirelessSecuritySetting->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaPsk); wirelessSecuritySetting->setPsk(apPassword); } apConnectPtr->update(apConnectSettingPtr->toMap()); } void KyWirelessConnectOperation::activeWirelessAp(const QString apUuid, const QString apName, const QString apPassword, const QString apDevice, const QString wirelessBand) { //1、检查连接是否存在 NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->findConnectByUuid(apUuid); if (nullptr == connectPtr) { NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceByName(apDevice); if (devicePtr.isNull()) { QString errorMsg ="Create hotspot faild. " + apDevice + " is not existed"; qWarning()<< errorMsg; return; } QString deviceIdentifier = devicePtr->uni(); NetworkManager::ConnectionSettings::Ptr apConnectSettingPtr = createWirelessApSetting(apName, apPassword, apDevice, wirelessBand); QString specificObject = ""; QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(apConnectSettingPtr->toMap(), deviceIdentifier, specificObject), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMsg = "Create hotspot faild. " + watcher->error().message(); qWarning() << errorMsg; } watcher->deleteLater(); }); } else { updateWirelessApSetting(connectPtr, apName, apPassword, apDevice, wirelessBand); QTimer::singleShot(500, this, [=](){ activateApConnectionByUuid(apUuid, apDevice); }); } } void KyWirelessConnectOperation::deactiveWirelessAp(const QString apName, const QString apUuid) { deactivateConnection(apUuid); } //private NetworkManager::WirelessNetwork::Ptr KyWirelessConnectOperation::checkWifiNetExist(QString ssid, QString devName) { NetworkManager::WirelessNetwork::List wifiNetList = m_networkResourceInstance->getWifiNetworkList(); for (auto const & net : wifiNetList) { auto dev = m_networkResourceInstance->findDeviceByUni(net->device()); if (dev == nullptr) { continue; } if (dev->type() != NetworkManager::Device::Wifi || dev->interfaceName() != devName) { continue; } NetworkManager::AccessPoint::Ptr accessPointPtr = net->referenceAccessPoint(); QByteArray rawSsid = accessPointPtr->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); if (ssid == wifiSsid) { return net; } } return nullptr; } KyKeyMgmt KyWirelessConnectOperation::getConnectKeyMgmt(const QString &uuid) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(uuid); if (connectPtr.isNull()) { return KyKeyMgmt::Unknown; } NetworkManager::WirelessSecuritySetting::Ptr security_sett = connectPtr->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if(security_sett.isNull()) { return KyKeyMgmt::Unknown; } return (KyKeyMgmt)security_sett->keyMgmt(); } KySecuType KyWirelessConnectOperation::getConnectSecuType(const QString &uuid) { KyKeyMgmt type = getConnectKeyMgmt(uuid); if (type == WpaNone) { return KySecuType::NONE; } else if (type == WpaPsk) { return KySecuType::WPA_AND_WPA2_PERSONAL; } else if (type == SAE) { return KySecuType::WPA3_PERSONAL; } else if (type == WpaEap) { return KySecuType::WPA_AND_WPA2_ENTERPRISE; } else { qWarning() << "KeyMgmt not support now " << type; return KySecuType::UNKNOWN; } } void KyWirelessConnectOperation::updateWirelessSecu(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange) { NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); KyKeyMgmt type = getConnectKeyMgmt(connSettingPtr->uuid()); if (type == WpaNone) { security_sett->setInitialized(false); return; } else { security_sett->setInitialized(true); } security_sett->setKeyMgmt((NetworkManager::WirelessSecuritySetting::KeyMgmt)type); if (bPwdChange) { security_sett->setPsk(connSettingInfo.m_psk); NetworkManager::Setting::SecretFlags flag = NetworkManager::Setting::None; security_sett->setPskFlags(flag); } } void KyWirelessConnectOperation::setWirelessSecuWpaXEap(NetworkManager::ConnectionSettings::Ptr connSettingPtr) { NetworkManager::WirelessSecuritySetting::Ptr security_sett = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); security_sett->setInitialized(true); security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::KeyMgmt::WpaEap); } void KyWirelessConnectOperation::setIpv4AndIpv6Setting(NetworkManager::ConnectionSettings::Ptr connSetting, const KyConnectSetting &connSettingInfo) { NetworkManager::Ipv4Setting::Ptr ipv4Setting = connSetting->setting(NetworkManager::Setting::Ipv4).dynamicCast(); ipv4SettingSet(ipv4Setting, connSettingInfo); NetworkManager::Ipv6Setting::Ptr ipv6Setting = connSetting->setting(NetworkManager::Setting::Ipv6).dynamicCast(); ipv6SettingSet(ipv6Setting, connSettingInfo); } void KyWirelessConnectOperation::activateApConnectionByUuid(const QString apUuid, const QString apDevice) { QString connectPath = ""; QString deviceIdentifier = ""; QString connectName = ""; QString specificObject = ""; NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->findConnectByUuid(apUuid); if (connectPtr.isNull()) { QString errorMessage = tr("Create hotspot faild.UUID is empty, its name") + apUuid; qWarning() << errorMessage; Q_EMIT activateConnectionError(errorMessage); return; } connectPath = connectPtr->path(); connectName = connectPtr->name(); auto dev = m_networkResourceInstance->findDeviceByName(apDevice); if (!dev.isNull()) { deviceIdentifier = dev->uni(); } if (deviceIdentifier.isEmpty()) { QString errorMessage = tr("Create hotspot faild.Device Identifier is empty, its name") + apDevice; qWarning() << errorMessage; Q_EMIT activateConnectionError(errorMessage); return ; } QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::activateConnection(connectPath, deviceIdentifier, specificObject), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this, connectName, apDevice] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("Create hotspot faild. ") + watcher->error().message(); qWarning()<activateConnectionError(errorMessage); } else { qWarning()<<"active wired connect complete."; } watcher->deleteLater(); }); } bool KyWirelessConnectOperation::isApConnection(QString uuid) { NetworkManager::Connection::Ptr connectPtr = nullptr; connectPtr = m_networkResourceInstance->findConnectByUuid(uuid); return m_networkResourceInstance->isApConnection(connectPtr); } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetitem.h0000664000175000017500000000247515160517205025430 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYWIRELESSNETITEM_H #define KYWIRELESSNETITEM_H #include #include "kywirelessconnectoperation.h" class KyWirelessNetItem { public: QString m_NetSsid = ""; QString m_connectUuid = ""; QString m_dbusPath = ""; KySecuType m_connectSecuType = KySecuType::NONE; bool m_isApConnection = false; QString m_secuType = ""; int m_signalStrength = 0; uint m_frequency; bool m_isMix = false; }; #endif // KYWIRELESSNETITEM_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectoperation.h0000664000175000017500000000475315160517205026263 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINCONNECTOPERATION_H #define KYLINCONNECTOPERATION_H #include "kylinnetworkresourcemanager.h" #include "kylinconnectsetting.h" class KyConnectOperation : public QObject { Q_OBJECT public: explicit KyConnectOperation(QObject *parent = nullptr); ~KyConnectOperation(); void updateConnect(QString connectUuid, const KyConnectSetting &connectSettingsInfo); void deleteConnect(const QString &connectUuid); void activateConnection(const QString connectUuid, const QString deviceName); void deactivateConnection(const QString &activeConnectUuid); protected: void connectSettingSet(NetworkManager::ConnectionSettings::Ptr connectionSettings, const KyConnectSetting &connectSettingsInfo); void ipv4SettingSet(NetworkManager::Ipv4Setting::Ptr &ipv4Setting, const KyConnectSetting &connectSettingsInfo); void ipv6SettingSet(NetworkManager::Ipv6Setting::Ptr &ipv6Setting, const KyConnectSetting &connectSettingsInfo); void setAutoConnect(NetworkManager::ConnectionSettings::Ptr &connectSetting, bool bAutoConnect); inline void errorProcess(QString errorMessage); Q_SIGNALS: void createConnectionError(QString errorMessage); void updateConnectionError(QString errorMessage); void deleteConnectionError(QString errorMessage); void activateConnectionError(QString errorMessage); void deactivateConnectionError(QString errorMessage); protected: KyNetworkResourceManager *m_networkResourceInstance = nullptr; }; #endif // KYLINCONNECTOPERATION_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwiredconnectoperation.h0000664000175000017500000000265715160517205027317 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINWIREDCONNECTOPERATION_H #define KYLINWIREDCONNECTOPERATION_H #include #include #include "kylinnetworkresourcemanager.h" #include "kylinconnectsetting.h" #include "kylinconnectoperation.h" const QString WIRED_NETWORK_STATE_CONF_FILE = QDir::homePath() + "/.config/ukui/kylin-nm-wired.ini"; class KyWiredConnectOperation : public KyConnectOperation { Q_OBJECT public: explicit KyWiredConnectOperation(QObject *parent = nullptr); void createWiredConnect(KyConnectSetting &connectSettingsInfo); }; #endif // KYLINWIREDCONNECTOPERATION_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectsetting.cpp0000664000175000017500000001060015160517205026257 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinconnectsetting.h" #include KyConnectSetting::KyConnectSetting(/*QObject *parent) : QObject(parent*/) { m_connectName = ""; m_ifaceName = ""; m_ipv4ConfigIpType = CONFIG_IP_DHCP; m_ipv4Address.clear(); m_ipv4Dns.clear(); m_ipv6ConfigIpType = CONFIG_IP_DHCP; m_ipv6Address.clear(); m_ipv6Dns.clear(); m_isAutoConnect = true; } KyConnectSetting::~KyConnectSetting() { } void KyConnectSetting::setIfaceName(QString &ifaceName) { m_ifaceName = ifaceName; } void KyConnectSetting::setConnectName(QString &connectName) { m_connectName = connectName; } int KyConnectSetting::setIpConfigType(KyIpAddressType ipType, KyIpConfigType ipConfigType) { if (ipType != IPADDRESS_V4 && ipType != IPADDRESS_V6) { qWarning()<<"set config ip type failed, the ip address type undefined"< #include "kylinnetworkmanagerutil.h" #include #include #define SIGNAL_DELAY 80000 #define EMIT_DELAY 10000 #define LOG_FLAG "[KyNetworkResourceManager]" //单例部分 KyNetworkResourceManager* KyNetworkResourceManager::m_pInstance = nullptr; KyNetworkResourceManager* KyNetworkResourceManager::getInstance() { if (m_pInstance == NULL) { m_pInstance = new KyNetworkResourceManager(); } return m_pInstance; } void KyNetworkResourceManager::Release() { if (m_pInstance != NULL) { delete m_pInstance; m_pInstance = NULL; } } KyNetworkResourceManager::KyNetworkResourceManager(QObject *parent) : QObject(parent) { //线程 信号槽 类型声明 qRegisterMetaType("KyConnectState"); qRegisterMetaType("KyConnectivity"); qRegisterMetaType("KyDeviceType"); } //start后执行 循环检查m_initFinished 非true阻塞 void KyNetworkResourceManager::onInitNetwork() { insertActiveConnections(); insertConnections(); insertDevices(); insertWifiNetworks(); //设备 connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceAdded, this, &KyNetworkResourceManager::onDeviceAdded); connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceRemoved, this, &KyNetworkResourceManager::onDeviceRemoved); //已连接 connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionAdded, this, &KyNetworkResourceManager::onActiveConnectionAdded); connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionRemoved, this, &KyNetworkResourceManager::onActiveConnectionRemoved); //Connection connect(NetworkManager::settingsNotifier(), &NetworkManager::SettingsNotifier::connectionAdded, this, &KyNetworkResourceManager::onConnectionAdded); connect(NetworkManager::settingsNotifier(), &NetworkManager::SettingsNotifier::connectionRemoved, this, static_cast(&KyNetworkResourceManager::onConnectionRemoved)); //通用能力 connect(NetworkManager::notifier(), &NetworkManager::Notifier::connectivityChanged, this, &KyNetworkResourceManager::onConnectivityChanged); connect(NetworkManager::notifier(), &NetworkManager::Notifier::networkingEnabledChanged, this, &KyNetworkResourceManager::networkingEnabledChanged); connect(NetworkManager::notifier(), &NetworkManager::Notifier::wirelessEnabledChanged, this, &KyNetworkResourceManager::wifiEnabledChanged); connect(NetworkManager::notifier(), &NetworkManager::Notifier::primaryConnectionTypeChanged, this, &KyNetworkResourceManager::onPrimaryConnectionTypeChanged); // Note: the connectionRemoved is never emitted in case network-manager service stop, // we need remove the connections manually. //NetworkManager服务 connect(NetworkManager::notifier(), &NetworkManager::Notifier::serviceDisappeared, this, &KyNetworkResourceManager::clearConnections); connect(NetworkManager::notifier(), &NetworkManager::Notifier::serviceDisappeared, this, &KyNetworkResourceManager::clearWifiNetworks); QDBusConnection::systemBus().connect(QString("org.freedesktop.DBus"), QString("/org/freedesktop/DBus"), QString("org.freedesktop.DBus"), QString("NameOwnerChanged"), this, SLOT(onServiceAppear(QString,QString,QString))); QDBusConnection::systemBus().connect(QString("org.freedesktop.NetworkManager"), QString("/org/freedesktop/NetworkManager"), QString("org.freedesktop.NetworkManager"), QString("PropertiesChanged"), this, SLOT(onPropertiesChanged(QVariantMap))); m_initFinished = true; } bool KyNetworkResourceManager::NetworkManagerIsInited() { return m_initFinished; } KyNetworkResourceManager::~KyNetworkResourceManager() { } //服务重启后 没有add信号 需要重新初始化wifi void KyNetworkResourceManager::onServiceAppear(QString interface, QString oldOwner, QString newOwner) { if (interface == "org.freedesktop.NetworkManager" && oldOwner.isEmpty() && !newOwner.isEmpty()) { qDebug() << LOG_FLAG << "org.freedesktop.NetworkManager start"; QTimer::singleShot(500,this,&KyNetworkResourceManager::insertWifiNetworks); } } //m_activeConnectList 删除 void KyNetworkResourceManager::removeActiveConnection(int pos) { //active connections signals NetworkManager::ActiveConnection::Ptr connectPtr = m_activeConnectList.takeAt(pos); connectPtr->disconnect(this); } //m_activeConnectList 清空 void KyNetworkResourceManager::clearActiveConnections() { while (0 < m_activeConnectList.size()) { removeActiveConnection(0); } } //m_activeConnectList 增加 void KyNetworkResourceManager::addActiveConnection(NetworkManager::ActiveConnection::Ptr conn) { m_activeConnectList.push_back(conn); connect(conn.data(), &NetworkManager::ActiveConnection::stateChanged, this, &KyNetworkResourceManager::onActiveConnectionChanged); // if (conn->vpn()) { // connect(qobject_cast(conn.data()), &NetworkManager::VpnConnection::bannerChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); // connect(qobject_cast(conn.data()), &NetworkManager::VpnConnection::stateChanged, this, &KyNetworkResourceManager::onVpnActiveConnectChangedReason); // } } //初始化m_activeConnectList void KyNetworkResourceManager::insertActiveConnections() { for (auto const & conn : NetworkManager::activeConnections()) { if (conn.isNull()) { continue; } addActiveConnection(conn); } } //m_connectList 删除 void KyNetworkResourceManager::removeConnection(int pos) { NetworkManager::Connection::Ptr conn = m_connectList.takeAt(pos); conn->disconnect(this); } //m_connectList 清空 void KyNetworkResourceManager::clearConnections() { while (0 < m_connectList.size()) { removeConnection(0); } } //m_connectList 增加 void KyNetworkResourceManager::addConnection(NetworkManager::Connection::Ptr connectPtr) { m_connectList.push_back(connectPtr); connect(connectPtr.data(), &NetworkManager::Connection::updated, this, &KyNetworkResourceManager::onConnectionUpdated); // connect(connectPtr.data(), &NetworkManager::Connection::removed, this, &KyNetworkResourceManager::onConnectionRemoved); } //m_connectList 初始化 void KyNetworkResourceManager::insertConnections() { for (auto const & connectPtr : NetworkManager::listConnections()) { if (connectPtr.isNull()) { continue; } if (connectPtr->name().isEmpty() || connectPtr->uuid().isEmpty()) { qWarning() << LOG_FLAG << " the name of connection is empty."; continue; } addConnection(connectPtr); } } //m_deviceList 删除 void KyNetworkResourceManager::removeDevice(int pos) { //connections signals NetworkManager::Device::Ptr devicePtr = m_deviceList.takeAt(pos); devicePtr->disconnect(this); m_deviceMap.remove(devicePtr->uni()); Q_EMIT deviceRemove(devicePtr->interfaceName()); } //m_deviceList 清空 void KyNetworkResourceManager::clearDevices() { while (0 < m_deviceList.size()) removeDevice(0); } //m_deviceList 增加 void KyNetworkResourceManager::addDevice(NetworkManager::Device::Ptr device) { m_deviceList.push_back(device); m_deviceMap.insert(device->uni(), device->interfaceName()); connect(device.data(), &NetworkManager::Device::activeConnectionChanged, this, &KyNetworkResourceManager::onDeviceActiveChange); connect(device.data(), &NetworkManager::Device::interfaceNameChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::managedChanged, this, &KyNetworkResourceManager::onDeviceManagedChange); connect(device.data(), &NetworkManager::Device::stateChanged, this, &KyNetworkResourceManager::onDeviceStateChanged); switch (device->type()) { case NetworkManager::Device::Ethernet: connect(qobject_cast(device.data()), &NetworkManager::WiredDevice::bitRateChanged, this, &KyNetworkResourceManager::onDeviceBitRateChange); connect(qobject_cast(device.data()), &NetworkManager::WiredDevice::carrierChanged, this, &KyNetworkResourceManager::onDeviceCarrierChange); connect(qobject_cast(device.data()), &NetworkManager::WiredDevice::hardwareAddressChanged, this, &KyNetworkResourceManager::onDeviceMacAddressChange); break; case NetworkManager::Device::Wifi: connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::networkAppeared, this, &KyNetworkResourceManager::onWifiNetworkAppeared); connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::networkDisappeared, this, &KyNetworkResourceManager::onWifiNetworkDisappeared); break; default: //TODO: other device types! break; } } //m_deviceList 初始化 void KyNetworkResourceManager::insertDevices() { for (auto const & device : NetworkManager::networkInterfaces()) { if (device.isNull()) { continue; } addDevice(device); } } //m_wifiNetList 删除 void KyNetworkResourceManager::removeWifiNetwork(int pos) { //network signals NetworkManager::WirelessNetwork::Ptr net = m_wifiNetList.takeAt(pos); net->disconnect(this); } //m_wifiNetList 清空 void KyNetworkResourceManager::clearWifiNetworks() { while (0 < m_wifiNetList.size()) removeWifiNetwork(0); } //m_wifiNetList 增加 void KyNetworkResourceManager::addWifiNetwork(NetworkManager::WirelessNetwork::Ptr net) { m_wifiNetList.push_back(net); connect(net.data(), &NetworkManager::WirelessNetwork::signalStrengthChanged, this, &KyNetworkResourceManager::onUpdateWirelessNet); connect(net.data(), &NetworkManager::WirelessNetwork::referenceAccessPointChanged, this, &KyNetworkResourceManager::onUpdateWirelessNet); connect(net.data(), &NetworkManager::WirelessNetwork::disappeared, this, &KyNetworkResourceManager::onUpdateWirelessNet); } //m_wifiNetList 初始化 void KyNetworkResourceManager::insertWifiNetworks() { for (auto const & device : m_deviceList) { if (device.isNull()) { continue; } if (NetworkManager::Device::Wifi == device->type()) { NetworkManager::WirelessDevice::Ptr w_dev = device.objectCast(); for (auto const & net : w_dev->networks()) { if (!net.isNull()) { addWifiNetwork(net); Q_EMIT wifiNetworkAdded(device->interfaceName(),net->ssid()); } } } } } //get NetworkManager::ActiveConnection::List KyNetworkResourceManager::getActiveConnectList() { return m_activeConnectList; } NetworkManager::Connection::List KyNetworkResourceManager::getConnectList() { return m_connectList; } NetworkManager::Device::List KyNetworkResourceManager::getNetworkDeviceList() { return m_deviceList; } NetworkManager::WirelessNetwork::List KyNetworkResourceManager::getWifiNetworkList() { return m_wifiNetList; } //查找类接口===================================================================================================== NetworkManager::ActiveConnection::Ptr KyNetworkResourceManager::findActiveConnectionByPath(QString const & path) { NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; if (path.isEmpty()) { return nullptr; } if (m_activeConnectList.isEmpty()) { return nullptr; } for (int index = 0; index < m_activeConnectList.size(); ++index) { activeConnectPtr = m_activeConnectList.at(index); if (activeConnectPtr.isNull()) { continue; } if (activeConnectPtr->path() == path) { return activeConnectPtr; } } return nullptr; } NetworkManager::Device::Ptr KyNetworkResourceManager::findDeviceByUni(QString const & deviceUni) { NetworkManager::Device::Ptr devicePtr = nullptr; if (deviceUni.isEmpty()) { return nullptr; } for (int index = 0; index < m_deviceList.size(); ++index) { devicePtr = m_deviceList.at(index); if (devicePtr.isNull()) { continue; } if (devicePtr->uni() == deviceUni) { return devicePtr; } } return nullptr; } NetworkManager::Device::Ptr KyNetworkResourceManager::findDeviceByName(QString interfaceName) { NetworkManager::Device::Ptr devicePtr = nullptr; if (interfaceName.isEmpty()) { return nullptr; } for (int index = 0; index < m_deviceList.size(); ++index) { devicePtr = m_deviceList.at(index); if (devicePtr.isNull()) { continue; } if (devicePtr->interfaceName() == interfaceName) { return devicePtr; } } return nullptr; } NetworkManager::WirelessNetwork::Ptr KyNetworkResourceManager::findWifiNetwork(QString const & ssid, QString const & deviceUni) { NetworkManager::WirelessNetwork::Ptr wifiNetPtr = nullptr; if (ssid.isEmpty() || deviceUni.isEmpty()) { return nullptr; } if (m_wifiNetList.isEmpty()) { return nullptr; } for (int index = 0; index < m_wifiNetList.size(); ++index) { wifiNetPtr = m_wifiNetList.at(index); if (wifiNetPtr.isNull()) { continue; } if (wifiNetPtr->ssid() == ssid && wifiNetPtr->device() == deviceUni) { return wifiNetPtr; } } return nullptr; } NetworkManager::ActiveConnection::Ptr KyNetworkResourceManager::findActiveConnectByUuid(const QString activeConnectUuid) { int index = 0; NetworkManager::ActiveConnection::Ptr activateConnectPtr = nullptr; qDebug()<<"[KyNetworkResourceManager]"<<"get activetate connect with uuid"<< activeConnectUuid; if (activeConnectUuid.isEmpty()) { return nullptr; } for (index = 0; index < m_activeConnectList.size(); ++index) { activateConnectPtr = m_activeConnectList.at(index); if (activateConnectPtr.isNull()) { continue; } if (activateConnectPtr->uuid() == activeConnectUuid) { return activateConnectPtr; } } qWarning()<<"[KyNetworkResourceManager]"<<"it can not find the activate connect with uuid" <uuid() == connectUuid) { return connectPtr; } } qWarning()<<"[KyNetworkResourceManager]"<<"it can not find connect with uuid"<uuid() == uuid && NetworkManager::ActiveConnection::State::Activated == activateConnectPtr->state()) { return true; } } return false; } //属性判断类接口===================================================================== bool KyNetworkResourceManager::isWiredConnect(QString connectPath) { QString connectionType = getConnectTypeByDbus(connectPath); if (ETHERNET_TYPE == connectionType) { return true; } return false; } bool KyNetworkResourceManager::isActivatingConnection(QString uuid) { int index = 0; NetworkManager::ActiveConnection::Ptr activateConnectPtr = nullptr; if (uuid.isEmpty()) { return false; } for (index = 0; index < m_activeConnectList.size(); ++index) { activateConnectPtr = m_activeConnectList.at(index); if (activateConnectPtr.isNull()) { continue; } if (activateConnectPtr->uuid() == uuid && NetworkManager::ActiveConnection::State::Activating == activateConnectPtr->state()) { return true; } } return false; } bool KyNetworkResourceManager::isApConnection(NetworkManager::Connection::Ptr connectPtr) { if (nullptr == connectPtr) { return false; } if (NetworkManager::ConnectionSettings::ConnectionType::Wireless != connectPtr->settings()->connectionType()) { return false; } NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); NetworkManager::WirelessSetting::Ptr wirelessSetting = settingPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); if (NetworkManager::WirelessSetting::NetworkMode::Ap != wirelessSetting->mode()) { return false; } return true; } void KyNetworkResourceManager::getConnectivity(KyConnectivity &connectivity) { connectivity = (KyConnectivity)NetworkManager::connectivity(); } void KyNetworkResourceManager::requestScan(NetworkManager::WirelessDevice *p_wirelessDevice) { if (nullptr == p_wirelessDevice) { qWarning() << LOG_FLAG << "request scan failed, wireless device is invalid."; return; } QDBusPendingReply<> reply = p_wirelessDevice->requestScan(); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, p_wirelessDevice); connect(watcher, &QDBusPendingCallWatcher::finished, [p_wirelessDevice] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { //TODO: in what form should we output the warning messages qWarning() << QStringLiteral("requestScan on device '%1' failed: %3").arg(p_wirelessDevice->interfaceName()) .arg(watcher->error().message()); } watcher->deleteLater(); }); return; } void KyNetworkResourceManager::onPropertiesChanged(QVariantMap qvm) { for(QString keyStr : qvm.keys()) { //收到wifi开关打开或关闭的信号后,进行处理 if (keyStr == "WiredEnabled") { bool wiredEnable = qvm.value("WiredEnabled").toBool(); qDebug() << "wiredEnabledChanged" << wiredEnable; Q_EMIT wiredEnabledChanged(wiredEnable); } } } void KyNetworkResourceManager::onConnectionUpdated() { NetworkManager::Connection *connectPtr = qobject_cast(sender()); if (nullptr != connectPtr && connectPtr->isValid()) { NetworkManager::ConnectionSettings::Ptr connectSettingPtr = connectPtr->settings(); if (NetworkManager::ConnectionSettings::ConnectionType::Wireless == connectSettingPtr->connectionType()) { Q_EMIT wirelessConnectionUpdate(connectSettingPtr->interfaceName(), connectPtr->uuid(), connectPtr->name(), connectPtr->path()); } else if (isWiredConnect(connectPtr->path())) { Q_EMIT wiredConnectionUpdate(connectSettingPtr->interfaceName(), connectPtr->uuid(), connectPtr->name(), connectPtr->path()); } else { Q_EMIT connectionUpdate(connectPtr->uuid(), connectPtr->name(), connectPtr->path()); } } else { qWarning()<< LOG_FLAG <<"onConnectionUpdate failed, the connect is invalid"; } } void KyNetworkResourceManager::wirelessActiveStateChange(NetworkManager::ConnectionSettings::Ptr connectSettingsPtr, QString deviceName, QString uuid, KyConnectState state) { NetworkManager::WirelessSetting::Ptr wirelessSettingsPtr = connectSettingsPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); if (wirelessSettingsPtr.isNull()) { qDebug()<< LOG_FLAG << "don't have WirelessSetting connection"; return; } QByteArray rawSsid = wirelessSettingsPtr->ssid(); QString ssid = getSsidFromByteArray(rawSsid); Q_EMIT wirelessConnectStateChange(deviceName, ssid, uuid, state); } void KyNetworkResourceManager::wiredActiveStateChange(QString connectPath, QString deviceName, QString uuid, KyConnectState state) { QString connectionType = getConnectTypeByDbus(connectPath); if (ETHERNET_TYPE == connectionType) { Q_EMIT wiredConnectStateChange(deviceName, uuid, state); } else { qWarning() << LOG_FLAG << "the connect type is not wired" << connectionType; } } void KyNetworkResourceManager::connectActiveStateChange(NetworkManager::Connection::Ptr connectPtr, QString deviceName, KyConnectState state) { QString uuid = connectPtr->uuid(); NetworkManager::ConnectionSettings::Ptr connectSettingsPtr = connectPtr->settings(); KyConnectionType connectionType = (KyConnectionType)connectSettingsPtr->connectionType(); if (connectionType == CONNECT_TYPE_WIRELESS) { wirelessActiveStateChange(connectSettingsPtr, deviceName, uuid, state); NetworkManager::WirelessSetting::Ptr wirelessSetting = connectSettingsPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); if (NetworkManager::WirelessSetting::NetworkMode::Ap == wirelessSetting->mode()) { Q_EMIT wirelessApConnectStateChange(); } } else if (connectionType == CONNECT_TYPE_WIRED) { wiredActiveStateChange(connectPtr->path(), deviceName, uuid, state); } else { qWarning() << LOG_FLAG << "connect type is undefined" << connectionType; } } void KyNetworkResourceManager::onActiveConnectionChanged( NetworkManager::ActiveConnection::State state) { NetworkManager::ActiveConnection * activeConnect = qobject_cast(sender()); if (nullptr != activeConnect && activeConnect->isValid()) { QString deviceName = ""; QStringList interfaces = activeConnect->devices(); if (interfaces.size() > 0) { QString ifaceUni = interfaces.at(0); NetworkManager::Device:: Ptr devicePtr = findDeviceByUni(ifaceUni); if (devicePtr != nullptr) { deviceName = devicePtr->interfaceName(); } } NetworkManager::Connection::Ptr connectPtr = activeConnect->connection(); connectActiveStateChange(connectPtr, deviceName, (KyConnectState)state); } else { qWarning() << LOG_FLAG << "onActiveConnectionChanged failed, the connection is invalid."; } } void KyNetworkResourceManager::onVpnActiveConnectChangedReason(NetworkManager::VpnConnection::State state, NetworkManager::VpnConnection::StateChangeReason reason) { NetworkManager::ActiveConnection *activeConnect = qobject_cast(sender()); if (nullptr != activeConnect && activeConnect->isValid()) { qDebug()<<"vpn connect uuid" << activeConnect->uuid() <<"state change " <uuid(), state, reason); } else { qWarning() << LOG_FLAG << "onVpnActiveConnectChangedReason failed, the connection is invalid."; } } void KyNetworkResourceManager::onDeviceActiveChange() { NetworkManager::Device *p_device = qobject_cast(sender()); if (nullptr == p_device) { return; } QString deviceName = p_device->interfaceName(); //此处需要取反,因为激活连接的网卡状态是false,断开连接的网卡状态是true bool isActive = !p_device->isActive(); qDebug()<< LOG_FLAG << "device active change, device name " << deviceName << "active state" << isActive; Q_EMIT deviceActiveChange(deviceName, isActive); } void KyNetworkResourceManager::updateDeviceName(NetworkManager::Device *p_device) { QString newDeviceName = p_device->interfaceName(); QString deviceUni = p_device->uni(); if (m_deviceMap.contains(deviceUni)) { if (m_deviceMap[deviceUni] != newDeviceName) { QString oldDeviceName = m_deviceMap[deviceUni]; m_deviceMap[deviceUni] = newDeviceName; if (DEVICE_TYPE_WIFI == (KyDeviceType)p_device->type()) { Q_EMIT wirelessDeviceUpdate(oldDeviceName, newDeviceName); } else if (DEVICE_TYPE_ETHERNET == (KyDeviceType)p_device->type() && !p_device->udi().startsWith(VIRTURAL_DEVICE_PATH)) { Q_EMIT wiredDeviceUpdate(oldDeviceName, newDeviceName);; } else { Q_EMIT deviceUpdate(oldDeviceName, newDeviceName); } } } } void KyNetworkResourceManager::onDeviceUpdated() { NetworkManager::Device *p_device = qobject_cast(sender()); if (nullptr == p_device) { return; } updateDeviceName(p_device); } void KyNetworkResourceManager::onDeviceManagedChange() { NetworkManager::Device *p_device = qobject_cast(sender()); if (nullptr == p_device) { return; } QString deviceName = p_device->interfaceName(); bool managed = p_device->managed(); Q_EMIT deviceManagedChange(deviceName, managed); } void KyNetworkResourceManager::onDeviceCarrierChange(bool pluged) { NetworkManager::WiredDevice * networkDevice = qobject_cast(sender()); qDebug()<< LOG_FLAG<<"device carrier change"<< pluged; if (nullptr !=networkDevice && networkDevice->isValid()) { Q_EMIT deviceCarrierChange(networkDevice->interfaceName(), pluged); } else { qWarning()<< LOG_FLAG<<"onDeviceCarrierChange failed."; } } void KyNetworkResourceManager::onDeviceBitRateChange(int bitRate) { NetworkManager::WiredDevice * networkDevice = qobject_cast(sender()); if (nullptr != networkDevice && networkDevice->isValid()) { Q_EMIT deviceBitRateChange(networkDevice->interfaceName(), bitRate); } else { qWarning()<< LOG_FLAG <<"the device is not invalid with bitrate" << bitRate; } } //暂未用到 void KyNetworkResourceManager::onDeviceMacAddressChange(const QString &hwAddress) { NetworkManager::WiredDevice * networkDevice = qobject_cast(sender()); if (nullptr != networkDevice && networkDevice->isValid()) { Q_EMIT deviceMacAddressChange(networkDevice->interfaceName(), hwAddress); } else { qWarning()<< LOG_FLAG <<"the device is not invalid with mac" << hwAddress; } } //设备状态变化 void KyNetworkResourceManager::onDeviceStateChanged( NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason) { qDebug() << LOG_FLAG <<"the device state "<(sender()); Q_EMIT deviceStateChange(networkDevice->interfaceName(), (KyDeviceState)newstate, (KyDeviceState)oldstate, reason); } void KyNetworkResourceManager::wifiNetworkAdd(NetworkManager::Device * dev, QString const & ssid) { if (nullptr == dev) { return; } NetworkManager::WirelessDevice * w_dev = qobject_cast(dev); NetworkManager::WirelessNetwork::Ptr net = w_dev->findNetwork(ssid); if (!net.isNull()) { if (0 > m_wifiNetList.indexOf(net)){ addWifiNetwork(net); } else { //TODO: onWifiNetworkUpdate qDebug()<< LOG_FLAG << "add but already exist"; } NetworkManager::AccessPoint::Ptr accessPoitPtr = net->referenceAccessPoint(); QByteArray rawSsid = accessPoitPtr->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); Q_EMIT wifiNetworkAdded(dev->interfaceName(), wifiSsid); } return; } void KyNetworkResourceManager::wifiNetworkUpdate(NetworkManager::WirelessNetwork * net) { if (nullptr == net) { return; } auto index = std::find(m_wifiNetList.cbegin(), m_wifiNetList.cend(), net); if (m_wifiNetList.cend() != index) { if (net->accessPoints().isEmpty()) { //emit bool bFlag = false; QString devIface; NetworkManager::Device::Ptr dev = findDeviceByUni(net->device()); if(dev.isNull()) { qDebug()<< LOG_FLAG << "device invalid"; bFlag = true; } else { devIface = dev->interfaceName(); } //remove auto pos = index - m_wifiNetList.cbegin(); removeWifiNetwork(pos); if(bFlag) { Q_EMIT wifiNetworkDeviceDisappear(); } else { NetworkManager::AccessPoint::Ptr accessPoitPtr = net->referenceAccessPoint(); if (accessPoitPtr.isNull()) { return; } QByteArray rawSsid = accessPoitPtr->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); Q_EMIT wifiNetworkRemoved(devIface, wifiSsid); } } else { Q_EMIT wifiNetworkPropertyChange(*index); } } return; } void KyNetworkResourceManager::wifiNetworkRemove(NetworkManager::Device * dev, QString const & ssid) { if (nullptr == dev) { return; } NetworkManager::WirelessNetwork::Ptr net = findWifiNetwork(ssid, dev->uni()); if (!net.isNull()) { auto pos = m_wifiNetList.indexOf(net); if (0 <= pos) { removeWifiNetwork(pos); NetworkManager::AccessPoint::Ptr accessPoitPtr = net->referenceAccessPoint(); QByteArray rawSsid = accessPoitPtr->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); Q_EMIT wifiNetworkRemoved(dev->interfaceName(), wifiSsid); } } return; } void KyNetworkResourceManager::onWifiNetworkAppeared(QString const & ssid) { NetworkManager::Device * p_device = qobject_cast(sender()); if (nullptr != p_device) { wifiNetworkAdd(p_device, ssid); updateDeviceName(p_device); } else { qWarning()<< LOG_FLAG << "onWifiNetworkAppeared failed."; } } void KyNetworkResourceManager::onWifiNetworkDisappeared(QString const & ssid) { NetworkManager::Device *p_device = qobject_cast(sender()); if (nullptr != p_device) { wifiNetworkRemove(p_device, ssid); updateDeviceName(p_device); } else { qWarning()<< LOG_FLAG << "onWifiNetworkDisappeared failed."; } } void KyNetworkResourceManager::onUpdateWirelessNet() { NetworkManager::WirelessNetwork *p_wirelessNet = qobject_cast(sender()); if (nullptr != p_wirelessNet) { wifiNetworkUpdate(p_wirelessNet); } } void KyNetworkResourceManager::onDeviceAdded(QString const & uni) { NetworkManager::Device::Ptr networkDevicePtr = NetworkManager::findNetworkInterface(uni); if (networkDevicePtr.isNull()) { qWarning()<<"the device is not exist in networkmanager."<< uni; return; } if (!networkDevicePtr->isValid()) { qWarning() << uni << " is currently not invalid"; return; } if (0 > m_deviceList.indexOf(networkDevicePtr)) { addDevice(networkDevicePtr); if (DEVICE_TYPE_WIFI == (KyDeviceType)networkDevicePtr->type()) { Q_EMIT wirelessDeviceAdd(networkDevicePtr->interfaceName()); } else if (DEVICE_TYPE_ETHERNET == (KyDeviceType)networkDevicePtr->type() && !networkDevicePtr->udi().startsWith(VIRTURAL_DEVICE_PATH)) { Q_EMIT wiredDeviceAdd(networkDevicePtr->interfaceName()); } else { Q_EMIT deviceAdd(networkDevicePtr->interfaceName(), (KyDeviceType)networkDevicePtr->type()); } } else { qWarning() << networkDevicePtr->interfaceName() <<"the device is exist in network device list."; } } void KyNetworkResourceManager::onDeviceRemoved(QString const & uni) { NetworkManager::Device::Ptr networkDevice = findDeviceByUni(uni); if (networkDevice.isNull()) { qWarning()<<"the device is not exist in network device list ."<< uni; return; } auto index = std::find(m_deviceList.cbegin(), m_deviceList.cend(), networkDevice); if (m_deviceList.cend() != index) { const int pos = index - m_deviceList.cbegin(); removeDevice(pos); } } void KyNetworkResourceManager::onActiveConnectionAdded(QString const & path) { NetworkManager::ActiveConnection::Ptr activeConnectPtr = NetworkManager::findActiveConnection(path); if (activeConnectPtr.isNull()) { qWarning() << "[KyNetworkResourceManager]" << "the active connect is null, so do not add it."<isValid()) { qWarning() << "[KyNetworkResourceManager]" << path << " connect is currently not valid"; return; } // qDebug()<<"add active connect"<connection()->name(); if (0 > m_activeConnectList.indexOf(activeConnectPtr)) { addActiveConnection(activeConnectPtr); Q_EMIT activeConnectionAdd(activeConnectPtr->uuid()); } else { //TODO: onActiveConnectionUpdate qWarning() << "[KyNetworkResourceManager]" << "update active connection to do"; //emit activeConnectionUpdate(conn->uuid()); } } void KyNetworkResourceManager::onActiveConnectionRemoved(QString const & path) { NetworkManager::ActiveConnection::Ptr activeConnectPtr = findActiveConnectionByPath(path);//XXX: const QString &uni if (activeConnectPtr.isNull()) { qWarning() <<"[KyNetworkResourceManager]" <<"the active connect is null, so do not remove it. "<< path; return; } auto index = std::find(m_activeConnectList.cbegin(), m_activeConnectList.cend(), activeConnectPtr); if (m_activeConnectList.cend() != index) { const int pos = index - m_activeConnectList.cbegin(); removeActiveConnection(pos); Q_EMIT activeConnectionRemove(activeConnectPtr->uuid()); } } void KyNetworkResourceManager::onConnectionAdded(QString const & path) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnection(path); if (connectPtr.isNull()) { qWarning() <<"[KyNetworkResourceManager]" <<"it can not find in networkmanager."<isValid()) { qWarning() <<"[KyNetworkResourceManager]" << path << " is currently not invalid"; return; } if (connectPtr->name().isEmpty() || connectPtr->uuid().isEmpty()) { qWarning() <<"[KyNetworkResourceManager]" << "the name or uuid of connection is empty"; return; } if (0 > m_connectList.indexOf(connectPtr)) { addConnection(connectPtr); NetworkManager::ConnectionSettings::Ptr connectSettingPtr = connectPtr->settings(); if (NetworkManager::ConnectionSettings::ConnectionType::Wireless == connectSettingPtr->connectionType()) { Q_EMIT wirelessConnectionAdd(connectPtr->uuid(), connectPtr->name(), connectPtr->path()); } else if (isWiredConnect(connectPtr->path())) { Q_EMIT wiredConnectionAdd(connectPtr->settings()->interfaceName(), connectPtr->uuid(), connectPtr->name(), connectPtr->path()); } else { Q_EMIT connectionAdd(connectPtr->uuid(), connectPtr->name(), connectPtr->path()); } } else { //TODO::updateconnect qWarning() << "[KyNetworkResourceManager]" << connectPtr->uuid() <<" connect is exist in connect list."; } } void KyNetworkResourceManager::onConnectionRemoved(QString const & path) { if (path.isEmpty()) { qDebug() <<"[KyNetworkResourceManager]" <<"the connect path is empty"; return; } NetworkManager::Connection::Ptr connectionPtr = nullptr; for (int index = 0; index < m_connectList.size(); ++index) { connectionPtr = m_connectList.at(index); if (connectionPtr->path() == path) { removeConnection(index); Q_EMIT connectionRemove(path); return; } } qWarning() <<"[KyNetworkResourceManager]" << path <<" connect is no exist in connect list"; } void KyNetworkResourceManager::onConnectivityChanged(NetworkManager::Connectivity connectivity) { qDebug() << "onConnectivityChanged"; Q_EMIT connectivityChanged((KyConnectivity)connectivity); } void KyNetworkResourceManager::onPrimaryConnectionTypeChanged(NetworkManager::ConnectionSettings::ConnectionType type) { Q_EMIT primaryConnectionTypeChanged((KyConnectionType)type); } void KyNetworkResourceManager::connectionDump() { NetworkManager::Connection::Ptr connectionPtr = nullptr; for (int index = 0; index < m_connectList.size(); ++index) { connectionPtr = m_connectList.at(index); qDebug()<<"connection info**********************"; qDebug()<<"connection name"<< connectionPtr->name(); qDebug()<<"connection uuid"<< connectionPtr->uuid(); qDebug()<<"connection path"<< connectionPtr->path(); } } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectoperation.cpp0000664000175000017500000002531015160517205026606 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinconnectoperation.h" #include "kylinnetworkdeviceresource.h" #include #include #include #include #include KyConnectOperation::KyConnectOperation(QObject *parent) : QObject(parent) { m_networkResourceInstance = KyNetworkResourceManager::getInstance(); } KyConnectOperation::~KyConnectOperation() { m_networkResourceInstance = nullptr; } void KyConnectOperation::ipv4SettingSet( NetworkManager::Ipv4Setting::Ptr &ipv4Setting, const KyConnectSetting &connectSettingsInfo) { ipv4Setting->setInitialized(true); ipv4Setting->setDns(connectSettingsInfo.m_ipv4Dns); if (CONFIG_IP_DHCP == connectSettingsInfo.m_ipv4ConfigIpType) { ipv4Setting->setMethod(NetworkManager::Ipv4Setting::Automatic); return; } else { ipv4Setting->setMethod(NetworkManager::Ipv4Setting::Manual); } ipv4Setting->setAddresses(connectSettingsInfo.m_ipv4Address); return; } void KyConnectOperation::ipv6SettingSet( NetworkManager::Ipv6Setting::Ptr &ipv6Setting, const KyConnectSetting &connectSettingsInfo) { ipv6Setting->setInitialized(true); ipv6Setting->setDns(connectSettingsInfo.m_ipv6Dns); if (CONFIG_IP_DHCP == connectSettingsInfo.m_ipv6ConfigIpType) { ipv6Setting->setMethod(NetworkManager::Ipv6Setting::Automatic); ipv6Setting->setPrivacy(NetworkManager::Ipv6Setting::Disabled); return; } ipv6Setting->setMethod(NetworkManager::Ipv6Setting::Manual); ipv6Setting->setAddresses(connectSettingsInfo.m_ipv6Address); return ; } void KyConnectOperation::connectSettingSet( NetworkManager::ConnectionSettings::Ptr connectionSettings, const KyConnectSetting &connectSettingsInfo) { connectionSettings->setId(connectSettingsInfo.m_connectName); connectionSettings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); connectionSettings->setAutoconnect(true); connectionSettings->setAutoconnectPriority(0); if (!connectSettingsInfo.m_ifaceName.isEmpty()) { connectionSettings->setInterfaceName(connectSettingsInfo.m_ifaceName); } return; } void KyConnectOperation::setAutoConnect(NetworkManager::ConnectionSettings::Ptr &connectSetting, bool bAutoConnect) { if (connectSetting.isNull()) { return; } connectSetting->setAutoconnect(bAutoConnect); return; } //ipv4 ipv6更新 void KyConnectOperation::updateConnect(QString connectUuid, const KyConnectSetting &connectSettingsInfo) { NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(connectUuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + connectUuid; qWarning() << errorMessage; Q_EMIT updateConnectionError(errorMessage); return; } NetworkManager::ConnectionSettings::Ptr connectSettingPtr = connectPtr->settings(); NetworkManager::Ipv4Setting::Ptr ipv4Setting = connectSettingPtr->setting(NetworkManager::Setting::Ipv4).dynamicCast(); ipv4SettingSet(ipv4Setting, connectSettingsInfo); NetworkManager::Ipv6Setting::Ptr ipv6Setting = connectSettingPtr->setting(NetworkManager::Setting::Ipv6).dynamicCast(); ipv6SettingSet(ipv6Setting, connectSettingsInfo); NMVariantMapMap connectMapMap = connectSettingPtr->toMap(); if (connectMapMap.contains("ipv4")) { QVariantMap ipv4SettingMap = connectMapMap.value(QLatin1String("ipv4")); if (ipv4SettingMap.contains("method") && ipv4SettingMap["method"] == "auto") { if (ipv4SettingMap.contains("address-data")) { ipv4SettingMap.remove("address-data"); } if (ipv4SettingMap.contains("addresses")) { ipv4SettingMap.remove("addresses"); } if (ipv4SettingMap.contains("gateway")) { ipv4SettingMap.remove("gateway"); } } connectMapMap["ipv4"] = ipv4SettingMap; } if (connectMapMap.contains("ipv6")) { QVariantMap ipv4SettingMap = connectMapMap.value(QLatin1String("ipv6")); if (ipv4SettingMap.contains("method") && ipv4SettingMap["method"] == "auto") { if (ipv4SettingMap.contains("address-data")) { ipv4SettingMap.remove("address-data"); } if (ipv4SettingMap.contains("addresses")) { ipv4SettingMap.remove("addresses"); } if (ipv4SettingMap.contains("gateway")) { ipv4SettingMap.remove("gateway"); } } connectMapMap["ipv6"] = ipv4SettingMap; } connectPtr->update(connectMapMap); } void KyConnectOperation::deleteConnect(const QString &connectUuid) { qDebug()<<"delete connect uuid " << connectUuid; NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnectionByUuid(connectUuid); if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + connectUuid; qWarning()<remove(); return ; } void KyConnectOperation::activateConnection(const QString connectUuid, const QString deviceName) { QString connectPath = ""; QString deviceIdentifier = ""; QString connectName = ""; QString specificObject = ""; NetworkManager::Connection::Ptr connectPtr = nullptr; qDebug()<<"it will activate connect"<settings()->connectionType()) { QString errorMessage = tr("the connect type is") + connectPtr->settings()->connectionType() + tr(", but it is not wired"); qWarning()<path(); connectName = connectPtr->name(); // deviceName = connectPtr->settings()->interfaceName(); // for (auto const & dev : m_networkResourceInstance->m_devices) { // for (auto const & dev_conn : dev->availableConnections()) { // if (dev_conn == connectPtr) { // deviceIdentifier = dev->uni(); // deviceName = dev->interfaceName(); // break; // } // } // } auto dev = m_networkResourceInstance->findDeviceByName(deviceName); if (!dev.isNull()) { deviceIdentifier = dev->uni(); } if (deviceIdentifier.isEmpty()) { QString errorMessage = tr("device Identifier is empty, its name") + deviceName; qWarning() << errorMessage; Q_EMIT activateConnectionError(errorMessage); return; } if (NetworkManager::ConnectionSettings::Wired == connectPtr->settings()->connectionType()) { KyNetworkDeviceResourse deviceResource; if (!deviceResource.wiredDeviceIsCarriered(deviceName)) { qWarning() << deviceName << "is not carried, so can not activate connection"; return; } } qDebug() <<"active wired connect: path "<< connectPath << "device identify " << deviceIdentifier << "connect name " << connectName << "device name" << deviceName << "specific parameter"<< specificObject; QDBusPendingCallWatcher * watcher; watcher = new QDBusPendingCallWatcher{NetworkManager::activateConnection(connectPath, deviceIdentifier, specificObject), this}; connect(watcher, &QDBusPendingCallWatcher::finished, [this, connectName, deviceName] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("activate connection failed: ") + watcher->error().message(); qWarning()<activateConnectionError(errorMessage); } else { qWarning()<<"active wired connect complete."; } watcher->deleteLater(); }); } void KyConnectOperation::deactivateConnection(const QString &activeConnectUuid) { NetworkManager::ActiveConnection::Ptr activateConnectPtr = nullptr; activateConnectPtr = m_networkResourceInstance->findActiveConnectByUuid(activeConnectUuid); if (nullptr == activateConnectPtr) { QString errorMessage = tr("it can not find the activate connect") + tr("uuid") + activeConnectUuid; qWarning()<path(); QDBusPendingReply<> reply = NetworkManager::deactivateConnection(activateConnectPtr->path()); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); connect(watcher, &QDBusPendingCallWatcher::finished, [this, activateConnectPtr] (QDBusPendingCallWatcher * watcher) { if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("deactivation of connection") + activateConnectPtr->connection()->name() + tr("failed:") + watcher->error().message(); qWarning()<deactivateConnectionError(errorMessage); } else { qWarning() << "deactive connect operation finished" << activateConnectPtr->connection()->name(); } watcher->deleteLater(); }); } libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwirednetresource.h0000664000175000017500000000412315160517205026271 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINCONNECTRESOURCE_H #define KYLINCONNECTRESOURCE_H #include #include "kylinnetworkresourcemanager.h" #include "kylinnetresource.h" #include "kylinconnectitem.h" #include "kylinnetworkdeviceresource.h" #include "kylinconnectsetting.h" #include "kylinapconnectitem.h" class KyWiredConnectResourse : public KyNetResource { Q_OBJECT public: explicit KyWiredConnectResourse(QObject *parent = nullptr); public: void getWiredList(QMap> &map); void getWiredConnectDetail(QString interface, QString uuid, KyDetailInfo &connectSetting); private: void kyWirdNetItemListInit(); KyWiredItem getConnectionItem(NetworkManager::Connection::Ptr connectPtr); Q_SIGNALS: void wiredConnectionAdd(QString devName, QString connectUuid, QString connectName, QString connectPath); void wiredConnectionUpdate(QString devName, QString connectUuid, QString connectName, QString connectPath); void connectionRemove(QString path); void wiredDeviceAdd(QString deviceName); void wiredDeviceUpdate(QString oldDeviceName, QString newDeviceName); void deviceRemove(QString deviceName); private: QMap> m_wiredNetworkMap; }; #endif // KYLINCONNECTRESOURCE_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/libnm-base-kylin_global.h0000664000175000017500000000216715160517205025055 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef LIBNMBASEKYLIN_GLOBAL_H #define LIBNMBASEKYLIN_GLOBAL_H #include #if defined(LIBNMBASEKYLIN_LIBRARY) # define LIBNMBASEKYLIN_EXPORT Q_DECL_EXPORT #else # define LIBNMBASEKYLIN_EXPORT Q_DECL_IMPORT #endif #endif // LIBNMBASEKYLIN_GLOBAL_H libkylin-nm-base/libnm-kylin/libnm-base-kylin/kylinnetworkmanager.h0000664000175000017500000002344615160517205024476 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINNETWORKMANAGER_H #define KYLINNETWORKMANAGER_H #include #include "libnm-base-kylin_global.h" #include "depend/kylinnetworkresourcemanager.h" #include "depend/kylinactiveconnectresource.h" #include "depend/kylinnetworkdeviceresource.h" #include "depend/kylinconnectoperation.h" #include "depend/kylinwiredconnectoperation.h" #include "depend/kylinwirednetresource.h" #include "depend/kywirelessconnectoperation.h" #include "depend/kywirelessnetresource.h" #include "depend/kylinnetresource.h" #include "depend/kyapnetresource.h" #include "depend/kylingeneral.h" class LIBNMBASEKYLIN_EXPORT KyNetworkManager : public QObject { Q_OBJECT public: explicit KyNetworkManager(QObject *parent = nullptr); ~KyNetworkManager(); private: bool m_init = false; KyNetworkResourceManager *m_networkResource; KyActiveConnectResourse *m_activeConnectResource; KyNetworkDeviceResourse *m_deviceResource; KylinGeneralOpration *m_general; KyWiredConnectResourse *m_wiredConnectResourse; KyWirelessNetResource *m_wirelessNetResource; KyApNetResource *m_apNetResource; void initConnect(); Q_SIGNALS: void initFinished(); //activeConnection void wiredStateChange(QString deviceName, QString uuid, KyConnectState state); void wirelessStateChange(QString deviceName, QString ssid, QString uuid, KyConnectState state); //device void deviceStateChange(QString deviceName, KyDeviceState newstate, KyDeviceState oldstate, NetworkManager::Device::StateChangeReason reason); void carrierChange(QString deviceName, bool pluged); void deviceRemove(QString deviceName); void deviceManagedChange(QString deviceName, bool managed); //general void wifiEnabledChanged(bool); void wiredEnabledChanged(bool); void networkingEnabledChanged(bool); void connectStatusChanged(KyConnectStatus); //wired void wiredConnectionAdd(QString devName, QString connectUuid, QString connectName, QString connectPath); void wiredConnectionUpdate(QString devName, QString connectUuid, QString connectName, QString connectPath); void connectionRemove(QString path); void wiredDeviceAdd(QString deviceName); void wiredDeviceUpdate(QString oldDeviceName, QString newDeviceName); //wireless void signalStrengthChange(QString deviceName, QString ssid, int strength); void secuTypeChange(QString deviceName, QString ssid, QString securityType); void wirelessConnectionRemove(QString deviceName, QString ssid); void wirelessConnectionAdd(QString deviceName, QString ssid, QString uuid, QString dbusPath); void wirelessConnectionUpdate(QString deviceName, QString ssid, QString uuid, QString dbusPath, KySecuType connectSecuType); void wifiNetworkUpdate(QString, QString, KyWirelessNetItem); void wifiNetworkAdd(QString deviceName, KyWirelessNetItem &item); void wifiNetworkRemove(QString deviceName, QString ssid); void wirelessDeviceAdd(QString deviceName); void wirelessDeviceNameUpdate(QString oldName, QString newName); void updateWifiList(QString, QList, QList); //移动热点 void wirelessApConnectStateChange(); public: bool isInitFinished(){return m_init;} //activeConnection void getActiveConnectionList(QString deviceName, KyConnectionType connectionType, QList &connectItemList); int getAcivateWifiSignal(); //device void getNetworkDeviceList(KyDeviceType deviceType, QStringList &networkDeviceList); bool getDeviceManaged(QString devName); KyDeviceState getDeviceState(QString deviceName); void getDeviceConnectivity(const QString deviceName, KyConnectivity &connectivity); //general bool getWirelessEnabled(); bool getWiredEnabled(); bool getNetworkingEnabled(); void getConnectStatus(KyConnectStatus &status); //wired void getWiredList(QMap> &map); //wireless void getWifiNetworkList(QString devName, QList &list); //移动热点 void getApConnections(QList &apConnectItemList); //详情页-->ipv4 + ipv6 + autoconnect void getConnectIpInfo(QString uuid, KyConnectSetting &connectSetting); //详情页-->有线连接detail void getWiredConnectDetail(QString interface, QString uuid, KyDetailInfo &connectSetting); //详情页-->无线连接detail void getWirelessConnectDetail(QString interface, QString ssid, QString uuid, KyDetailInfo &connectSetting); //无线连接-->安全 bool getNormalWifiConnectSecuInfo(QString &uuid, KyWpaPasswordInfo &info); bool getEnterPriseInfoTls(QString &uuid, KyEapMethodTlsInfo &info); bool getEnterPriseInfoPeap(QString &uuid, KyEapMethodPeapInfo &info); bool getEnterPriseInfoTtls(QString &uuid, KyEapMethodTtlsInfo &info); bool getEnterPriseInfoLeap(QString &uuid, KyEapMethodLeapInfo &info); bool getEnterPriseInfoPwd(QString &uuid, KyEapMethodPwdInfo &info); bool getEnterPriseInfoFast(QString &uuid, KyEapMethodFastInfo &info); //获取企业网类型 bool getEnterpiseEapMethod(const QString &uuid, KyEapMethodType &type); bool wiredConnectIsActived(); bool wirelessConnectIsActived(); // bool getWiredDeviceIsCarriered(QString wiredDevName); public Q_SLOTS: void kylinNetworkManagerInit(); //general void onSetWirelessNetworkEnabled(bool enabled); void onSetNetworkingEnabled(bool enabled); void onSetWiredEnabled(bool enabled); void onSetDeviceManaged(QString devName, bool managed); void onSetWiredDeviceEnable(QString interface, bool enable); //有线无线公用 void onDeleteConnect(const QString &connectUuid); void onActivateConnection(const QString connectUuid, const QString deviceName); void onDeactivateConnection(const QString &activeConnectUuid); //wireless //申请扫描 void onRequestWirelessScan(); void onCreateWiredConnect(KyConnectSetting connectSettingsInfo); //详情页 //=======================连接操作==================== //连接无本地配置的非企业网热点 void onAddAndActivateNormalWifi(KyWirelessConnectSetting connSettingInfo, KySecuType type); //连接无本地配置的企业网热点 void onAddAndActiveWirelessEnterPriseTlsConnect(KyEapMethodTlsInfo info, KyWirelessConnectSetting connSettingInfo); void onAddAndActiveWirelessEnterPrisePeapConnect(KyEapMethodPeapInfo info, KyWirelessConnectSetting connSettingInfo); void onAddAndActiveWirelessEnterPriseTtlsConnect(KyEapMethodTtlsInfo info, KyWirelessConnectSetting connSettingInfo); void onAddAndActiveWirelessEnterPriseLeapConnect(KyEapMethodLeapInfo info, KyWirelessConnectSetting connSettingInfo); void onAddAndActiveWirelessEnterPrisePwdConnect(KyEapMethodPwdInfo info, KyWirelessConnectSetting connSettingInfo); void onAddAndActiveWirelessEnterPriseFastConnect(KyEapMethodFastInfo info, KyWirelessConnectSetting connSettingInfo); //=====================新增配置操作==================== //新增普通连接 void onAddNormalConnect(const KyWirelessConnectSetting &connSettingInfo, KySecuType &type); //新增TLS连接 void onAddTlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTlsInfo &tlsinfo); //新增PEAP连接 void onAddPeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPeapInfo &peapInfo); //新增TTLS连接 void onAddTtlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTtlsInfo &ttlsInfo); //=====================更新配置操作==================== void onUpdateIpv4AndIpv6SettingInfo(const QString &uuid, const KyConnectSetting &connectSettingsInfo); //连接修改(安全改为个人/None) void onUpdateWirelessPersonalConnect(const QString &uuid, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange); //连接修改(安全改为改为企业) void onUpdateWirelessEnterPriseTlsConnect(const QString &uuid, const KyEapMethodTlsInfo &tlsinfo); void onUpdateWirelessEnterPrisePeapConnect(const QString &uuid, const KyEapMethodPeapInfo &peapInfo); void onUpdateWirelessEnterPriseTtlsConnect(const QString &uuid, const KyEapMethodTtlsInfo &ttlsInfo); void onUpdateWirelessEnterPriseLeapConnect(const QString &uuid, const KyEapMethodLeapInfo &leapInfo); void onUpdateWirelessEnterPrisePwdConnect(const QString &uuid, const KyEapMethodPwdInfo &pwdInfo); void onUpdateWirelessEnterPriseFastConnect(const QString &uuid, const KyEapMethodFastInfo &fastInfo); void onUpdateWirelessAutoConnectState(const QString &uuid, bool bAutoConnect); }; #endif // KYLINNETWORKMANAGER_H libkylin-nm-base/libnm-kylin/libnm-kylin.pro0000664000175000017500000000031115160517167020035 0ustar fengfengTEMPLATE = subdirs SUBDIRS += \ libnm-base-kylin \ # libnm-external-kylin \ # libnm-icon-kylin #libnm-external-kylin.depends = libnm-base-kylin #libnm-icon-kylin.depends = libnm-base-kylin libkylin-nm-base/kylin-keyring/0000775000175000017500000000000015160517205015433 5ustar fengfenglibkylin-nm-base/kylin-keyring/authorize.svg0000775000175000017500000002060615160517167020204 0ustar fengfeng libkylin-nm-base/kylin-keyring/translations/0000775000175000017500000000000015160522067020156 5ustar fengfenglibkylin-nm-base/kylin-keyring/translations/kylin-keyring_tr.ts0000664000175000017500000000541615160517205024033 0ustar fengfeng KyPasswordDialog Wi-Fi authentication required Access wireless networks needs password or encryption key user name Connect Cancel password KylinSecretAgent userAndPwd tls libkylin-nm-base/kylin-keyring/translations/kylin-keyring_bo_CN.ts0000664000175000017500000000767515160517205024377 0ustar fengfeng KyPasswordDialog kylin network desktop message དྲ་རྒྱའི་གསལ་འདེབས་ཆ་འཕྲིན། Wi-Fi authentication required སྐུད་མེད་དྲ་རྒྱ་འདི་ལ་གསང་བའི་བདེན་དཔང་ར་སྤྲོད་བྱེད་དགོས། Access wireless networks སྐུད་མེད་དྲ་རྒྱར་བཅར་འདྲི་བྱེད་པ། needs password or encryption key གསང་བ་དང་གསང་བའི་ལྡེ་མིག་དགོས། password གསང་བའི་ཨང་གྲངས། user name སྤྱོད་མཁན་གྱི་མིང་། Connect འབྲེལ་མཐུད་བཅས་བྱ་དགོས། Cancel མེད་པར་བཟོ་དགོས། password error! གསང་བའི་ཨང་གྲངས་ནོར་བ། username or password error! སྤྱོད་མཁན་གྱི་མིང་ངམ་གསང་གྲངས་ནོར་འཁྲུལ་རེད། KylinSecretAgent userAndPwd སྤྱོད་མཁན་གྱི་མིང་དང་གསང་གྲངས། tls libkylin-nm-base/kylin-keyring/translations/kylin-keyring_bo.ts0000664000175000017500000000541615160517205024006 0ustar fengfeng KyPasswordDialog Wi-Fi authentication required Access wireless networks needs password or encryption key user name Connect Cancel password KylinSecretAgent userAndPwd tls libkylin-nm-base/kylin-keyring/translations/kylin-keyring_zh_CN.ts0000664000175000017500000000672415160517205024412 0ustar fengfeng KyPasswordDialog kylin network desktop message 网络提示信息 Wi-Fi authentication required 此无线网络需要密码认证 Access wireless networks 访问无线网络 needs password or encryption key 需要密码或加密秘钥 user name 用户名 Connect 连接 Cancel 取消 password error! 密码错误! username or password error! 用户名或密码错误! WiFi 访问无线网络 needs password 需要密码或加密秘钥 password 密码 KylinSecretAgent userAndPwd 用户名和密码 tls libkylin-nm-base/kylin-keyring/translations/kylin-keyring_mn_MN.ts0000664000175000017500000000630715160517205024412 0ustar fengfeng KyPasswordDialog Wi-Fi authentication required Wi-Fi ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠬᠡᠷᠡᠴᠢᠯᠡᠯ ᠢ᠋ ᠱᠠᠭᠠᠷᠳᠠᠬᠤ Access wireless networks ᠤᠲᠠᠰᠤ ᠦᠭᠡᠢ ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠳᠤ ᠵᠠᠯᠭᠠᠨ ᠣᠷᠣᠭᠤᠯᠪᠠ needs password or encryption key ᠨᠢᠭᠤᠴᠠ ᠨᠣᠮᠧᠷ ᠪᠤᠶᠤ ᠪᠢᠲᠡᠭᠦᠮᠵᠢᠯᠡᠭᠰᠡᠨ ᠴᠠᠷᠭᠠᠰᠤ ᠬᠡᠷᠡᠭᠰᠡᠨ᠎ᠡ ᠃ password ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ user name ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠡᠷ᠎ᠡ Connect ᠴᠦᠷᠬᠡᠯᠡᠬᠡ Cancel ᠦᠬᠡᠢᠰᠬᠡᠬᠦ KylinSecretAgent userAndPwd ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠶᠢᠨ ᠨᠡᠷ᠎ᠡ ᠪᠠ ᠨᠢᠭᠤᠴᠠ ᠨᠣᠮᠧᠷ ᠃ tls libkylin-nm-base/kylin-keyring/translations/kylin-keyring_zh_HK.ts0000664000175000017500000000534315160517205024410 0ustar fengfeng KyPasswordDialog Wi-Fi authentication required 需要Wi-Fi身份驗證 Access wireless networks 接入無線網路 needs password or encryption key 需要密碼或加密金鑰 password 密碼 user name 使用者名 Connect 連接 Cancel 取消 KylinSecretAgent userAndPwd 使用者名和密碼 tls libkylin-nm-base/kylin-keyring/main.cpp0000664000175000017500000000311315160517205017061 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include "kylinagent.h" #include bool isAppRuning(); int main(int argc, char *argv[]) { QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QApplication a(argc, argv); KylinAgent* agent = new KylinAgent(); agent->startKylinAgent(); QTranslator trans_global; qDebug() << "QLocale " << QLocale(); if (trans_global.load(QLocale(), "kylin-keyring", "_", "/usr/share/kylin-keyring/")) { a.installTranslator(&trans_global); qDebug()<<"Translations load success"; } else { qWarning() << "Translations load fail"; } return a.exec(); } libkylin-nm-base/kylin-keyring/translate_generation.sh0000775000175000017500000000056715160517205022212 0ustar fengfeng#!/bin/bash export PATH="/usr/lib/qt6/bin:$PATH" ts_list=(`ls translations/*.ts`) source /etc/os-release version=(`echo $ID`) for ts in "${ts_list[@]}" do printf "\nprocess ${ts}\n" if [ "$version" == "fedora" ] || [ "$version" == "opensuse-leap" ] || [ "$version" == "opensuse-tumbleweed" ];then lrelease-qt5 "${ts}" else lrelease "${ts}" fi done libkylin-nm-base/kylin-keyring/kylin-agent/0000775000175000017500000000000015160517205017655 5ustar fengfenglibkylin-nm-base/kylin-keyring/kylin-agent/kylinagent.cpp0000664000175000017500000000312715160517205022531 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinagent.h" #include #include KylinAgent::KylinAgent(QObject *parent) : QObject(parent) { QLocale local; QString locale = /*QLocale::system().*/local.name(); QTranslator* translator = new QTranslator(this); if (translator->load("/usr/share/kylin-nm/kylin-keyring/kylin-keyring_" + locale)) { QApplication::installTranslator(translator); } else { // qWarning() << "Translations load fail"; } } KylinAgent::~KylinAgent() { } void KylinAgent::startKylinAgent() { m_secretAgnet = new KylinSecretAgent("kylinScreenAgent", pWidget, this); } //void KylinAgent::stopKylinAgent() //{ // delete m_kylinAgnetObject; // m_kylinAgnetObject = nullptr; // return; //} libkylin-nm-base/kylin-keyring/kylin-agent/agentutils.h0000664000175000017500000000760715160517205022217 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef AGENTUTILS_H #define AGENTUTILS_H #define VPN_TYPE "vpn" #define VPN_NAME "vpn" #define VPN_SERVICE "service-type" #define VPN_DATA "data" #define VPN_SECRET "secrets" #define VPN_FLAG "password-flags" #define CONNECTION_KEY "connection" #define UUID_KEY "uuid" #define SSID_KEY "ssid" #define ID_KEY "id" #define TYPE_KEY "type" #define WIRELESS_SECURITY_NAME "802-11-wireless-security" #define KEY_MGMT "key-mgmt" #define PSK_MGMT "wpa-psk" #define SAE_MGMT "sae" #define PSK_FLAG "psk-flags" #define PSK_KEY "psk" #define WEP_MGMT "none" #define WEP128_MGMT "passphrase" #define WEP_FLAG_KEY "wep-key-flags" #define WEP_ID_KEY "wep-tx-keyidx" #define WEP_KEY0 "wep-key0" #define WEP_KEY1 "wep-key1" #define WEP_KEY2 "wep-key2" #define WEP_KEY3 "wep-key3" #define LEAP_MGMT "ieee8021x" #define LEAP_PASSWORD_FLAG "leap-password-flags" #define LEAP_PASSWORD_KEY "leap-password" #define LEAP_USER_KEY "leap-username" #define ENTERPRICE_NAME "802-1x" #define EAP_KEY "eap" #define PWD_EAP "pwd" #define LEAP_EAP "leap" #define FAST_EAP "fast" #define PEAP_EAP "peap" #define TTLS_EAP "ttls" #define TLS_EAP "tls" #define IDENTITY_KEY "identity" #define PASSWORD_FLAG "password-flags" #define PASSWORD_KEY "password" #define PIN_FLAG "pin-flags" #define PIN_KEY "pin" #define PHASE2_PRIVATE_KEY_FLAG "phase2-private-key-password-flags" #define PHASE2_PRIVATE_KEY "phase2-private-key-password" #define PRIVATE_KEY_FLAG "private-key-password-flags" #define PRIVATE_KEY "private-key-password" #define DOMAIN_KEY "domain-suffix-match" #define PHASE2_CLIENT_FLAG "phase2-client-cert-password-flags" #define PHASE2_CLIENT "phase2-client-cert-password" #define PHASE2_CACERT_FLAG "phase2-ca-cert-password-flags" #define PHASE2_CACERT "phase2-ca-cert-password" #define PHASE1_AUTH_FLAG "phase1-auth-flags" #define PHASE1_AUTH "phase1-auth" #define CLIENT_CERT_FLAG "client-cert-password-flags" #define CLIENT_CERT "client-cert-password" #define CACERT_FLAG "ca-cert-password-flags" #define CACERT "ca-cert-password" enum SecretPolicyFlag{ POLICY_NONE = 0, POLICY_AGENT_OWNED = 0x01, POLICY_NOT_SAVED = 0x02, POLICY_NOT_REQUIRED = 0x04 }; enum SecretWepKeyId{ KEY_TYPE0 = 0, KEY_TYPE1 = 1, KEY_TYPE2 = 2, KEY_TYPE3 = 3 }; #endif // AGENTUTILS_H libkylin-nm-base/kylin-keyring/kylin-agent/kylinagentobject.cpp0000664000175000017500000000232415160517205023716 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinagentobject.h" KylinAgentObject::KylinAgentObject(QObject *parent) : QObject(parent) { } KylinAgentObject::~KylinAgentObject() { if (nullptr != m_secretAgnet) { delete m_secretAgnet; m_secretAgnet = nullptr; } } void KylinAgentObject::onInitAgent() { m_secretAgnet = new KylinSecretAgent("kylinagent"); return; } libkylin-nm-base/kylin-keyring/kylin-agent/kylinagentobject.h0000664000175000017500000000056615160517167023400 0ustar fengfeng#ifndef KYLINAGENTOBJECT_H #define KYLINAGENTOBJECT_H #include "kylinsecretagent.h" #include class KylinAgentObject : public QObject { Q_OBJECT public: explicit KylinAgentObject(QObject *parent = nullptr); ~KylinAgentObject(); public Q_SLOTS: void onInitAgent(); private: KylinSecretAgent *m_secretAgnet; }; #endif // KYLINAGENTOBJECT_H libkylin-nm-base/kylin-keyring/kylin-agent/kylinagent.h0000664000175000017500000000265115160517205022177 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINAGENT_H #define KYLINAGENT_H #include "kylinsecretagent.h".h" #if defined(LIBKYLIN_KEYRING_LIBRARY) # define LIBKYLIN_KEYRING_LIBRARY Q_DECL_EXPORT #else # define LIBKYLIN_KEYRING_LIBRARY Q_DECL_IMPORT #endif class LIBKYLIN_KEYRING_LIBRARY KylinAgent : public QObject { public: explicit KylinAgent(QObject *parent = nullptr); ~KylinAgent(); void startKylinAgent(); void setParentWidget(QWidget *widget){ pWidget = widget; } private: KylinSecretAgent *m_secretAgnet; QWidget* pWidget = nullptr; }; #endif // KYLINAGENT_H libkylin-nm-base/kylin-keyring/kylin-agent/kylinpassworddialog.h0000664000175000017500000000437215160517205024125 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINPASSWORDDIALOG_H #define KYLINPASSWORDDIALOG_H #include #include #include #include #include #include #include #include #include #include "kpasswordedit.h" using namespace kdk; class RowWidget : public QWidget { Q_OBJECT public: RowWidget(QWidget *widget, QWidget *parent = nullptr); ~RowWidget(); void setKey(QString text); private: QHBoxLayout *mainLayout; QLabel *keyLabel; QWidget *valueWidget; }; class KyPasswordDialog : public QDialog { Q_OBJECT public: KyPasswordDialog(QString dialogType, QString connectionID = "", QWidget *parent = 0); ~KyPasswordDialog(); void InitConnect(); private: QString dialogType; QString connectionID; QLineEdit *m_usrLineEdit = nullptr; QPushButton *m_connectBtn = nullptr; QPushButton *m_exitBtn = nullptr; KPasswordEdit *m_sdkPasswdEdit = nullptr; //void onPaletteChanged(); protected: void paintEvent(QPaintEvent *event); public: void initUI(QString dialogType); QString getPassword(); void setPassword(QString password); QString getUserName(); void setUserName(QString name); private Q_SLOTS: void login(); void onTextChanged(const QString &); Q_SIGNALS: void signal_username(QString); }; #endif // KYLINPASSWORDDIALOG_H libkylin-nm-base/kylin-keyring/kylin-agent/kylinpassworddialog.cpp0000664000175000017500000004466015160517205024464 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "kylinpassworddialog.h" #include #include #include #include #include #include #include #include #define CLOSE_TIME 30*1000 #if 0 static QPalette lightPalette(QWidget *widget) { auto palette = widget->palette(); //ukui-light palette UKUI3.1 QColor windowText_at(38, 38, 38), windowText_iat(38, 38, 38), windowText_dis(166, 166, 166), button_at(230, 230, 230), button_iat(230, 230, 230), button_dis(233, 233, 233), light_at(255, 255, 255), light_iat(255, 255, 255), light_dis(242, 242, 242), midlight_at(218, 218, 218), midlight_iat(218, 218, 218), midlight_dis(230, 230, 230), dark_at(77, 77, 77), dark_iat(77, 77, 77), dark_dis(64, 64, 64), mid_at(115, 115, 115), mid_iat(115, 115, 115), mid_dis(102, 102, 102), text_at(38, 38, 38), text_iat(38, 38, 38), text_dis(140, 140, 140), brightText_at(89, 89, 89), brightText_iat(89, 89, 89), brightText_dis(77, 77, 77), buttonText_at(38, 38, 38), buttonText_iat(38, 38, 38), buttonText_dis(179, 179, 179), base_at(255, 255, 255), base_iat(245, 245, 245), base_dis(237, 237, 237), window_at(245, 245, 245), window_iat(237, 237, 237), window_dis(230, 230, 230), shadow_at(0, 0, 0, 16), shadow_iat(0, 0, 0, 16), shadow_dis(0, 0, 0, 21), // shadow_at(214, 214, 214), // shadow_iat(214, 214, 214), // shadow_dis(201, 201, 201), highLight_at(55, 144, 250), highLight_iat(55, 144, 250), highLight_dis(233, 233, 233), highLightText_at(255, 255, 255), highLightText_iat(255, 255, 255), highLightText_dis(179, 179, 179), link_at(55, 144, 250), link_iat(55, 144, 250), link_dis(55, 144, 250), linkVisited_at(114, 46, 209), linkVisited_iat(114, 46, 209), linkVisited_dis(114, 46, 209), alternateBase_at(245, 245, 245), alternateBase_iat(245, 245, 245), alternateBase_dis(245, 245, 245), noRale_at(240, 240, 240), noRole_iat(240, 240, 240), noRole_dis(217, 217, 217), toolTipBase_at(255, 255, 255), toolTipBase_iat(255, 255, 255), toolTipBase_dis(255, 255, 255), toolTipText_at(38, 38, 38), toolTipText_iat(38, 38, 38), toolTipText_dis(38, 38, 38), placeholderText_at(38, 38, 38), placeholderText_iat(38, 38, 38), placeholderText_dis(38, 38, 38); palette.setColor(QPalette::Active, QPalette::WindowText, windowText_at); palette.setColor(QPalette::Inactive, QPalette::WindowText, windowText_iat); palette.setColor(QPalette::Disabled, QPalette::WindowText, windowText_dis); palette.setColor(QPalette::Active, QPalette::Button, button_at); palette.setColor(QPalette::Inactive, QPalette::Button, button_iat); palette.setColor(QPalette::Disabled, QPalette::Button, button_dis); palette.setColor(QPalette::Active, QPalette::Light, light_at); palette.setColor(QPalette::Inactive, QPalette::Light, light_iat); palette.setColor(QPalette::Disabled, QPalette::Light, light_dis); palette.setColor(QPalette::Active, QPalette::Midlight, midlight_at); palette.setColor(QPalette::Inactive, QPalette::Midlight, midlight_iat); palette.setColor(QPalette::Disabled, QPalette::Midlight, midlight_dis); palette.setColor(QPalette::Active, QPalette::Dark, dark_at); palette.setColor(QPalette::Inactive, QPalette::Dark, dark_iat); palette.setColor(QPalette::Disabled, QPalette::Dark, dark_dis); palette.setColor(QPalette::Active, QPalette::Mid, mid_at); palette.setColor(QPalette::Inactive, QPalette::Mid, mid_iat); palette.setColor(QPalette::Disabled, QPalette::Mid, mid_dis); palette.setColor(QPalette::Active, QPalette::Text, text_at); palette.setColor(QPalette::Inactive, QPalette::Text, text_iat); palette.setColor(QPalette::Disabled, QPalette::Text, text_dis); palette.setColor(QPalette::Active, QPalette::BrightText, brightText_at); palette.setColor(QPalette::Inactive, QPalette::BrightText, brightText_iat); palette.setColor(QPalette::Disabled, QPalette::BrightText, brightText_dis); palette.setColor(QPalette::Active, QPalette::ButtonText, buttonText_at); palette.setColor(QPalette::Inactive, QPalette::ButtonText, buttonText_iat); palette.setColor(QPalette::Disabled, QPalette::ButtonText, buttonText_dis); palette.setColor(QPalette::Active, QPalette::Base, base_at); palette.setColor(QPalette::Inactive, QPalette::Base, base_iat); palette.setColor(QPalette::Disabled, QPalette::Base, base_dis); palette.setColor(QPalette::Active, QPalette::Window, window_at); palette.setColor(QPalette::Inactive, QPalette::Window, window_iat); palette.setColor(QPalette::Disabled, QPalette::Window, window_dis); palette.setColor(QPalette::Active, QPalette::Shadow, shadow_at); palette.setColor(QPalette::Inactive, QPalette::Shadow, shadow_iat); palette.setColor(QPalette::Disabled, QPalette::Shadow, shadow_dis); palette.setColor(QPalette::Active, QPalette::Highlight, highLight_at); palette.setColor(QPalette::Inactive, QPalette::Highlight, highLight_iat); palette.setColor(QPalette::Disabled, QPalette::Highlight, highLight_dis); palette.setColor(QPalette::Active, QPalette::HighlightedText, highLightText_at); palette.setColor(QPalette::Inactive, QPalette::HighlightedText, highLightText_iat); palette.setColor(QPalette::Disabled, QPalette::HighlightedText, highLightText_dis); palette.setColor(QPalette::Active, QPalette::Link, link_at); palette.setColor(QPalette::Inactive, QPalette::Link, link_iat); palette.setColor(QPalette::Disabled, QPalette::Link, link_dis); palette.setColor(QPalette::Active, QPalette::LinkVisited, linkVisited_at); palette.setColor(QPalette::Inactive, QPalette::LinkVisited, linkVisited_iat); palette.setColor(QPalette::Disabled, QPalette::LinkVisited, linkVisited_dis); palette.setColor(QPalette::Active, QPalette::AlternateBase, alternateBase_at); palette.setColor(QPalette::Inactive, QPalette::AlternateBase, alternateBase_iat); palette.setColor(QPalette::Disabled, QPalette::AlternateBase, alternateBase_dis); palette.setColor(QPalette::Active, QPalette::NoRole, noRale_at); palette.setColor(QPalette::Inactive, QPalette::NoRole, noRole_iat); palette.setColor(QPalette::Disabled, QPalette::NoRole, noRole_dis); palette.setColor(QPalette::Active, QPalette::ToolTipBase, toolTipBase_at); palette.setColor(QPalette::Inactive, QPalette::ToolTipBase, toolTipBase_iat); palette.setColor(QPalette::Disabled, QPalette::ToolTipBase, toolTipBase_dis); palette.setColor(QPalette::Active, QPalette::ToolTipText, toolTipText_at); palette.setColor(QPalette::Inactive, QPalette::ToolTipText, toolTipText_iat); palette.setColor(QPalette::Disabled, QPalette::ToolTipText, toolTipText_dis); #if (QT_VERSION >= QT_VERSION_CHECK(5,12,0)) palette.setColor(QPalette::Active, QPalette::PlaceholderText, placeholderText_at); palette.setColor(QPalette::Inactive, QPalette::PlaceholderText, placeholderText_iat); palette.setColor(QPalette::Disabled, QPalette::PlaceholderText, placeholderText_dis); #endif return palette; } #endif RowWidget::RowWidget(QWidget *widget, QWidget *parent) : valueWidget(widget), QWidget(parent) { mainLayout = new QHBoxLayout(this); mainLayout->setContentsMargins(0,0,0,0); this->setLayout(mainLayout); keyLabel = new QLabel(this); keyLabel->setMaximumWidth(87); valueWidget->setMinimumWidth(280); mainLayout->addWidget(keyLabel); mainLayout->addStretch(); mainLayout->addWidget(valueWidget); } RowWidget::~RowWidget() { } void RowWidget::setKey(QString text) { this->keyLabel->setText(text); } KyPasswordDialog::KyPasswordDialog(QString dialogType, QString connectionID, QWidget *parent) :connectionID(connectionID),dialogType(dialogType),QDialog(parent) { this->setAttribute(Qt::WA_QuitOnClose, false); // this->setWindowFlags(Qt::Dialog); // this->setWindowIcon(QIcon::fromTheme("kylin-network")); // this->setWindowTitle(connectionID); initUI(dialogType); QPalette pal = parent->palette(); pal.setColor(QPalette::ButtonText, Qt::black); m_sdkPasswdEdit->setPalette(pal); m_sdkPasswdEdit->setEnabled(true); m_sdkPasswdEdit->installEventFilter(this); this->setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Window | Qt::FramelessWindowHint); #if 0 connect(qApp, &QApplication::paletteChanged, this, &KyPasswordDialog::onPaletteChanged); onPaletteChanged(); #endif } KyPasswordDialog::~KyPasswordDialog(){ } void KyPasswordDialog::InitConnect() { connect(m_connectBtn, &QPushButton::clicked, this, &KyPasswordDialog::login); connect(m_exitBtn, &QPushButton::clicked, this, &KyPasswordDialog::reject); connect(m_sdkPasswdEdit, &KPasswordEdit::textChanged, this, &KyPasswordDialog::onTextChanged); if (m_usrLineEdit != nullptr) { connect(m_usrLineEdit, &QLineEdit::textChanged, this, &KyPasswordDialog::onTextChanged); } QTimer::singleShot(CLOSE_TIME, this, [=](){ reject(); }); } void KyPasswordDialog::initUI(QString dialogType) { #define MAIN_LAYOUT_MARGINS 24,24,24,24 #define DEFAULT_LAYOUT_MARGINS 0,0,0,0 #define DEFAULT_LAYOUT_SPACE 24 #define LESS_LAYOUT_SPACE 16 #define DEFAULT_BTN_FIXSIZE 112,56 #define DEFAULT_FIXHEIGHT 48 #define DEFAULT_PICTURE_FIXSIZE 48,48 #define DEFAULT_LABEL_WIDTH 328 #define DEFAULT_EDIT_WIDTH 278 #define WPA2_EDIT_WIDTH 270 #define DEFAULT_PAGE_SIZE 446,286 #define WPA2_PAGE_SIZE 446,342 #define LABEL_WIDTH 48 #define MIN_EDIT_WIDTH 140 //设置字体大小 QFont fontTitle; fontTitle.setPointSizeF(13.5); fontTitle.setWeight(QFont::Bold); QFontMetrics titleFontMetrics(fontTitle); QFont fontNormal; fontNormal.setPointSizeF(11.5); fontNormal.setWeight(QFont::Normal); QFontMetrics fontMetrics(fontNormal); //主布局 QVBoxLayout *mainVBoxLayout = new QVBoxLayout(this); mainVBoxLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); mainVBoxLayout->setSpacing(LESS_LAYOUT_SPACE); this->setLayout(mainVBoxLayout); //不包含按钮的横向布局 QHBoxLayout *hBoxLayout = new QHBoxLayout(this); hBoxLayout->setContentsMargins(DEFAULT_LAYOUT_MARGINS); hBoxLayout->setSpacing(DEFAULT_LAYOUT_SPACE); //图标 QLabel *picture = new QLabel(this); picture->setContentsMargins(DEFAULT_LAYOUT_MARGINS); picture->setFixedSize(DEFAULT_PICTURE_FIXSIZE); picture->setPixmap(QPixmap(":/authorize.svg")); //标题 QLabel *titleLabel = new QLabel(this); QString titleLabelText(tr("Wi-Fi authentication required")); titleLabel->setFont(fontTitle); titleLabel->setFixedWidth(DEFAULT_LABEL_WIDTH); //标题文本省略处理 titleLabel->setText(titleFontMetrics.elidedText(titleLabelText, Qt::ElideRight, DEFAULT_LABEL_WIDTH)); if (titleFontMetrics.horizontalAdvance(titleLabelText) > DEFAULT_LABEL_WIDTH) { titleLabel->setToolTip(titleLabelText); } //提示信息 QLabel *tipLabel = new QLabel(this); tipLabel->setFixedWidth(DEFAULT_LABEL_WIDTH); tipLabel->setAlignment(Qt::AlignTop); tipLabel->setWordWrap(true); QString text = tr("Access wireless networks"); text += " " + connectionID + " "; text += tr("needs password or encryption key"); tipLabel->setText(text); tipLabel->setFont(fontNormal); //密码输入框 QLabel *pwdLabel = new QLabel(this); QString pwdLabelText(tr("password")); pwdLabel->setFont(fontNormal); m_sdkPasswdEdit = new KPasswordEdit(this); m_sdkPasswdEdit->setUseCustomPalette(true); if (dialogType != "") { this->setFixedSize(WPA2_PAGE_SIZE); m_sdkPasswdEdit->setFixedWidth(WPA2_EDIT_WIDTH); pwdLabel->setFixedWidth(LABEL_WIDTH); } else { this->setFixedSize(DEFAULT_PAGE_SIZE); m_sdkPasswdEdit->setMaximumWidth(DEFAULT_EDIT_WIDTH); m_sdkPasswdEdit->setMinimumWidth(MIN_EDIT_WIDTH); } m_sdkPasswdEdit->setClearButtonEnabled(false); m_sdkPasswdEdit->setState(LoginFailed); m_sdkPasswdEdit->setAttribute(Qt::WA_InputMethodEnabled, true); QRegularExpression rx("^[A-Za-z0-9`~!@#$%^&*()_-+=<>,.\\\/]+$"); QRegularExpressionValidator *latitude = new QRegularExpressionValidator(rx, this); m_sdkPasswdEdit->setValidator(latitude); //密码输入框布局 QHBoxLayout *pwdLayout = new QHBoxLayout(this); pwdLayout->setContentsMargins(DEFAULT_LAYOUT_MARGINS); pwdLayout->setSpacing(8); pwdLayout->addWidget(pwdLabel); pwdLayout->addWidget(m_sdkPasswdEdit); pwdLabel->setText(fontMetrics.elidedText(pwdLabelText, Qt::ElideRight, pwdLabel->width())); if (fontMetrics.horizontalAdvance(pwdLabelText) > pwdLabel->width()) { pwdLabel->setToolTip(pwdLabelText); } //不包含图标的纵向布局 QVBoxLayout *contentLayout = new QVBoxLayout(this); contentLayout->setContentsMargins(DEFAULT_LAYOUT_MARGINS); contentLayout->setSpacing(LESS_LAYOUT_SPACE); contentLayout->setAlignment(Qt::AlignTop); contentLayout->addWidget(titleLabel); contentLayout->addWidget(tipLabel); if (dialogType != "") { //WPA2企业加密方式用户名输入框 QLabel *userNameLabel = new QLabel(this); QString usernameLabelText(tr("user name")); userNameLabel->setFont(fontNormal); userNameLabel->setFixedWidth(LABEL_WIDTH); userNameLabel->setText(fontMetrics.elidedText(usernameLabelText, Qt::ElideRight, LABEL_WIDTH)); if (fontMetrics.horizontalAdvance(usernameLabelText) > LABEL_WIDTH) { userNameLabel->setToolTip(usernameLabelText); } m_usrLineEdit = new QLineEdit(this); m_usrLineEdit->setFixedWidth(WPA2_EDIT_WIDTH); //用户名输入框布局 QHBoxLayout *userNameLayout = new QHBoxLayout(this); userNameLayout->setContentsMargins(DEFAULT_LAYOUT_MARGINS); userNameLayout->setSpacing(8); userNameLayout->addWidget(userNameLabel); userNameLayout->addWidget(m_usrLineEdit); contentLayout->addLayout(userNameLayout); } contentLayout->addLayout(pwdLayout); contentLayout->addStretch(); //连接按钮 m_connectBtn = new QPushButton(this); m_connectBtn->setText(tr("Connect")); m_connectBtn->setFont(fontNormal); //取消按钮 m_exitBtn = new QPushButton(this); m_exitBtn->setText(tr("Cancel")); m_exitBtn->setFont(fontNormal); //按钮布局 QHBoxLayout *btnLayout = new QHBoxLayout(this); btnLayout->setContentsMargins(DEFAULT_LAYOUT_MARGINS); btnLayout->setSpacing(LESS_LAYOUT_SPACE); btnLayout->addStretch(); btnLayout->addWidget(m_exitBtn); btnLayout->addWidget(m_connectBtn); hBoxLayout->addWidget(picture); hBoxLayout->setAlignment(picture, Qt::AlignTop); hBoxLayout->addLayout(contentLayout); mainVBoxLayout->addLayout(hBoxLayout); mainVBoxLayout->addLayout(btnLayout); } QString KyPasswordDialog::getPassword() { return m_sdkPasswdEdit->text(); } void KyPasswordDialog::setPassword(QString password) { m_sdkPasswdEdit->setText(password); m_sdkPasswdEdit->setFocus(); } QString KyPasswordDialog::getUserName() { return m_usrLineEdit->text(); } void KyPasswordDialog::setUserName(QString name) { m_usrLineEdit->setText(name); } void KyPasswordDialog::login() { qDebug() << "KyPasswordDialog login"; if ((!m_sdkPasswdEdit->text().isEmpty()) && (m_usrLineEdit == nullptr? true : (!m_usrLineEdit->text().isEmpty()))) { accept(); } else { m_sdkPasswdEdit->clear(); if (m_usrLineEdit != nullptr) { m_usrLineEdit->clear(); m_usrLineEdit->setFocus(); } } } void KyPasswordDialog::onTextChanged(const QString & text) { m_sdkPasswdEdit->setState(Ordinary); if (text == "") { //任何输入框为空,则不许按下连接按钮 m_connectBtn->setEnabled(false); return ; } if (m_usrLineEdit != nullptr) { //企业网修改密码页面 if (!m_usrLineEdit->text().isEmpty() && !m_sdkPasswdEdit->text().isEmpty()) { //用户名和密码均不为空,允许按下连接按钮 m_connectBtn->setEnabled(true); } else { m_connectBtn->setEnabled(false); } return ; } if (m_sdkPasswdEdit->text().isEmpty() || m_sdkPasswdEdit->text().length() < 8) { //普通热点密码修改页面,若密码为空,或长度小于8位,不许按下连接按钮 m_connectBtn->setEnabled(false); return ; } m_connectBtn->setEnabled(true); } #if 0 void KyPasswordDialog::onPaletteChanged() { QPalette pal = lightPalette(this); this->setPalette(pal); m_sdkPasswdEdit->setPalette(pal); if (nullptr != m_usrLineEdit) m_usrLineEdit->setPalette(pal); // setFramePalette(this, pal); } #endif void KyPasswordDialog::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); painter.setBrush(pal.color(QPalette::Base)); QRect rect = this->rect(); painter.drawRoundedRect(rect, 12, 12); QDialog::paintEvent(event); } libkylin-nm-base/kylin-keyring/kylin-agent/kylinsecretagent.cpp0000664000175000017500000012653215160517205023745 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include "kylinsecretagent.h" #include "kylinpassworddialog.h" #define LOG_FLAG "[KylinSecretAgent]" #define KEYRING_UUID_TAG "connection-uuid" #define KEYRING_SN_TAG "setting-name" #define KEYRING_SK_TAG "setting-key" static const SecretSchema network_manager_secret_schema = { "org.freedesktop.NetworkManager.Connection", SECRET_SCHEMA_DONT_MATCH_NAME, { { KEYRING_UUID_TAG, SECRET_SCHEMA_ATTRIBUTE_STRING }, { KEYRING_SN_TAG, SECRET_SCHEMA_ATTRIBUTE_STRING }, { KEYRING_SK_TAG, SECRET_SCHEMA_ATTRIBUTE_STRING }, { NULL, SECRET_SCHEMA_ATTRIBUTE_STRING }, } }; /* * 目前wpa3存在的问题: * 1、所有用户可见的存储策略情况下,当密码错误的时候,networkmanager不会调用getSecret接口 * 2、当选择仅用户可见时,存储错误密码,由于传递给getSecret的flag参数一直是13, * 导致无法弹出修改密码的框, * 正常情况下,flag第一次是5,从keyring获取密码 第二次是7,由于密码错误,弹框获取新密码 * 3、每次询问密码正常。 * * wep的存在的问题: * 1、所有用户可见时,当输入错误的密码的时候,networkmanager没有调用getSecret函数,弹出密码框 * 2、仅用户可见的时候,正确的密码可以正常连接,当密码错误的时候,不调用getsecret,不会弹出密码框 * 3、每次询问密码的时候,第一次可以弹出密码框,如果输入错误的密码,有时弹出密码框,有时不弹,取决于输入的密码位数 * * * 企业wifi leap加密方式 * 无法选择每次询问用户 * */ KylinSecretAgent::KylinSecretAgent(const QString &id, QWidget *pWidget, QObject *parent):SecretAgent(id, parent) { parentWidget = pWidget; enterpriceInfo[PASSWORD_FLAG] = PASSWORD_KEY; enterpriceInfo[PIN_FLAG] = PIN_KEY; enterpriceInfo[PHASE2_PRIVATE_KEY_FLAG] = PHASE2_PRIVATE_KEY; enterpriceInfo[PRIVATE_KEY_FLAG] = PRIVATE_KEY; enterpriceInfo[PHASE2_CLIENT_FLAG] = PHASE2_CLIENT; enterpriceInfo[PHASE2_CACERT_FLAG] = PHASE2_CACERT; enterpriceInfo[PHASE1_AUTH_FLAG] = PHASE1_AUTH; enterpriceInfo[CLIENT_CERT_FLAG] = CLIENT_CERT; enterpriceInfo[CACERT_FLAG] = CACERT; wirelessInfo[PSK_FLAG] = PSK_KEY; wirelessInfo[LEAP_PASSWORD_FLAG] = LEAP_PASSWORD_KEY; } KylinSecretAgent::~KylinSecretAgent() { } bool KylinSecretAgent::hintIsFind(GList *p_secretList, const QStringList &hints) { GList *p_iter; bool hintFind = false; if (hints.isEmpty()) { return true; } for (p_iter = p_secretList; p_iter != NULL; p_iter = g_list_next(p_iter)) { SecretItem *p_item = (SecretItem *)p_iter->data; SecretValue *p_secret; const char *p_keyName; GHashTable *p_attributes; p_secret = secret_item_get_secret(p_item); if (p_secret) { p_attributes = secret_item_get_attributes (p_item); p_keyName = (char *)g_hash_table_lookup (p_attributes, KEYRING_SK_TAG); if (!p_keyName) { g_hash_table_unref (p_attributes); secret_value_unref (p_secret); continue; } /* See if this property matches a given hint */ for (int index = 0; index < hints.size(); ++index) { QString hintValue = hints.at(index); if (!g_strcmp0(hintValue.toUtf8().constData(), p_keyName)) { hintFind = true; } } g_hash_table_unref (p_attributes); secret_value_unref (p_secret); break; } } return hintFind; } void KylinSecretAgent::getSecretFromKeyring(GList *p_secretList, const QString &settingName, QString connectType, NMVariantMapMap &secretMap) { GList *p_iter = nullptr; QVariantMap secretKeyMap; for (p_iter = p_secretList; p_iter != NULL; p_iter = g_list_next(p_iter)) { SecretItem *p_item = (SecretItem *)p_iter->data; SecretValue *p_secret; const char *p_keyName; GHashTable *p_attributes; p_secret = secret_item_get_secret(p_item); if (p_secret) { p_attributes = secret_item_get_attributes (p_item); p_keyName = (char *)g_hash_table_lookup (p_attributes, KEYRING_SK_TAG); if (!p_keyName) { g_hash_table_unref (p_attributes); secret_value_unref (p_secret); continue; } if (VPN_TYPE == connectType) { /* * 目前根据测试的情况vpn只会存储密码,涉及的字段 * vpn.secrets: password = 123456 * 注意的问题:不知道会不会出现多个密码的问题, */ QString vpnSecretValue = QString(p_keyName) + "=" + QString(secret_value_get(p_secret, NULL)); secretKeyMap[VPN_SECRET] = vpnSecretValue; } else { secretKeyMap[p_keyName] = QString(secret_value_get(p_secret, NULL)); } g_hash_table_unref (p_attributes); secret_value_unref (p_secret); break; } } secretMap[settingName] = secretKeyMap; return; } /* * 目前根据测试掌握的情况来看,该函数无用原因: * 当每次都是询问的时候,keyring上面并不会存储密码,那么从keyring上面获取的密码为空 * 程序根本无法走到此处 * * 注意事项: * 后期根据测试遇到的情况在调整该函数。 */ bool KylinSecretAgent::connectionIsAlwaysAsk(const NMVariantMapMap &connection) { return false; } /* * * 802-11-wireless-security.key-mgmt: sae/wpa-psk * wpa-psk 是WPA/WPA2个人加密方式 * sae 是WPA3个人加密方式 * 涉及的字段: * 802-11-wireless-security.key-mgmt: sae * 802-11-wireless-security.psk: asdasd * 802-11-wireless-security.psk-flags: 0(无) * * 该函数通过弹出密码框获取密码,并构建相应类型的密码 */ void KylinSecretAgent::askSecretForPassword(QVariantMap &securityMap, QString passwordKey, const QString &settingName, NMVariantMapMap &secretMap, QString connectionID) { QString secretValue = ""; if (secretMap.contains(settingName)) { QVariantMap secretKeyMap = secretMap.value(settingName); if (!secretKeyMap.isEmpty()) { secretValue = secretKeyMap.value(passwordKey).toString(); } } if (secretValue.isEmpty()) { secretValue = securityMap.value(passwordKey).toString(); } KyPasswordDialog pwdDialog(tr(""), connectionID, parentWidget); pwdDialog.setPassword(secretValue); pwdDialog.InitConnect(); pwdDialog.show(); pwdDialog.raise(); pwdDialog.activateWindow(); if(pwdDialog.exec()==QDialog::Accepted){ QString password = pwdDialog.getPassword(); QVariantMap newSecretKeyMap = securityMap; newSecretKeyMap[passwordKey] = password; secretMap[settingName] = newSecretKeyMap; qDebug() << LOG_FLAG << "password:" << password; } else { secretMap.clear(); } return; } /* * 802-11-wireless-security.wep-key-type: passphrase or key * passphrase 是 WEP128位密码句 * key 是WEP40/128位秘钥(十六进制 或 ASCII) * 两者对应的相同的mgmt类型:802-11-wireless-security.key-mgmt: none * 共用该函数,保存密码到秘钥环 * 涉及的字段 * 802-11-wireless-security.key-mgmt: none * 802-11-wireless-security.wep-tx-keyidx: 2 * 802-11-wireless-security.wep-key0: -- * 802-11-wireless-security.wep-key1: -- * 802-11-wireless-security.wep-key2: -- * 802-11-wireless-security.wep-key3: -- * 802-11-wireless-security.wep-key-flags: 1 * 802-11-wireless-security.wep-key-type: passphrase */ QString KylinSecretAgent::getWepKeyFromId(uint wepId) { QString wepKey = ""; switch(wepId) { case KEY_TYPE0: wepKey = WEP_KEY0; break; case KEY_TYPE1: wepKey = WEP_KEY1; break; case KEY_TYPE2: wepKey = WEP_KEY2; break; case KEY_TYPE3: wepKey = WEP_KEY3; break; default: qWarning() << LOG_FLAG << "the wep key id" << wepId << "is undefined."; } return wepKey; } void KylinSecretAgent::askSecretForWep(QVariantMap &wirelessSecurityMap, const QString &settingName, NMVariantMapMap &secretMap, QString connectionID) { QString wepKey = ""; QString wepSecretValue = ""; uint wepId = 0; if (wirelessSecurityMap.contains(WEP_ID_KEY)) { wepId = wirelessSecurityMap.value(WEP_ID_KEY).toUInt(); } wepKey = getWepKeyFromId(wepId); if (wepKey.isEmpty()) { QString errorMsg = "the wep key is invalide."; qWarning() << LOG_FLAG << errorMsg; //sendError(); return; } if (secretMap.contains(settingName)) { QVariantMap secretKeyMap = secretMap.value(settingName); if (!secretKeyMap.isEmpty()) { wepSecretValue = secretKeyMap.value(wepKey).toString(); } } if (wepSecretValue.isEmpty()) { wepSecretValue = wirelessSecurityMap.value(wepKey).toString(); } KyPasswordDialog pwdDialog("", connectionID, parentWidget); pwdDialog.setPassword(wepSecretValue); pwdDialog.InitConnect(); pwdDialog.show(); pwdDialog.activateWindow(); if(pwdDialog.exec()==QDialog::Accepted){ QString password = pwdDialog.getPassword(); QVariantMap newSecretKeyMap = wirelessSecurityMap; newSecretKeyMap[wepKey] = password; secretMap[settingName] = newSecretKeyMap; qDebug() << LOG_FLAG << "password:" << password; } else { secretMap.clear(); } return; } /* * leap加密类型对应的mgmt值: * 802-11-wireless-security.key-mgmt: ieee8021x * 涉及的字段 * 802-11-wireless-security.leap-username: sadasd * 802-11-wireless-security.leap-password: sadasd * 802-11-wireless-security.leap-password-flags:0 * * 该函数通过弹窗获取正确的密码和用户名,需要构建相应的secretmap */ void KylinSecretAgent::askSecretForLeap(QVariantMap &wirelessSecurityMap, const QString &settingName, NMVariantMapMap &secretMap, QString connectionID) { uint leapPasswordFlag = 0; QString leapPassword = ""; QString leapUserName = ""; if (wirelessSecurityMap.contains(LEAP_USER_KEY)) { leapUserName = wirelessSecurityMap.value(LEAP_USER_KEY).toString(); } if (wirelessSecurityMap.contains(LEAP_PASSWORD_FLAG)) { leapPasswordFlag = wirelessSecurityMap.value(LEAP_PASSWORD_FLAG).toUInt(); } if (secretMap.contains(settingName)) { QVariantMap secretKeyMap = secretMap.value(settingName); if (!secretKeyMap.isEmpty()) { leapPassword = secretKeyMap.value(LEAP_PASSWORD_KEY).toString(); } } if (leapPassword.isEmpty()) { leapPassword = wirelessSecurityMap.value(LEAP_PASSWORD_KEY).toString(); } KyPasswordDialog pwdDialog("userAndPwd", connectionID, parentWidget); pwdDialog.setUserName(leapUserName); pwdDialog.setPassword(leapPassword); pwdDialog.InitConnect(); pwdDialog.show(); pwdDialog.activateWindow(); if(pwdDialog.exec()==QDialog::Accepted){ QString password = pwdDialog.getPassword(); QString userName = pwdDialog.getUserName(); QVariantMap securityMap; securityMap[LEAP_PASSWORD_KEY] = password; securityMap[LEAP_PASSWORD_FLAG] = leapPasswordFlag; securityMap[LEAP_USER_KEY] = userName; secretMap[settingName] = securityMap; qDebug() << LOG_FLAG << "password:" << password << userName; } else { secretMap.clear(); } return; } /* * 功能:获取普通wifi的密码,分为三类 * 1)wpa/wpa2/wpa3 * 2) leap * 3) wep */ void KylinSecretAgent::askSecretForWireless(const NMVariantMapMap &connection, const QString settingName, NMVariantMapMap &secretMap) { qDebug() << LOG_FLAG <<"askSecretForWireless connection" << connection; QString secretType = ""; QVariantMap wirelessSecurityMap = connection.value(settingName); if (wirelessSecurityMap.contains(KEY_MGMT)) { secretType = wirelessSecurityMap.value(KEY_MGMT).toString(); } else { QString errorMsg = "can not get wireless secret type."; sendError(InvalidConnection, errorMsg); qWarning()<< LOG_FLAG << errorMsg; return; } QVariantMap connectMap = connection.value(CONNECTION_KEY); QString connectId = connectMap.value(ID_KEY).toString(); if (PSK_MGMT == secretType || SAE_MGMT == secretType) { askSecretForPassword(wirelessSecurityMap, PSK_KEY, settingName, secretMap, connectId); } else if (WEP_MGMT == secretType || WEP128_MGMT == secretType) { askSecretForWep(wirelessSecurityMap, settingName, secretMap, connectId); } else if (LEAP_MGMT == secretType) { askSecretForLeap(wirelessSecurityMap, settingName, secretMap, connectId); } else { QString errorMsg = "the secret type" + secretType + "is undefined"; sendError(InvalidConnection, errorMsg); qWarning()<< LOG_FLAG << errorMsg; return; } if (secretMap.isEmpty()) { QString errorMsg = "user cancel get wireless secret"; sendError(UserCanceled, errorMsg); qWarning()<< LOG_FLAG << errorMsg; return; } QVariantMap newSecurityMap = secretMap.value(WIRELESS_SECURITY_NAME); // QVariantMap connectMap = connection.value(CONNECTION_KEY); QString connectUuid = connectMap.value(UUID_KEY).toString(); // QString connectId = connectMap.value(ID_KEY).toString(); saveWirelessSecret(newSecurityMap, connectId, connectUuid); return; } /* 功能:获取企业wifi类型为非tls的密码,涉及的字段 802-11-wireless-security.key-mgmt: wpa-eap/ieee8021x wpa-eap 是wpa/wpa2企业 ieee8021x 是动态wep(802.1x)需要和普通wifi的leep作区分 802-1x.eap: ttls/pwd/leap/fast/peap 802-1x.identity: steve 802-1x.password: 23445 802-1x.password-flags: 1 */ void KylinSecretAgent::askSecretWithIdentityAndPassword(QVariantMap securityMap, QString userKey, QString passwordKey, const QString &settingName, NMVariantMapMap &secretMap, QString connectionID) { QString password = ""; QString userName = ""; if (securityMap.contains(userKey)) { userName = securityMap.value(userKey).toString(); } if (secretMap.contains(settingName)) { QVariantMap secretKeyMap = secretMap.value(settingName); if (!secretKeyMap.isEmpty()) { password = secretKeyMap.value(passwordKey).toString(); } } if (password.isEmpty()) { password = securityMap.value(passwordKey).toString(); } KyPasswordDialog pwdDialog(tr("userAndPwd"), connectionID, parentWidget); pwdDialog.setUserName(userName); pwdDialog.setPassword(password); pwdDialog.InitConnect(); pwdDialog.show(); pwdDialog.activateWindow(); if(pwdDialog.exec()==QDialog::Accepted){ QString newPassword = pwdDialog.getPassword(); QString newUserName = pwdDialog.getUserName(); QVariantMap newSecurityMap = securityMap; newSecurityMap[userKey] = newUserName; newSecurityMap[passwordKey] = newPassword; secretMap[settingName] = newSecurityMap; qDebug() << LOG_FLAG << "password:" << newPassword << newUserName; } else { secretMap.clear(); } return; } /* * 功能:获取tls类型的密码,涉及的字段 802-1x.eap: tls 802-1x.domain-suffix-match: 802-1x.private-key-password: -- 802-1x.private-key-password-flags: 0(无) 802-1x.identity: steve */ void KylinSecretAgent::askSecretForTls(QVariantMap securityMap, const QString &settingName, NMVariantMapMap &secretMap, QString connectionID) { QString password = ""; QString identity = ""; QString domain = ""; qDebug() << LOG_FLAG << "tls security map" << securityMap; if (securityMap.contains(IDENTITY_KEY)) { identity = securityMap.value(IDENTITY_KEY).toString(); } if (securityMap.contains(DOMAIN_KEY)) { domain = securityMap.value(DOMAIN_KEY).toString(); qDebug() << LOG_FLAG << "domain match" << domain; } if (secretMap.contains(settingName)) { QVariantMap secretKeyMap = secretMap.value(settingName); if (!secretKeyMap.isEmpty()) { password = secretKeyMap.value(PRIVATE_KEY).toString(); } } if (password.isEmpty()) { password = securityMap.value(PRIVATE_KEY).toString(); } KyPasswordDialog pwdDialog(tr("tls"), connectionID, parentWidget); pwdDialog.setUserName(identity); pwdDialog.setPassword(password); pwdDialog.InitConnect(); pwdDialog.show(); pwdDialog.activateWindow(); if(pwdDialog.exec()==QDialog::Accepted){ QString newPassword = pwdDialog.getPassword(); QString newIdentity = pwdDialog.getUserName(); QVariantMap newSecurityMap = securityMap; newSecurityMap[IDENTITY_KEY] = newIdentity; newSecurityMap[PRIVATE_KEY] = newPassword; newSecurityMap[DOMAIN_KEY] = domain; secretMap[settingName] = newSecurityMap; qDebug() << LOG_FLAG << "tls password:" << newPassword << newIdentity << domain; } else { secretMap.clear(); } return; } void KylinSecretAgent::askSecretForEnterpriceWireless(const NMVariantMapMap &connection, const QString settingName, NMVariantMapMap &secretMap) { qDebug() << LOG_FLAG <<"askSecretForEnterpriceWireless connection" << connection; QString secretType = ""; QVariantMap enterpriceSecurityMap = connection.value(settingName); if (enterpriceSecurityMap.contains(EAP_KEY)) { secretType = enterpriceSecurityMap.value(EAP_KEY).toString(); } else { QString errorStr = "can not get enterprice secret type."; sendError(InvalidConnection, errorStr); qWarning()<< LOG_FLAG << errorStr; return; } QVariantMap connectMap = connection.value(CONNECTION_KEY); QString connectId = connectMap.value(ID_KEY).toString(); if (TLS_EAP == secretType) { askSecretForTls(enterpriceSecurityMap, settingName, secretMap, connectId); } else { askSecretWithIdentityAndPassword(enterpriceSecurityMap, IDENTITY_KEY, PASSWORD_KEY, settingName, secretMap, connectId); } if (secretMap.isEmpty()) { QString errorStr = "user cancel get enterprice wireless secret"; sendError(UserCanceled, errorStr); qWarning()<< LOG_FLAG << errorStr; } QVariantMap newSecurityMap = secretMap.value(settingName); // QVariantMap connectMap = connection.value(CONNECTION_KEY); QString connectUuid = connectMap.value(UUID_KEY).toString(); // QString connectId = connectMap.value(ID_KEY).toString(); saveEnterpriceSecret(newSecurityMap, connectId, connectUuid); return; } void KylinSecretAgent::askSecretForVpn(const NMVariantMapMap &connection, const QString settingName, NMVariantMapMap &secretMap) { QVariantMap newVpnSetingMap; QVariantMap vpnSetingMap = connection.value(VPN_NAME); if (vpnSetingMap.isEmpty()) { QString errorStr = "the VPN map of connection is invalide"; sendError(InvalidConnection, errorStr); qWarning() << LOG_FLAG << errorStr; return; } QVariantMap vpnSecretMap = secretMap.value(VPN_NAME); QStringList vpnSecret = getVpnPassword(vpnSecretMap); if (vpnSecret.isEmpty() || vpnSecret.size() < 2) { vpnSecret = getVpnPassword(vpnSetingMap); } QString secretKey = vpnSecret.at(0); QString secretValue= vpnSecret.at(1); KyPasswordDialog pwdDialog("","", parentWidget); pwdDialog.setPassword(secretValue); pwdDialog.InitConnect(); pwdDialog.show(); pwdDialog.activateWindow(); if(pwdDialog.exec()==QDialog::Accepted){ QString newPassword = pwdDialog.getPassword(); newVpnSetingMap = vpnSetingMap; newVpnSetingMap[VPN_SECRET] = secretKey + "=" + newPassword; secretMap[VPN_NAME] = newVpnSetingMap; QVariantMap connectMap = connection.value(CONNECTION_KEY); QString connectUuid = connectMap.value(UUID_KEY).toString(); QString connectId = connectMap.value(ID_KEY).toString(); saveSecretForVpn(newVpnSetingMap, connectId, connectUuid); qDebug() << LOG_FLAG << "vpn password:" << newPassword ; } else { QString errorStr = "user canceled get vpn secret"; sendError(UserCanceled, errorStr); qWarning() << LOG_FLAG << errorStr; } return; } void KylinSecretAgent::askForSecret(const NMVariantMapMap &connection, const QString &settingName, QString connectType, NMVariantMapMap &secretMap) { if (VPN_TYPE == connectType) { askSecretForVpn(connection, settingName, secretMap); } else { QVariantMap enterpriceSecurityMap = connection.value(ENTERPRICE_NAME); if (!enterpriceSecurityMap.isEmpty()) { askSecretForEnterpriceWireless(connection, settingName, secretMap); } else { QVariantMap wirelessSecurityMap = connection.value(WIRELESS_SECURITY_NAME); if (!wirelessSecurityMap.isEmpty()) { askSecretForWireless(connection, settingName, secretMap); } else { qWarning()<< LOG_FLAG << "can not ask secret for wireless"; } } } return; } NMVariantMapMap KylinSecretAgent::GetSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path, const QString &settingName, const QStringList &hints, uint flags) { //qDebug() << LOG_FLAG <<"GetSecrets connection" << connection; qDebug() << LOG_FLAG <<"GetSecrets setting name" << settingName; qDebug() << LOG_FLAG <<"GetSecrets hints" << hints; qDebug() << LOG_FLAG <<"GetSecrets flag" << flags; NMVariantMapMap secretMap; GHashTable *p_attributes = NULL; GError *p_secretError = NULL; GCancellable *p_cancellable = g_cancellable_new(); QVariantMap connectMap = connection.value(CONNECTION_KEY); QString connectUuid = connectMap.value(UUID_KEY).toString(); QString connectType = connectMap.value(TYPE_KEY).toString(); p_attributes = secret_attributes_build (&network_manager_secret_schema, KEYRING_UUID_TAG, connectUuid.toLocal8Bit().data(), KEYRING_SN_TAG, settingName.toLocal8Bit().data(), NULL); if (NULL == p_attributes) { qWarning() << LOG_FLAG << "create secret arributes for getting secret failed."; //sendError(); return secretMap; } GList *p_secretList = secret_service_search_sync(NULL, &network_manager_secret_schema, p_attributes, (SecretSearchFlags)(SECRET_SEARCH_ALL | SECRET_SEARCH_UNLOCK | SECRET_SEARCH_LOAD_SECRETS), p_cancellable, &p_secretError); if (p_secretError) { if ((flags & AllowInteraction) && g_error_matches (p_secretError, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN)) { /* If the connection always asks for secrets, tolerate * keyring service not being present. */ qWarning() << LOG_FLAG << "secret dbus failed"; g_clear_error (&p_secretError); } else { QString errorStr = "read secret from keyring error msg: (" + QString(p_secretError->message) + ")"; qWarning() << LOG_FLAG << errorStr; sendError(InternalError, errorStr); g_hash_table_unref (p_attributes); g_error_free (p_secretError); g_object_unref(p_cancellable); return secretMap; } } if ((flags & AllowInteraction) && g_list_length (p_secretList) == 0) { qDebug() << LOG_FLAG << "get secret list is empty"; askForSecret(connection, settingName, connectType, secretMap); } else { getSecretFromKeyring(p_secretList, settingName, connectType, secretMap); bool hintFind = hintIsFind(p_secretList, hints); if (flags) { if (!hintFind) { qDebug() << LOG_FLAG << "can not find hints int keyring"; askForSecret(connection, settingName, connectType, secretMap); } else if (flags & RequestNew) { qDebug() << LOG_FLAG <<"request new secret"; askForSecret(connection, settingName, connectType, secretMap); } else if ((flags & AllowInteraction) && connectionIsAlwaysAsk (connection)) { qDebug() << LOG_FLAG << "secret is asked always"; askForSecret(connection, settingName, connectType, secretMap); } } } g_hash_table_unref (p_attributes); g_object_unref(p_cancellable); return secretMap; } void KylinSecretAgent::CancelGetSecrets(const QDBusObjectPath &connection_path, const QString &setting_name) { //qDebug() << LOG_FLAG <<"CancelGetSecrets setting name" << setting_name; //qDebug() << LOG_FLAG <<"CancelGetSecrets path" << connection_path; return; } void KylinSecretAgent::saveOneSecret(QString &connectUuid, QString settingName, QString secretKey, QString &secretValue, QString &displayName) { qDebug()<< LOG_FLAG << "save one secret" << "display name" << displayName << "uuid" << connectUuid << "setting name" << settingName << "psk key" << secretKey << "psk secret" << secretValue; GHashTable *attrs = NULL; GError *secretError = NULL; GCancellable *cancellable = g_cancellable_new(); attrs = secret_attributes_build(&network_manager_secret_schema, KEYRING_UUID_TAG, connectUuid.toLocal8Bit().data(), KEYRING_SN_TAG, settingName.toLocal8Bit().data(), KEYRING_SK_TAG, secretKey.toLocal8Bit().data(), NULL); if (!attrs) { QString errorStr = "create secret attri failed"; qWarning() << LOG_FLAG << errorStr; g_object_unref (cancellable); sendError(InternalError, errorStr); return; } gboolean ret = secret_password_storev_sync(&network_manager_secret_schema, attrs, NULL, displayName.toLocal8Bit().data(), secretValue.toLocal8Bit().data(), cancellable, &secretError); if (!ret) { qWarning() << LOG_FLAG << "save secret failed"; if (secretError) { QString errorStr = "secret password storev error msg: (" + QString(secretError->message) + ")"; qWarning() << LOG_FLAG << errorStr; sendError(InternalError, errorStr); g_object_unref(secretError); } } g_object_unref (cancellable); g_hash_table_unref (attrs); return; } void KylinSecretAgent::saveConnectSecret(QVariantMap &securityMap, QString secretSettingName, QString &secretKey, QString &connectId, QString &connectUuid) { //to do and test this case QString secretValue = ""; if (!securityMap.contains(secretKey)) { qWarning() << LOG_FLAG << "the secret key" << secretKey << "is not contain in security map."; return; } secretValue = securityMap.value(secretKey).toString(); if (secretValue.isEmpty()) { qWarning() << LOG_FLAG << "the leap password is invalid."; return; } QString displayName = "Network secret for " + connectId + "/" + secretSettingName + "/" + secretKey; saveOneSecret(connectUuid, secretSettingName, secretKey, secretValue, displayName); return; } /* * 802-11-wireless-security.wep-key-type: passphrase or key * passphrase 是 WEP128位密码句 * key 是WEP40/128位秘钥(十六进制 或 ASCII) * 两者对应的相同的mgmt类型:802-11-wireless-security.key-mgmt: none * 共用该函数,保存密码到秘钥环 * 涉及的字段 * 802-11-wireless-security.key-mgmt: none * 802-11-wireless-security.wep-tx-keyidx: 2 * 802-11-wireless-security.wep-key0: -- * 802-11-wireless-security.wep-key1: -- * 802-11-wireless-security.wep-key2: -- * 802-11-wireless-security.wep-key3: -- * 802-11-wireless-security.wep-key-flags: 1 * 802-11-wireless-security.wep-key-type: passphrase */ void KylinSecretAgent::saveWepSecret(QVariantMap &wirelessSecurityMap, QString &connectId, QString &connectUuid) { QString wepSecret = ""; QString wepKey = ""; uint wepKeyId = wirelessSecurityMap.value(WEP_ID_KEY).toUInt(); wepKey = getWepKeyFromId(wepKeyId); if (wepKey.isEmpty()) { QString errorMsg = "save wep secret, but wep key is invalide."; qWarning() << LOG_FLAG << errorMsg; //sendError(); return; } if (!wirelessSecurityMap.contains(wepKey)) { qWarning()<::iterator iter; iter = wirelessInfo.begin(); while (iter != wirelessInfo.end()) { QString flagName = iter.key(); QString secretName = iter.value(); if (wirelessSecurityMap.contains(flagName)) { uint secretFlag = wirelessSecurityMap.value(flagName).toUInt(); if (POLICY_AGENT_OWNED == secretFlag) { saveConnectSecret(wirelessSecurityMap, WIRELESS_SECURITY_NAME, secretName, connectId, connectUuid); } return; } iter ++; } if (wirelessSecurityMap.contains(WEP_FLAG_KEY)) { uint wepFLags = wirelessSecurityMap.value(WEP_FLAG_KEY).toUInt(); if (POLICY_AGENT_OWNED == wepFLags) { saveWepSecret(wirelessSecurityMap, connectId, connectUuid); } } return; } /* * 功能:保存企业级的wifi密码到keyring,涉及的主要字段: * 802-1x.optional: 否 802-1x.eap: peap 802-1x.identity: steve 802-1x.ca-cert-password: -- 802-1x.ca-cert-password-flags: 0(无) 802-1x.client-cert-password: -- 802-1x.client-cert-password-flags: 0(无) 802-1x.phase2-ca-cert-password: -- 802-1x.phase2-ca-cert-password-flags: 0(无) 802-1x.phase2-client-cert-password: -- 802-1x.phase2-client-cert-password-flags:0(无) 802-1x.password: testing 802-1x.password-flags: 0(无) 802-1x.private-key-password: -- 802-1x.private-key-password-flags: 0(无) 802-1x.phase2-private-key-password: -- 802-1x.phase2-private-key-password-flags:0(无) 802-1x.pin: -- 802-1x.pin-flags: 0(无) 目前根据测试情况,企业wifi密码类型主要分为两类: 1) 802-11-wireless-security.key-mgmt: wpa-eap/ieee8021x wpa-eap 是wpa/wpa2企业 ieee8021x 是动态wep(802.1x)需要和普通wifi的leep作区分 802-1x.eap: ttls/pwd/leap/fast/peap 802-1x.identity: steve 802-1x.password: 23445 802-1x.password-flags: 1 2) 802-1x.eap: tls 802-1x.domain-suffix-match: 802-1x.private-key-password: -- 802-1x.private-key-password-flags: 0(无) 802-1x.identity: steve 对于这种密码类型nm-applet的agnet没有保存,不处理 802-1x.password-raw: -- 802-1x.password-raw-flags: 0(无) 通过如下命令可以查看信息: nmcli connection show [connection uuid] --show-secrets 通过打印日志,将SaveSecrets函数的入参connection打印出,也可以查看这些信息, */ void KylinSecretAgent::saveEnterpriceSecret(QVariantMap &enterpriceSecurityMap, QString &connectId, QString &connectUuid) { QMap::iterator iter; iter = enterpriceInfo.begin(); while (iter != enterpriceInfo.end()) { QString flagName = iter.key(); QString secretName = iter.value(); if (enterpriceSecurityMap.contains(flagName)) { uint secretFlags = enterpriceSecurityMap.value(flagName).toUInt(); if (POLICY_AGENT_OWNED == secretFlags) { saveConnectSecret(enterpriceSecurityMap, ENTERPRICE_NAME, secretName, connectId, connectUuid); } } iter++; } return; } /* * 功能:将wifi的密码保存到keyring上面 * 先判断有没有企业级wifi的安全字段,有的话就从其获取要保存到keyring的密码 * 如果没有那就从普通wifi的安全字段获取要保存到keyring的密码 * * 注意事项: * 目前的测试情况:企业wifi和普通wifi的安全字段只有一个起作用,即互斥关系, * 不能排除共存的情况,如果出现需要另做调整 */ void KylinSecretAgent::saveSecretForWireless(const NMVariantMapMap &connection, QString &connectId, QString &connectUuid) { QVariantMap enterpriceSecurityMap = connection.value(ENTERPRICE_NAME); if (!enterpriceSecurityMap.isEmpty()) { saveEnterpriceSecret(enterpriceSecurityMap, connectId, connectUuid); } else { QVariantMap wirelessSecurityMap = connection.value(WIRELESS_SECURITY_NAME); if (!wirelessSecurityMap.isEmpty()) { saveWirelessSecret(wirelessSecurityMap, connectId, connectUuid); } else { QString errorStr = "wireless is invalid, save secret failed."; sendError(InvalidConnection, errorStr); qWarning() << LOG_FLAG << errorStr; } } return; } QString KylinSecretAgent::getVpnDataItemByKey(QVariantMap &vpnMap, QString key) { QString value = ""; QString vpnData = vpnMap.value(VPN_DATA).toString(); if (vpnData.isEmpty()) { qWarning() << LOG_FLAG << "vpn data is empty"; return value; } QStringList vpnDataList = vpnData.split(","); int index = vpnDataList.indexOf(key); if (index < 0) { qWarning() << LOG_FLAG << "it can not find key" << key << "from vpn data"; return value; } QString vpnDataItem = vpnDataList.at(index); QStringList keyList = vpnDataItem.split("="); if (keyList.isEmpty() || keyList.size() < 2) { return value; } value = keyList.at(1); return value; } QStringList KylinSecretAgent::getVpnPassword(QVariantMap &vpnMap) { QStringList vpnPassword; QString vpnSecret; vpnSecret.clear(); vpnPassword.clear(); vpnSecret = vpnMap.value(VPN_SECRET).toString(); if (vpnSecret.contains("=")) { vpnPassword = vpnSecret.split("="); } return vpnPassword; } /* * 功能:将vpn的密码保存到keyring上面,vpn涉及的字段如下: vpn.service-type: org.freedesktop.NetworkManager.pptp vpn.user-name: -- vpn.data: gateway = 127.2.2.2, password-flags = 1, user = admin vpn.secrets: password = 123456 vpn.persistent: 否 vpn.timeout: 0 其中主要的字段: 1)vpn.data中的password-flags,检查是否存于keyring 2)vpn.secrets中的password 是要存于keyring的密码,存密码时的key为password 注意事项: vpn.secrets可能会有多个密码,目前没有遇到,等遇到的时候在调试,目前先按一个处理 通过如下命令可以查看信息: nmcli connection show [connection uuid] --show-secrets 通过打印日志,将SaveSecrets函数的入参connection打印出,也可以查看这些信息, ***/ void KylinSecretAgent::saveSecretForVpn(QVariantMap &vpnSetingMap, QString &connectId, QString &connectUuid) { if (vpnSetingMap.isEmpty()) { QString errorStr = "VPN map is empty"; sendError(InvalidConnection, errorStr); qWarning() << LOG_FLAG << errorStr; return; } QString vpnFlag = getVpnDataItemByKey(vpnSetingMap, VPN_FLAG); if (vpnFlag.isEmpty() || POLICY_AGENT_OWNED != vpnFlag.toInt()){ return; } QStringList vpnSecret = getVpnPassword(vpnSetingMap); if (vpnSecret.isEmpty() || vpnSecret.size() < 2) { QString errorStr = "the vpn secret is invalid"; sendError(NoSecrets, errorStr); qWarning() << LOG_FLAG << errorStr; return; } QString secretKey = vpnSecret.at(0); QString secretValue= vpnSecret.at(1); QString vpnService = vpnSetingMap.value(VPN_SERVICE).toString(); QString displayName = "VPN" + vpnSecret.at(0) + "secret for" + connectId + vpnService + "/vpn"; saveOneSecret(connectUuid, VPN_NAME, secretKey, secretValue, displayName); return; } void KylinSecretAgent::SaveSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path) { qDebug() << LOG_FLAG <<"SaveSecrets connection" << connection; //GError *secretError = NULL; GCancellable *cancellable = g_cancellable_new(); QVariantMap connectMap = connection.value(CONNECTION_KEY); QString connectUuid = connectMap.value(UUID_KEY).toString(); secret_password_clear_sync(&network_manager_secret_schema, cancellable, NULL, KEYRING_UUID_TAG, connectUuid.toLocal8Bit().data(), NULL); if (g_cancellable_is_cancelled(cancellable)) { qWarning() << LOG_FLAG << "save secret is canceled"; g_object_unref(cancellable); return; } QString connectType = connectMap.value(TYPE_KEY).toString(); QString connectId = connectMap.value(ID_KEY).toString(); if (VPN_TYPE == connectType) { QVariantMap vpnSetingMap = connection.value(VPN_NAME); saveSecretForVpn(vpnSetingMap, connectId, connectUuid); } else { saveSecretForWireless(connection, connectId, connectUuid); } return; } void KylinSecretAgent::DeleteSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path) { //qDebug() << LOG_FLAG <<"DeleteSecrets connection" << connection; GError *secretError = NULL; GCancellable *cancellable = g_cancellable_new(); QVariantMap connectMap = connection.value(CONNECTION_KEY); QString uuid = connectMap.value(UUID_KEY).toString(); secret_password_clear_sync(&network_manager_secret_schema, cancellable, &secretError, KEYRING_UUID_TAG, uuid.toLocal8Bit().data(), NULL); if (g_cancellable_is_cancelled(cancellable)) { qWarning() << LOG_FLAG << "delete secret is canceled"; g_object_unref(cancellable); return; } if (secretError != NULL) { QString errorStr = "The request could not be completed (" + QString(secretError->message) + ")"; sendError(InternalError, errorStr); g_error_free(secretError); } g_object_unref(cancellable); return; } libkylin-nm-base/kylin-keyring/kylin-agent/kylin-agent.pri0000664000175000017500000000050015160517167022615 0ustar fengfengINCLUDEPATH += $$PWD HEADERS += \ $$PWD/agentutils.h \ $$PWD/kylinagent.h \ $$PWD/kylinagentobject.h \ $$PWD/kylinpassworddialog.h \ $$PWD/kylinsecretagent.h SOURCES += \ $$PWD/kylinagent.cpp \ $$PWD/kylinagentobject.cpp \ $$PWD/kylinpassworddialog.cpp \ $$PWD/kylinsecretagent.cpp libkylin-nm-base/kylin-keyring/kylin-agent/kylinsecretagent.h0000664000175000017500000001472215160517205023407 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KYLINSECRETAGENT_H #define KYLINSECRETAGENT_H #include #include //#include #include "networkmanagerqt/secretagent.h" #include "agentutils.h" class KylinSecretAgent: public NetworkManager::SecretAgent { Q_OBJECT public: explicit KylinSecretAgent(const QString &id, QWidget *pWidget = nullptr, QObject *parent = nullptr); ~KylinSecretAgent(); private: QWidget *parentWidget = nullptr; void saveOneSecret(QString &connectUuid, QString settingName, QString secretKey, QString &secretValue, QString &displayNmae); void saveConnectSecret(QVariantMap &securityMap, QString secretSettingName, QString &secretKey, QString &connectId, QString &connectUuid); void saveWepSecret(QVariantMap &wirelessSecurityMap, QString &connectId, QString &connectUuid); void saveWirelessSecret(QVariantMap &wirelessSecurityMap, QString &connectId, QString &connectUuid); void saveEnterpriceSecret(QVariantMap &enterpriceSecurityMap, QString &connectId, QString &connectUuidd); void saveSecretForWireless(const NMVariantMapMap &connection, QString &connectId, QString &connectUuid); QStringList getVpnPassword(QVariantMap &vpnSettingMap); QString getVpnDataItemByKey(QVariantMap &vpnSettingMap, QString key); void saveSecretForVpn(QVariantMap &vpnSetingMap, QString &connectId, QString &connectUuid); void getSecretFromKeyring(GList *p_secretList, const QString &settingName, QString connectType, NMVariantMapMap &secretMap); bool hintIsFind(GList *p_secretList, const QStringList &hints); bool connectionIsAlwaysAsk(const NMVariantMapMap &connection); QString getWepKeyFromId(uint wepId); void askSecretForLeap(QVariantMap &wirelessSecurityMap, const QString &settingName, NMVariantMapMap &secretMap, QString connectionID); void askSecretForWep(QVariantMap &wirelessSecurityMap, const QString &settingName, NMVariantMapMap &secretMap, QString connectionID); void askSecretForPassword(QVariantMap &securityMap, QString passwordKey, const QString &settingName, NMVariantMapMap &secretMap, QString connectionID); void askSecretForWireless(const NMVariantMapMap &connection, const QString settingName, NMVariantMapMap &secretMap); void askSecretForTls(QVariantMap securityMap, const QString &settingName, NMVariantMapMap &secretMap, QString connectionID); void askSecretWithIdentityAndPassword(QVariantMap securityMap, QString userKey, QString passwordKey, const QString &settingName, NMVariantMapMap &secretMap, QString connectionID); void askSecretForEnterpriceWireless(const NMVariantMapMap &connection, const QString settingName, NMVariantMapMap &secretMap); void askSecretForVpn(const NMVariantMapMap &connection, const QString settingName, NMVariantMapMap &secretMap); void askForSecret(const NMVariantMapMap &connection, const QString &settingName, QString connectType, NMVariantMapMap &secretMap); public Q_SLOTS: /* * kylin-nm的agent功能主要是实现如下四个函数,这四个函数继承自父类NetworkManager::SecretAgent * 当发生错误的时候,调用父类的sendError函数,给networkmanager返回结果 * 调试方式 * 根据kylin-nm移植的nm-applet的agent功能代码添加日志,进行流程调试梳理,完成了该代码的开发, * 后续出了问题可以通过这种方式理顺流程调试解决问题。 * 注意事项: * 1)所有的函数keyring、的操作都是同步的,需要其单独的agent线程,否则容易阻塞 * 2)目前代码只是对能够测试到的情况做了代码实现,有可能会有遗漏的地方,后续出现新情况,在完善。 */ /* * 该函数从秘钥环上面获取密码,并将获取到的密码组成安全的mapmap返回,失败后通过sendError返回错误, * 函数的返回值将变得无效 */ NMVariantMapMap GetSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path, const QString &setting_name, const QStringList &hints, uint flags); /* * 该函数用于取消agent的操作,从测试的情况来看,目前没有发现在什么时候会出现这种情况 * 暂时未实现,后期注意观察,出现问题后根据具体情况实现, * 返回值为空,如果出现错误,通过sendError返回错误 */ void CancelGetSecrets(const QDBusObjectPath &connection_path, const QString &setting_name); /* * 该函数将密码保存到keyring上面,要保存的密码可以在connection参数中查找到, * 返回值为空,如果出现错误,通过sendError返回错误 */ void SaveSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path); /* * 该函数将密码从keyring上面删除,返回值为空,如果出现错误,通过sendError返回错误 */ void DeleteSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path); private: QMap enterpriceInfo; QMap wirelessInfo; }; #endif // KYLINSECRETAGENT_H libkylin-nm-base/kylin-keyring/kylin-keyring.pro0000664000175000017500000000535715160517205020763 0ustar fengfengQT += core gui dbus svg concurrent network greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = kylin-keyring TEMPLATE = lib DEFINES += LIBKYLIN_KEYRING_LIBRARY CONFIG += c++14 qt warn_on link_pkgconfig console CONFIG += no_keywords PKGCONFIG +=gio-2.0 glib-2.0 gio-unix-2.0 libnm libnma libsecret-1 gsettings-qt6 libcap kysdk-applications KF6WindowSystem #gtk+-3.0 INCLUDEPATH += /usr/include/KF6/NetworkManagerQt LIBS += -L/usr/lib/ -lKF6NetworkManagerQt # The following define makes your compiler emit warnings if you use # any Qt feature that has been marked deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if it uses deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 # QMAKE_CXXFLAGS += -Wno-unused-parameter QMAKE_CPPFLAGS *= $(shell dpkg-buildflags --get CPPFLAGS) QMAKE_CFLAGS *= $(shell dpkg-buildflags --get CFLAGS) QMAKE_CXXFLAGS *= $(shell dpkg-buildflags --get CXXFLAGS) QMAKE_LFLAGS *= $(shell dpkg-buildflags --get LDFLAGS) #include(kylin-agent/kylin-agent.pri) INCLUDEPATH += $$PWD INCLUDEPATH += ./kylin-agent CONFIG(release, debug|release) { !system($$PWD/translate_generation.sh): error("Failed to generate translation") } HEADERS += \ ./kylin-agent/agentutils.h \ ./kylin-agent/kylinagent.h \ # ./kylin-agent/kylinagentobject.h \ ./kylin-agent/kylinpassworddialog.h \ ./kylin-agent/kylinsecretagent.h SOURCES += \ ./kylin-agent/kylinagent.cpp \ # ./kylin-agent/kylinagentobject.cpp \ ./kylin-agent/kylinpassworddialog.cpp \ ./kylin-agent/kylinsecretagent.cpp \ TRANSLATIONS += \ ./translations/kylin-keyring_zh_CN.ts \ ./translations/kylin-keyring_tr.ts \ ./translations/kylin-keyring_bo.ts \ ./translations/kylin-keyring_bo_CN.ts \ ./translations/kylin-keyring_mn_MN.ts \ ./translations/kylin-keyring_zh_HK.ts unix { target.path = /usr/lib/ manager.path = /usr/include/kylin-nm/kylin-agent manager.files = kylin-agent/agentutils.h \ kylin-agent/kylinagent.h \ kylin-agent/kylinagentobject.h \ kylin-agent/kylinpassworddialog.h \ kylin-agent/kylinsecretagent.h qm_files.path = /usr/share/kylin-nm/kylin-keyring qm_files.files = translations/*.qm INSTALLS += manager \ qm_files \ } !isEmpty(target.path): INSTALLS += target RESOURCES += \ svg.qrc libkylin-nm-base/kylin-keyring/svg.qrc0000664000175000017500000000013415160517205016737 0ustar fengfeng authorize.svg libkylin-nm-base/tests/0000775000175000017500000000000015160517205014001 5ustar fengfenglibkylin-nm-base/tests/kt-test-utils/0000775000175000017500000000000015160517205016532 5ustar fengfenglibkylin-nm-base/tests/kt-test-utils/cpp-stub/0000775000175000017500000000000015160517205020267 5ustar fengfenglibkylin-nm-base/tests/kt-test-utils/cpp-stub/addr_pri.h0000664000175000017500000002436415160517205022235 0ustar fengfeng#ifndef __ADDR_PRI_H__ #define __ADDR_PRI_H__ #include #include //base on C++11 /********************************************************** access private function **********************************************************/ namespace std { template using enable_if_t = typename enable_if::type; template using remove_reference_t = typename remove_reference::type; } // std // Unnamed namespace is used to avoid duplicate symbols if the macros are used namespace { namespace private_access_detail { // @tparam TagType, used to declare different "get" funciton overloads for // different members/statics template struct private_access { // Normal lookup cannot find in-class defined (inline) friend functions. friend PtrType get(TagType) { return PtrValue; } }; } // namespace private_access_detail } // namespace // Used macro naming conventions: // The "namespace" of this macro library is PRIVATE_ACCESS, i.e. all // macro here has this prefix. // All implementation macro, which are not meant to be used directly have the // PRIVATE_ACCESS_DETAIL prefix. // Some macros have the ABCD_IMPL form, which means they contain the // implementation details for the specific ABCD macro. #define PRIVATE_ACCESS_DETAIL_CONCATENATE_IMPL(x, y) x##y #define PRIVATE_ACCESS_DETAIL_CONCATENATE(x, y) \ PRIVATE_ACCESS_DETAIL_CONCATENATE_IMPL(x, y) // @param PtrTypeKind E.g if we have "class A", then it can be "A::*" in case of // members, or it can be "*" in case of statics. #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, \ PtrTypeKind) \ namespace { \ namespace private_access_detail { \ /* Tag type, used to declare different get funcitons for different \ * members \ */ \ struct Tag {}; \ /* Explicit instantiation */ \ template struct private_access; \ /* We can build the PtrType only with two aliases */ \ /* E.g. using PtrType = int(int) *; would be illformed */ \ using PRIVATE_ACCESS_DETAIL_CONCATENATE(Alias_, Tag) = Type; \ using PRIVATE_ACCESS_DETAIL_CONCATENATE(PtrType_, Tag) = \ PRIVATE_ACCESS_DETAIL_CONCATENATE(Alias_, Tag) PtrTypeKind; \ /* Declare the friend function, now it is visible in namespace scope. \ * Note, \ * we could declare it inside the Tag type too, in that case ADL would \ * find \ * the declaration. By choosing to declare it here, the Tag type remains \ * a \ * simple tag type, it has no other responsibilities. */ \ PRIVATE_ACCESS_DETAIL_CONCATENATE(PtrType_, Tag) get(Tag); \ } \ } #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_FIELD(Tag, Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, Class::*) \ namespace { \ namespace access_private_field { \ Type &Class##Name(Class &&t) { return t.*get(private_access_detail::Tag{}); } \ Type &Class##Name(Class &t) { return t.*get(private_access_detail::Tag{}); } \ /* The following usings are here to avoid duplicate const qualifier \ * warnings \ */ \ using PRIVATE_ACCESS_DETAIL_CONCATENATE(X, Tag) = Type; \ using PRIVATE_ACCESS_DETAIL_CONCATENATE(Y, Tag) = \ const PRIVATE_ACCESS_DETAIL_CONCATENATE(X, Tag); \ PRIVATE_ACCESS_DETAIL_CONCATENATE(Y, Tag) & Class##Name(const Class &t) {\ return t.*get(private_access_detail::Tag{}); \ } \ } \ } #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_FUN(Tag, Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, Class::*) \ namespace { \ namespace call_private_fun { \ /* We do perfect forwarding, but we want to restrict the overload set \ * only for objects which have the type Class. */ \ template , \ Class>::value> * = nullptr, \ typename... Args> \ auto Class##Name(Obj &&o, Args &&... args) -> decltype( \ (std::forward(o).* \ get(private_access_detail::Tag{}))(std::forward(args)...)) { \ return (std::forward(o).*get(private_access_detail::Tag{}))( \ std::forward(args)...); \ } \ } \ namespace get_private_fun { \ auto Class##Name() -> decltype( \ get(private_access_detail::Tag{})) { \ return (get(private_access_detail::Tag{})); \ } \ } \ } #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_STATIC_FIELD(Tag, Class, Type, \ Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, *) \ namespace { \ namespace access_private_static_field { \ namespace Class { \ Type &Class##Name() { return *get(private_access_detail::Tag{}); } \ } \ } \ } #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_STATIC_FUN(Tag, Class, Type, \ Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, *) \ namespace { \ namespace call_private_static_fun { \ namespace Class { \ template \ auto Class##Name(Args &&... args) -> decltype( \ get(private_access_detail::Tag{})(std::forward(args)...)) { \ return get(private_access_detail::Tag{})( \ std::forward(args)...); \ } \ } \ } \ namespace get_private_static_fun { \ namespace Class { \ auto Class##Name() -> decltype(get(private_access_detail::Tag{})) { \ return get(private_access_detail::Tag{}); \ } \ } \ } \ } #define PRIVATE_ACCESS_DETAIL_UNIQUE_TAG \ PRIVATE_ACCESS_DETAIL_CONCATENATE(PrivateAccessTag, __COUNTER__) #define ACCESS_PRIVATE_FIELD(Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_FIELD(PRIVATE_ACCESS_DETAIL_UNIQUE_TAG, \ Class, Type, Name) #define ACCESS_PRIVATE_FUN(Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_FUN(PRIVATE_ACCESS_DETAIL_UNIQUE_TAG, \ Class, Type, Name) #define ACCESS_PRIVATE_STATIC_FIELD(Class, Type, Name) \ Type Class::Name; \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_STATIC_FIELD( \ PRIVATE_ACCESS_DETAIL_UNIQUE_TAG, Class, Type, Name) #define ACCESS_PRIVATE_STATIC_FUN(Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_STATIC_FUN( \ PRIVATE_ACCESS_DETAIL_UNIQUE_TAG, Class, Type, Name) #endif libkylin-nm-base/tests/kt-test-utils/cpp-stub/addr_any.h0000664000175000017500000002113415160517205022222 0ustar fengfeng#ifndef __ADDR_ANY_H__ #define __ADDR_ANY_H__ //linux #include #include //c #include #include #include //c++ #include #include //project #include "elfio.hpp" class AddrAny { public: AddrAny() { m_init = get_exe_pathname(m_fullname); m_baseaddr = 0; } AddrAny(std::string libname) { m_init = get_lib_pathname_and_baseaddr(libname, m_fullname, m_baseaddr); } int get_local_func_addr_symtab(std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_SYMTAB, STB_LOCAL, func_name_regex_str, result); } int get_global_func_addr_symtab(std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_SYMTAB, STB_GLOBAL, func_name_regex_str, result); } int get_weak_func_addr_symtab(std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_SYMTAB, STB_WEAK, func_name_regex_str, result); } int get_global_func_addr_dynsym( std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_DYNSYM, STB_GLOBAL, func_name_regex_str, result); } int get_weak_func_addr_dynsym(std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_DYNSYM, STB_WEAK, func_name_regex_str, result); } private: bool demangle(std::string& s, std::string& name) { int status; char* pname = abi::__cxa_demangle(s.c_str(), 0, 0, &status); if (status != 0) { switch(status) { case -1: name = "memory allocation error"; break; case -2: name = "invalid name given"; break; case -3: name = "internal error: __cxa_demangle: invalid argument"; break; default: name = "unknown error occured"; break; } return false; } name = pname; free(pname); return true; } bool get_exe_pathname( std::string& name) { char line[512]; FILE *fp; uintptr_t base_addr; char perm[5]; unsigned long offset; int pathname_pos; char *pathname; size_t pathname_len; int match = 0; if(NULL == (fp = fopen("/proc/self/maps", "r"))) { return false; } while(fgets(line, sizeof(line), fp)) { if(sscanf(line, "%" PRIxPTR "-%*lx %4s %lx %*x:%*x %*d%n", &base_addr, perm, &offset, &pathname_pos) != 3) continue; if(0 != offset) continue; //get pathname while(isspace(line[pathname_pos]) && pathname_pos < (int)(sizeof(line) - 1)) pathname_pos += 1; if(pathname_pos >= (int)(sizeof(line) - 1)) continue; pathname = line + pathname_pos; pathname_len = strlen(pathname); if(0 == pathname_len) continue; if(pathname[pathname_len - 1] == '\n') { pathname[pathname_len - 1] = '\0'; pathname_len -= 1; } if(0 == pathname_len) continue; if('[' == pathname[0]) continue; name = pathname; match = 1; break; } fclose(fp); if(0 == match) { return false; } else { return true; } } bool get_lib_pathname_and_baseaddr(std::string pathname_regex_str, std::string& name, unsigned long& addr) { char line[512]; FILE *fp; uintptr_t base_addr; char perm[5]; unsigned long offset; int pathname_pos; char *pathname; size_t pathname_len; int match; regex_t pathname_regex; regcomp(&pathname_regex, pathname_regex_str.c_str(), 0); if(NULL == (fp = fopen("/proc/self/maps", "r"))) { return false; } while(fgets(line, sizeof(line), fp)) { if(sscanf(line, "%" PRIxPTR "-%*lx %4s %lx %*x:%*x %*d%n", &base_addr, perm, &offset, &pathname_pos) != 3) continue; //check permission if(perm[0] != 'r') continue; if(perm[3] != 'p') continue; //do not touch the shared memory //check offset // //We are trying to find ELF header in memory. //It can only be found at the beginning of a mapped memory regions //whose offset is 0. if(0 != offset) continue; //get pathname while(isspace(line[pathname_pos]) && pathname_pos < (int)(sizeof(line) - 1)) pathname_pos += 1; if(pathname_pos >= (int)(sizeof(line) - 1)) continue; pathname = line + pathname_pos; pathname_len = strlen(pathname); if(0 == pathname_len) continue; if(pathname[pathname_len - 1] == '\n') { pathname[pathname_len - 1] = '\0'; pathname_len -= 1; } if(0 == pathname_len) continue; if('[' == pathname[0]) continue; //check pathname //if we need to hook this elf? match = 0; if(0 == regexec(&pathname_regex, pathname, 0, NULL, 0)) { match = 1; name = pathname; addr = (unsigned long)base_addr; break; } if(0 == match) continue; } fclose(fp); if(0 == match) { return false; } else { return true; } } int get_func_addr(unsigned int ttype, unsigned int stype, std::string& func_name_regex_str, std::map& result) { // Create an elfio reader ELFIO::elfio reader; int count = 0; regex_t pathname_regex; if(!m_init) { return -1; } regcomp(&pathname_regex, func_name_regex_str.c_str(), 0); // Load ELF data if(!reader.load(m_fullname.c_str())) { return -1; } ELFIO::Elf_Half sec_num = reader.sections.size(); for(int i = 0; i < sec_num; ++i) { ELFIO::section* psec = reader.sections[i]; // Check section type if(psec->get_type() == ttype) { const ELFIO::symbol_section_accessor symbols( reader, psec ); for ( unsigned int j = 0; j < symbols.get_symbols_num(); ++j ) { std::string name; std::string name_mangle; ELFIO::Elf64_Addr value; ELFIO::Elf_Xword size; unsigned char bind; unsigned char type; ELFIO::Elf_Half section_index; unsigned char other; // Read symbol properties symbols.get_symbol( j, name, value, size, bind, type, section_index, other ); if(type == STT_FUNC && bind == stype) { bool ret = demangle(name,name_mangle); if(ret == true) { if (0 == regexec(&pathname_regex, name_mangle.c_str(), 0, NULL, 0)) { result.insert ( std::pair(name_mangle,(void*)(value + m_baseaddr))); count++; } } else { if (0 == regexec(&pathname_regex, name.c_str(), 0, NULL, 0)) { result.insert ( std::pair(name,(void*)(value + m_baseaddr))); count++; } } } } break; } } return count; } private: bool m_init; std::string m_name; std::string m_fullname; unsigned long m_baseaddr; }; #endif libkylin-nm-base/tests/kt-test-utils/cpp-stub/elfio.hpp0000664000175000017500000045310415160517205022105 0ustar fengfeng /*** Start of inlined file: elfio_dump.hpp ***/ #ifndef ELFIO_DUMP_HPP #define ELFIO_DUMP_HPP #include #include #include #include #include /*** Start of inlined file: elfio.hpp ***/ #ifndef ELFIO_HPP #define ELFIO_HPP #ifdef _MSC_VER #pragma warning( push ) #pragma warning( disable : 4996 ) #pragma warning( disable : 4355 ) #pragma warning( disable : 4244 ) #endif #include #include #include #include #include #include #include #include /*** Start of inlined file: elf_types.hpp ***/ #ifndef ELFTYPES_H #define ELFTYPES_H #ifndef ELFIO_NO_OWN_TYPES #if !defined( ELFIO_NO_CSTDINT ) && !defined( ELFIO_NO_INTTYPES ) #include #else typedef unsigned char uint8_t; typedef signed char int8_t; typedef unsigned short uint16_t; typedef signed short int16_t; #ifdef _MSC_VER typedef unsigned __int32 uint32_t; typedef signed __int32 int32_t; typedef unsigned __int64 uint64_t; typedef signed __int64 int64_t; #else typedef unsigned int uint32_t; typedef signed int int32_t; typedef unsigned long long uint64_t; typedef signed long long int64_t; #endif // _MSC_VER #endif // ELFIO_NO_CSTDINT #endif // ELFIO_NO_OWN_TYPES namespace ELFIO { // Attention! Platform depended definitions. typedef uint16_t Elf_Half; typedef uint32_t Elf_Word; typedef int32_t Elf_Sword; typedef uint64_t Elf_Xword; typedef int64_t Elf_Sxword; typedef uint32_t Elf32_Addr; typedef uint32_t Elf32_Off; typedef uint64_t Elf64_Addr; typedef uint64_t Elf64_Off; #define Elf32_Half Elf_Half #define Elf64_Half Elf_Half #define Elf32_Word Elf_Word #define Elf64_Word Elf_Word #define Elf32_Sword Elf_Sword #define Elf64_Sword Elf_Sword /////////////////////// // ELF Header Constants // File type #define ET_NONE 0 #define ET_REL 1 #define ET_EXEC 2 #define ET_DYN 3 #define ET_CORE 4 #define ET_LOOS 0xFE00 #define ET_HIOS 0xFEFF #define ET_LOPROC 0xFF00 #define ET_HIPROC 0xFFFF #define EM_NONE 0 // No machine #define EM_M32 1 // AT&T WE 32100 #define EM_SPARC 2 // SUN SPARC #define EM_386 3 // Intel 80386 #define EM_68K 4 // Motorola m68k family #define EM_88K 5 // Motorola m88k family #define EM_486 6 // Intel 80486// Reserved for future use #define EM_860 7 // Intel 80860 #define EM_MIPS 8 // MIPS R3000 (officially, big-endian only) #define EM_S370 9 // IBM System/370 #define EM_MIPS_RS3_LE \ 10 // MIPS R3000 little-endian (Oct 4 1999 Draft) Deprecated #define EM_res011 11 // Reserved #define EM_res012 12 // Reserved #define EM_res013 13 // Reserved #define EM_res014 14 // Reserved #define EM_PARISC 15 // HPPA #define EM_res016 16 // Reserved #define EM_VPP550 17 // Fujitsu VPP500 #define EM_SPARC32PLUS 18 // Sun's "v8plus" #define EM_960 19 // Intel 80960 #define EM_PPC 20 // PowerPC #define EM_PPC64 21 // 64-bit PowerPC #define EM_S390 22 // IBM S/390 #define EM_SPU 23 // Sony/Toshiba/IBM SPU #define EM_res024 24 // Reserved #define EM_res025 25 // Reserved #define EM_res026 26 // Reserved #define EM_res027 27 // Reserved #define EM_res028 28 // Reserved #define EM_res029 29 // Reserved #define EM_res030 30 // Reserved #define EM_res031 31 // Reserved #define EM_res032 32 // Reserved #define EM_res033 33 // Reserved #define EM_res034 34 // Reserved #define EM_res035 35 // Reserved #define EM_V800 36 // NEC V800 series #define EM_FR20 37 // Fujitsu FR20 #define EM_RH32 38 // TRW RH32 #define EM_MCORE 39 // Motorola M*Core // May also be taken by Fujitsu MMA #define EM_RCE 39 // Old name for MCore #define EM_ARM 40 // ARM #define EM_OLD_ALPHA 41 // Digital Alpha #define EM_SH 42 // Renesas (formerly Hitachi) / SuperH SH #define EM_SPARCV9 43 // SPARC v9 64-bit #define EM_TRICORE 44 // Siemens Tricore embedded processor #define EM_ARC 45 // ARC Cores #define EM_H8_300 46 // Renesas (formerly Hitachi) H8/300 #define EM_H8_300H 47 // Renesas (formerly Hitachi) H8/300H #define EM_H8S 48 // Renesas (formerly Hitachi) H8S #define EM_H8_500 49 // Renesas (formerly Hitachi) H8/500 #define EM_IA_64 50 // Intel IA-64 Processor #define EM_MIPS_X 51 // Stanford MIPS-X #define EM_COLDFIRE 52 // Motorola Coldfire #define EM_68HC12 53 // Motorola M68HC12 #define EM_MMA 54 // Fujitsu Multimedia Accelerator #define EM_PCP 55 // Siemens PCP #define EM_NCPU 56 // Sony nCPU embedded RISC processor #define EM_NDR1 57 // Denso NDR1 microprocesspr #define EM_STARCORE 58 // Motorola Star*Core processor #define EM_ME16 59 // Toyota ME16 processor #define EM_ST100 60 // STMicroelectronics ST100 processor #define EM_TINYJ 61 // Advanced Logic Corp. TinyJ embedded processor #define EM_X86_64 62 // Advanced Micro Devices X86-64 processor #define EM_PDSP 63 // Sony DSP Processor #define EM_PDP10 64 // Digital Equipment Corp. PDP-10 #define EM_PDP11 65 // Digital Equipment Corp. PDP-11 #define EM_FX66 66 // Siemens FX66 microcontroller #define EM_ST9PLUS 67 // STMicroelectronics ST9+ 8/16 bit microcontroller #define EM_ST7 68 // STMicroelectronics ST7 8-bit microcontroller #define EM_68HC16 69 // Motorola MC68HC16 Microcontroller #define EM_68HC11 70 // Motorola MC68HC11 Microcontroller #define EM_68HC08 71 // Motorola MC68HC08 Microcontroller #define EM_68HC05 72 // Motorola MC68HC05 Microcontroller #define EM_SVX 73 // Silicon Graphics SVx #define EM_ST19 74 // STMicroelectronics ST19 8-bit cpu #define EM_VAX 75 // Digital VAX #define EM_CRIS 76 // Axis Communications 32-bit embedded processor #define EM_JAVELIN 77 // Infineon Technologies 32-bit embedded cpu #define EM_FIREPATH 78 // Element 14 64-bit DSP processor #define EM_ZSP 79 // LSI Logic's 16-bit DSP processor #define EM_MMIX 80 // Donald Knuth's educational 64-bit processor #define EM_HUANY 81 // Harvard's machine-independent format #define EM_PRISM 82 // SiTera Prism #define EM_AVR 83 // Atmel AVR 8-bit microcontroller #define EM_FR30 84 // Fujitsu FR30 #define EM_D10V 85 // Mitsubishi D10V #define EM_D30V 86 // Mitsubishi D30V #define EM_V850 87 // NEC v850 #define EM_M32R 88 // Renesas M32R (formerly Mitsubishi M32R) #define EM_MN10300 89 // Matsushita MN10300 #define EM_MN10200 90 // Matsushita MN10200 #define EM_PJ 91 // picoJava #define EM_OPENRISC 92 // OpenRISC 32-bit embedded processor #define EM_ARC_A5 93 // ARC Cores Tangent-A5 #define EM_XTENSA 94 // Tensilica Xtensa Architecture #define EM_VIDEOCORE 95 // Alphamosaic VideoCore processor #define EM_TMM_GPP 96 // Thompson Multimedia General Purpose Processor #define EM_NS32K 97 // National Semiconductor 32000 series #define EM_TPC 98 // Tenor Network TPC processor #define EM_SNP1K 99 // Trebia SNP 1000 processor #define EM_ST200 100 // STMicroelectronics ST200 microcontroller #define EM_IP2K 101 // Ubicom IP2022 micro controller #define EM_MAX 102 // MAX Processor #define EM_CR 103 // National Semiconductor CompactRISC #define EM_F2MC16 104 // Fujitsu F2MC16 #define EM_MSP430 105 // TI msp430 micro controller #define EM_BLACKFIN 106 // ADI Blackfin #define EM_SE_C33 107 // S1C33 Family of Seiko Epson processors #define EM_SEP 108 // Sharp embedded microprocessor #define EM_ARCA 109 // Arca RISC Microprocessor #define EM_UNICORE \ 110 // Microprocessor series from PKU-Unity Ltd. and MPRC of Peking University #define EM_EXCESS 111 // eXcess: 16/32/64-bit configurable embedded CPU #define EM_DXP 112 // Icera Semiconductor Inc. Deep Execution Processor #define EM_ALTERA_NIOS2 113 // Altera Nios II soft-core processor #define EM_CRX 114 // National Semiconductor CRX #define EM_XGATE 115 // Motorola XGATE embedded processor #define EM_C166 116 // Infineon C16x/XC16x processor #define EM_M16C 117 // Renesas M16C series microprocessors #define EM_DSPIC30F \ 118 // Microchip Technology dsPIC30F Digital Signal Controller #define EM_CE 119 // Freescale Communication Engine RISC core #define EM_M32C 120 // Renesas M32C series microprocessors #define EM_res121 121 // Reserved #define EM_res122 122 // Reserved #define EM_res123 123 // Reserved #define EM_res124 124 // Reserved #define EM_res125 125 // Reserved #define EM_res126 126 // Reserved #define EM_res127 127 // Reserved #define EM_res128 128 // Reserved #define EM_res129 129 // Reserved #define EM_res130 130 // Reserved #define EM_TSK3000 131 // Altium TSK3000 core #define EM_RS08 132 // Freescale RS08 embedded processor #define EM_res133 133 // Reserved #define EM_ECOG2 134 // Cyan Technology eCOG2 microprocessor #define EM_SCORE 135 // Sunplus Score #define EM_SCORE7 135 // Sunplus S+core7 RISC processor #define EM_DSP24 136 // New Japan Radio (NJR) 24-bit DSP Processor #define EM_VIDEOCORE3 137 // Broadcom VideoCore III processor #define EM_LATTICEMICO32 138 // RISC processor for Lattice FPGA architecture #define EM_SE_C17 139 // Seiko Epson C17 family #define EM_TI_C6000 140 // Texas Instruments TMS320C6000 DSP family #define EM_TI_C2000 141 // Texas Instruments TMS320C2000 DSP family #define EM_TI_C5500 142 // Texas Instruments TMS320C55x DSP family #define EM_res143 143 // Reserved #define EM_res144 144 // Reserved #define EM_res145 145 // Reserved #define EM_res146 146 // Reserved #define EM_res147 147 // Reserved #define EM_res148 148 // Reserved #define EM_res149 149 // Reserved #define EM_res150 150 // Reserved #define EM_res151 151 // Reserved #define EM_res152 152 // Reserved #define EM_res153 153 // Reserved #define EM_res154 154 // Reserved #define EM_res155 155 // Reserved #define EM_res156 156 // Reserved #define EM_res157 157 // Reserved #define EM_res158 158 // Reserved #define EM_res159 159 // Reserved #define EM_MMDSP_PLUS 160 // STMicroelectronics 64bit VLIW Data Signal Processor #define EM_CYPRESS_M8C 161 // Cypress M8C microprocessor #define EM_R32C 162 // Renesas R32C series microprocessors #define EM_TRIMEDIA 163 // NXP Semiconductors TriMedia architecture family #define EM_QDSP6 164 // QUALCOMM DSP6 Processor #define EM_8051 165 // Intel 8051 and variants #define EM_STXP7X 166 // STMicroelectronics STxP7x family #define EM_NDS32 \ 167 // Andes Technology compact code size embedded RISC processor family #define EM_ECOG1 168 // Cyan Technology eCOG1X family #define EM_ECOG1X 168 // Cyan Technology eCOG1X family #define EM_MAXQ30 169 // Dallas Semiconductor MAXQ30 Core Micro-controllers #define EM_XIMO16 170 // New Japan Radio (NJR) 16-bit DSP Processor #define EM_MANIK 171 // M2000 Reconfigurable RISC Microprocessor #define EM_CRAYNV2 172 // Cray Inc. NV2 vector architecture #define EM_RX 173 // Renesas RX family #define EM_METAG 174 // Imagination Technologies META processor architecture #define EM_MCST_ELBRUS 175 // MCST Elbrus general purpose hardware architecture #define EM_ECOG16 176 // Cyan Technology eCOG16 family #define EM_CR16 177 // National Semiconductor CompactRISC 16-bit processor #define EM_ETPU 178 // Freescale Extended Time Processing Unit #define EM_SLE9X 179 // Infineon Technologies SLE9X core #define EM_L1OM 180 // Intel L1OM #define EM_INTEL181 181 // Reserved by Intel #define EM_INTEL182 182 // Reserved by Intel #define EM_res183 183 // Reserved by ARM #define EM_res184 184 // Reserved by ARM #define EM_AVR32 185 // Atmel Corporation 32-bit microprocessor family #define EM_STM8 186 // STMicroeletronics STM8 8-bit microcontroller #define EM_TILE64 187 // Tilera TILE64 multicore architecture family #define EM_TILEPRO 188 // Tilera TILEPro multicore architecture family #define EM_MICROBLAZE 189 // Xilinx MicroBlaze 32-bit RISC soft processor core #define EM_CUDA 190 // NVIDIA CUDA architecture #define EM_TILEGX 191 // Tilera TILE-Gx multicore architecture family #define EM_CLOUDSHIELD 192 // CloudShield architecture family #define EM_COREA_1ST 193 // KIPO-KAIST Core-A 1st generation processor family #define EM_COREA_2ND 194 // KIPO-KAIST Core-A 2nd generation processor family #define EM_ARC_COMPACT2 195 // Synopsys ARCompact V2 #define EM_OPEN8 196 // Open8 8-bit RISC soft processor core #define EM_RL78 197 // Renesas RL78 family #define EM_VIDEOCORE5 198 // Broadcom VideoCore V processor #define EM_78KOR 199 // Renesas 78KOR family #define EM_56800EX 200 // Freescale 56800EX Digital Signal Controller (DSC) #define EM_BA1 201 // Beyond BA1 CPU architecture #define EM_BA2 202 // Beyond BA2 CPU architecture #define EM_XCORE 203 // XMOS xCORE processor family #define EM_MCHP_PIC 204 // Microchip 8-bit PIC(r) family #define EM_INTEL205 205 // Reserved by Intel #define EM_INTEL206 206 // Reserved by Intel #define EM_INTEL207 207 // Reserved by Intel #define EM_INTEL208 208 // Reserved by Intel #define EM_INTEL209 209 // Reserved by Intel #define EM_KM32 210 // KM211 KM32 32-bit processor #define EM_KMX32 211 // KM211 KMX32 32-bit processor #define EM_KMX16 212 // KM211 KMX16 16-bit processor #define EM_KMX8 213 // KM211 KMX8 8-bit processor #define EM_KVARC 214 // KM211 KVARC processor #define EM_CDP 215 // Paneve CDP architecture family #define EM_COGE 216 // Cognitive Smart Memory Processor #define EM_COOL 217 // iCelero CoolEngine #define EM_NORC 218 // Nanoradio Optimized RISC #define EM_CSR_KALIMBA 219 // CSR Kalimba architecture family #define EM_Z80 220 // Zilog Z80 #define EM_VISIUM 221 // Controls and Data Services VISIUMcore processor #define EM_FT32 222 // FTDI Chip FT32 high performance 32-bit RISC architecture #define EM_MOXIE 223 // Moxie processor family #define EM_AMDGPU 224 // AMD GPU architecture #define EM_RISCV 243 // RISC-V #define EM_LANAI 244 // Lanai processor #define EM_CEVA 245 // CEVA Processor Architecture Family #define EM_CEVA_X2 246 // CEVA X2 Processor Family #define EM_BPF 247 // Linux BPF – in-kernel virtual machine #define EM_GRAPHCORE_IPU 248 // Graphcore Intelligent Processing Unit #define EM_IMG1 249 // Imagination Technologies #define EM_NFP 250 // Netronome Flow Processor (P) #define EM_CSKY 252 // C-SKY processor family // File version #define EV_NONE 0 #define EV_CURRENT 1 // Identification index #define EI_MAG0 0 #define EI_MAG1 1 #define EI_MAG2 2 #define EI_MAG3 3 #define EI_CLASS 4 #define EI_DATA 5 #define EI_VERSION 6 #define EI_OSABI 7 #define EI_ABIVERSION 8 #define EI_PAD 9 #define EI_NIDENT 16 // Magic number #define ELFMAG0 0x7F #define ELFMAG1 'E' #define ELFMAG2 'L' #define ELFMAG3 'F' // File class #define ELFCLASSNONE 0 #define ELFCLASS32 1 #define ELFCLASS64 2 // Encoding #define ELFDATANONE 0 #define ELFDATA2LSB 1 #define ELFDATA2MSB 2 // OS extensions #define ELFOSABI_NONE 0 // No extensions or unspecified #define ELFOSABI_HPUX 1 // Hewlett-Packard HP-UX #define ELFOSABI_NETBSD 2 // NetBSD #define ELFOSABI_LINUX 3 // Linux #define ELFOSABI_SOLARIS 6 // Sun Solaris #define ELFOSABI_AIX 7 // AIX #define ELFOSABI_IRIX 8 // IRIX #define ELFOSABI_FREEBSD 9 // FreeBSD #define ELFOSABI_TRU64 10 // Compaq TRU64 UNIX #define ELFOSABI_MODESTO 11 // Novell Modesto #define ELFOSABI_OPENBSD 12 // Open BSD #define ELFOSABI_OPENVMS 13 // Open VMS #define ELFOSABI_NSK 14 // Hewlett-Packard Non-Stop Kernel #define ELFOSABI_AROS 15 // Amiga Research OS #define ELFOSABI_FENIXOS 16 // The FenixOS highly scalable multi-core OS // 64-255 Architecture-specific value range #define ELFOSABI_AMDGPU_HSA \ 64 // AMDGPU OS for HSA compatible compute // kernels. #define ELFOSABI_AMDGPU_PAL \ 65 // AMDGPU OS for AMD PAL compatible graphics // shaders and compute kernels. #define ELFOSABI_AMDGPU_MESA3D \ 66 // AMDGPU OS for Mesa3D compatible graphics // shaders and compute kernels. // AMDGPU specific e_flags #define EF_AMDGPU_MACH 0x0ff // AMDGPU processor selection mask. #define EF_AMDGPU_XNACK \ 0x100 // Indicates if the XNACK target feature is // enabled for all code contained in the ELF. // AMDGPU processors #define EF_AMDGPU_MACH_NONE 0x000 // Unspecified processor. #define EF_AMDGPU_MACH_R600_R600 0x001 #define EF_AMDGPU_MACH_R600_R630 0x002 #define EF_AMDGPU_MACH_R600_RS880 0x003 #define EF_AMDGPU_MACH_R600_RV670 0x004 #define EF_AMDGPU_MACH_R600_RV710 0x005 #define EF_AMDGPU_MACH_R600_RV730 0x006 #define EF_AMDGPU_MACH_R600_RV770 0x007 #define EF_AMDGPU_MACH_R600_CEDAR 0x008 #define EF_AMDGPU_MACH_R600_CYPRESS 0x009 #define EF_AMDGPU_MACH_R600_JUNIPER 0x00a #define EF_AMDGPU_MACH_R600_REDWOOD 0x00b #define EF_AMDGPU_MACH_R600_SUMO 0x00c #define EF_AMDGPU_MACH_R600_BARTS 0x00d #define EF_AMDGPU_MACH_R600_CAICOS 0x00e #define EF_AMDGPU_MACH_R600_CAYMAN 0x00f #define EF_AMDGPU_MACH_R600_TURKS 0x010 #define EF_AMDGPU_MACH_R600_RESERVED_FIRST 0x011 #define EF_AMDGPU_MACH_R600_RESERVED_LAST 0x01f #define EF_AMDGPU_MACH_R600_FIRST EF_AMDGPU_MACH_R600_R600 #define EF_AMDGPU_MACH_R600_LAST EF_AMDGPU_MACH_R600_TURKS #define EF_AMDGPU_MACH_AMDGCN_GFX600 0x020 #define EF_AMDGPU_MACH_AMDGCN_GFX601 0x021 #define EF_AMDGPU_MACH_AMDGCN_GFX700 0x022 #define EF_AMDGPU_MACH_AMDGCN_GFX701 0x023 #define EF_AMDGPU_MACH_AMDGCN_GFX702 0x024 #define EF_AMDGPU_MACH_AMDGCN_GFX703 0x025 #define EF_AMDGPU_MACH_AMDGCN_GFX704 0x026 #define EF_AMDGPU_MACH_AMDGCN_GFX801 0x028 #define EF_AMDGPU_MACH_AMDGCN_GFX802 0x029 #define EF_AMDGPU_MACH_AMDGCN_GFX803 0x02a #define EF_AMDGPU_MACH_AMDGCN_GFX810 0x02b #define EF_AMDGPU_MACH_AMDGCN_GFX900 0x02c #define EF_AMDGPU_MACH_AMDGCN_GFX902 0x02d #define EF_AMDGPU_MACH_AMDGCN_GFX904 0x02e #define EF_AMDGPU_MACH_AMDGCN_GFX906 0x02f #define EF_AMDGPU_MACH_AMDGCN_RESERVED0 0x027 #define EF_AMDGPU_MACH_AMDGCN_RESERVED1 0x030 #define EF_AMDGPU_MACH_AMDGCN_FIRST EF_AMDGPU_MACH_AMDGCN_GFX600 #define EF_AMDGPU_MACH_AMDGCN_LAST EF_AMDGPU_MACH_AMDGCN_GFX906 ///////////////////// // Sections constants // Section indexes #define SHN_UNDEF 0 #define SHN_LORESERVE 0xFF00 #define SHN_LOPROC 0xFF00 #define SHN_HIPROC 0xFF1F #define SHN_LOOS 0xFF20 #define SHN_HIOS 0xFF3F #define SHN_ABS 0xFFF1 #define SHN_COMMON 0xFFF2 #define SHN_XINDEX 0xFFFF #define SHN_HIRESERVE 0xFFFF // Section types #define SHT_NULL 0 #define SHT_PROGBITS 1 #define SHT_SYMTAB 2 #define SHT_STRTAB 3 #define SHT_RELA 4 #define SHT_HASH 5 #define SHT_DYNAMIC 6 #define SHT_NOTE 7 #define SHT_NOBITS 8 #define SHT_REL 9 #define SHT_SHLIB 10 #define SHT_DYNSYM 11 #define SHT_INIT_ARRAY 14 #define SHT_FINI_ARRAY 15 #define SHT_PREINIT_ARRAY 16 #define SHT_GROUP 17 #define SHT_SYMTAB_SHNDX 18 #define SHT_LOOS 0x60000000 #define SHT_HIOS 0x6fffffff #define SHT_LOPROC 0x70000000 #define SHT_HIPROC 0x7FFFFFFF #define SHT_LOUSER 0x80000000 #define SHT_HIUSER 0xFFFFFFFF // Section attribute flags #define SHF_WRITE 0x1 #define SHF_ALLOC 0x2 #define SHF_EXECINSTR 0x4 #define SHF_MERGE 0x10 #define SHF_STRINGS 0x20 #define SHF_INFO_LINK 0x40 #define SHF_LINK_ORDER 0x80 #define SHF_OS_NONCONFORMING 0x100 #define SHF_GROUP 0x200 #define SHF_TLS 0x400 #define SHF_MASKOS 0x0ff00000 #define SHF_MASKPROC 0xF0000000 // Section group flags #define GRP_COMDAT 0x1 #define GRP_MASKOS 0x0ff00000 #define GRP_MASKPROC 0xf0000000 // Symbol binding #define STB_LOCAL 0 #define STB_GLOBAL 1 #define STB_WEAK 2 #define STB_LOOS 10 #define STB_HIOS 12 #define STB_MULTIDEF 13 #define STB_LOPROC 13 #define STB_HIPROC 15 // Note types #define NT_AMDGPU_METADATA 1 #define NT_AMD_AMDGPU_HSA_METADATA 10 #define NT_AMD_AMDGPU_ISA 11 #define NT_AMD_AMDGPU_PAL_METADATA 12 // Symbol types #define STT_NOTYPE 0 #define STT_OBJECT 1 #define STT_FUNC 2 #define STT_SECTION 3 #define STT_FILE 4 #define STT_COMMON 5 #define STT_TLS 6 #define STT_LOOS 10 #define STT_AMDGPU_HSA_KERNEL 10 #define STT_HIOS 12 #define STT_LOPROC 13 #define STT_HIPROC 15 // Symbol visibility #define STV_DEFAULT 0 #define STV_INTERNAL 1 #define STV_HIDDEN 2 #define STV_PROTECTED 3 // Undefined name #define STN_UNDEF 0 // Relocation types #define R_386_NONE 0 #define R_X86_64_NONE 0 #define R_AMDGPU_NONE 0 #define R_386_32 1 #define R_X86_64_64 1 #define R_AMDGPU_ABS32_LO 1 #define R_386_PC32 2 #define R_X86_64_PC32 2 #define R_AMDGPU_ABS32_HI 2 #define R_386_GOT32 3 #define R_X86_64_GOT32 3 #define R_AMDGPU_ABS64 3 #define R_386_PLT32 4 #define R_X86_64_PLT32 4 #define R_AMDGPU_REL32 4 #define R_386_COPY 5 #define R_X86_64_COPY 5 #define R_AMDGPU_REL64 5 #define R_386_GLOB_DAT 6 #define R_X86_64_GLOB_DAT 6 #define R_AMDGPU_ABS32 6 #define R_386_JMP_SLOT 7 #define R_X86_64_JUMP_SLOT 7 #define R_AMDGPU_GOTPCREL 7 #define R_386_RELATIVE 8 #define R_X86_64_RELATIVE 8 #define R_AMDGPU_GOTPCREL32_LO 8 #define R_386_GOTOFF 9 #define R_X86_64_GOTPCREL 9 #define R_AMDGPU_GOTPCREL32_HI 9 #define R_386_GOTPC 10 #define R_X86_64_32 10 #define R_AMDGPU_REL32_LO 10 #define R_386_32PLT 11 #define R_X86_64_32S 11 #define R_AMDGPU_REL32_HI 11 #define R_X86_64_16 12 #define R_X86_64_PC16 13 #define R_AMDGPU_RELATIVE64 13 #define R_386_TLS_TPOFF 14 #define R_X86_64_8 14 #define R_386_TLS_IE 15 #define R_X86_64_PC8 15 #define R_386_TLS_GOTIE 16 #define R_X86_64_DTPMOD64 16 #define R_386_TLS_LE 17 #define R_X86_64_DTPOFF64 17 #define R_386_TLS_GD 18 #define R_X86_64_TPOFF64 18 #define R_386_TLS_LDM 19 #define R_X86_64_TLSGD 19 #define R_386_16 20 #define R_X86_64_TLSLD 20 #define R_386_PC16 21 #define R_X86_64_DTPOFF32 21 #define R_386_8 22 #define R_X86_64_GOTTPOFF 22 #define R_386_PC8 23 #define R_X86_64_TPOFF32 23 #define R_386_TLS_GD_32 24 #define R_X86_64_PC64 24 #define R_386_TLS_GD_PUSH 25 #define R_X86_64_GOTOFF64 25 #define R_386_TLS_GD_CALL 26 #define R_X86_64_GOTPC32 26 #define R_386_TLS_GD_POP 27 #define R_X86_64_GOT64 27 #define R_386_TLS_LDM_32 28 #define R_X86_64_GOTPCREL64 28 #define R_386_TLS_LDM_PUSH 29 #define R_X86_64_GOTPC64 29 #define R_386_TLS_LDM_CALL 30 #define R_X86_64_GOTPLT64 30 #define R_386_TLS_LDM_POP 31 #define R_X86_64_PLTOFF64 31 #define R_386_TLS_LDO_32 32 #define R_386_TLS_IE_32 33 #define R_386_TLS_LE_32 34 #define R_X86_64_GOTPC32_TLSDESC 34 #define R_386_TLS_DTPMOD32 35 #define R_X86_64_TLSDESC_CALL 35 #define R_386_TLS_DTPOFF32 36 #define R_X86_64_TLSDESC 36 #define R_386_TLS_TPOFF32 37 #define R_X86_64_IRELATIVE 37 #define R_386_SIZE32 38 #define R_386_TLS_GOTDESC 39 #define R_386_TLS_DESC_CALL 40 #define R_386_TLS_DESC 41 #define R_386_IRELATIVE 42 #define R_386_GOT32X 43 #define R_X86_64_GNU_VTINHERIT 250 #define R_X86_64_GNU_VTENTRY 251 // Segment types #define PT_NULL 0 #define PT_LOAD 1 #define PT_DYNAMIC 2 #define PT_INTERP 3 #define PT_NOTE 4 #define PT_SHLIB 5 #define PT_PHDR 6 #define PT_TLS 7 #define PT_LOOS 0x60000000 #define PT_HIOS 0x6fffffff #define PT_LOPROC 0x70000000 #define PT_HIPROC 0x7FFFFFFF // Segment flags #define PF_X 1 // Execute #define PF_W 2 // Write #define PF_R 4 // Read #define PF_MASKOS 0x0ff00000 // Unspecified #define PF_MASKPROC 0xf0000000 // Unspecified // Dynamic Array Tags #define DT_NULL 0 #define DT_NEEDED 1 #define DT_PLTRELSZ 2 #define DT_PLTGOT 3 #define DT_HASH 4 #define DT_STRTAB 5 #define DT_SYMTAB 6 #define DT_RELA 7 #define DT_RELASZ 8 #define DT_RELAENT 9 #define DT_STRSZ 10 #define DT_SYMENT 11 #define DT_INIT 12 #define DT_FINI 13 #define DT_SONAME 14 #define DT_RPATH 15 #define DT_SYMBOLIC 16 #define DT_REL 17 #define DT_RELSZ 18 #define DT_RELENT 19 #define DT_PLTREL 20 #define DT_DEBUG 21 #define DT_TEXTREL 22 #define DT_JMPREL 23 #define DT_BIND_NOW 24 #define DT_INIT_ARRAY 25 #define DT_FINI_ARRAY 26 #define DT_INIT_ARRAYSZ 27 #define DT_FINI_ARRAYSZ 28 #define DT_RUNPATH 29 #define DT_FLAGS 30 #define DT_ENCODING 32 #define DT_PREINIT_ARRAY 32 #define DT_PREINIT_ARRAYSZ 33 #define DT_MAXPOSTAGS 34 #define DT_LOOS 0x6000000D #define DT_HIOS 0x6ffff000 #define DT_LOPROC 0x70000000 #define DT_HIPROC 0x7FFFFFFF // DT_FLAGS values #define DF_ORIGIN 0x1 #define DF_SYMBOLIC 0x2 #define DF_TEXTREL 0x4 #define DF_BIND_NOW 0x8 #define DF_STATIC_TLS 0x10 // ELF file header struct Elf32_Ehdr { unsigned char e_ident[EI_NIDENT]; Elf_Half e_type; Elf_Half e_machine; Elf_Word e_version; Elf32_Addr e_entry; Elf32_Off e_phoff; Elf32_Off e_shoff; Elf_Word e_flags; Elf_Half e_ehsize; Elf_Half e_phentsize; Elf_Half e_phnum; Elf_Half e_shentsize; Elf_Half e_shnum; Elf_Half e_shstrndx; }; struct Elf64_Ehdr { unsigned char e_ident[EI_NIDENT]; Elf_Half e_type; Elf_Half e_machine; Elf_Word e_version; Elf64_Addr e_entry; Elf64_Off e_phoff; Elf64_Off e_shoff; Elf_Word e_flags; Elf_Half e_ehsize; Elf_Half e_phentsize; Elf_Half e_phnum; Elf_Half e_shentsize; Elf_Half e_shnum; Elf_Half e_shstrndx; }; // Section header struct Elf32_Shdr { Elf_Word sh_name; Elf_Word sh_type; Elf_Word sh_flags; Elf32_Addr sh_addr; Elf32_Off sh_offset; Elf_Word sh_size; Elf_Word sh_link; Elf_Word sh_info; Elf_Word sh_addralign; Elf_Word sh_entsize; }; struct Elf64_Shdr { Elf_Word sh_name; Elf_Word sh_type; Elf_Xword sh_flags; Elf64_Addr sh_addr; Elf64_Off sh_offset; Elf_Xword sh_size; Elf_Word sh_link; Elf_Word sh_info; Elf_Xword sh_addralign; Elf_Xword sh_entsize; }; // Segment header struct Elf32_Phdr { Elf_Word p_type; Elf32_Off p_offset; Elf32_Addr p_vaddr; Elf32_Addr p_paddr; Elf_Word p_filesz; Elf_Word p_memsz; Elf_Word p_flags; Elf_Word p_align; }; struct Elf64_Phdr { Elf_Word p_type; Elf_Word p_flags; Elf64_Off p_offset; Elf64_Addr p_vaddr; Elf64_Addr p_paddr; Elf_Xword p_filesz; Elf_Xword p_memsz; Elf_Xword p_align; }; // Symbol table entry struct Elf32_Sym { Elf_Word st_name; Elf32_Addr st_value; Elf_Word st_size; unsigned char st_info; unsigned char st_other; Elf_Half st_shndx; }; struct Elf64_Sym { Elf_Word st_name; unsigned char st_info; unsigned char st_other; Elf_Half st_shndx; Elf64_Addr st_value; Elf_Xword st_size; }; #define ELF_ST_BIND( i ) ( ( i ) >> 4 ) #define ELF_ST_TYPE( i ) ( (i)&0xf ) #define ELF_ST_INFO( b, t ) ( ( ( b ) << 4 ) + ( (t)&0xf ) ) #define ELF_ST_VISIBILITY( o ) ( (o)&0x3 ) // Relocation entries struct Elf32_Rel { Elf32_Addr r_offset; Elf_Word r_info; }; struct Elf32_Rela { Elf32_Addr r_offset; Elf_Word r_info; Elf_Sword r_addend; }; struct Elf64_Rel { Elf64_Addr r_offset; Elf_Xword r_info; }; struct Elf64_Rela { Elf64_Addr r_offset; Elf_Xword r_info; Elf_Sxword r_addend; }; #define ELF32_R_SYM( i ) ( ( i ) >> 8 ) #define ELF32_R_TYPE( i ) ( (unsigned char)( i ) ) #define ELF32_R_INFO( s, t ) ( ( ( s ) << 8 ) + (unsigned char)( t ) ) #define ELF64_R_SYM( i ) ( ( i ) >> 32 ) #define ELF64_R_TYPE( i ) ( (i)&0xffffffffL ) #define ELF64_R_INFO( s, t ) \ ( ( ( ( int64_t )( s ) ) << 32 ) + ( (t)&0xffffffffL ) ) // Dynamic structure struct Elf32_Dyn { Elf_Sword d_tag; union { Elf_Word d_val; Elf32_Addr d_ptr; } d_un; }; struct Elf64_Dyn { Elf_Sxword d_tag; union { Elf_Xword d_val; Elf64_Addr d_ptr; } d_un; }; } // namespace ELFIO #endif // ELFTYPES_H /*** End of inlined file: elf_types.hpp ***/ /*** Start of inlined file: elfio_version.hpp ***/ #define ELFIO_VERSION "3.8" /*** End of inlined file: elfio_version.hpp ***/ /*** Start of inlined file: elfio_utils.hpp ***/ #ifndef ELFIO_UTILS_HPP #define ELFIO_UTILS_HPP #define ELFIO_GET_ACCESS( TYPE, NAME, FIELD ) \ TYPE get_##NAME() const { return ( *convertor )( FIELD ); } #define ELFIO_SET_ACCESS( TYPE, NAME, FIELD ) \ void set_##NAME( TYPE value ) \ { \ FIELD = value; \ FIELD = ( *convertor )( FIELD ); \ } #define ELFIO_GET_SET_ACCESS( TYPE, NAME, FIELD ) \ TYPE get_##NAME() const { return ( *convertor )( FIELD ); } \ void set_##NAME( TYPE value ) \ { \ FIELD = value; \ FIELD = ( *convertor )( FIELD ); \ } #define ELFIO_GET_ACCESS_DECL( TYPE, NAME ) virtual TYPE get_##NAME() const = 0 #define ELFIO_SET_ACCESS_DECL( TYPE, NAME ) \ virtual void set_##NAME( TYPE value ) = 0 #define ELFIO_GET_SET_ACCESS_DECL( TYPE, NAME ) \ virtual TYPE get_##NAME() const = 0; \ virtual void set_##NAME( TYPE value ) = 0 namespace ELFIO { //------------------------------------------------------------------------------ class endianess_convertor { public: //------------------------------------------------------------------------------ endianess_convertor() { need_conversion = false; } //------------------------------------------------------------------------------ void setup( unsigned char elf_file_encoding ) { need_conversion = ( elf_file_encoding != get_host_encoding() ); } //------------------------------------------------------------------------------ uint64_t operator()( uint64_t value ) const { if ( !need_conversion ) { return value; } value = ( ( value & 0x00000000000000FFull ) << 56 ) | ( ( value & 0x000000000000FF00ull ) << 40 ) | ( ( value & 0x0000000000FF0000ull ) << 24 ) | ( ( value & 0x00000000FF000000ull ) << 8 ) | ( ( value & 0x000000FF00000000ull ) >> 8 ) | ( ( value & 0x0000FF0000000000ull ) >> 24 ) | ( ( value & 0x00FF000000000000ull ) >> 40 ) | ( ( value & 0xFF00000000000000ull ) >> 56 ); return value; } //------------------------------------------------------------------------------ int64_t operator()( int64_t value ) const { if ( !need_conversion ) { return value; } return ( int64_t )( *this )( (uint64_t)value ); } //------------------------------------------------------------------------------ uint32_t operator()( uint32_t value ) const { if ( !need_conversion ) { return value; } value = ( ( value & 0x000000FF ) << 24 ) | ( ( value & 0x0000FF00 ) << 8 ) | ( ( value & 0x00FF0000 ) >> 8 ) | ( ( value & 0xFF000000 ) >> 24 ); return value; } //------------------------------------------------------------------------------ int32_t operator()( int32_t value ) const { if ( !need_conversion ) { return value; } return ( int32_t )( *this )( (uint32_t)value ); } //------------------------------------------------------------------------------ uint16_t operator()( uint16_t value ) const { if ( !need_conversion ) { return value; } value = ( ( value & 0x00FF ) << 8 ) | ( ( value & 0xFF00 ) >> 8 ); return value; } //------------------------------------------------------------------------------ int16_t operator()( int16_t value ) const { if ( !need_conversion ) { return value; } return ( int16_t )( *this )( (uint16_t)value ); } //------------------------------------------------------------------------------ int8_t operator()( int8_t value ) const { return value; } //------------------------------------------------------------------------------ uint8_t operator()( uint8_t value ) const { return value; } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ unsigned char get_host_encoding() const { static const int tmp = 1; if ( 1 == *(const char*)&tmp ) { return ELFDATA2LSB; } else { return ELFDATA2MSB; } } //------------------------------------------------------------------------------ private: bool need_conversion; }; //------------------------------------------------------------------------------ inline uint32_t elf_hash( const unsigned char* name ) { uint32_t h = 0, g; while ( *name ) { h = ( h << 4 ) + *name++; g = h & 0xf0000000; if ( g != 0 ) h ^= g >> 24; h &= ~g; } return h; } } // namespace ELFIO #endif // ELFIO_UTILS_HPP /*** End of inlined file: elfio_utils.hpp ***/ /*** Start of inlined file: elfio_header.hpp ***/ #ifndef ELF_HEADER_HPP #define ELF_HEADER_HPP #include namespace ELFIO { class elf_header { public: virtual ~elf_header(){}; virtual bool load( std::istream& stream ) = 0; virtual bool save( std::ostream& stream ) const = 0; // ELF header functions ELFIO_GET_ACCESS_DECL( unsigned char, class ); ELFIO_GET_ACCESS_DECL( unsigned char, elf_version ); ELFIO_GET_ACCESS_DECL( unsigned char, encoding ); ELFIO_GET_ACCESS_DECL( Elf_Half, header_size ); ELFIO_GET_ACCESS_DECL( Elf_Half, section_entry_size ); ELFIO_GET_ACCESS_DECL( Elf_Half, segment_entry_size ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, version ); ELFIO_GET_SET_ACCESS_DECL( unsigned char, os_abi ); ELFIO_GET_SET_ACCESS_DECL( unsigned char, abi_version ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, type ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, machine ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, flags ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, entry ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, sections_num ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Off, sections_offset ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, segments_num ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Off, segments_offset ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, section_name_str_index ); }; template struct elf_header_impl_types; template <> struct elf_header_impl_types { typedef Elf32_Phdr Phdr_type; typedef Elf32_Shdr Shdr_type; static const unsigned char file_class = ELFCLASS32; }; template <> struct elf_header_impl_types { typedef Elf64_Phdr Phdr_type; typedef Elf64_Shdr Shdr_type; static const unsigned char file_class = ELFCLASS64; }; template class elf_header_impl : public elf_header { public: //------------------------------------------------------------------------------ elf_header_impl( endianess_convertor* convertor_, unsigned char encoding ) { convertor = convertor_; std::fill_n( reinterpret_cast( &header ), sizeof( header ), '\0' ); header.e_ident[EI_MAG0] = ELFMAG0; header.e_ident[EI_MAG1] = ELFMAG1; header.e_ident[EI_MAG2] = ELFMAG2; header.e_ident[EI_MAG3] = ELFMAG3; header.e_ident[EI_CLASS] = elf_header_impl_types::file_class; header.e_ident[EI_DATA] = encoding; header.e_ident[EI_VERSION] = EV_CURRENT; header.e_version = ( *convertor )( (Elf_Word)EV_CURRENT ); header.e_ehsize = ( sizeof( header ) ); header.e_ehsize = ( *convertor )( header.e_ehsize ); header.e_shstrndx = ( *convertor )( (Elf_Half)1 ); header.e_phentsize = sizeof( typename elf_header_impl_types::Phdr_type ); header.e_shentsize = sizeof( typename elf_header_impl_types::Shdr_type ); header.e_phentsize = ( *convertor )( header.e_phentsize ); header.e_shentsize = ( *convertor )( header.e_shentsize ); } //------------------------------------------------------------------------------ bool load( std::istream& stream ) { stream.seekg( 0 ); stream.read( reinterpret_cast( &header ), sizeof( header ) ); return ( stream.gcount() == sizeof( header ) ); } //------------------------------------------------------------------------------ bool save( std::ostream& stream ) const { stream.seekp( 0 ); stream.write( reinterpret_cast( &header ), sizeof( header ) ); return stream.good(); } //------------------------------------------------------------------------------ // ELF header functions ELFIO_GET_ACCESS( unsigned char, class, header.e_ident[EI_CLASS] ); ELFIO_GET_ACCESS( unsigned char, elf_version, header.e_ident[EI_VERSION] ); ELFIO_GET_ACCESS( unsigned char, encoding, header.e_ident[EI_DATA] ); ELFIO_GET_ACCESS( Elf_Half, header_size, header.e_ehsize ); ELFIO_GET_ACCESS( Elf_Half, section_entry_size, header.e_shentsize ); ELFIO_GET_ACCESS( Elf_Half, segment_entry_size, header.e_phentsize ); ELFIO_GET_SET_ACCESS( Elf_Word, version, header.e_version ); ELFIO_GET_SET_ACCESS( unsigned char, os_abi, header.e_ident[EI_OSABI] ); ELFIO_GET_SET_ACCESS( unsigned char, abi_version, header.e_ident[EI_ABIVERSION] ); ELFIO_GET_SET_ACCESS( Elf_Half, type, header.e_type ); ELFIO_GET_SET_ACCESS( Elf_Half, machine, header.e_machine ); ELFIO_GET_SET_ACCESS( Elf_Word, flags, header.e_flags ); ELFIO_GET_SET_ACCESS( Elf_Half, section_name_str_index, header.e_shstrndx ); ELFIO_GET_SET_ACCESS( Elf64_Addr, entry, header.e_entry ); ELFIO_GET_SET_ACCESS( Elf_Half, sections_num, header.e_shnum ); ELFIO_GET_SET_ACCESS( Elf64_Off, sections_offset, header.e_shoff ); ELFIO_GET_SET_ACCESS( Elf_Half, segments_num, header.e_phnum ); ELFIO_GET_SET_ACCESS( Elf64_Off, segments_offset, header.e_phoff ); private: T header; endianess_convertor* convertor; }; } // namespace ELFIO #endif // ELF_HEADER_HPP /*** End of inlined file: elfio_header.hpp ***/ /*** Start of inlined file: elfio_section.hpp ***/ #ifndef ELFIO_SECTION_HPP #define ELFIO_SECTION_HPP #include #include #include namespace ELFIO { class section { friend class elfio; public: virtual ~section(){}; ELFIO_GET_ACCESS_DECL( Elf_Half, index ); ELFIO_GET_SET_ACCESS_DECL( std::string, name ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, type ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, flags ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, info ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, link ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, addr_align ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, entry_size ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, address ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, size ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, name_string_offset ); ELFIO_GET_ACCESS_DECL( Elf64_Off, offset ); virtual const char* get_data() const = 0; virtual void set_data( const char* pData, Elf_Word size ) = 0; virtual void set_data( const std::string& data ) = 0; virtual void append_data( const char* pData, Elf_Word size ) = 0; virtual void append_data( const std::string& data ) = 0; virtual size_t get_stream_size() const = 0; virtual void set_stream_size( size_t value ) = 0; protected: ELFIO_SET_ACCESS_DECL( Elf64_Off, offset ); ELFIO_SET_ACCESS_DECL( Elf_Half, index ); virtual void load( std::istream& stream, std::streampos header_offset ) = 0; virtual void save( std::ostream& stream, std::streampos header_offset, std::streampos data_offset ) = 0; virtual bool is_address_initialized() const = 0; }; template class section_impl : public section { public: //------------------------------------------------------------------------------ section_impl( const endianess_convertor* convertor_ ) : convertor( convertor_ ) { std::fill_n( reinterpret_cast( &header ), sizeof( header ), '\0' ); is_address_set = false; data = 0; data_size = 0; index = 0; stream_size = 0; } //------------------------------------------------------------------------------ ~section_impl() { delete[] data; } //------------------------------------------------------------------------------ // Section info functions ELFIO_GET_SET_ACCESS( Elf_Word, type, header.sh_type ); ELFIO_GET_SET_ACCESS( Elf_Xword, flags, header.sh_flags ); ELFIO_GET_SET_ACCESS( Elf_Xword, size, header.sh_size ); ELFIO_GET_SET_ACCESS( Elf_Word, link, header.sh_link ); ELFIO_GET_SET_ACCESS( Elf_Word, info, header.sh_info ); ELFIO_GET_SET_ACCESS( Elf_Xword, addr_align, header.sh_addralign ); ELFIO_GET_SET_ACCESS( Elf_Xword, entry_size, header.sh_entsize ); ELFIO_GET_SET_ACCESS( Elf_Word, name_string_offset, header.sh_name ); ELFIO_GET_ACCESS( Elf64_Addr, address, header.sh_addr ); //------------------------------------------------------------------------------ Elf_Half get_index() const { return index; } //------------------------------------------------------------------------------ std::string get_name() const { return name; } //------------------------------------------------------------------------------ void set_name( std::string name_ ) { name = name_; } //------------------------------------------------------------------------------ void set_address( Elf64_Addr value ) { header.sh_addr = value; header.sh_addr = ( *convertor )( header.sh_addr ); is_address_set = true; } //------------------------------------------------------------------------------ bool is_address_initialized() const { return is_address_set; } //------------------------------------------------------------------------------ const char* get_data() const { return data; } //------------------------------------------------------------------------------ void set_data( const char* raw_data, Elf_Word size ) { if ( get_type() != SHT_NOBITS ) { delete[] data; data = new ( std::nothrow ) char[size]; if ( 0 != data && 0 != raw_data ) { data_size = size; std::copy( raw_data, raw_data + size, data ); } else { data_size = 0; } } set_size( data_size ); } //------------------------------------------------------------------------------ void set_data( const std::string& str_data ) { return set_data( str_data.c_str(), (Elf_Word)str_data.size() ); } //------------------------------------------------------------------------------ void append_data( const char* raw_data, Elf_Word size ) { if ( get_type() != SHT_NOBITS ) { if ( get_size() + size < data_size ) { std::copy( raw_data, raw_data + size, data + get_size() ); } else { data_size = 2 * ( data_size + size ); char* new_data = new ( std::nothrow ) char[data_size]; if ( 0 != new_data ) { std::copy( data, data + get_size(), new_data ); std::copy( raw_data, raw_data + size, new_data + get_size() ); delete[] data; data = new_data; } else { size = 0; } } set_size( get_size() + size ); } } //------------------------------------------------------------------------------ void append_data( const std::string& str_data ) { return append_data( str_data.c_str(), (Elf_Word)str_data.size() ); } //------------------------------------------------------------------------------ protected: //------------------------------------------------------------------------------ ELFIO_GET_SET_ACCESS( Elf64_Off, offset, header.sh_offset ); //------------------------------------------------------------------------------ void set_index( Elf_Half value ) { index = value; } //------------------------------------------------------------------------------ void load( std::istream& stream, std::streampos header_offset ) { std::fill_n( reinterpret_cast( &header ), sizeof( header ), '\0' ); stream.seekg( 0, stream.end ); set_stream_size( stream.tellg() ); stream.seekg( header_offset ); stream.read( reinterpret_cast( &header ), sizeof( header ) ); Elf_Xword size = get_size(); if ( 0 == data && SHT_NULL != get_type() && SHT_NOBITS != get_type() && size < get_stream_size() ) { data = new ( std::nothrow ) char[size + 1]; if ( ( 0 != size ) && ( 0 != data ) ) { stream.seekg( ( *convertor )( header.sh_offset ) ); stream.read( data, size ); data[size] = 0; // Ensure data is ended with 0 to avoid oob read data_size = size; } else { data_size = 0; } } } //------------------------------------------------------------------------------ void save( std::ostream& stream, std::streampos header_offset, std::streampos data_offset ) { if ( 0 != get_index() ) { header.sh_offset = data_offset; header.sh_offset = ( *convertor )( header.sh_offset ); } save_header( stream, header_offset ); if ( get_type() != SHT_NOBITS && get_type() != SHT_NULL && get_size() != 0 && data != 0 ) { save_data( stream, data_offset ); } } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ void save_header( std::ostream& stream, std::streampos header_offset ) const { stream.seekp( header_offset ); stream.write( reinterpret_cast( &header ), sizeof( header ) ); } //------------------------------------------------------------------------------ void save_data( std::ostream& stream, std::streampos data_offset ) const { stream.seekp( data_offset ); stream.write( get_data(), get_size() ); } //------------------------------------------------------------------------------ size_t get_stream_size() const { return stream_size; } //------------------------------------------------------------------------------ void set_stream_size( size_t value ) { stream_size = value; } //------------------------------------------------------------------------------ private: T header; Elf_Half index; std::string name; char* data; Elf_Word data_size; const endianess_convertor* convertor; bool is_address_set; size_t stream_size; }; } // namespace ELFIO #endif // ELFIO_SECTION_HPP /*** End of inlined file: elfio_section.hpp ***/ /*** Start of inlined file: elfio_segment.hpp ***/ #ifndef ELFIO_SEGMENT_HPP #define ELFIO_SEGMENT_HPP #include #include #include namespace ELFIO { class segment { friend class elfio; public: virtual ~segment(){}; ELFIO_GET_ACCESS_DECL( Elf_Half, index ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, type ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, flags ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, align ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, virtual_address ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, physical_address ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, file_size ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, memory_size ); ELFIO_GET_ACCESS_DECL( Elf64_Off, offset ); virtual const char* get_data() const = 0; virtual Elf_Half add_section_index( Elf_Half index, Elf_Xword addr_align ) = 0; virtual Elf_Half get_sections_num() const = 0; virtual Elf_Half get_section_index_at( Elf_Half num ) const = 0; virtual bool is_offset_initialized() const = 0; protected: ELFIO_SET_ACCESS_DECL( Elf64_Off, offset ); ELFIO_SET_ACCESS_DECL( Elf_Half, index ); virtual const std::vector& get_sections() const = 0; virtual void load( std::istream& stream, std::streampos header_offset ) = 0; virtual void save( std::ostream& stream, std::streampos header_offset, std::streampos data_offset ) = 0; }; //------------------------------------------------------------------------------ template class segment_impl : public segment { public: //------------------------------------------------------------------------------ segment_impl( endianess_convertor* convertor_ ) : stream_size( 0 ), index( 0 ), data( 0 ), convertor( convertor_ ) { is_offset_set = false; std::fill_n( reinterpret_cast( &ph ), sizeof( ph ), '\0' ); } //------------------------------------------------------------------------------ virtual ~segment_impl() { delete[] data; } //------------------------------------------------------------------------------ // Section info functions ELFIO_GET_SET_ACCESS( Elf_Word, type, ph.p_type ); ELFIO_GET_SET_ACCESS( Elf_Word, flags, ph.p_flags ); ELFIO_GET_SET_ACCESS( Elf_Xword, align, ph.p_align ); ELFIO_GET_SET_ACCESS( Elf64_Addr, virtual_address, ph.p_vaddr ); ELFIO_GET_SET_ACCESS( Elf64_Addr, physical_address, ph.p_paddr ); ELFIO_GET_SET_ACCESS( Elf_Xword, file_size, ph.p_filesz ); ELFIO_GET_SET_ACCESS( Elf_Xword, memory_size, ph.p_memsz ); ELFIO_GET_ACCESS( Elf64_Off, offset, ph.p_offset ); size_t stream_size; //------------------------------------------------------------------------------ size_t get_stream_size() const { return stream_size; } //------------------------------------------------------------------------------ void set_stream_size( size_t value ) { stream_size = value; } //------------------------------------------------------------------------------ Elf_Half get_index() const { return index; } //------------------------------------------------------------------------------ const char* get_data() const { return data; } //------------------------------------------------------------------------------ Elf_Half add_section_index( Elf_Half sec_index, Elf_Xword addr_align ) { sections.push_back( sec_index ); if ( addr_align > get_align() ) { set_align( addr_align ); } return (Elf_Half)sections.size(); } //------------------------------------------------------------------------------ Elf_Half get_sections_num() const { return (Elf_Half)sections.size(); } //------------------------------------------------------------------------------ Elf_Half get_section_index_at( Elf_Half num ) const { if ( num < sections.size() ) { return sections[num]; } return Elf_Half( -1 ); } //------------------------------------------------------------------------------ protected: //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void set_offset( Elf64_Off value ) { ph.p_offset = value; ph.p_offset = ( *convertor )( ph.p_offset ); is_offset_set = true; } //------------------------------------------------------------------------------ bool is_offset_initialized() const { return is_offset_set; } //------------------------------------------------------------------------------ const std::vector& get_sections() const { return sections; } //------------------------------------------------------------------------------ void set_index( Elf_Half value ) { index = value; } //------------------------------------------------------------------------------ void load( std::istream& stream, std::streampos header_offset ) { stream.seekg( 0, stream.end ); set_stream_size( stream.tellg() ); stream.seekg( header_offset ); stream.read( reinterpret_cast( &ph ), sizeof( ph ) ); is_offset_set = true; if ( PT_NULL != get_type() && 0 != get_file_size() ) { stream.seekg( ( *convertor )( ph.p_offset ) ); Elf_Xword size = get_file_size(); if ( size > get_stream_size() ) { data = 0; } else { data = new (std::nothrow) char[size + 1]; if ( 0 != data ) { stream.read( data, size ); data[size] = 0; } } } } //------------------------------------------------------------------------------ void save( std::ostream& stream, std::streampos header_offset, std::streampos data_offset ) { ph.p_offset = data_offset; ph.p_offset = ( *convertor )( ph.p_offset ); stream.seekp( header_offset ); stream.write( reinterpret_cast( &ph ), sizeof( ph ) ); } //------------------------------------------------------------------------------ private: T ph; Elf_Half index; char* data; std::vector sections; endianess_convertor* convertor; bool is_offset_set; }; } // namespace ELFIO #endif // ELFIO_SEGMENT_HPP /*** End of inlined file: elfio_segment.hpp ***/ /*** Start of inlined file: elfio_strings.hpp ***/ #ifndef ELFIO_STRINGS_HPP #define ELFIO_STRINGS_HPP #include #include #include namespace ELFIO { //------------------------------------------------------------------------------ template class string_section_accessor_template { public: //------------------------------------------------------------------------------ string_section_accessor_template( S* section_ ) : string_section( section_ ) { } //------------------------------------------------------------------------------ const char* get_string( Elf_Word index ) const { if ( string_section ) { if ( index < string_section->get_size() ) { const char* data = string_section->get_data(); if ( 0 != data ) { return data + index; } } } return 0; } //------------------------------------------------------------------------------ Elf_Word add_string( const char* str ) { Elf_Word current_position = 0; if ( string_section ) { // Strings are addeded to the end of the current section data current_position = (Elf_Word)string_section->get_size(); if ( current_position == 0 ) { char empty_string = '\0'; string_section->append_data( &empty_string, 1 ); current_position++; } string_section->append_data( str, (Elf_Word)std::strlen( str ) + 1 ); } return current_position; } //------------------------------------------------------------------------------ Elf_Word add_string( const std::string& str ) { return add_string( str.c_str() ); } //------------------------------------------------------------------------------ private: S* string_section; }; using string_section_accessor = string_section_accessor_template
; using const_string_section_accessor = string_section_accessor_template; } // namespace ELFIO #endif // ELFIO_STRINGS_HPP /*** End of inlined file: elfio_strings.hpp ***/ #define ELFIO_HEADER_ACCESS_GET( TYPE, FNAME ) \ TYPE get_##FNAME() const { return header ? ( header->get_##FNAME() ) : 0; } #define ELFIO_HEADER_ACCESS_GET_SET( TYPE, FNAME ) \ TYPE get_##FNAME() const \ { \ return header ? ( header->get_##FNAME() ) : 0; \ } \ void set_##FNAME( TYPE val ) \ { \ if ( header ) { \ header->set_##FNAME( val ); \ } \ } namespace ELFIO { //------------------------------------------------------------------------------ class elfio { public: //------------------------------------------------------------------------------ elfio() : sections( this ), segments( this ) { header = 0; current_file_pos = 0; create( ELFCLASS32, ELFDATA2LSB ); } //------------------------------------------------------------------------------ ~elfio() { clean(); } //------------------------------------------------------------------------------ void create( unsigned char file_class, unsigned char encoding ) { clean(); convertor.setup( encoding ); header = create_header( file_class, encoding ); create_mandatory_sections(); } //------------------------------------------------------------------------------ bool load( const std::string& file_name ) { std::ifstream stream; stream.open( file_name.c_str(), std::ios::in | std::ios::binary ); if ( !stream ) { return false; } return load( stream ); } //------------------------------------------------------------------------------ bool load( std::istream& stream ) { clean(); unsigned char e_ident[EI_NIDENT]; // Read ELF file signature stream.read( reinterpret_cast( &e_ident ), sizeof( e_ident ) ); // Is it ELF file? if ( stream.gcount() != sizeof( e_ident ) || e_ident[EI_MAG0] != ELFMAG0 || e_ident[EI_MAG1] != ELFMAG1 || e_ident[EI_MAG2] != ELFMAG2 || e_ident[EI_MAG3] != ELFMAG3 ) { return false; } if ( ( e_ident[EI_CLASS] != ELFCLASS64 ) && ( e_ident[EI_CLASS] != ELFCLASS32 ) ) { return false; } convertor.setup( e_ident[EI_DATA] ); header = create_header( e_ident[EI_CLASS], e_ident[EI_DATA] ); if ( 0 == header ) { return false; } if ( !header->load( stream ) ) { return false; } load_sections( stream ); bool is_still_good = load_segments( stream ); return is_still_good; } //------------------------------------------------------------------------------ bool save( const std::string& file_name ) { std::ofstream stream; stream.open( file_name.c_str(), std::ios::out | std::ios::binary ); if ( !stream ) { return false; } return save( stream ); } //------------------------------------------------------------------------------ bool save( std::ostream& stream ) { if ( !stream || !header ) { return false; } bool is_still_good = true; // Define layout specific header fields // The position of the segment table is fixed after the header. // The position of the section table is variable and needs to be fixed // before saving. header->set_segments_num( segments.size() ); header->set_segments_offset( segments.size() ? header->get_header_size() : 0 ); header->set_sections_num( sections.size() ); header->set_sections_offset( 0 ); // Layout the first section right after the segment table current_file_pos = header->get_header_size() + header->get_segment_entry_size() * (Elf_Xword)header->get_segments_num(); calc_segment_alignment(); is_still_good = layout_segments_and_their_sections(); is_still_good = is_still_good && layout_sections_without_segments(); is_still_good = is_still_good && layout_section_table(); is_still_good = is_still_good && save_header( stream ); is_still_good = is_still_good && save_sections( stream ); is_still_good = is_still_good && save_segments( stream ); return is_still_good; } //------------------------------------------------------------------------------ // ELF header access functions ELFIO_HEADER_ACCESS_GET( unsigned char, class ); ELFIO_HEADER_ACCESS_GET( unsigned char, elf_version ); ELFIO_HEADER_ACCESS_GET( unsigned char, encoding ); ELFIO_HEADER_ACCESS_GET( Elf_Word, version ); ELFIO_HEADER_ACCESS_GET( Elf_Half, header_size ); ELFIO_HEADER_ACCESS_GET( Elf_Half, section_entry_size ); ELFIO_HEADER_ACCESS_GET( Elf_Half, segment_entry_size ); ELFIO_HEADER_ACCESS_GET_SET( unsigned char, os_abi ); ELFIO_HEADER_ACCESS_GET_SET( unsigned char, abi_version ); ELFIO_HEADER_ACCESS_GET_SET( Elf_Half, type ); ELFIO_HEADER_ACCESS_GET_SET( Elf_Half, machine ); ELFIO_HEADER_ACCESS_GET_SET( Elf_Word, flags ); ELFIO_HEADER_ACCESS_GET_SET( Elf64_Addr, entry ); ELFIO_HEADER_ACCESS_GET_SET( Elf64_Off, sections_offset ); ELFIO_HEADER_ACCESS_GET_SET( Elf64_Off, segments_offset ); ELFIO_HEADER_ACCESS_GET_SET( Elf_Half, section_name_str_index ); //------------------------------------------------------------------------------ const endianess_convertor& get_convertor() const { return convertor; } //------------------------------------------------------------------------------ Elf_Xword get_default_entry_size( Elf_Word section_type ) const { switch ( section_type ) { case SHT_RELA: if ( header->get_class() == ELFCLASS64 ) { return sizeof( Elf64_Rela ); } else { return sizeof( Elf32_Rela ); } case SHT_REL: if ( header->get_class() == ELFCLASS64 ) { return sizeof( Elf64_Rel ); } else { return sizeof( Elf32_Rel ); } case SHT_SYMTAB: if ( header->get_class() == ELFCLASS64 ) { return sizeof( Elf64_Sym ); } else { return sizeof( Elf32_Sym ); } case SHT_DYNAMIC: if ( header->get_class() == ELFCLASS64 ) { return sizeof( Elf64_Dyn ); } else { return sizeof( Elf32_Dyn ); } default: return 0; } } //------------------------------------------------------------------------------ private: bool is_offset_in_section( Elf64_Off offset, const section* sec ) const { return ( offset >= sec->get_offset() ) && ( offset < ( sec->get_offset() + sec->get_size() ) ); } //------------------------------------------------------------------------------ public: //! returns an empty string if no problems are detected, //! or a string containing an error message if problems are found std::string validate() const { // check for overlapping sections in the file for ( int i = 0; i < sections.size(); ++i ) { for ( int j = i + 1; j < sections.size(); ++j ) { const section* a = sections[i]; const section* b = sections[j]; if ( !( a->get_type() & SHT_NOBITS ) && !( b->get_type() & SHT_NOBITS ) && ( a->get_size() > 0 ) && ( b->get_size() > 0 ) && ( a->get_offset() > 0 ) && ( b->get_offset() > 0 ) ) { if ( is_offset_in_section( a->get_offset(), b ) || is_offset_in_section( a->get_offset() + a->get_size() - 1, b ) || is_offset_in_section( b->get_offset(), a ) || is_offset_in_section( b->get_offset() + b->get_size() - 1, a ) ) { return "Sections " + a->get_name() + " and " + b->get_name() + " overlap in file"; } } } } // more checks to be added here... return ""; } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ void clean() { delete header; header = 0; std::vector::const_iterator it; for ( it = sections_.begin(); it != sections_.end(); ++it ) { delete *it; } sections_.clear(); std::vector::const_iterator it1; for ( it1 = segments_.begin(); it1 != segments_.end(); ++it1 ) { delete *it1; } segments_.clear(); } //------------------------------------------------------------------------------ elf_header* create_header( unsigned char file_class, unsigned char encoding ) { elf_header* new_header = 0; if ( file_class == ELFCLASS64 ) { new_header = new elf_header_impl( &convertor, encoding ); } else if ( file_class == ELFCLASS32 ) { new_header = new elf_header_impl( &convertor, encoding ); } else { return 0; } return new_header; } //------------------------------------------------------------------------------ section* create_section() { section* new_section; unsigned char file_class = get_class(); if ( file_class == ELFCLASS64 ) { new_section = new section_impl( &convertor ); } else if ( file_class == ELFCLASS32 ) { new_section = new section_impl( &convertor ); } else { return 0; } new_section->set_index( (Elf_Half)sections_.size() ); sections_.push_back( new_section ); return new_section; } //------------------------------------------------------------------------------ segment* create_segment() { segment* new_segment; unsigned char file_class = header->get_class(); if ( file_class == ELFCLASS64 ) { new_segment = new segment_impl( &convertor ); } else if ( file_class == ELFCLASS32 ) { new_segment = new segment_impl( &convertor ); } else { return 0; } new_segment->set_index( (Elf_Half)segments_.size() ); segments_.push_back( new_segment ); return new_segment; } //------------------------------------------------------------------------------ void create_mandatory_sections() { // Create null section without calling to 'add_section' as no string // section containing section names exists yet section* sec0 = create_section(); sec0->set_index( 0 ); sec0->set_name( "" ); sec0->set_name_string_offset( 0 ); set_section_name_str_index( 1 ); section* shstrtab = sections.add( ".shstrtab" ); shstrtab->set_type( SHT_STRTAB ); shstrtab->set_addr_align( 1 ); } //------------------------------------------------------------------------------ Elf_Half load_sections( std::istream& stream ) { Elf_Half entry_size = header->get_section_entry_size(); Elf_Half num = header->get_sections_num(); Elf64_Off offset = header->get_sections_offset(); for ( Elf_Half i = 0; i < num; ++i ) { section* sec = create_section(); sec->load( stream, (std::streamoff)offset + (std::streampos)i * entry_size ); sec->set_index( i ); // To mark that the section is not permitted to reassign address // during layout calculation sec->set_address( sec->get_address() ); } Elf_Half shstrndx = get_section_name_str_index(); if ( SHN_UNDEF != shstrndx ) { string_section_accessor str_reader( sections[shstrndx] ); for ( Elf_Half i = 0; i < num; ++i ) { Elf_Word section_offset = sections[i]->get_name_string_offset(); const char* p = str_reader.get_string( section_offset ); if ( p != 0 ) { sections[i]->set_name( p ); } } } return num; } //------------------------------------------------------------------------------ //! Checks whether the addresses of the section entirely fall within the given segment. //! It doesn't matter if the addresses are memory addresses, or file offsets, //! they just need to be in the same address space bool is_sect_in_seg( Elf64_Off sect_begin, Elf_Xword sect_size, Elf64_Off seg_begin, Elf64_Off seg_end ) { return ( seg_begin <= sect_begin ) && ( sect_begin + sect_size <= seg_end ) && ( sect_begin < seg_end ); // this is important criteria when sect_size == 0 // Example: seg_begin=10, seg_end=12 (-> covering the bytes 10 and 11) // sect_begin=12, sect_size=0 -> shall return false! } //------------------------------------------------------------------------------ bool load_segments( std::istream& stream ) { Elf_Half entry_size = header->get_segment_entry_size(); Elf_Half num = header->get_segments_num(); Elf64_Off offset = header->get_segments_offset(); for ( Elf_Half i = 0; i < num; ++i ) { segment* seg; unsigned char file_class = header->get_class(); if ( file_class == ELFCLASS64 ) { seg = new segment_impl( &convertor ); } else if ( file_class == ELFCLASS32 ) { seg = new segment_impl( &convertor ); } else { return false; } seg->load( stream, (std::streamoff)offset + (std::streampos)i * entry_size ); seg->set_index( i ); // Add sections to the segments (similar to readelfs algorithm) Elf64_Off segBaseOffset = seg->get_offset(); Elf64_Off segEndOffset = segBaseOffset + seg->get_file_size(); Elf64_Off segVBaseAddr = seg->get_virtual_address(); Elf64_Off segVEndAddr = segVBaseAddr + seg->get_memory_size(); for ( Elf_Half j = 0; j < sections.size(); ++j ) { const section* psec = sections[j]; // SHF_ALLOC sections are matched based on the virtual address // otherwise the file offset is matched if ( ( psec->get_flags() & SHF_ALLOC ) ? is_sect_in_seg( psec->get_address(), psec->get_size(), segVBaseAddr, segVEndAddr ) : is_sect_in_seg( psec->get_offset(), psec->get_size(), segBaseOffset, segEndOffset ) ) { // Alignment of segment shall not be updated, to preserve original value // It will be re-calculated on saving. seg->add_section_index( psec->get_index(), 0 ); } } // Add section into the segments' container segments_.push_back( seg ); } return true; } //------------------------------------------------------------------------------ bool save_header( std::ostream& stream ) { return header->save( stream ); } //------------------------------------------------------------------------------ bool save_sections( std::ostream& stream ) { for ( unsigned int i = 0; i < sections_.size(); ++i ) { section* sec = sections_.at( i ); std::streampos headerPosition = (std::streamoff)header->get_sections_offset() + (std::streampos)header->get_section_entry_size() * sec->get_index(); sec->save( stream, headerPosition, sec->get_offset() ); } return true; } //------------------------------------------------------------------------------ bool save_segments( std::ostream& stream ) { for ( unsigned int i = 0; i < segments_.size(); ++i ) { segment* seg = segments_.at( i ); std::streampos headerPosition = header->get_segments_offset() + (std::streampos)header->get_segment_entry_size() * seg->get_index(); seg->save( stream, headerPosition, seg->get_offset() ); } return true; } //------------------------------------------------------------------------------ bool is_section_without_segment( unsigned int section_index ) { bool found = false; for ( unsigned int j = 0; !found && ( j < segments.size() ); ++j ) { for ( unsigned int k = 0; !found && ( k < segments[j]->get_sections_num() ); ++k ) { found = segments[j]->get_section_index_at( k ) == section_index; } } return !found; } //------------------------------------------------------------------------------ bool is_subsequence_of( segment* seg1, segment* seg2 ) { // Return 'true' if sections of seg1 are a subset of sections in seg2 const std::vector& sections1 = seg1->get_sections(); const std::vector& sections2 = seg2->get_sections(); bool found = false; if ( sections1.size() < sections2.size() ) { found = std::includes( sections2.begin(), sections2.end(), sections1.begin(), sections1.end() ); } return found; } //------------------------------------------------------------------------------ std::vector get_ordered_segments() { std::vector res; std::deque worklist; res.reserve( segments.size() ); std::copy( segments_.begin(), segments_.end(), std::back_inserter( worklist ) ); // Bring the segments which start at address 0 to the front size_t nextSlot = 0; for ( size_t i = 0; i < worklist.size(); ++i ) { if ( i != nextSlot && worklist[i]->is_offset_initialized() && worklist[i]->get_offset() == 0 ) { if ( worklist[nextSlot]->get_offset() == 0 ) { ++nextSlot; } std::swap( worklist[i], worklist[nextSlot] ); ++nextSlot; } } while ( !worklist.empty() ) { segment* seg = worklist.front(); worklist.pop_front(); size_t i = 0; for ( ; i < worklist.size(); ++i ) { if ( is_subsequence_of( seg, worklist[i] ) ) { break; } } if ( i < worklist.size() ) worklist.push_back( seg ); else res.push_back( seg ); } return res; } //------------------------------------------------------------------------------ bool layout_sections_without_segments() { for ( unsigned int i = 0; i < sections_.size(); ++i ) { if ( is_section_without_segment( i ) ) { section* sec = sections_[i]; Elf_Xword section_align = sec->get_addr_align(); if ( section_align > 1 && current_file_pos % section_align != 0 ) { current_file_pos += section_align - current_file_pos % section_align; } if ( 0 != sec->get_index() ) sec->set_offset( current_file_pos ); if ( SHT_NOBITS != sec->get_type() && SHT_NULL != sec->get_type() ) { current_file_pos += sec->get_size(); } } } return true; } //------------------------------------------------------------------------------ void calc_segment_alignment() { for ( std::vector::iterator s = segments_.begin(); s != segments_.end(); ++s ) { segment* seg = *s; for ( int i = 0; i < seg->get_sections_num(); ++i ) { section* sect = sections_[seg->get_section_index_at( i )]; if ( sect->get_addr_align() > seg->get_align() ) { seg->set_align( sect->get_addr_align() ); } } } } //------------------------------------------------------------------------------ bool layout_segments_and_their_sections() { std::vector worklist; std::vector section_generated( sections.size(), false ); // Get segments in a order in where segments which contain a // sub sequence of other segments are located at the end worklist = get_ordered_segments(); for ( unsigned int i = 0; i < worklist.size(); ++i ) { Elf_Xword segment_memory = 0; Elf_Xword segment_filesize = 0; Elf_Xword seg_start_pos = current_file_pos; segment* seg = worklist[i]; // Special case: PHDR segment // This segment contains the program headers but no sections if ( seg->get_type() == PT_PHDR && seg->get_sections_num() == 0 ) { seg_start_pos = header->get_segments_offset(); segment_memory = segment_filesize = header->get_segment_entry_size() * (Elf_Xword)header->get_segments_num(); } // Special case: else if ( seg->is_offset_initialized() && seg->get_offset() == 0 ) { seg_start_pos = 0; if ( seg->get_sections_num() ) { segment_memory = segment_filesize = current_file_pos; } } // New segments with not generated sections // have to be aligned else if ( seg->get_sections_num() && !section_generated[seg->get_section_index_at( 0 )] ) { Elf_Xword align = seg->get_align() > 0 ? seg->get_align() : 1; Elf64_Off cur_page_alignment = current_file_pos % align; Elf64_Off req_page_alignment = seg->get_virtual_address() % align; Elf64_Off error = req_page_alignment - cur_page_alignment; current_file_pos += ( seg->get_align() + error ) % align; seg_start_pos = current_file_pos; } else if ( seg->get_sections_num() ) { seg_start_pos = sections[seg->get_section_index_at( 0 )]->get_offset(); } // Write segment's data for ( unsigned int j = 0; j < seg->get_sections_num(); ++j ) { Elf_Half index = seg->get_section_index_at( j ); section* sec = sections[index]; // The NULL section is always generated if ( SHT_NULL == sec->get_type() ) { section_generated[index] = true; continue; } Elf_Xword secAlign = 0; // Fix up the alignment if ( !section_generated[index] && sec->is_address_initialized() && SHT_NOBITS != sec->get_type() && SHT_NULL != sec->get_type() && 0 != sec->get_size() ) { // Align the sections based on the virtual addresses // when possible (this is what matters for execution) Elf64_Off req_offset = sec->get_address() - seg->get_virtual_address(); Elf64_Off cur_offset = current_file_pos - seg_start_pos; if ( req_offset < cur_offset ) { // something has gone awfully wrong, abort! // secAlign would turn out negative, seeking backwards and overwriting previous data return false; } secAlign = req_offset - cur_offset; } else if ( !section_generated[index] && !sec->is_address_initialized() ) { // If no address has been specified then only the section // alignment constraint has to be matched Elf_Xword align = sec->get_addr_align(); if ( align == 0 ) { align = 1; } Elf64_Off error = current_file_pos % align; secAlign = ( align - error ) % align; } else if ( section_generated[index] ) { // Alignment for already generated sections secAlign = sec->get_offset() - seg_start_pos - segment_filesize; } // Determine the segment file and memory sizes // Special case .tbss section (NOBITS) in non TLS segment if ( ( sec->get_flags() & SHF_ALLOC ) && !( ( sec->get_flags() & SHF_TLS ) && ( seg->get_type() != PT_TLS ) && ( SHT_NOBITS == sec->get_type() ) ) ) segment_memory += sec->get_size() + secAlign; if ( SHT_NOBITS != sec->get_type() ) segment_filesize += sec->get_size() + secAlign; // Nothing to be done when generating nested segments if ( section_generated[index] ) { continue; } current_file_pos += secAlign; // Set the section addresses when missing if ( !sec->is_address_initialized() ) sec->set_address( seg->get_virtual_address() + current_file_pos - seg_start_pos ); if ( 0 != sec->get_index() ) sec->set_offset( current_file_pos ); if ( SHT_NOBITS != sec->get_type() ) current_file_pos += sec->get_size(); section_generated[index] = true; } seg->set_file_size( segment_filesize ); // If we already have a memory size from loading an elf file (value > 0), // it must not shrink! // Memory size may be bigger than file size and it is the loader's job to do something // with the surplus bytes in memory, like initializing them with a defined value. if ( seg->get_memory_size() < segment_memory ) { seg->set_memory_size( segment_memory ); } seg->set_offset( seg_start_pos ); } return true; } //------------------------------------------------------------------------------ bool layout_section_table() { // Simply place the section table at the end for now Elf64_Off alignmentError = current_file_pos % 4; current_file_pos += ( 4 - alignmentError ) % 4; header->set_sections_offset( current_file_pos ); return true; } //------------------------------------------------------------------------------ public: friend class Sections; class Sections { public: //------------------------------------------------------------------------------ Sections( elfio* parent_ ) : parent( parent_ ) {} //------------------------------------------------------------------------------ Elf_Half size() const { return (Elf_Half)parent->sections_.size(); } //------------------------------------------------------------------------------ section* operator[]( unsigned int index ) const { section* sec = 0; if ( index < parent->sections_.size() ) { sec = parent->sections_[index]; } return sec; } //------------------------------------------------------------------------------ section* operator[]( const std::string& name ) const { section* sec = 0; std::vector::const_iterator it; for ( it = parent->sections_.begin(); it != parent->sections_.end(); ++it ) { if ( ( *it )->get_name() == name ) { sec = *it; break; } } return sec; } //------------------------------------------------------------------------------ section* add( const std::string& name ) { section* new_section = parent->create_section(); new_section->set_name( name ); Elf_Half str_index = parent->get_section_name_str_index(); section* string_table( parent->sections_[str_index] ); string_section_accessor str_writer( string_table ); Elf_Word pos = str_writer.add_string( name ); new_section->set_name_string_offset( pos ); return new_section; } //------------------------------------------------------------------------------ std::vector::iterator begin() { return parent->sections_.begin(); } //------------------------------------------------------------------------------ std::vector::iterator end() { return parent->sections_.end(); } //------------------------------------------------------------------------------ std::vector::const_iterator begin() const { return parent->sections_.cbegin(); } //------------------------------------------------------------------------------ std::vector::const_iterator end() const { return parent->sections_.cend(); } //------------------------------------------------------------------------------ private: elfio* parent; } sections; //------------------------------------------------------------------------------ public: friend class Segments; class Segments { public: //------------------------------------------------------------------------------ Segments( elfio* parent_ ) : parent( parent_ ) {} //------------------------------------------------------------------------------ Elf_Half size() const { return (Elf_Half)parent->segments_.size(); } //------------------------------------------------------------------------------ segment* operator[]( unsigned int index ) const { return parent->segments_[index]; } //------------------------------------------------------------------------------ segment* add() { return parent->create_segment(); } //------------------------------------------------------------------------------ std::vector::iterator begin() { return parent->segments_.begin(); } //------------------------------------------------------------------------------ std::vector::iterator end() { return parent->segments_.end(); } //------------------------------------------------------------------------------ std::vector::const_iterator begin() const { return parent->segments_.cbegin(); } //------------------------------------------------------------------------------ std::vector::const_iterator end() const { return parent->segments_.cend(); } //------------------------------------------------------------------------------ private: elfio* parent; } segments; //------------------------------------------------------------------------------ private: elf_header* header; std::vector sections_; std::vector segments_; endianess_convertor convertor; Elf_Xword current_file_pos; }; } // namespace ELFIO /*** Start of inlined file: elfio_symbols.hpp ***/ #ifndef ELFIO_SYMBOLS_HPP #define ELFIO_SYMBOLS_HPP namespace ELFIO { //------------------------------------------------------------------------------ template class symbol_section_accessor_template { public: //------------------------------------------------------------------------------ symbol_section_accessor_template( const elfio& elf_file_, S* symbol_section_ ) : elf_file( elf_file_ ), symbol_section( symbol_section_ ) { find_hash_section(); } //------------------------------------------------------------------------------ Elf_Xword get_symbols_num() const { Elf_Xword nRet = 0; if ( 0 != symbol_section->get_entry_size() ) { nRet = symbol_section->get_size() / symbol_section->get_entry_size(); } return nRet; } //------------------------------------------------------------------------------ bool get_symbol( Elf_Xword index, std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( elf_file.get_class() == ELFCLASS32 ) { ret = generic_get_symbol( index, name, value, size, bind, type, section_index, other ); } else { ret = generic_get_symbol( index, name, value, size, bind, type, section_index, other ); } return ret; } //------------------------------------------------------------------------------ bool get_symbol( const std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( 0 != get_hash_table_index() ) { Elf_Word nbucket = *(const Elf_Word*)hash_section->get_data(); Elf_Word nchain = *(const Elf_Word*)( hash_section->get_data() + sizeof( Elf_Word ) ); Elf_Word val = elf_hash( (const unsigned char*)name.c_str() ); Elf_Word y = *(const Elf_Word*)( hash_section->get_data() + ( 2 + val % nbucket ) * sizeof( Elf_Word ) ); std::string str; get_symbol( y, str, value, size, bind, type, section_index, other ); while ( str != name && STN_UNDEF != y && y < nchain ) { y = *(const Elf_Word*)( hash_section->get_data() + ( 2 + nbucket + y ) * sizeof( Elf_Word ) ); get_symbol( y, str, value, size, bind, type, section_index, other ); } if ( str == name ) { ret = true; } } else { for ( Elf_Xword i = 0; i < get_symbols_num() && !ret; i++ ) { std::string symbol_name; if ( get_symbol( i, symbol_name, value, size, bind, type, section_index, other ) ) { if ( symbol_name == name ) { ret = true; } } } } return ret; } //------------------------------------------------------------------------------ bool get_symbol( const Elf64_Addr& value, std::string& name, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { const endianess_convertor& convertor = elf_file.get_convertor(); Elf_Xword idx = 0; bool match = false; Elf64_Addr v = 0; if ( elf_file.get_class() == ELFCLASS32 ) { match = generic_search_symbols( [&]( const Elf32_Sym* sym ) { return convertor( sym->st_value ) == value; }, idx ); } else { match = generic_search_symbols( [&]( const Elf64_Sym* sym ) { return convertor( sym->st_value ) == value; }, idx ); } if ( match ) { return get_symbol( idx, name, v, size, bind, type, section_index, other ); } return false; } //------------------------------------------------------------------------------ Elf_Word add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { Elf_Word nRet; if ( symbol_section->get_size() == 0 ) { if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_add_symbol( 0, 0, 0, 0, 0, 0 ); } else { nRet = generic_add_symbol( 0, 0, 0, 0, 0, 0 ); } } if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_add_symbol( name, value, size, info, other, shndx ); } else { nRet = generic_add_symbol( name, value, size, info, other, shndx ); } return nRet; } //------------------------------------------------------------------------------ Elf_Word add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char bind, unsigned char type, unsigned char other, Elf_Half shndx ) { return add_symbol( name, value, size, ELF_ST_INFO( bind, type ), other, shndx ); } //------------------------------------------------------------------------------ Elf_Word add_symbol( string_section_accessor& pStrWriter, const char* str, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { Elf_Word index = pStrWriter.add_string( str ); return add_symbol( index, value, size, info, other, shndx ); } //------------------------------------------------------------------------------ Elf_Word add_symbol( string_section_accessor& pStrWriter, const char* str, Elf64_Addr value, Elf_Xword size, unsigned char bind, unsigned char type, unsigned char other, Elf_Half shndx ) { return add_symbol( pStrWriter, str, value, size, ELF_ST_INFO( bind, type ), other, shndx ); } //------------------------------------------------------------------------------ Elf_Xword arrange_local_symbols( std::function func = nullptr ) { int nRet = 0; if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_arrange_local_symbols( func ); } else { nRet = generic_arrange_local_symbols( func ); } return nRet; } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ void find_hash_section() { hash_section = 0; hash_section_index = 0; Elf_Half nSecNo = elf_file.sections.size(); for ( Elf_Half i = 0; i < nSecNo && 0 == hash_section_index; ++i ) { const section* sec = elf_file.sections[i]; if ( sec->get_link() == symbol_section->get_index() ) { hash_section = sec; hash_section_index = i; } } } //------------------------------------------------------------------------------ Elf_Half get_string_table_index() const { return (Elf_Half)symbol_section->get_link(); } //------------------------------------------------------------------------------ Elf_Half get_hash_table_index() const { return hash_section_index; } //------------------------------------------------------------------------------ template const T* generic_get_symbol_ptr( Elf_Xword index ) const { if ( 0 != symbol_section->get_data() && index < get_symbols_num() ) { const T* pSym = reinterpret_cast( symbol_section->get_data() + index * symbol_section->get_entry_size() ); return pSym; } return nullptr; } //------------------------------------------------------------------------------ template bool generic_search_symbols( std::function match, Elf_Xword& idx ) const { for ( Elf_Xword i = 0; i < get_symbols_num(); i++ ) { const T* symPtr = generic_get_symbol_ptr( i ); if ( symPtr == nullptr ) return false; if ( match( symPtr ) ) { idx = i; return true; } } return false; } //------------------------------------------------------------------------------ template bool generic_get_symbol( Elf_Xword index, std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( 0 != symbol_section->get_data() && index < get_symbols_num() ) { const T* pSym = reinterpret_cast( symbol_section->get_data() + index * symbol_section->get_entry_size() ); const endianess_convertor& convertor = elf_file.get_convertor(); section* string_section = elf_file.sections[get_string_table_index()]; string_section_accessor str_reader( string_section ); const char* pStr = str_reader.get_string( convertor( pSym->st_name ) ); if ( 0 != pStr ) { name = pStr; } value = convertor( pSym->st_value ); size = convertor( pSym->st_size ); bind = ELF_ST_BIND( pSym->st_info ); type = ELF_ST_TYPE( pSym->st_info ); section_index = convertor( pSym->st_shndx ); other = pSym->st_other; ret = true; } return ret; } //------------------------------------------------------------------------------ template Elf_Word generic_add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; entry.st_name = convertor( name ); entry.st_value = value; entry.st_value = convertor( entry.st_value ); entry.st_size = size; entry.st_size = convertor( entry.st_size ); entry.st_info = convertor( info ); entry.st_other = convertor( other ); entry.st_shndx = convertor( shndx ); symbol_section->append_data( reinterpret_cast( &entry ), sizeof( entry ) ); Elf_Word nRet = symbol_section->get_size() / sizeof( entry ) - 1; return nRet; } //------------------------------------------------------------------------------ template Elf_Xword generic_arrange_local_symbols( std::function func ) { const endianess_convertor& convertor = elf_file.get_convertor(); const Elf_Xword size = symbol_section->get_entry_size(); Elf_Xword first_not_local = 1; // Skip the first entry. It is always NOTYPE Elf_Xword current = 0; Elf_Xword count = get_symbols_num(); while ( true ) { T* p1 = nullptr; T* p2 = nullptr; while ( first_not_local < count ) { p1 = const_cast( generic_get_symbol_ptr( first_not_local ) ); if ( ELF_ST_BIND( convertor( p1->st_info ) ) != STB_LOCAL ) break; ++first_not_local; } current = first_not_local + 1; while ( current < count ) { p2 = const_cast( generic_get_symbol_ptr( current ) ); if ( ELF_ST_BIND( convertor( p2->st_info ) ) == STB_LOCAL ) break; ++current; } if ( first_not_local < count && current < count ) { if ( func ) func( first_not_local, current ); // Swap the symbols T tmp; std::copy( p1, p1 + 1, &tmp ); std::copy( p2, p2 + 1, p1 ); std::copy( &tmp, &tmp + 1, p2 ); } else { // Update 'info' field of the section symbol_section->set_info( first_not_local ); break; } } // Elf_Word nRet = symbol_section->get_size() / sizeof(entry) - 1; return first_not_local; } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* symbol_section; Elf_Half hash_section_index; const section* hash_section; }; using symbol_section_accessor = symbol_section_accessor_template
; using const_symbol_section_accessor = symbol_section_accessor_template; } // namespace ELFIO #endif // ELFIO_SYMBOLS_HPP /*** End of inlined file: elfio_symbols.hpp ***/ /*** Start of inlined file: elfio_note.hpp ***/ #ifndef ELFIO_NOTE_HPP #define ELFIO_NOTE_HPP namespace ELFIO { //------------------------------------------------------------------------------ // There are discrepancies in documentations. SCO documentation // (http://www.sco.com/developers/gabi/latest/ch5.pheader.html#note_section) // requires 8 byte entries alignment for 64-bit ELF file, // but Oracle's definition uses the same structure // for 32-bit and 64-bit formats. // (https://docs.oracle.com/cd/E23824_01/html/819-0690/chapter6-18048.html) // // It looks like EM_X86_64 Linux implementation is similar to Oracle's // definition. Therefore, the same alignment works for both formats //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ template class note_section_accessor_template { public: //------------------------------------------------------------------------------ note_section_accessor_template( const elfio& elf_file_, S* section_ ) : elf_file( elf_file_ ), note_section( section_ ) { process_section(); } //------------------------------------------------------------------------------ Elf_Word get_notes_num() const { return (Elf_Word)note_start_positions.size(); } //------------------------------------------------------------------------------ bool get_note( Elf_Word index, Elf_Word& type, std::string& name, void*& desc, Elf_Word& descSize ) const { if ( index >= note_section->get_size() ) { return false; } const char* pData = note_section->get_data() + note_start_positions[index]; int align = sizeof( Elf_Word ); const endianess_convertor& convertor = elf_file.get_convertor(); type = convertor( *(const Elf_Word*)( pData + 2 * align ) ); Elf_Word namesz = convertor( *(const Elf_Word*)( pData ) ); descSize = convertor( *(const Elf_Word*)( pData + sizeof( namesz ) ) ); Elf_Xword max_name_size = note_section->get_size() - note_start_positions[index]; if ( namesz < 1 || namesz > max_name_size || (Elf_Xword)namesz + descSize > max_name_size ) { return false; } name.assign( pData + 3 * align, namesz - 1 ); if ( 0 == descSize ) { desc = 0; } else { desc = const_cast( pData + 3 * align + ( ( namesz + align - 1 ) / align ) * align ); } return true; } //------------------------------------------------------------------------------ void add_note( Elf_Word type, const std::string& name, const void* desc, Elf_Word descSize ) { const endianess_convertor& convertor = elf_file.get_convertor(); int align = sizeof( Elf_Word ); Elf_Word nameLen = (Elf_Word)name.size() + 1; Elf_Word nameLenConv = convertor( nameLen ); std::string buffer( reinterpret_cast( &nameLenConv ), align ); Elf_Word descSizeConv = convertor( descSize ); buffer.append( reinterpret_cast( &descSizeConv ), align ); type = convertor( type ); buffer.append( reinterpret_cast( &type ), align ); buffer.append( name ); buffer.append( 1, '\x00' ); const char pad[] = { '\0', '\0', '\0', '\0' }; if ( nameLen % align != 0 ) { buffer.append( pad, align - nameLen % align ); } if ( desc != 0 && descSize != 0 ) { buffer.append( reinterpret_cast( desc ), descSize ); if ( descSize % align != 0 ) { buffer.append( pad, align - descSize % align ); } } note_start_positions.push_back( note_section->get_size() ); note_section->append_data( buffer ); } private: //------------------------------------------------------------------------------ void process_section() { const endianess_convertor& convertor = elf_file.get_convertor(); const char* data = note_section->get_data(); Elf_Xword size = note_section->get_size(); Elf_Xword current = 0; note_start_positions.clear(); // Is it empty? if ( 0 == data || 0 == size ) { return; } Elf_Word align = sizeof( Elf_Word ); while ( current + (Elf_Xword)3 * align <= size ) { note_start_positions.push_back( current ); Elf_Word namesz = convertor( *(const Elf_Word*)( data + current ) ); Elf_Word descsz = convertor( *(const Elf_Word*)( data + current + sizeof( namesz ) ) ); current += (Elf_Xword)3 * sizeof( Elf_Word ) + ( ( namesz + align - 1 ) / align ) * (Elf_Xword)align + ( ( descsz + align - 1 ) / align ) * (Elf_Xword)align; } } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* note_section; std::vector note_start_positions; }; using note_section_accessor = note_section_accessor_template
; using const_note_section_accessor = note_section_accessor_template; } // namespace ELFIO #endif // ELFIO_NOTE_HPP /*** End of inlined file: elfio_note.hpp ***/ /*** Start of inlined file: elfio_relocation.hpp ***/ #ifndef ELFIO_RELOCATION_HPP #define ELFIO_RELOCATION_HPP namespace ELFIO { template struct get_sym_and_type; template <> struct get_sym_and_type { static int get_r_sym( Elf_Xword info ) { return ELF32_R_SYM( (Elf_Word)info ); } static int get_r_type( Elf_Xword info ) { return ELF32_R_TYPE( (Elf_Word)info ); } }; template <> struct get_sym_and_type { static int get_r_sym( Elf_Xword info ) { return ELF32_R_SYM( (Elf_Word)info ); } static int get_r_type( Elf_Xword info ) { return ELF32_R_TYPE( (Elf_Word)info ); } }; template <> struct get_sym_and_type { static int get_r_sym( Elf_Xword info ) { return ELF64_R_SYM( info ); } static int get_r_type( Elf_Xword info ) { return ELF64_R_TYPE( info ); } }; template <> struct get_sym_and_type { static int get_r_sym( Elf_Xword info ) { return ELF64_R_SYM( info ); } static int get_r_type( Elf_Xword info ) { return ELF64_R_TYPE( info ); } }; //------------------------------------------------------------------------------ template class relocation_section_accessor_template { public: //------------------------------------------------------------------------------ relocation_section_accessor_template( const elfio& elf_file_, S* section_ ) : elf_file( elf_file_ ), relocation_section( section_ ) { } //------------------------------------------------------------------------------ Elf_Xword get_entries_num() const { Elf_Xword nRet = 0; if ( 0 != relocation_section->get_entry_size() ) { nRet = relocation_section->get_size() / relocation_section->get_entry_size(); } return nRet; } //------------------------------------------------------------------------------ bool get_entry( Elf_Xword index, Elf64_Addr& offset, Elf_Word& symbol, Elf_Word& type, Elf_Sxword& addend ) const { if ( index >= get_entries_num() ) { // Is index valid return false; } if ( elf_file.get_class() == ELFCLASS32 ) { if ( SHT_REL == relocation_section->get_type() ) { generic_get_entry_rel( index, offset, symbol, type, addend ); } else if ( SHT_RELA == relocation_section->get_type() ) { generic_get_entry_rela( index, offset, symbol, type, addend ); } } else { if ( SHT_REL == relocation_section->get_type() ) { generic_get_entry_rel( index, offset, symbol, type, addend ); } else if ( SHT_RELA == relocation_section->get_type() ) { generic_get_entry_rela( index, offset, symbol, type, addend ); } } return true; } //------------------------------------------------------------------------------ bool get_entry( Elf_Xword index, Elf64_Addr& offset, Elf64_Addr& symbolValue, std::string& symbolName, Elf_Word& type, Elf_Sxword& addend, Elf_Sxword& calcValue ) const { // Do regular job Elf_Word symbol; bool ret = get_entry( index, offset, symbol, type, addend ); // Find the symbol Elf_Xword size; unsigned char bind; unsigned char symbolType; Elf_Half section; unsigned char other; symbol_section_accessor symbols( elf_file, elf_file.sections[get_symbol_table_index()] ); ret = ret && symbols.get_symbol( symbol, symbolName, symbolValue, size, bind, symbolType, section, other ); if ( ret ) { // Was it successful? switch ( type ) { case R_386_NONE: // none calcValue = 0; break; case R_386_32: // S + A calcValue = symbolValue + addend; break; case R_386_PC32: // S + A - P calcValue = symbolValue + addend - offset; break; case R_386_GOT32: // G + A - P calcValue = 0; break; case R_386_PLT32: // L + A - P calcValue = 0; break; case R_386_COPY: // none calcValue = 0; break; case R_386_GLOB_DAT: // S case R_386_JMP_SLOT: // S calcValue = symbolValue; break; case R_386_RELATIVE: // B + A calcValue = addend; break; case R_386_GOTOFF: // S + A - GOT calcValue = 0; break; case R_386_GOTPC: // GOT + A - P calcValue = 0; break; default: // Not recognized symbol! calcValue = 0; break; } } return ret; } //------------------------------------------------------------------------------ bool set_entry( Elf_Xword index, Elf64_Addr offset, Elf_Word symbol, Elf_Word type, Elf_Sxword addend ) { if ( index >= get_entries_num() ) { // Is index valid return false; } if ( elf_file.get_class() == ELFCLASS32 ) { if ( SHT_REL == relocation_section->get_type() ) { generic_set_entry_rel( index, offset, symbol, type, addend ); } else if ( SHT_RELA == relocation_section->get_type() ) { generic_set_entry_rela( index, offset, symbol, type, addend ); } } else { if ( SHT_REL == relocation_section->get_type() ) { generic_set_entry_rel( index, offset, symbol, type, addend ); } else if ( SHT_RELA == relocation_section->get_type() ) { generic_set_entry_rela( index, offset, symbol, type, addend ); } } return true; } //------------------------------------------------------------------------------ void add_entry( Elf64_Addr offset, Elf_Xword info ) { if ( elf_file.get_class() == ELFCLASS32 ) { generic_add_entry( offset, info ); } else { generic_add_entry( offset, info ); } } //------------------------------------------------------------------------------ void add_entry( Elf64_Addr offset, Elf_Word symbol, unsigned char type ) { Elf_Xword info; if ( elf_file.get_class() == ELFCLASS32 ) { info = ELF32_R_INFO( (Elf_Xword)symbol, type ); } else { info = ELF64_R_INFO( (Elf_Xword)symbol, type ); } add_entry( offset, info ); } //------------------------------------------------------------------------------ void add_entry( Elf64_Addr offset, Elf_Xword info, Elf_Sxword addend ) { if ( elf_file.get_class() == ELFCLASS32 ) { generic_add_entry( offset, info, addend ); } else { generic_add_entry( offset, info, addend ); } } //------------------------------------------------------------------------------ void add_entry( Elf64_Addr offset, Elf_Word symbol, unsigned char type, Elf_Sxword addend ) { Elf_Xword info; if ( elf_file.get_class() == ELFCLASS32 ) { info = ELF32_R_INFO( (Elf_Xword)symbol, type ); } else { info = ELF64_R_INFO( (Elf_Xword)symbol, type ); } add_entry( offset, info, addend ); } //------------------------------------------------------------------------------ void add_entry( string_section_accessor str_writer, const char* str, symbol_section_accessor sym_writer, Elf64_Addr value, Elf_Word size, unsigned char sym_info, unsigned char other, Elf_Half shndx, Elf64_Addr offset, unsigned char type ) { Elf_Word str_index = str_writer.add_string( str ); Elf_Word sym_index = sym_writer.add_symbol( str_index, value, size, sym_info, other, shndx ); add_entry( offset, sym_index, type ); } //------------------------------------------------------------------------------ void swap_symbols( Elf_Xword first, Elf_Xword second ) { Elf64_Addr offset; Elf_Word symbol; Elf_Word rtype; Elf_Sxword addend; for ( Elf_Word i = 0; i < get_entries_num(); i++ ) { get_entry( i, offset, symbol, rtype, addend ); if ( symbol == first ) { set_entry( i, offset, (Elf_Word)second, rtype, addend ); } if ( symbol == second ) { set_entry( i, offset, (Elf_Word)first, rtype, addend ); } } } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ Elf_Half get_symbol_table_index() const { return (Elf_Half)relocation_section->get_link(); } //------------------------------------------------------------------------------ template void generic_get_entry_rel( Elf_Xword index, Elf64_Addr& offset, Elf_Word& symbol, Elf_Word& type, Elf_Sxword& addend ) const { const endianess_convertor& convertor = elf_file.get_convertor(); const T* pEntry = reinterpret_cast( relocation_section->get_data() + index * relocation_section->get_entry_size() ); offset = convertor( pEntry->r_offset ); Elf_Xword tmp = convertor( pEntry->r_info ); symbol = get_sym_and_type::get_r_sym( tmp ); type = get_sym_and_type::get_r_type( tmp ); addend = 0; } //------------------------------------------------------------------------------ template void generic_get_entry_rela( Elf_Xword index, Elf64_Addr& offset, Elf_Word& symbol, Elf_Word& type, Elf_Sxword& addend ) const { const endianess_convertor& convertor = elf_file.get_convertor(); const T* pEntry = reinterpret_cast( relocation_section->get_data() + index * relocation_section->get_entry_size() ); offset = convertor( pEntry->r_offset ); Elf_Xword tmp = convertor( pEntry->r_info ); symbol = get_sym_and_type::get_r_sym( tmp ); type = get_sym_and_type::get_r_type( tmp ); addend = convertor( pEntry->r_addend ); } //------------------------------------------------------------------------------ template void generic_set_entry_rel( Elf_Xword index, Elf64_Addr offset, Elf_Word symbol, Elf_Word type, Elf_Sxword ) { const endianess_convertor& convertor = elf_file.get_convertor(); T* pEntry = const_cast( reinterpret_cast( relocation_section->get_data() + index * relocation_section->get_entry_size() ) ); if ( elf_file.get_class() == ELFCLASS32 ) { pEntry->r_info = ELF32_R_INFO( (Elf_Xword)symbol, type ); } else { pEntry->r_info = ELF64_R_INFO( (Elf_Xword)symbol, type ); } pEntry->r_offset = offset; pEntry->r_offset = convertor( pEntry->r_offset ); pEntry->r_info = convertor( pEntry->r_info ); } //------------------------------------------------------------------------------ template void generic_set_entry_rela( Elf_Xword index, Elf64_Addr offset, Elf_Word symbol, Elf_Word type, Elf_Sxword addend ) { const endianess_convertor& convertor = elf_file.get_convertor(); T* pEntry = const_cast( reinterpret_cast( relocation_section->get_data() + index * relocation_section->get_entry_size() ) ); if ( elf_file.get_class() == ELFCLASS32 ) { pEntry->r_info = ELF32_R_INFO( (Elf_Xword)symbol, type ); } else { pEntry->r_info = ELF64_R_INFO( (Elf_Xword)symbol, type ); } pEntry->r_offset = offset; pEntry->r_addend = addend; pEntry->r_offset = convertor( pEntry->r_offset ); pEntry->r_info = convertor( pEntry->r_info ); pEntry->r_addend = convertor( pEntry->r_addend ); } //------------------------------------------------------------------------------ template void generic_add_entry( Elf64_Addr offset, Elf_Xword info ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; entry.r_offset = offset; entry.r_info = info; entry.r_offset = convertor( entry.r_offset ); entry.r_info = convertor( entry.r_info ); relocation_section->append_data( reinterpret_cast( &entry ), sizeof( entry ) ); } //------------------------------------------------------------------------------ template void generic_add_entry( Elf64_Addr offset, Elf_Xword info, Elf_Sxword addend ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; entry.r_offset = offset; entry.r_info = info; entry.r_addend = addend; entry.r_offset = convertor( entry.r_offset ); entry.r_info = convertor( entry.r_info ); entry.r_addend = convertor( entry.r_addend ); relocation_section->append_data( reinterpret_cast( &entry ), sizeof( entry ) ); } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* relocation_section; }; using relocation_section_accessor = relocation_section_accessor_template
; using const_relocation_section_accessor = relocation_section_accessor_template; } // namespace ELFIO #endif // ELFIO_RELOCATION_HPP /*** End of inlined file: elfio_relocation.hpp ***/ /*** Start of inlined file: elfio_dynamic.hpp ***/ #ifndef ELFIO_DYNAMIC_HPP #define ELFIO_DYNAMIC_HPP namespace ELFIO { //------------------------------------------------------------------------------ template class dynamic_section_accessor_template { public: //------------------------------------------------------------------------------ dynamic_section_accessor_template( const elfio& elf_file_, S* section_ ) : elf_file( elf_file_ ), dynamic_section( section_ ) { } //------------------------------------------------------------------------------ Elf_Xword get_entries_num() const { Elf_Xword nRet = 0; if ( 0 != dynamic_section->get_entry_size() ) { nRet = dynamic_section->get_size() / dynamic_section->get_entry_size(); } return nRet; } //------------------------------------------------------------------------------ bool get_entry( Elf_Xword index, Elf_Xword& tag, Elf_Xword& value, std::string& str ) const { if ( index >= get_entries_num() ) { // Is index valid return false; } if ( elf_file.get_class() == ELFCLASS32 ) { generic_get_entry_dyn( index, tag, value ); } else { generic_get_entry_dyn( index, tag, value ); } // If the tag may have a string table reference, prepare the string if ( tag == DT_NEEDED || tag == DT_SONAME || tag == DT_RPATH || tag == DT_RUNPATH ) { string_section_accessor strsec = elf_file.sections[get_string_table_index()]; const char* result = strsec.get_string( value ); if ( 0 == result ) { str.clear(); return false; } str = result; } else { str.clear(); } return true; } //------------------------------------------------------------------------------ void add_entry( Elf_Xword tag, Elf_Xword value ) { if ( elf_file.get_class() == ELFCLASS32 ) { generic_add_entry( tag, value ); } else { generic_add_entry( tag, value ); } } //------------------------------------------------------------------------------ void add_entry( Elf_Xword tag, const std::string& str ) { string_section_accessor strsec = elf_file.sections[get_string_table_index()]; Elf_Xword value = strsec.add_string( str ); add_entry( tag, value ); } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ Elf_Half get_string_table_index() const { return (Elf_Half)dynamic_section->get_link(); } //------------------------------------------------------------------------------ template void generic_get_entry_dyn( Elf_Xword index, Elf_Xword& tag, Elf_Xword& value ) const { const endianess_convertor& convertor = elf_file.get_convertor(); // Check unusual case when dynamic section has no data if ( dynamic_section->get_data() == 0 || ( index + 1 ) * dynamic_section->get_entry_size() > dynamic_section->get_size() ) { tag = DT_NULL; value = 0; return; } const T* pEntry = reinterpret_cast( dynamic_section->get_data() + index * dynamic_section->get_entry_size() ); tag = convertor( pEntry->d_tag ); switch ( tag ) { case DT_NULL: case DT_SYMBOLIC: case DT_TEXTREL: case DT_BIND_NOW: value = 0; break; case DT_NEEDED: case DT_PLTRELSZ: case DT_RELASZ: case DT_RELAENT: case DT_STRSZ: case DT_SYMENT: case DT_SONAME: case DT_RPATH: case DT_RELSZ: case DT_RELENT: case DT_PLTREL: case DT_INIT_ARRAYSZ: case DT_FINI_ARRAYSZ: case DT_RUNPATH: case DT_FLAGS: case DT_PREINIT_ARRAYSZ: value = convertor( pEntry->d_un.d_val ); break; case DT_PLTGOT: case DT_HASH: case DT_STRTAB: case DT_SYMTAB: case DT_RELA: case DT_INIT: case DT_FINI: case DT_REL: case DT_DEBUG: case DT_JMPREL: case DT_INIT_ARRAY: case DT_FINI_ARRAY: case DT_PREINIT_ARRAY: default: value = convertor( pEntry->d_un.d_ptr ); break; } } //------------------------------------------------------------------------------ template void generic_add_entry( Elf_Xword tag, Elf_Xword value ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; switch ( tag ) { case DT_NULL: case DT_SYMBOLIC: case DT_TEXTREL: case DT_BIND_NOW: value = 0; case DT_NEEDED: case DT_PLTRELSZ: case DT_RELASZ: case DT_RELAENT: case DT_STRSZ: case DT_SYMENT: case DT_SONAME: case DT_RPATH: case DT_RELSZ: case DT_RELENT: case DT_PLTREL: case DT_INIT_ARRAYSZ: case DT_FINI_ARRAYSZ: case DT_RUNPATH: case DT_FLAGS: case DT_PREINIT_ARRAYSZ: entry.d_un.d_val = convertor( value ); break; case DT_PLTGOT: case DT_HASH: case DT_STRTAB: case DT_SYMTAB: case DT_RELA: case DT_INIT: case DT_FINI: case DT_REL: case DT_DEBUG: case DT_JMPREL: case DT_INIT_ARRAY: case DT_FINI_ARRAY: case DT_PREINIT_ARRAY: default: entry.d_un.d_ptr = convertor( value ); break; } entry.d_tag = convertor( tag ); dynamic_section->append_data( reinterpret_cast( &entry ), sizeof( entry ) ); } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* dynamic_section; }; using dynamic_section_accessor = dynamic_section_accessor_template
; using const_dynamic_section_accessor = dynamic_section_accessor_template; } // namespace ELFIO #endif // ELFIO_DYNAMIC_HPP /*** End of inlined file: elfio_dynamic.hpp ***/ /*** Start of inlined file: elfio_modinfo.hpp ***/ #ifndef ELFIO_MODINFO_HPP #define ELFIO_MODINFO_HPP #include #include namespace ELFIO { //------------------------------------------------------------------------------ template class modinfo_section_accessor_template { public: //------------------------------------------------------------------------------ modinfo_section_accessor_template( S* section_ ) : modinfo_section( section_ ) { process_section(); } //------------------------------------------------------------------------------ Elf_Word get_attribute_num() const { return (Elf_Word)content.size(); } //------------------------------------------------------------------------------ bool get_attribute( Elf_Word no, std::string& field, std::string& value ) const { if ( no < content.size() ) { field = content[no].first; value = content[no].second; return true; } return false; } //------------------------------------------------------------------------------ bool get_attribute( std::string field_name, std::string& value ) const { for ( auto i = content.begin(); i != content.end(); i++ ) { if ( field_name == i->first ) { value = i->second; return true; } } return false; } //------------------------------------------------------------------------------ Elf_Word add_attribute( std::string field, std::string value ) { Elf_Word current_position = 0; if ( modinfo_section ) { // Strings are addeded to the end of the current section data current_position = (Elf_Word)modinfo_section->get_size(); std::string attribute = field + "=" + value; modinfo_section->append_data( attribute + '\0' ); content.push_back( std::pair( field, value ) ); } return current_position; } //------------------------------------------------------------------------------ private: void process_section() { const char* pdata = modinfo_section->get_data(); if ( pdata ) { ELFIO::Elf_Xword i = 0; while ( i < modinfo_section->get_size() ) { while ( i < modinfo_section->get_size() && !pdata[i] ) i++; if ( i < modinfo_section->get_size() ) { std::string info = pdata + i; size_t loc = info.find( '=' ); std::pair attribute( info.substr( 0, loc ), info.substr( loc + 1 ) ); content.push_back( attribute ); i += info.length(); } } } } //------------------------------------------------------------------------------ private: S* modinfo_section; std::vector> content; }; using modinfo_section_accessor = modinfo_section_accessor_template
; using const_modinfo_section_accessor = modinfo_section_accessor_template; } // namespace ELFIO #endif // ELFIO_MODINFO_HPP /*** End of inlined file: elfio_modinfo.hpp ***/ #ifdef _MSC_VER #pragma warning( pop ) #endif #endif // ELFIO_HPP /*** End of inlined file: elfio.hpp ***/ namespace ELFIO { static struct class_table_t { const char key; const char* str; } class_table[] = { { ELFCLASS32, "ELF32" }, { ELFCLASS64, "ELF64" }, }; static struct endian_table_t { const char key; const char* str; } endian_table[] = { { ELFDATANONE, "None" }, { ELFDATA2LSB, "Little endian" }, { ELFDATA2MSB, "Big endian" }, }; static struct version_table_t { const Elf64_Word key; const char* str; } version_table[] = { { EV_NONE, "None" }, { EV_CURRENT, "Current" }, }; static struct type_table_t { const Elf32_Half key; const char* str; } type_table[] = { { ET_NONE, "No file type" }, { ET_REL, "Relocatable file" }, { ET_EXEC, "Executable file" }, { ET_DYN, "Shared object file" }, { ET_CORE, "Core file" }, }; static struct machine_table_t { const Elf64_Half key; const char* str; } machine_table[] = { { EM_NONE, "No machine" }, { EM_M32, "AT&T WE 32100" }, { EM_SPARC, "SUN SPARC" }, { EM_386, "Intel 80386" }, { EM_68K, "Motorola m68k family" }, { EM_88K, "Motorola m88k family" }, { EM_486, "Intel 80486// Reserved for future use" }, { EM_860, "Intel 80860" }, { EM_MIPS, "MIPS R3000 (officially, big-endian only)" }, { EM_S370, "IBM System/370" }, { EM_MIPS_RS3_LE, "MIPS R3000 little-endian (Oct 4 1999 Draft) Deprecated" }, { EM_res011, "Reserved" }, { EM_res012, "Reserved" }, { EM_res013, "Reserved" }, { EM_res014, "Reserved" }, { EM_PARISC, "HPPA" }, { EM_res016, "Reserved" }, { EM_VPP550, "Fujitsu VPP500" }, { EM_SPARC32PLUS, "Sun's v8plus" }, { EM_960, "Intel 80960" }, { EM_PPC, "PowerPC" }, { EM_PPC64, "64-bit PowerPC" }, { EM_S390, "IBM S/390" }, { EM_SPU, "Sony/Toshiba/IBM SPU" }, { EM_res024, "Reserved" }, { EM_res025, "Reserved" }, { EM_res026, "Reserved" }, { EM_res027, "Reserved" }, { EM_res028, "Reserved" }, { EM_res029, "Reserved" }, { EM_res030, "Reserved" }, { EM_res031, "Reserved" }, { EM_res032, "Reserved" }, { EM_res033, "Reserved" }, { EM_res034, "Reserved" }, { EM_res035, "Reserved" }, { EM_V800, "NEC V800 series" }, { EM_FR20, "Fujitsu FR20" }, { EM_RH32, "TRW RH32" }, { EM_MCORE, "Motorola M*Core // May also be taken by Fujitsu MMA" }, { EM_RCE, "Old name for MCore" }, { EM_ARM, "ARM" }, { EM_OLD_ALPHA, "Digital Alpha" }, { EM_SH, "Renesas (formerly Hitachi) / SuperH SH" }, { EM_SPARCV9, "SPARC v9 64-bit" }, { EM_TRICORE, "Siemens Tricore embedded processor" }, { EM_ARC, "ARC Cores" }, { EM_H8_300, "Renesas (formerly Hitachi) H8/300" }, { EM_H8_300H, "Renesas (formerly Hitachi) H8/300H" }, { EM_H8S, "Renesas (formerly Hitachi) H8S" }, { EM_H8_500, "Renesas (formerly Hitachi) H8/500" }, { EM_IA_64, "Intel IA-64 Processor" }, { EM_MIPS_X, "Stanford MIPS-X" }, { EM_COLDFIRE, "Motorola Coldfire" }, { EM_68HC12, "Motorola M68HC12" }, { EM_MMA, "Fujitsu Multimedia Accelerator" }, { EM_PCP, "Siemens PCP" }, { EM_NCPU, "Sony nCPU embedded RISC processor" }, { EM_NDR1, "Denso NDR1 microprocesspr" }, { EM_STARCORE, "Motorola Star*Core processor" }, { EM_ME16, "Toyota ME16 processor" }, { EM_ST100, "STMicroelectronics ST100 processor" }, { EM_TINYJ, "Advanced Logic Corp. TinyJ embedded processor" }, { EM_X86_64, "Advanced Micro Devices X86-64 processor" }, { EM_PDSP, "Sony DSP Processor" }, { EM_PDP10, "Digital Equipment Corp. PDP-10" }, { EM_PDP11, "Digital Equipment Corp. PDP-11" }, { EM_FX66, "Siemens FX66 microcontroller" }, { EM_ST9PLUS, "STMicroelectronics ST9+ 8/16 bit microcontroller" }, { EM_ST7, "STMicroelectronics ST7 8-bit microcontroller" }, { EM_68HC16, "Motorola MC68HC16 Microcontroller" }, { EM_68HC11, "Motorola MC68HC11 Microcontroller" }, { EM_68HC08, "Motorola MC68HC08 Microcontroller" }, { EM_68HC05, "Motorola MC68HC05 Microcontroller" }, { EM_SVX, "Silicon Graphics SVx" }, { EM_ST19, "STMicroelectronics ST19 8-bit cpu" }, { EM_VAX, "Digital VAX" }, { EM_CRIS, "Axis Communications 32-bit embedded processor" }, { EM_JAVELIN, "Infineon Technologies 32-bit embedded cpu" }, { EM_FIREPATH, "Element 14 64-bit DSP processor" }, { EM_ZSP, "LSI Logic's 16-bit DSP processor" }, { EM_MMIX, "Donald Knuth's educational 64-bit processor" }, { EM_HUANY, "Harvard's machine-independent format" }, { EM_PRISM, "SiTera Prism" }, { EM_AVR, "Atmel AVR 8-bit microcontroller" }, { EM_FR30, "Fujitsu FR30" }, { EM_D10V, "Mitsubishi D10V" }, { EM_D30V, "Mitsubishi D30V" }, { EM_V850, "NEC v850" }, { EM_M32R, "Renesas M32R (formerly Mitsubishi M32R)" }, { EM_MN10300, "Matsushita MN10300" }, { EM_MN10200, "Matsushita MN10200" }, { EM_PJ, "picoJava" }, { EM_OPENRISC, "OpenRISC 32-bit embedded processor" }, { EM_ARC_A5, "ARC Cores Tangent-A5" }, { EM_XTENSA, "Tensilica Xtensa Architecture" }, { EM_VIDEOCORE, "Alphamosaic VideoCore processor" }, { EM_TMM_GPP, "Thompson Multimedia General Purpose Processor" }, { EM_NS32K, "National Semiconductor 32000 series" }, { EM_TPC, "Tenor Network TPC processor" }, { EM_SNP1K, "Trebia SNP 1000 processor" }, { EM_ST200, "STMicroelectronics ST200 microcontroller" }, { EM_IP2K, "Ubicom IP2022 micro controller" }, { EM_MAX, "MAX Processor" }, { EM_CR, "National Semiconductor CompactRISC" }, { EM_F2MC16, "Fujitsu F2MC16" }, { EM_MSP430, "TI msp430 micro controller" }, { EM_BLACKFIN, "ADI Blackfin" }, { EM_SE_C33, "S1C33 Family of Seiko Epson processors" }, { EM_SEP, "Sharp embedded microprocessor" }, { EM_ARCA, "Arca RISC Microprocessor" }, { EM_UNICORE, "Microprocessor series from PKU-Unity Ltd. and MPRC of " "Peking University" }, { EM_EXCESS, "eXcess: 16/32/64-bit configurable embedded CPU" }, { EM_DXP, "Icera Semiconductor Inc. Deep Execution Processor" }, { EM_ALTERA_NIOS2, "Altera Nios II soft-core processor" }, { EM_CRX, "National Semiconductor CRX" }, { EM_XGATE, "Motorola XGATE embedded processor" }, { EM_C166, "Infineon C16x/XC16x processor" }, { EM_M16C, "Renesas M16C series microprocessors" }, { EM_DSPIC30F, "Microchip Technology dsPIC30F Digital Signal Controller" }, { EM_CE, "Freescale Communication Engine RISC core" }, { EM_M32C, "Renesas M32C series microprocessors" }, { EM_res121, "Reserved" }, { EM_res122, "Reserved" }, { EM_res123, "Reserved" }, { EM_res124, "Reserved" }, { EM_res125, "Reserved" }, { EM_res126, "Reserved" }, { EM_res127, "Reserved" }, { EM_res128, "Reserved" }, { EM_res129, "Reserved" }, { EM_res130, "Reserved" }, { EM_TSK3000, "Altium TSK3000 core" }, { EM_RS08, "Freescale RS08 embedded processor" }, { EM_res133, "Reserved" }, { EM_ECOG2, "Cyan Technology eCOG2 microprocessor" }, { EM_SCORE, "Sunplus Score" }, { EM_SCORE7, "Sunplus S+core7 RISC processor" }, { EM_DSP24, "New Japan Radio (NJR) 24-bit DSP Processor" }, { EM_VIDEOCORE3, "Broadcom VideoCore III processor" }, { EM_LATTICEMICO32, "RISC processor for Lattice FPGA architecture" }, { EM_SE_C17, "Seiko Epson C17 family" }, { EM_TI_C6000, "Texas Instruments TMS320C6000 DSP family" }, { EM_TI_C2000, "Texas Instruments TMS320C2000 DSP family" }, { EM_TI_C5500, "Texas Instruments TMS320C55x DSP family" }, { EM_res143, "Reserved" }, { EM_res144, "Reserved" }, { EM_res145, "Reserved" }, { EM_res146, "Reserved" }, { EM_res147, "Reserved" }, { EM_res148, "Reserved" }, { EM_res149, "Reserved" }, { EM_res150, "Reserved" }, { EM_res151, "Reserved" }, { EM_res152, "Reserved" }, { EM_res153, "Reserved" }, { EM_res154, "Reserved" }, { EM_res155, "Reserved" }, { EM_res156, "Reserved" }, { EM_res157, "Reserved" }, { EM_res158, "Reserved" }, { EM_res159, "Reserved" }, { EM_MMDSP_PLUS, "STMicroelectronics 64bit VLIW Data Signal Processor" }, { EM_CYPRESS_M8C, "Cypress M8C microprocessor" }, { EM_R32C, "Renesas R32C series microprocessors" }, { EM_TRIMEDIA, "NXP Semiconductors TriMedia architecture family" }, { EM_QDSP6, "QUALCOMM DSP6 Processor" }, { EM_8051, "Intel 8051 and variants" }, { EM_STXP7X, "STMicroelectronics STxP7x family" }, { EM_NDS32, "Andes Technology compact code size embedded RISC processor family" }, { EM_ECOG1, "Cyan Technology eCOG1X family" }, { EM_ECOG1X, "Cyan Technology eCOG1X family" }, { EM_MAXQ30, "Dallas Semiconductor MAXQ30 Core Micro-controllers" }, { EM_XIMO16, "New Japan Radio (NJR) 16-bit DSP Processor" }, { EM_MANIK, "M2000 Reconfigurable RISC Microprocessor" }, { EM_CRAYNV2, "Cray Inc. NV2 vector architecture" }, { EM_RX, "Renesas RX family" }, { EM_METAG, "Imagination Technologies META processor architecture" }, { EM_MCST_ELBRUS, "MCST Elbrus general purpose hardware architecture" }, { EM_ECOG16, "Cyan Technology eCOG16 family" }, { EM_CR16, "National Semiconductor CompactRISC 16-bit processor" }, { EM_ETPU, "Freescale Extended Time Processing Unit" }, { EM_SLE9X, "Infineon Technologies SLE9X core" }, { EM_L1OM, "Intel L1OM" }, { EM_INTEL181, "Reserved by Intel" }, { EM_INTEL182, "Reserved by Intel" }, { EM_res183, "Reserved by ARM" }, { EM_res184, "Reserved by ARM" }, { EM_AVR32, "Atmel Corporation 32-bit microprocessor family" }, { EM_STM8, "STMicroeletronics STM8 8-bit microcontroller" }, { EM_TILE64, "Tilera TILE64 multicore architecture family" }, { EM_TILEPRO, "Tilera TILEPro multicore architecture family" }, { EM_MICROBLAZE, "Xilinx MicroBlaze 32-bit RISC soft processor core" }, { EM_CUDA, "NVIDIA CUDA architecture " }, }; static struct section_type_table_t { const Elf64_Half key; const char* str; } section_type_table[] = { { SHT_NULL, "NULL" }, { SHT_PROGBITS, "PROGBITS" }, { SHT_SYMTAB, "SYMTAB" }, { SHT_STRTAB, "STRTAB" }, { SHT_RELA, "RELA" }, { SHT_HASH, "HASH" }, { SHT_DYNAMIC, "DYNAMIC" }, { SHT_NOTE, "NOTE" }, { SHT_NOBITS, "NOBITS" }, { SHT_REL, "REL" }, { SHT_SHLIB, "SHLIB" }, { SHT_DYNSYM, "DYNSYM" }, { SHT_INIT_ARRAY, "INIT_ARRAY" }, { SHT_FINI_ARRAY, "FINI_ARRAY" }, { SHT_PREINIT_ARRAY, "PREINIT_ARRAY" }, { SHT_GROUP, "GROUP" }, { SHT_SYMTAB_SHNDX, "SYMTAB_SHNDX " }, }; static struct segment_type_table_t { const Elf_Word key; const char* str; } segment_type_table[] = { { PT_NULL, "NULL" }, { PT_LOAD, "LOAD" }, { PT_DYNAMIC, "DYNAMIC" }, { PT_INTERP, "INTERP" }, { PT_NOTE, "NOTE" }, { PT_SHLIB, "SHLIB" }, { PT_PHDR, "PHDR" }, { PT_TLS, "TLS" }, }; static struct segment_flag_table_t { const Elf_Word key; const char* str; } segment_flag_table[] = { { 0, "" }, { 1, "X" }, { 2, "W" }, { 3, "WX" }, { 4, "R" }, { 5, "RX" }, { 6, "RW" }, { 7, "RWX" }, }; static struct symbol_bind_t { const Elf_Word key; const char* str; } symbol_bind_table[] = { { STB_LOCAL, "LOCAL" }, { STB_GLOBAL, "GLOBAL" }, { STB_WEAK, "WEAK" }, { STB_LOOS, "LOOS" }, { STB_HIOS, "HIOS" }, { STB_MULTIDEF, "MULTIDEF" }, { STB_LOPROC, "LOPROC" }, { STB_HIPROC, "HIPROC" }, }; static struct symbol_type_t { const Elf_Word key; const char* str; } symbol_type_table[] = { { STT_NOTYPE, "NOTYPE" }, { STT_OBJECT, "OBJECT" }, { STT_FUNC, "FUNC" }, { STT_SECTION, "SECTION" }, { STT_FILE, "FILE" }, { STT_COMMON, "COMMON" }, { STT_TLS, "TLS" }, { STT_LOOS, "LOOS" }, { STT_HIOS, "HIOS" }, { STT_LOPROC, "LOPROC" }, { STT_HIPROC, "HIPROC" }, }; static struct dynamic_tag_t { const Elf_Word key; const char* str; } dynamic_tag_table[] = { { DT_NULL, "NULL" }, { DT_NEEDED, "NEEDED" }, { DT_PLTRELSZ, "PLTRELSZ" }, { DT_PLTGOT, "PLTGOT" }, { DT_HASH, "HASH" }, { DT_STRTAB, "STRTAB" }, { DT_SYMTAB, "SYMTAB" }, { DT_RELA, "RELA" }, { DT_RELASZ, "RELASZ" }, { DT_RELAENT, "RELAENT" }, { DT_STRSZ, "STRSZ" }, { DT_SYMENT, "SYMENT" }, { DT_INIT, "INIT" }, { DT_FINI, "FINI" }, { DT_SONAME, "SONAME" }, { DT_RPATH, "RPATH" }, { DT_SYMBOLIC, "SYMBOLIC" }, { DT_REL, "REL" }, { DT_RELSZ, "RELSZ" }, { DT_RELENT, "RELENT" }, { DT_PLTREL, "PLTREL" }, { DT_DEBUG, "DEBUG" }, { DT_TEXTREL, "TEXTREL" }, { DT_JMPREL, "JMPREL" }, { DT_BIND_NOW, "BIND_NOW" }, { DT_INIT_ARRAY, "INIT_ARRAY" }, { DT_FINI_ARRAY, "FINI_ARRAY" }, { DT_INIT_ARRAYSZ, "INIT_ARRAYSZ" }, { DT_FINI_ARRAYSZ, "FINI_ARRAYSZ" }, { DT_RUNPATH, "RUNPATH" }, { DT_FLAGS, "FLAGS" }, { DT_ENCODING, "ENCODING" }, { DT_PREINIT_ARRAY, "PREINIT_ARRAY" }, { DT_PREINIT_ARRAYSZ, "PREINIT_ARRAYSZ" }, { DT_MAXPOSTAGS, "MAXPOSTAGS" }, }; static const ELFIO::Elf_Xword MAX_DATA_ENTRIES = 64; //------------------------------------------------------------------------------ class dump { #define DUMP_DEC_FORMAT( width ) \ std::setw( width ) << std::setfill( ' ' ) << std::dec << std::right #define DUMP_HEX_FORMAT( width ) \ std::setw( width ) << std::setfill( '0' ) << std::hex << std::right #define DUMP_STR_FORMAT( width ) \ std::setw( width ) << std::setfill( ' ' ) << std::hex << std::left public: //------------------------------------------------------------------------------ static void header( std::ostream& out, const elfio& reader ) { if ( !reader.get_header_size() ) { return; } out << "ELF Header" << std::endl << std::endl << " Class: " << str_class( reader.get_class() ) << std::endl << " Encoding: " << str_endian( reader.get_encoding() ) << std::endl << " ELFVersion: " << str_version( reader.get_elf_version() ) << std::endl << " Type: " << str_type( reader.get_type() ) << std::endl << " Machine: " << str_machine( reader.get_machine() ) << std::endl << " Version: " << str_version( reader.get_version() ) << std::endl << " Entry: " << "0x" << std::hex << reader.get_entry() << std::endl << " Flags: " << "0x" << std::hex << reader.get_flags() << std::endl << std::endl; } //------------------------------------------------------------------------------ static void section_headers( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.sections.size(); if ( n == 0 ) { return; } out << "Section Headers:" << std::endl; if ( reader.get_class() == ELFCLASS32 ) { // Output for 32-bit out << "[ Nr ] Type Addr Size ES Flg Lk Inf " "Al Name" << std::endl; } else { // Output for 64-bit out << "[ Nr ] Type Addr Size " " ES Flg" << std::endl << " Lk Inf Al Name" << std::endl; } for ( Elf_Half i = 0; i < n; ++i ) { // For all sections section* sec = reader.sections[i]; section_header( out, i, sec, reader.get_class() ); } out << "Key to Flags: W (write), A (alloc), X (execute)\n\n" << std::endl; } //------------------------------------------------------------------------------ static void section_header( std::ostream& out, Elf_Half no, const section* sec, unsigned char elf_class ) { std::ios_base::fmtflags original_flags = out.flags(); if ( elf_class == ELFCLASS32 ) { // Output for 32-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 17 ) << str_section_type( sec->get_type() ) << " " << DUMP_HEX_FORMAT( 8 ) << sec->get_address() << " " << DUMP_HEX_FORMAT( 8 ) << sec->get_size() << " " << DUMP_HEX_FORMAT( 2 ) << sec->get_entry_size() << " " << DUMP_STR_FORMAT( 3 ) << section_flags( sec->get_flags() ) << " " << DUMP_HEX_FORMAT( 2 ) << sec->get_link() << " " << DUMP_HEX_FORMAT( 3 ) << sec->get_info() << " " << DUMP_HEX_FORMAT( 2 ) << sec->get_addr_align() << " " << DUMP_STR_FORMAT( 17 ) << sec->get_name() << " " << std::endl; } else { // Output for 64-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 17 ) << str_section_type( sec->get_type() ) << " " << DUMP_HEX_FORMAT( 16 ) << sec->get_address() << " " << DUMP_HEX_FORMAT( 16 ) << sec->get_size() << " " << DUMP_HEX_FORMAT( 4 ) << sec->get_entry_size() << " " << DUMP_STR_FORMAT( 3 ) << section_flags( sec->get_flags() ) << " " << std::endl << " " << DUMP_HEX_FORMAT( 4 ) << sec->get_link() << " " << DUMP_HEX_FORMAT( 4 ) << sec->get_info() << " " << DUMP_HEX_FORMAT( 4 ) << sec->get_addr_align() << " " << DUMP_STR_FORMAT( 17 ) << sec->get_name() << " " << std::endl; } out.flags( original_flags ); return; } //------------------------------------------------------------------------------ static void segment_headers( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.segments.size(); if ( n == 0 ) { return; } out << "Segment headers:" << std::endl; if ( reader.get_class() == ELFCLASS32 ) { // Output for 32-bit out << "[ Nr ] Type VirtAddr PhysAddr FileSize Mem.Size " "Flags Align" << std::endl; } else { // Output for 64-bit out << "[ Nr ] Type VirtAddr PhysAddr " "Flags" << std::endl << " FileSize Mem.Size " "Align" << std::endl; } for ( Elf_Half i = 0; i < n; ++i ) { segment* seg = reader.segments[i]; segment_header( out, i, seg, reader.get_class() ); } out << std::endl; } //------------------------------------------------------------------------------ static void segment_header( std::ostream& out, Elf_Half no, const segment* seg, unsigned int elf_class ) { std::ios_base::fmtflags original_flags = out.flags(); if ( elf_class == ELFCLASS32 ) { // Output for 32-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 14 ) << str_segment_type( seg->get_type() ) << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_virtual_address() << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_physical_address() << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_file_size() << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_memory_size() << " " << DUMP_STR_FORMAT( 8 ) << str_segment_flag( seg->get_flags() ) << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_align() << " " << std::endl; } else { // Output for 64-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 14 ) << str_segment_type( seg->get_type() ) << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_virtual_address() << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_physical_address() << " " << DUMP_STR_FORMAT( 16 ) << str_segment_flag( seg->get_flags() ) << " " << std::endl << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_file_size() << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_memory_size() << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_align() << " " << std::endl; } out.flags( original_flags ); } //------------------------------------------------------------------------------ static void symbol_tables( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.sections.size(); for ( Elf_Half i = 0; i < n; ++i ) { // For all sections section* sec = reader.sections[i]; if ( SHT_SYMTAB == sec->get_type() || SHT_DYNSYM == sec->get_type() ) { symbol_section_accessor symbols( reader, sec ); Elf_Xword sym_no = symbols.get_symbols_num(); if ( sym_no > 0 ) { out << "Symbol table (" << sec->get_name() << ")" << std::endl; if ( reader.get_class() == ELFCLASS32 ) { // Output for 32-bit out << "[ Nr ] Value Size Type Bind " "Sect Name" << std::endl; } else { // Output for 64-bit out << "[ Nr ] Value Size Type " " Bind Sect" << std::endl << " Name" << std::endl; } for ( Elf_Xword i = 0; i < sym_no; ++i ) { std::string name; Elf64_Addr value = 0; Elf_Xword size = 0; unsigned char bind = 0; unsigned char type = 0; Elf_Half section = 0; unsigned char other = 0; symbols.get_symbol( i, name, value, size, bind, type, section, other ); symbol_table( out, i, name, value, size, bind, type, section, reader.get_class() ); } out << std::endl; } } } } //------------------------------------------------------------------------------ static void symbol_table( std::ostream& out, Elf_Xword no, std::string& name, Elf64_Addr value, Elf_Xword size, unsigned char bind, unsigned char type, Elf_Half section, unsigned int elf_class ) { std::ios_base::fmtflags original_flags = out.flags(); if ( elf_class == ELFCLASS32 ) { // Output for 32-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_HEX_FORMAT( 8 ) << value << " " << DUMP_HEX_FORMAT( 8 ) << size << " " << DUMP_STR_FORMAT( 7 ) << str_symbol_type( type ) << " " << DUMP_STR_FORMAT( 8 ) << str_symbol_bind( bind ) << " " << DUMP_DEC_FORMAT( 5 ) << section << " " << DUMP_STR_FORMAT( 1 ) << name << " " << std::endl; } else { // Output for 64-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_HEX_FORMAT( 16 ) << value << " " << DUMP_HEX_FORMAT( 16 ) << size << " " << DUMP_STR_FORMAT( 7 ) << str_symbol_type( type ) << " " << DUMP_STR_FORMAT( 8 ) << str_symbol_bind( bind ) << " " << DUMP_DEC_FORMAT( 5 ) << section << " " << std::endl << " " << DUMP_STR_FORMAT( 1 ) << name << " " << std::endl; } out.flags( original_flags ); } //------------------------------------------------------------------------------ static void notes( std::ostream& out, const elfio& reader ) { Elf_Half no = reader.sections.size(); for ( Elf_Half i = 0; i < no; ++i ) { // For all sections section* sec = reader.sections[i]; if ( SHT_NOTE == sec->get_type() ) { // Look at notes note_section_accessor notes( reader, sec ); Elf_Word no_notes = notes.get_notes_num(); if ( no > 0 ) { out << "Note section (" << sec->get_name() << ")" << std::endl << " No Type Name" << std::endl; for ( Elf_Word j = 0; j < no_notes; ++j ) { // For all notes Elf_Word type; std::string name; void* desc; Elf_Word descsz; if ( notes.get_note( j, type, name, desc, descsz ) ) { // 'name' usually contains \0 at the end. Try to fix it name = name.c_str(); note( out, j, type, name ); } } out << std::endl; } } } } //------------------------------------------------------------------------------ static void modinfo( std::ostream& out, const elfio& reader ) { Elf_Half no = reader.sections.size(); for ( Elf_Half i = 0; i < no; ++i ) { // For all sections section* sec = reader.sections[i]; if ( ".modinfo" == sec->get_name() ) { // Look for the section out << "Section .modinfo" << std::endl; const_modinfo_section_accessor modinfo( sec ); for ( Elf_Word i = 0; i < modinfo.get_attribute_num(); i++ ) { std::string field; std::string value; if ( modinfo.get_attribute( i, field, value ) ) { out << " " << std::setw( 20 ) << field << std::setw( 0 ) << " = " << value << std::endl; } } out << std::endl; break; } } } //------------------------------------------------------------------------------ static void note( std::ostream& out, int no, Elf_Word type, const std::string& name ) { out << " [" << DUMP_DEC_FORMAT( 2 ) << no << "] " << DUMP_HEX_FORMAT( 8 ) << type << " " << DUMP_STR_FORMAT( 1 ) << name << std::endl; } //------------------------------------------------------------------------------ static void dynamic_tags( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.sections.size(); for ( Elf_Half i = 0; i < n; ++i ) { // For all sections section* sec = reader.sections[i]; if ( SHT_DYNAMIC == sec->get_type() ) { dynamic_section_accessor dynamic( reader, sec ); Elf_Xword dyn_no = dynamic.get_entries_num(); if ( dyn_no > 0 ) { out << "Dynamic section (" << sec->get_name() << ")" << std::endl; out << "[ Nr ] Tag Name/Value" << std::endl; for ( Elf_Xword i = 0; i < dyn_no; ++i ) { Elf_Xword tag = 0; Elf_Xword value = 0; std::string str; dynamic.get_entry( i, tag, value, str ); dynamic_tag( out, i, tag, value, str, reader.get_class() ); if ( DT_NULL == tag ) { break; } } out << std::endl; } } } } //------------------------------------------------------------------------------ static void dynamic_tag( std::ostream& out, Elf_Xword no, Elf_Xword tag, Elf_Xword value, std::string str, unsigned int /*elf_class*/ ) { out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 16 ) << str_dynamic_tag( tag ) << " "; if ( str.empty() ) { out << DUMP_HEX_FORMAT( 16 ) << value << " "; } else { out << DUMP_STR_FORMAT( 32 ) << str << " "; } out << std::endl; } //------------------------------------------------------------------------------ static void section_data( std::ostream& out, const section* sec ) { std::ios_base::fmtflags original_flags = out.flags(); out << sec->get_name() << std::endl; const char* pdata = sec->get_data(); if ( pdata ) { ELFIO::Elf_Xword i; for ( i = 0; i < std::min( sec->get_size(), MAX_DATA_ENTRIES ); ++i ) { if ( i % 16 == 0 ) { out << "[" << DUMP_HEX_FORMAT( 8 ) << i << "]"; } out << " " << DUMP_HEX_FORMAT( 2 ) << ( pdata[i] & 0x000000FF ); if ( i % 16 == 15 ) { out << std::endl; } } if ( i % 16 != 0 ) { out << std::endl; } out.flags( original_flags ); } return; } //------------------------------------------------------------------------------ static void section_datas( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.sections.size(); if ( n == 0 ) { return; } out << "Section Data:" << std::endl; for ( Elf_Half i = 1; i < n; ++i ) { // For all sections section* sec = reader.sections[i]; if ( sec->get_type() == SHT_NOBITS ) { continue; } section_data( out, sec ); } out << std::endl; } //------------------------------------------------------------------------------ static void segment_data( std::ostream& out, Elf_Half no, const segment* seg ) { std::ios_base::fmtflags original_flags = out.flags(); out << "Segment # " << no << std::endl; const char* pdata = seg->get_data(); if ( pdata ) { ELFIO::Elf_Xword i; for ( i = 0; i < std::min( seg->get_file_size(), MAX_DATA_ENTRIES ); ++i ) { if ( i % 16 == 0 ) { out << "[" << DUMP_HEX_FORMAT( 8 ) << i << "]"; } out << " " << DUMP_HEX_FORMAT( 2 ) << ( pdata[i] & 0x000000FF ); if ( i % 16 == 15 ) { out << std::endl; } } if ( i % 16 != 0 ) { out << std::endl; } out.flags( original_flags ); } return; } //------------------------------------------------------------------------------ static void segment_datas( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.segments.size(); if ( n == 0 ) { return; } out << "Segment Data:" << std::endl; for ( Elf_Half i = 0; i < n; ++i ) { // For all sections segment* seg = reader.segments[i]; segment_data( out, i, seg ); } out << std::endl; } private: //------------------------------------------------------------------------------ template std::string static find_value_in_table( const T& table, const K& key ) { std::string res = "?"; for ( unsigned int i = 0; i < sizeof( table ) / sizeof( table[0] ); ++i ) { if ( table[i].key == key ) { res = table[i].str; break; } } return res; } //------------------------------------------------------------------------------ template static std::string format_assoc( const T& table, const K& key ) { std::string str = find_value_in_table( table, key ); if ( str == "?" ) { std::ostringstream oss; oss << str << " (0x" << std::hex << key << ")"; str = oss.str(); } return str; } //------------------------------------------------------------------------------ template static std::string format_assoc( const T& table, const char key ) { return format_assoc( table, (const int)key ); } //------------------------------------------------------------------------------ static std::string section_flags( Elf_Xword flags ) { std::string ret = ""; if ( flags & SHF_WRITE ) { ret += "W"; } if ( flags & SHF_ALLOC ) { ret += "A"; } if ( flags & SHF_EXECINSTR ) { ret += "X"; } return ret; } //------------------------------------------------------------------------------ #define STR_FUNC_TABLE( name ) \ template static std::string str_##name( const T key ) \ { \ return format_assoc( name##_table, key ); \ } STR_FUNC_TABLE( class ) STR_FUNC_TABLE( endian ) STR_FUNC_TABLE( version ) STR_FUNC_TABLE( type ) STR_FUNC_TABLE( machine ) STR_FUNC_TABLE( section_type ) STR_FUNC_TABLE( segment_type ) STR_FUNC_TABLE( segment_flag ) STR_FUNC_TABLE( symbol_bind ) STR_FUNC_TABLE( symbol_type ) STR_FUNC_TABLE( dynamic_tag ) #undef STR_FUNC_TABLE #undef DUMP_DEC_FORMAT #undef DUMP_HEX_FORMAT #undef DUMP_STR_FORMAT }; // class dump }; // namespace ELFIO #endif // ELFIO_DUMP_HPP /*** End of inlined file: elfio_dump.hpp ***/ libkylin-nm-base/tests/kt-test-utils/cpp-stub/stub.h0000664000175000017500000002340715160517205021423 0ustar fengfeng#ifndef __STUB_H__ #define __STUB_H__ #ifdef _WIN32 //windows #include #include #else //linux #include #include #include #endif //c #include #include //c++ #include #define ADDR(CLASS_NAME,MEMBER_NAME) (&CLASS_NAME::MEMBER_NAME) /********************************************************** replace function **********************************************************/ #ifdef _WIN32 #define CACHEFLUSH(addr, size) FlushInstructionCache(GetCurrentProcess(), addr, size) #else #define CACHEFLUSH(addr, size) __builtin___clear_cache(addr, addr + size) #endif #if defined(__aarch64__) || defined(_M_ARM64) #define CODESIZE 16U #define CODESIZE_MIN 16U #define CODESIZE_MAX CODESIZE // ldr x9, +8 // br x9 // addr #define REPLACE_FAR(t, fn, fn_stub)\ ((uint32_t*)fn)[0] = 0x58000040 | 9;\ ((uint32_t*)fn)[1] = 0xd61f0120 | (9 << 5);\ *(long long *)(fn + 8) = (long long )fn_stub;\ CACHEFLUSH((char *)fn, CODESIZE); #define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub) #elif defined(__arm__) || defined(_M_ARM) #define CODESIZE 8U #define CODESIZE_MIN 8U #define CODESIZE_MAX CODESIZE // ldr pc, [pc, #-4] #define REPLACE_FAR(t, fn, fn_stub)\ ((uint32_t*)fn)[0] = 0xe51ff004;\ ((uint32_t*)fn)[1] = (uint32_t)fn_stub;\ CACHEFLUSH((char *)fn, CODESIZE); #define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub) #elif defined(__mips64) #define CACHEFLUSH(addr, size) __builtin___clear_cache(addr, addr + size) #define CODESIZE 80U #define CODESIZE_MIN 80U #define CODESIZE_MAX CODESIZE //mips没有PC指针,所以需要手动入栈出栈 //120000ce0: 67bdffe0 daddiu sp, sp, -32 //入栈 //120000ce4: ffbf0018 sd ra, 24(sp) //120000ce8: ffbe0010 sd s8, 16(sp) //120000cec: ffbc0008 sd gp, 8(sp) //120000cf0: 03a0f025 move s8, sp //120000d2c: 03c0e825 move sp, s8 //出栈 //120000d30: dfbf0018 ld ra, 24(sp) //120000d34: dfbe0010 ld s8, 16(sp) //120000d38: dfbc0008 ld gp, 8(sp) //120000d3c: 67bd0020 daddiu sp, sp, 32 //120000d40: 03e00008 jr ra #define REPLACE_FAR(t, fn, fn_stub)\ ((uint32_t *)fn)[0] = 0x67bdffe0;\ ((uint32_t *)fn)[1] = 0xffbf0018;\ ((uint32_t *)fn)[2] = 0xffbe0010;\ ((uint32_t *)fn)[3] = 0xffbc0008;\ ((uint32_t *)fn)[4] = 0x03a0f025;\ *(uint16_t *)(fn + 20) = (long long)fn_stub >> 32;\ *(fn + 22) = 0x19;\ *(fn + 23) = 0x24;\ ((uint32_t *)fn)[6] = 0x0019cc38;\ *(uint16_t *)(fn + 28) = (long long)fn_stub >> 16;\ *(fn + 30) = 0x39;\ *(fn + 31) = 0x37;\ ((uint32_t *)fn)[8] = 0x0019cc38;\ *(uint16_t *)(fn + 36) = (long long)fn_stub;\ *(fn + 38) = 0x39;\ *(fn + 39) = 0x37;\ ((uint32_t *)fn)[10] = 0x0320f809;\ ((uint32_t *)fn)[11] = 0x00000000;\ ((uint32_t *)fn)[12] = 0x00000000;\ ((uint32_t *)fn)[13] = 0x03c0e825;\ ((uint32_t *)fn)[14] = 0xdfbf0018;\ ((uint32_t *)fn)[15] = 0xdfbe0010;\ ((uint32_t *)fn)[16] = 0xdfbc0008;\ ((uint32_t *)fn)[17] = 0x67bd0020;\ ((uint32_t *)fn)[18] = 0x03e00008;\ ((uint32_t *)fn)[19] = 0x00000000;\ CACHEFLUSH((char *)fn, CODESIZE); #define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub) #elif defined(__thumb__) || defined(_M_THUMB) #error "Thumb is not supported" #else //__i386__ _x86_64__ #define CODESIZE 13U #define CODESIZE_MIN 5U #define CODESIZE_MAX CODESIZE //13 byte(jmp m16:64) //movabs $0x102030405060708,%r11 //jmpq *%r11 static void REPLACE_FAR(void *t, char *fn, char *fn_stub) { *fn = 0x49; *(fn + 1) = 0xbb; *(long long *)(fn + 2) = (long long)fn_stub; *(fn + 10) = 0x41; *(fn + 11) = 0xff; *(fn + 12) = 0xe3; CACHEFLUSH((char *)fn, CODESIZE); } //5 byte(jmp rel32) #define REPLACE_NEAR(t, fn, fn_stub)\ *fn = 0xE9;\ *(int *)(fn + 1) = (int)(fn_stub - fn - CODESIZE_MIN);\ CACHEFLUSH((char *)fn, CODESIZE); #endif struct func_stub { char *fn; unsigned char code_buf[CODESIZE]; bool far_jmp; }; class Stub { public: Stub() { #ifdef _WIN32 SYSTEM_INFO sys_info; GetSystemInfo(&sys_info); m_pagesize = sys_info.dwPageSize; #else m_pagesize = sysconf(_SC_PAGE_SIZE); #endif if (m_pagesize < 0) { m_pagesize = 4096; } } ~Stub() { clear(); } virtual void clear() { std::map::iterator iter; struct func_stub *pstub; for(iter=m_result.begin(); iter != m_result.end(); iter++) { pstub = iter->second; #ifdef _WIN32 DWORD lpflOldProtect; if(0 != VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READWRITE, &lpflOldProtect)) #else if (0 == mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_WRITE | PROT_EXEC)) #endif { if(pstub->far_jmp) { std::memcpy(pstub->fn, pstub->code_buf, CODESIZE_MAX); } else { std::memcpy(pstub->fn, pstub->code_buf, CODESIZE_MIN); } #ifdef _WIN32 VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READ, &lpflOldProtect); #else CACHEFLUSH(pstub->fn,CODESIZE); mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_EXEC); #endif } iter->second = NULL; delete pstub; } m_result.clear(); return; } template bool set(T addr, S addr_stub) { char * fn; char * fn_stub; fn = addrof(addr); fn_stub = addrof(addr_stub); struct func_stub *pstub; std::map::iterator iter = m_result.find(fn); if (iter == m_result.end()) { pstub = new func_stub; //start pstub->fn = fn; if(distanceof(fn, fn_stub)) { pstub->far_jmp = true; std::memcpy(pstub->code_buf, fn, CODESIZE_MAX); } else { pstub->far_jmp = false; std::memcpy(pstub->code_buf, fn, CODESIZE_MIN); } } else { pstub = iter->second; pstub->far_jmp = distanceof(fn, fn_stub); } #ifdef _WIN32 DWORD lpflOldProtect; if(0 == VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READWRITE, &lpflOldProtect)) #else if (-1 == mprotect(pageof(pstub->fn), static_cast(m_pagesize * 2), PROT_READ | PROT_WRITE | PROT_EXEC)) #endif { throw("stub set memory protect to w+r+x faild"); return false; } if(pstub->far_jmp) { REPLACE_FAR(this, fn, fn_stub); } else { REPLACE_NEAR(this, fn, fn_stub); } #ifdef _WIN32 if(0 == VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READ, &lpflOldProtect)) #else if (-1 == mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_EXEC)) #endif { throw("stub set memory protect to r+x failed"); return false; } m_result.insert(std::pair(fn,pstub)); return true; } template bool reset(T addr) { char * fn; fn = addrof(addr); std::map::iterator iter = m_result.find(fn); if (iter == m_result.end()) { return true; } struct func_stub *pstub; pstub = iter->second; #ifdef _WIN32 DWORD lpflOldProtect; if(0 == VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READWRITE, &lpflOldProtect)) #else if (-1 == mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_WRITE | PROT_EXEC)) #endif { throw("stub reset memory protect to w+r+x faild"); return false; } if(pstub->far_jmp) { std::memcpy(pstub->fn, pstub->code_buf, CODESIZE_MAX); } else { std::memcpy(pstub->fn, pstub->code_buf, CODESIZE_MIN); } #ifdef _WIN32 if(0 == VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READ, &lpflOldProtect)) #else CACHEFLUSH(pstub->fn,CODESIZE); if (-1 == mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_EXEC)) #endif { throw("stub reset memory protect to r+x failed"); return false; } m_result.erase(iter); delete pstub; return true; } protected: char *pageof(char* addr) { #ifdef _WIN32 return (char *)((unsigned long long)addr & ~(m_pagesize - 1)); #else return (char *)((unsigned long)addr & ~(m_pagesize - 1)); #endif } template char* addrof(T addr) { union { T _s; char* _d; }ut; ut._s = addr; return ut._d; } bool distanceof(char* addr, char* addr_stub) { std::ptrdiff_t diff = addr_stub >= addr ? addr_stub - addr : addr - addr_stub; if((sizeof(addr) > 4) && (((diff >> 31) - 1) > 0)) { return true; } return false; } protected: #ifdef _WIN32 //LLP64 long long m_pagesize; #else //LP64 long m_pagesize; #endif std::map m_result; }; #endif libkylin-nm-base/tests/kt-test-utils/cpp-stub-ext/0000775000175000017500000000000015160517205021065 5ustar fengfenglibkylin-nm-base/tests/kt-test-utils/cpp-stub-ext/stubext.h0000664000175000017500000000734115160517205022741 0ustar fengfeng #ifndef STUBEXT_H #define STUBEXT_H /* * Author: Zhang Yu * Maintainer: Zhang Yu * * MIT License * * Copyright (c) 2020 Zhang Yu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ //需修改Stub的私用成员函数和成员变量为保护类型 #include "stub.h" #include "stub-shadow.h" #ifdef DEBUG_STUB_INVOKE // use to make sure the stub function is invoked. # define __DBG_STUB_INVOKE__ printf("stub at %s:%d is invoked.\n", __FILE__, __LINE__); #else # define __DBG_STUB_INVOKE__ #endif #define VADDR(CLASS_NAME, MEMBER_NAME) (typename stub_ext::VFLocator::Func)(&CLASS_NAME::MEMBER_NAME) namespace stub_ext { class StubExt : public Stub { public: StubExt() : Stub() { } template bool set_lamda(T addr, Lamda lamda) { char *fn = addrof(addr); if (m_result.find(fn) != m_result.end()) reset(addr); Wrapper *wrapper = nullptr; auto addr_stub = depictShadow(&wrapper, addr, lamda); if (set(addr, addr_stub)) { m_wrappers.insert(std::make_pair(fn, wrapper)); return true; } else { freeWrapper(wrapper); } return false; } template void reset(T addr) { Stub::reset(addr); char *fn = addrof(addr); auto iter = m_wrappers.find(fn); if (iter != m_wrappers.end()) { freeWrapper(iter->second); m_wrappers.erase(iter); } } ~StubExt() { clear(); } void clear() override { Stub::clear(); for (auto iter = m_wrappers.begin(); iter != m_wrappers.end(); ++iter) { freeWrapper(iter->second); } m_wrappers.clear(); } template static void *get_ctor_addr(bool start = true) { // the start vairable must be true, or the compiler will optimize out. if (start) goto Start; Call_Constructor: // This line of code will not be executed. // The purpose of the code is to allow the compiler to generate the assembly code that calls the constructor. T(); Start: // The address of the line of code T() obtained by assembly char *p = (char *)&&Call_Constructor; // https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html // CALL rel32 void *ret = 0; char pos; char call = 0xe8; do { pos = *p; if (pos == call) { ret = p + 5 + (*(int *)(p + 1)); } } while (!ret && (++p)); return ret; } protected: std::map m_wrappers; }; } #endif // STUBEXT_H libkylin-nm-base/tests/kt-test-utils/cpp-stub-ext/stub-shadow.cpp0000664000175000017500000000315015160517205024030 0ustar fengfeng/* * Author: Zhang Yu * Maintainer: Zhang Yu * * MIT License * * Copyright (c) 2020 Zhang Yu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "stub-shadow.h" namespace stub_ext { WrapperMap stub_wrappers; Wrapper::Wrapper() { } Wrapper::~Wrapper() { } void freeWrapper(Wrapper *wrapper) { if (!wrapper) return; for (auto iter = stub_wrappers.begin(); iter != stub_wrappers.end();) { if (iter->second == wrapper) iter = stub_wrappers.erase(iter); else ++iter; } delete wrapper; } } libkylin-nm-base/tests/kt-test-utils/cpp-stub-ext/stub-shadow.h0000664000175000017500000001143415160517205023501 0ustar fengfeng #ifndef STUBSHADOW_H #define STUBSHADOW_H /* * Author: Zhang Yu * Maintainer: Zhang Yu * * MIT License * * Copyright (c) 2020 Zhang Yu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include namespace stub_ext { #define LAMDA_FUNCTION_TYPE decltype(&Lamda::operator()) class Wrapper { public: Wrapper(); virtual ~Wrapper(); }; typedef std::unordered_map WrapperMap; extern WrapperMap stub_wrappers; template class LamdaWrapper : public Wrapper { public: LamdaWrapper(Lamda func): Wrapper(),_func(func){} ~LamdaWrapper(){} Lamda _func; }; template struct VFLocator { }; template struct VFLocator { typedef Ret (*Func)(Obj*, Args...); }; template struct VFLocator { typedef Ret (*Func)(Obj*, Args...); }; template struct LamdaCaller { }; template struct LamdaCaller { template static Ret call(LamdaWrapper *wrapper, OrgArgs&&... args) { return wrapper->_func(std::forward(args)...); } }; template struct LamdaCaller { template static Ret call(LamdaWrapper *wrapper, OrgArgs&&... args) { return wrapper->_func(); } }; template struct FuncShadow { }; template struct FuncShadow { typedef Ret (*Shadow)(Args...); typedef Ret RetType; static Ret call(Args ...args) { Shadow shadow = &call; long id = (long)shadow; auto iter = stub_wrappers.find(id); assert(stub_wrappers.find(id) != stub_wrappers.end()); LamdaWrapper *wrapper = dynamic_cast *>(iter->second); return LamdaCaller::call(wrapper, args...); } }; template struct FuncShadow { typedef Ret (*Shadow)(Obj *,Args...); typedef Ret RetType; static Ret call(Obj *obj, Args ...args) { Shadow shadow = &call; long id = (long)shadow; auto iter = stub_wrappers.find(id); assert(stub_wrappers.find(id) != stub_wrappers.end()); LamdaWrapper *wrapper = dynamic_cast *>(iter->second); return LamdaCaller::call(wrapper, obj, args...); } }; template struct FuncShadow { typedef Ret (*Shadow)(Obj *,Args...); typedef Ret RetType; static Ret call(Obj *obj, Args ...args) { Shadow shadow = &call; long id = (long)shadow; auto iter = stub_wrappers.find(id); assert(stub_wrappers.find(id) != stub_wrappers.end()); LamdaWrapper *wrapper = dynamic_cast *>(iter->second); return LamdaCaller::call(wrapper, obj, args...); } }; template typename FuncShadow::Shadow depictShadow(Wrapper **wrapper, Func func, Lamda lamda) { *wrapper = new LamdaWrapper(lamda); typename FuncShadow::Shadow shadow = &FuncShadow::call; long id = (long)shadow; assert(stub_wrappers.find(id) == stub_wrappers.end()); stub_wrappers.insert(std::make_pair(id,*wrapper)); return shadow; } void freeWrapper(Wrapper *wrapper); } #endif // STUBSHADOW_H libkylin-nm-base/tests/unit_test_wired/0000775000175000017500000000000015160517431017212 5ustar fengfenglibkylin-nm-base/tests/unit_test_wired/unit_test_wired.cpp0000664000175000017500000001466115160517205023135 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include "../../libnm-kylin/libnm-base-kylin/kylinnetworkmanager.h" #include "stubext.h" using namespace stub_ext; class NetWiredTest : public testing::Test { protected: static void SetUpTestSuite() { thread = new QThread; manager = new KyNetworkManager(); manager->moveToThread(thread); QObject::connect(thread, &QThread::started, manager, &KyNetworkManager::kylinNetworkManagerInit); QObject::connect(thread, &QThread::finished, manager, &KyNetworkManager::deleteLater); QObject::connect(thread, &QThread::finished, [=](){ qDebug() << "NetConnect thread quit"; }); thread->start(); sleep(2); } static void TearDownTestSuite() { if (thread) { thread->quit(); thread->wait(); delete thread; } } static KyNetworkManager *manager; static QThread *thread; static KyWiredConnectOperation* moperate; }; KyNetworkManager *NetWiredTest::manager = nullptr; QThread *NetWiredTest::thread = nullptr; KyWiredConnectOperation *NetWiredTest::moperate=nullptr; TEST_F(NetWiredTest, getWireDevice) { KyConnectStatus connectType; QMap> map; if (!manager) { return; } bool bEnable=manager->getNetworkingEnabled(); EXPECT_TRUE(bEnable); bEnable=manager->getWiredEnabled(); manager->getConnectStatus(connectType); //ASSERT_EQ(newValue, false); QStringList wiredDevList; wiredDevList.clear(); manager->getNetworkDeviceList(DEVICE_TYPE_ETHERNET, wiredDevList); EXPECT_FALSE(wiredDevList.isEmpty()); qDebug() << wiredDevList; printf("3333\n"); if (!wiredDevList.isEmpty()) { for (int i = 0; i < wiredDevList.size(); ++i) { KyConnectivity connectivity; QString devName = wiredDevList.at(i); KyWirelessConnectSetting connetSetting; connetSetting.setIfaceName(devName); connetSetting.setIpConfigType(IPADDRESS_V4, CONFIG_IP_DHCP); connetSetting.m_connectName=QString("mqtest"); moperate->createWiredConnect(connetSetting); //manager->onCreateWiredConnect(connetSetting); qDebug() << devName; if( manager->getDeviceManaged(devName)) { manager->getDeviceState(devName); manager->getDeviceConnectivity(devName,connectivity); } } } } TEST_F(NetWiredTest, WireConnect) { QMap> map; KyConnectOperation operate; KyConnectSetting connectSetting; KyDetailInfo detailConnectSetting; QList connectItemList; if (!manager) { return; } manager->getWiredList(map); EXPECT_FALSE(map.isEmpty()); QMap >::iterator iter = map.begin(); while (iter != map.end()) { QListlistCon =iter.value(); manager->getActiveConnectionList(iter.key(),CONNECT_TYPE_WIRED, connectItemList); qDebug() <<"device name "<getWiredConnectDetail(iter.key(),listCon.at(i).m_connectUuid,detailConnectSetting); manager->getConnectIpInfo(listCon.at(i).m_connectUuid,connectSetting); if(listCon.at(i).m_connectName==QString("mqtest")) { manager->onDeactivateConnection(listCon.at(i).m_connectUuid); manager->onDeactivateConnection(listCon.at(i).m_connectUuid); manager->onDeleteConnect(listCon.at(i).m_connectUuid); } } iter++; } } TEST_F(NetWiredTest, getWirelessList) { KyConnectStatus connectType; KyConnectSetting connectSetting; KyDetailInfo detailConnectSetting; KyWpaPasswordInfo wpainfo; KyEapMethodLeapInfo leapinfo; KyEapMethodPeapInfo peapinfo; KyEapMethodTtlsInfo ttlsinfo; if (!manager) { return; } bool bEnable=manager->getNetworkingEnabled(); EXPECT_TRUE(bEnable); bEnable=manager->getWirelessEnabled(); manager->getConnectStatus(connectType); manager->onRequestWirelessScan(); //ASSERT_EQ(newValue, false); QStringList wirelessDevList; wirelessDevList.clear(); manager->getNetworkDeviceList(DEVICE_TYPE_WIFI, wirelessDevList); EXPECT_FALSE(wirelessDevList.isEmpty()); manager->getAcivateWifiSignal(); qDebug() << wirelessDevList; if (!wirelessDevList.isEmpty()) { QList list; for (int i = 0; i < wirelessDevList.size(); ++i) { QString devName = wirelessDevList.at(i); qDebug() << devName; if( manager->getDeviceManaged(devName)) { manager->getWifiNetworkList(devName, list); if(!list.isEmpty()) { manager->getWirelessConnectDetail(devName, list.at(0).m_NetSsid,list.at(0).m_connectUuid,detailConnectSetting); QString uuid=list.at(0).m_connectUuid; manager->getNormalWifiConnectSecuInfo(uuid, wpainfo); manager->getEnterPriseInfoPeap(uuid, peapinfo); manager->getEnterPriseInfoTtls(uuid, ttlsinfo); manager->getEnterPriseInfoLeap(uuid, leapinfo); qDebug() << list.at(0).m_NetSsid<getConnectIpInfo(list.at(0).m_connectUuid,connectSetting); } } } } } libkylin-nm-base/tests/unit_test_wired/main.cpp0000664000175000017500000000175415160517205020650 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } libkylin-nm-base/tests/unit_test_wired/unit_test_wired.pro0000664000175000017500000001033215160517205023142 0ustar fengfeng#------------------------------------------------- # # Project created by QtCreator 2019-08-22T11:12:59 # #------------------------------------------------- QT += core dbus xml network QT -= gui #greaterThan(QT_MAJOR_VERSION, 4): QT += widgets concurrent sql xml TEMPLATE = app TARGET = unit_test_wired target.source += $$TARGET target.path = ./ #代码覆盖率工具gcov QMAKE_LFLAGS +=-fprofile-arcs -ftest-coverage QMAKE_CXXFLAGS += --coverage -fno-inline -fno-access-control -fno-exceptions LIBS += -lgtest_main -lpthread LIBS += -L$$[QT_INSTALL_LIBS] -lgtest -lgcov -ldconf LIBS += -L/usr/lib/ -lKF6NetworkManagerQt #OBJECTS_DIR = ./obj #MOC_DIR = ./moc CONFIG += c++11 qt warn_on no_keywords CONFIG += create_pc create_prl no_install_prl CONFIG += link_pkgconfig PKGCONFIG += gsettings-qt6 \ gio-2.0 \ libnm \ gtk+-3.0 \ INCLUDEPATH += /usr/include/dconf INCLUDEPATH += /usr/include/KF6/NetworkManagerQt INCLUDEPATH += /usr/include/dbus-1.0/dbus #打桩工具 TEST_UTILS_PATH = $$PWD/../kt-test-utils # Include directories INCLUDEPATH += $$PROJECT_ROOTDIR \ $$TEST_UTILS_PATH/cpp-stub \ $$TEST_UTILS_PATH/cpp-stub-ext \ SOURCES += ../../libnm-kylin/libnm-base-kylin/kylinnetworkmanger.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kyapnetresource.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kyenterpricesettinginfo.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kylinactiveconnectresource.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kylinconnectoperation.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kylinconnectsetting.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kylingeneral.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kylinnetresource.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kylinnetworkdeviceresource.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kylinnetworkmanagerutil.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kynetloadratethread.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcemanager.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kylinwiredconnectoperation.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kylinwirednetresource.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kywirelessconnectoperation.cpp \ ../../libnm-kylin/libnm-base-kylin/depend/kywirelessnetresource.cpp \ unit_test_wired.cpp \ main.cpp HEADERS += ../../libnm-kylin/libnm-base-kylin/kylinnetworkmanager.h \ ../../libnm-kylin/libnm-base-kylin/depend/kynetloadratethread.h \ ../../libnm-kylin/libnm-base-kylin/libnm-base-kylin_global.h \ ../../libnm-kylin/libnm-base-kylin/kylin-nm-interface.h \ ../../libnm-kylin/libnm-base-kylin/depend/kyapnetresource.h \ ../../libnm-kylin/libnm-base-kylin/depend/kyenterpricesettinginfo.h \ ../../libnm-kylin/libnm-base-kylin/depend/kylinactiveconnectresource.h \ ../../libnm-kylin/libnm-base-kylin/depend/kylinapconnectitem.h \ ../../libnm-kylin/libnm-base-kylin/depend/kylinconnectitem.h \ ../../libnm-kylin/libnm-base-kylin/depend/kylinconnectoperation.h \ ../../libnm-kylin/libnm-base-kylin/depend/kylinconnectsetting.h \ ../../libnm-kylin/libnm-base-kylin/depend/kylingeneral.h \ ../../libnm-kylin/libnm-base-kylin/depend/kylinnetresource.h \ ../../libnm-kylin/libnm-base-kylin/depend/kylinnetworkdeviceresource.h \ ../../libnm-kylin/libnm-base-kylin/depend/kylinnetworkmanagerutil.h \ ../../libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcemanager.h \ ../../libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcetype.h \ ../../libnm-kylin/libnm-base-kylin/depend/kylinwiredconnectoperation.h \ ../../libnm-kylin/libnm-base-kylin/depend/kylinwirednetresource.h \ ../../libnm-kylin/libnm-base-kylin/depend/kywirelessconnectoperation.h \ ../../libnm-kylin/libnm-base-kylin/depend/kywirelessnetitem.h \ ../../libnm-kylin/libnm-base-kylin/depend/kywirelessnetresource.h libkylin-nm-base/tests/tests.pro0000664000175000017500000000064615160517205015673 0ustar fengfengTEMPLATE = subdirs SUBDIRS = unit_test_wired # 打桩工具 # Define paths TEST_UTILS_PATH = $$PWD/kt-test-utils # Header files (if needed) HEADERS += $$files($$TEST_UTILS_PATH/cpp-stub/*.h $$TEST_UTILS_PATH/cpp-stub/*.hpp) \ $$files($$TEST_UTILS_PATH/cpp-stub-ext/*.h) # Gather source files SOURCES += $$files($$TEST_UTILS_PATH/cpp-stub/*.cpp) \ $$files($$TEST_UTILS_PATH/cpp-stub-ext/*.cpp) libkylin-nm-base/tests/auto_test.sh0000664000175000017500000000272515160517205016352 0ustar fengfeng#!/bin/bash # 设置退出脚本当命令失败时 (非零退出状态) #set -e # 函数:运行单元测试 run_unit_tests() { local pattern="unit_test_*" # 遍历所有匹配模式的目录 for dir in $pattern; do if [ -d "$dir" ] && [ -x "$dir/$(basename "$dir")" ]; then echo "Running tests in $dir and Collecting coverage data..." # 收集代码覆盖率数据 (cd "$dir" && "./$(basename "$dir")" && (find ./ -name '*.o' | xargs gcov --preserve-paths)) else echo "Skipping non-existent or non-executable directory: $dir, $dir/$(basename "$dir")" fi done } # 上传 result.zip 到平台 upload_result() { echo "current pwd : $(pwd)" # 收集覆盖率信息 lcov -d . -c -o r.info # 删除不需要的文件或路径 lcov -r r.info "$(pwd)/unit_test_*" "$(pwd)/../registeredSession/universalinterface.cpp" "/usr/include/*" "/opt/*" -o coverage.info # 生成html覆盖率报告 genhtml "$(pwd)/coverage.info" -o result # 打包 zip -r result.zip result # 上传平台 curl --insecure -X POST -F "file=@/$(pwd)/result.zip" -F "package=ukui-control-center" -F "username=$1" $2 echo "all parameter : $@" } # 编译项目 echo "Compiling the project..." qmake && make # 运行各个单元测试 echo "Running unit tests..." run_unit_tests # 上传到平台 #upload_result echo "All tests have been run successfully, and coverage data has been collected."