diff --git a/core/smb4kauthinfo.cpp b/core/smb4kauthinfo.cpp index eb29b99..e96a2da 100644 --- a/core/smb4kauthinfo.cpp +++ b/core/smb4kauthinfo.cpp @@ -1,296 +1,280 @@ /*************************************************************************** This class provides a container for the authentication data. ------------------- begin : Sa Feb 28 2004 copyright : (C) 2004-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kauthinfo.h" // Qt includes #include #include // KDE includes #include class Smb4KAuthInfoPrivate { public: QUrl url; QString workgroup; NetworkItem type; bool homesShare; QHostAddress ip; }; Smb4KAuthInfo::Smb4KAuthInfo(const Smb4KHost *host) : d(new Smb4KAuthInfoPrivate) { d->url = host->url(); d->type = Host; d->workgroup = host->workgroupName(); d->homesShare = false; d->ip.setAddress(host->ipAddress()); } Smb4KAuthInfo::Smb4KAuthInfo(const Smb4KShare *share) : d(new Smb4KAuthInfoPrivate) { if (!share->isHomesShare()) { d->url = share->url(); } else { d->url = share->homeUrl(); } d->type = Share; d->workgroup = share->workgroupName(); d->homesShare = share->isHomesShare(); d->ip.setAddress(share->hostIpAddress()); } Smb4KAuthInfo::Smb4KAuthInfo() : d(new Smb4KAuthInfoPrivate) { d->type = UnknownNetworkItem; d->homesShare = false; d->url.clear(); d->workgroup.clear(); d->ip.clear(); } Smb4KAuthInfo::Smb4KAuthInfo(const Smb4KAuthInfo &i) : d(new Smb4KAuthInfoPrivate) { *d = *i.d; } Smb4KAuthInfo::~Smb4KAuthInfo() { } void Smb4KAuthInfo::setHost(Smb4KHost *host) { Q_ASSERT(host); if (host) { d->url = host->url(); d->type = Host; d->workgroup = host->workgroupName(); d->homesShare = false; d->ip.setAddress(host->ipAddress()); } - else - { - // Do nothing - } } void Smb4KAuthInfo::setShare(Smb4KShare *share) { Q_ASSERT(share); if (share) { if (!share->isHomesShare()) { d->url = share->url(); } else { d->url = share->homeUrl(); } d->type = Share; d->workgroup = share->workgroupName(); d->homesShare = share->isHomesShare(); d->ip.setAddress(share->hostIpAddress()); } - else - { - // Do nothing - } } void Smb4KAuthInfo::setWorkgroupName(const QString &workgroup) { d->workgroup = workgroup; } QString Smb4KAuthInfo::workgroupName() const { return d->workgroup; } void Smb4KAuthInfo::setUrl(const QUrl &url) { d->url = url; d->url.setScheme("smb"); // Set the type. if (!d->url.path().isEmpty() && d->url.path().length() > 1 && !d->url.path().endsWith('/')) { d->type = Share; } else { d->type = Host; } // Determine whether this is a homes share. qDebug() << "Smb4KAuthInfo::setUrl(): Check if determination of homes share works"; d->homesShare = (QString::compare(d->url.path().remove(0, 1), "homes", Qt::CaseSensitive) == 0); } void Smb4KAuthInfo::setUrl(const QString &url) { d->url.setUrl(url, QUrl::TolerantMode); d->url.setScheme("smb"); // Set the type. if (!d->url.path().isEmpty() && d->url.path().length() > 1 && !d->url.path().endsWith('/')) { d->type = Share; } else { d->type = Host; } // Determine whether this is a homes share. qDebug() << "Smb4KAuthInfo::setUrl(): Check if determination of homes share works"; d->homesShare = (QString::compare(d->url.path().remove(0, 1), "homes", Qt::CaseSensitive) == 0); } QUrl Smb4KAuthInfo::url() const { return d->url; } QString Smb4KAuthInfo::hostName() const { return d->url.host().toUpper(); } QString Smb4KAuthInfo::shareName() const { if (d->url.path().startsWith('/')) { return d->url.path().remove(0, 1); } - else - { - // Do nothing - } return d->url.path(); } void Smb4KAuthInfo::setUserName(const QString &username) { d->url.setUserName(username); if (d->homesShare) { d->url.setPath(username); } - else - { - // Do nothing - } } QString Smb4KAuthInfo::userName() const { return d->url.userName(); } void Smb4KAuthInfo::setPassword(const QString &passwd) { d->url.setPassword(passwd); } QString Smb4KAuthInfo::password() const { return d->url.password(); } Smb4KGlobal::NetworkItem Smb4KAuthInfo::type() const { return d->type; } bool Smb4KAuthInfo::isHomesShare() const { return d->homesShare; } void Smb4KAuthInfo::setIpAddress(const QString &ip) { d->ip.setAddress(ip); } QString Smb4KAuthInfo::ipAddress() const { return d->ip.toString(); } QString Smb4KAuthInfo::displayString() const { return i18n("%1 on %2", shareName(), hostName()); } diff --git a/core/smb4kbasicnetworkitem.cpp b/core/smb4kbasicnetworkitem.cpp index 788fd89..af55d25 100644 --- a/core/smb4kbasicnetworkitem.cpp +++ b/core/smb4kbasicnetworkitem.cpp @@ -1,189 +1,173 @@ /*************************************************************************** This class provides the basic network item for the core library of Smb4K. ------------------- begin : Do Apr 2 2009 - copyright : (C) 2009-2017 by Alexander Reinholdt + copyright : (C) 2009-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kbasicnetworkitem.h" // Qt includes #include #include using namespace Smb4KGlobal; class Smb4KBasicNetworkItemPrivate { public: NetworkItem type; QIcon icon; QUrl url; }; Smb4KBasicNetworkItem::Smb4KBasicNetworkItem(NetworkItem type) : d(new Smb4KBasicNetworkItemPrivate) { // // Set the type // d->type = type; // // Initialize the protected variables // pUrl = &d->url; pIcon = &d->icon; } Smb4KBasicNetworkItem::Smb4KBasicNetworkItem(const Smb4KBasicNetworkItem &item) : d(new Smb4KBasicNetworkItemPrivate) { // // Copy the private variables // *d = *item.d; // // Initialize the protected variables // pUrl = &d->url; pIcon = &d->icon; } Smb4KBasicNetworkItem::~Smb4KBasicNetworkItem() { } Smb4KGlobal::NetworkItem Smb4KBasicNetworkItem::type() const { return d->type; } void Smb4KBasicNetworkItem::setIcon(const QIcon &icon) { d->icon = icon; } QIcon Smb4KBasicNetworkItem::icon() const { return d->icon; } void Smb4KBasicNetworkItem::setUrl(const QUrl& url) { // // Check that the URL is valid // if (!url.isValid()) { return; } - else - { - // Do nothing - } // // Do some checks depending on the type of the network item // switch (d->type) { case Network: { break; } case Workgroup: case Host: { // // Check that the host name is present and there is no path // if (url.host().isEmpty() || !url.path().isEmpty()) { return; } - else - { - // Do nothing - } break; } case Share: { // // Check that the share name is present // if (url.path().isEmpty() || (url.path().size() == 1 && url.path().endsWith('/'))) { return; } - else - { - // Do nothing - } break; } default: { break; } } // // Set the URL // d->url = url; // // Force the scheme // if (d->url.scheme() != "smb") { d->url.setScheme("smb"); } - else - { - // Do nothing - } } QUrl Smb4KBasicNetworkItem::url() const { return d->url; } diff --git a/core/smb4kbasicnetworkitem.h b/core/smb4kbasicnetworkitem.h index 0d2dc0a..7bcb4b9 100644 --- a/core/smb4kbasicnetworkitem.h +++ b/core/smb4kbasicnetworkitem.h @@ -1,121 +1,121 @@ /*************************************************************************** This class provides the basic network item for the core library of Smb4K. ------------------- begin : Do Apr 2 2009 - copyright : (C) 2009-2017 by Alexander Reinholdt + copyright : (C) 2009-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifndef SMB4KBASICNETWORKITEM_H #define SMB4KBASICNETWORKITEM_H // application specific includes #include "smb4kglobal.h" // Qt includes #include #include #include #include // forward declarations class Smb4KBasicNetworkItemPrivate; /** * This is the basic class from which all other network item classes * are derived. * * @author Alexander Reinholdt * @since 1.0.0 */ class Q_DECL_EXPORT Smb4KBasicNetworkItem { public: /** * The constructor */ explicit Smb4KBasicNetworkItem(Smb4KGlobal::NetworkItem type = Smb4KGlobal::UnknownNetworkItem); /** * The copy constructor */ Smb4KBasicNetworkItem(const Smb4KBasicNetworkItem &item); /** * The destructor */ ~Smb4KBasicNetworkItem(); /** * This function returns the type of the basic network * item. * * @returns the type. */ Smb4KGlobal::NetworkItem type() const; /** * This function sets the icon of the network item. * * @param icon The icon */ void setIcon(const QIcon &icon); /** * This function returns the icon of the network item. By default, it * is the null icon. You must set the appropriate icon either in * a class that inherits this one or from somewhere else. * * @returns the network item's icon. */ QIcon icon() const; /** * Set the URL for this network item. * * @param url The URL */ void setUrl(const QUrl &url); /** * Return the URL for this network item. * * @returns the URL */ QUrl url() const; protected: /** * Expose a pointer to the private URL variable. */ QUrl *pUrl; /** * Export a pointer to the private icon variable. */ QIcon *pIcon; private: const QScopedPointer d; }; #endif diff --git a/core/smb4kbookmark.cpp b/core/smb4kbookmark.cpp index 7be3057..eddcb63 100644 --- a/core/smb4kbookmark.cpp +++ b/core/smb4kbookmark.cpp @@ -1,253 +1,249 @@ /*************************************************************************** This is the bookmark container for Smb4K (next generation). ------------------- begin : So Jun 8 2008 copyright : (C) 2008-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kbookmark.h" #include "smb4kshare.h" // Qt includes #include #include // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include #include using namespace Smb4KGlobal; class Smb4KBookmarkPrivate { public: QUrl url; QString workgroup; QHostAddress ip; QString label; QString group; QString profile; QIcon icon; Smb4KGlobal::ShareType type; }; Smb4KBookmark::Smb4KBookmark(Smb4KShare *share, const QString &label) : d(new Smb4KBookmarkPrivate) { if (!share->isHomesShare()) { d->url = share->url(); } else { d->url = share->homeUrl(); } d->workgroup = share->workgroupName(); d->type = share->shareType(); d->label = label; d->icon = KDE::icon("folder-network"); d->ip.setAddress(share->hostIpAddress()); } Smb4KBookmark::Smb4KBookmark(const Smb4KBookmark &b) : d(new Smb4KBookmarkPrivate) { *d = *b.d; } Smb4KBookmark::Smb4KBookmark() : d(new Smb4KBookmarkPrivate) { d->type = FileShare; d->icon = KDE::icon("folder-network"); } Smb4KBookmark::~Smb4KBookmark() { } void Smb4KBookmark::setWorkgroupName( const QString &workgroup ) { d->workgroup = workgroup; } QString Smb4KBookmark::workgroupName() const { return d->workgroup; } void Smb4KBookmark::setHostName(const QString &host) { d->url.setHost(host); d->url.setScheme("smb"); } QString Smb4KBookmark::hostName() const { return d->url.host().toUpper(); } void Smb4KBookmark::setShareName(const QString &share) { d->url.setPath(share); } QString Smb4KBookmark::shareName() const { if (d->url.path().startsWith('/')) { return d->url.path().remove(0, 1); } - else - { - // Do nothing - } return d->url.path(); } void Smb4KBookmark::setHostIpAddress(const QString &ip) { d->ip.setAddress(ip); } QString Smb4KBookmark::hostIpAddress() const { return d->ip.toString(); } void Smb4KBookmark::setShareType(Smb4KGlobal::ShareType type) { d->type = type; } Smb4KGlobal::ShareType Smb4KBookmark::shareType() const { return d->type; } void Smb4KBookmark::setLabel(const QString &label) { d->label = label; } QString Smb4KBookmark::label() const { return d->label; } void Smb4KBookmark::setLogin(const QString &login) { d->url.setUserName(login); } QString Smb4KBookmark::login() const { return d->url.userName(); } void Smb4KBookmark::setUrl(const QUrl &url) { d->url = url; d->url.setScheme("smb"); } void Smb4KBookmark::setUrl(const QString &url) { d->url.setUrl(url, QUrl::TolerantMode); d->url.setScheme("smb"); } QUrl Smb4KBookmark::url() const { return d->url; } void Smb4KBookmark::setGroupName(const QString &name) { d->group = name; } QString Smb4KBookmark::groupName() const { return d->group; } void Smb4KBookmark::setProfile(const QString &profile) { d->profile = profile; } QString Smb4KBookmark::profile() const { return d->profile; } void Smb4KBookmark::setIcon(const QIcon &icon) { d->icon = icon; } QIcon Smb4KBookmark::icon() const { return d->icon; } QString Smb4KBookmark::displayString() const { return i18n("%1 on %2", shareName(), hostName()); } diff --git a/core/smb4kbookmarkhandler.cpp b/core/smb4kbookmarkhandler.cpp index 2a83d12..ca65c5b 100644 --- a/core/smb4kbookmarkhandler.cpp +++ b/core/smb4kbookmarkhandler.cpp @@ -1,791 +1,675 @@ /*************************************************************************** This class handles the bookmarks. ------------------- begin : Fr Jan 9 2004 copyright : (C) 2004-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kbookmarkhandler.h" #include "smb4kbookmarkhandler_p.h" #include "smb4khomesshareshandler.h" #include "smb4kglobal.h" #include "smb4kbookmark.h" #include "smb4khost.h" #include "smb4kshare.h" #include "smb4ksettings.h" #include "smb4knotification.h" #include "smb4kprofilemanager.h" // Qt includes #include #include #include #include #include #include #include #include #include // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include using namespace Smb4KGlobal; Q_GLOBAL_STATIC(Smb4KBookmarkHandlerStatic, p); Smb4KBookmarkHandler::Smb4KBookmarkHandler(QObject *parent) : QObject(parent), d(new Smb4KBookmarkHandlerPrivate) { // // First we need the directory. // QString path = dataLocation(); QDir dir; if (!dir.exists(path)) { dir.mkpath(path); } - else - { - // Do nothing - } // // Read the list of bookmarks // readBookmarkList(); // // Init the bookmark editor // d->editor = 0; } Smb4KBookmarkHandler::~Smb4KBookmarkHandler() { while (!d->bookmarks.isEmpty()) { d->bookmarks.takeFirst().clear(); } } Smb4KBookmarkHandler *Smb4KBookmarkHandler::self() { return &p->instance; } void Smb4KBookmarkHandler::addBookmark(const SharePtr &share) { if (share) { QList shares; shares << share; addBookmarks(shares); } - else - { - // Do nothing - } } void Smb4KBookmarkHandler::addBookmarks(const QList &list) { // // Prepare the list of bookmarks that should be added // QList newBookmarks; for (const SharePtr &share : list) { // // Printer shares cannot be bookmarked // if (share->isPrinter()) { Smb4KNotification::cannotBookmarkPrinter(share); continue; } - else - { - // Do nothing - } // // Process homes shares // if (share->isHomesShare()) { if (!Smb4KHomesSharesHandler::self()->specifyUser(share, true)) { continue; } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // Check if the share has already been bookmarked and skip it if it // already exists // BookmarkPtr knownBookmark = findBookmarkByUrl(share->isHomesShare() ? share->homeUrl() : share->url()); if (knownBookmark) { Smb4KNotification::bookmarkExists(knownBookmark.data()); continue; } - else - { - // Do nothing - } BookmarkPtr bookmark = BookmarkPtr(new Smb4KBookmark(share.data())); bookmark->setProfile(Smb4KProfileManager::self()->activeProfile()); newBookmarks << bookmark; } // // Show the bookmark dialog, if necessary // if (!newBookmarks.isEmpty()) { QPointer dlg = new Smb4KBookmarkDialog(newBookmarks, groupsList(), QApplication::activeWindow()); if (dlg->exec() == QDialog::Accepted) { // The bookmark dialog uses an internal list of bookmarks, // so use that one instead of the temporary list created // above. addBookmarks(dlg->bookmarks(), false); } - else - { - // Do nothing - } delete dlg; } - else - { - // Do nothing - } // // Clear the temporary list of bookmarks // while (!newBookmarks.isEmpty()) { newBookmarks.takeFirst().clear(); } } void Smb4KBookmarkHandler::addBookmarks(const QList &list, bool replace) { // // Process the incoming list. // In case the internal list should be replaced, clear the internal // list first. // if (replace) { QMutableListIterator it(d->bookmarks); while (it.hasNext()) { BookmarkPtr bookmark = it.next(); if (Smb4KSettings::useProfiles() && bookmark->profile() != Smb4KProfileManager::self()->activeProfile()) { continue; } - else - { - // Do nothing - } it.remove(); } } - else - { - // Do nothing - } // // Copy all bookmarks that are not in the list // for (const BookmarkPtr &bookmark : list) { // // Check if the bookmark label is already in use // if (!bookmark->label().isEmpty() && findBookmarkByLabel(bookmark->label())) { Smb4KNotification::bookmarkLabelInUse(bookmark.data()); bookmark->setLabel(QString("%1 (1)").arg(bookmark->label())); } - else - { - // Do nothing - } // // Check if we have to add the bookmark // BookmarkPtr existingBookmark = findBookmarkByUrl(bookmark->url()); if (!existingBookmark) { d->bookmarks << bookmark; } else { // We do not need to update the bookmark, because we are // operating on a shared pointer. } } // // Save the bookmark list and emit the updated() signal // writeBookmarkList(); emit updated(); } void Smb4KBookmarkHandler::removeBookmark(const BookmarkPtr &bookmark) { if (bookmark) { for (int i = 0; i < d->bookmarks.size(); ++i) { if ((!Smb4KSettings::useProfiles() || Smb4KSettings::activeProfile() == d->bookmarks.at(i)->profile()) && QString::compare(d->bookmarks.at(i)->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), bookmark->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0 && QString::compare(bookmark->groupName(), d->bookmarks.at(i)->groupName(), Qt::CaseInsensitive) == 0) { d->bookmarks.takeAt(i).clear(); break; } - else - { - // Do nothing - } } // Write the list to the bookmarks file. writeBookmarkList(); emit updated(); } - else - { - // Do nothing - } } void Smb4KBookmarkHandler::removeGroup(const QString& name) { QMutableListIterator it(d->bookmarks); while (it.hasNext()) { const BookmarkPtr &b = it.next(); if ((!Smb4KSettings::useProfiles() || Smb4KSettings::activeProfile() == b->profile()) || QString::compare(b->groupName(), name, Qt::CaseInsensitive) == 0) { it.remove(); } - else - { - // Do nothing - } } // Write the list to the bookmarks file. writeBookmarkList(); emit updated(); } void Smb4KBookmarkHandler::writeBookmarkList() { QFile xmlFile(dataLocation()+QDir::separator()+"bookmarks.xml"); if (!d->bookmarks.isEmpty()) { if (xmlFile.open(QIODevice::WriteOnly|QIODevice::Text)) { QXmlStreamWriter xmlWriter(&xmlFile); xmlWriter.setAutoFormatting(true); xmlWriter.writeStartDocument(); xmlWriter.writeStartElement("bookmarks"); xmlWriter.writeAttribute("version", "2"); for (const BookmarkPtr &bookmark : d->bookmarks) { if (!bookmark->url().isValid()) { Smb4KNotification::invalidURLPassed(); continue; } - else - { - // Do nothing - } xmlWriter.writeStartElement("bookmark"); xmlWriter.writeAttribute("profile", bookmark->profile()); xmlWriter.writeAttribute("group", bookmark->groupName()); xmlWriter.writeTextElement("workgroup", bookmark->workgroupName()); xmlWriter.writeTextElement("url", bookmark->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort)); xmlWriter.writeTextElement("login", bookmark->login()); xmlWriter.writeTextElement("ip", bookmark->hostIpAddress()); xmlWriter.writeTextElement("label", bookmark->label()); xmlWriter.writeEndElement(); } xmlWriter.writeEndDocument(); xmlFile.close(); } else { Smb4KNotification::openingFileFailed(xmlFile); } } else { xmlFile.remove(); } } void Smb4KBookmarkHandler::readBookmarkList() { // // Clear the list of bookmarks // while (!d->bookmarks.isEmpty()) { d->bookmarks.takeFirst().clear(); } // // Locate the XML file and read the bookmarks // QFile xmlFile(dataLocation()+QDir::separator()+"bookmarks.xml"); if (xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QXmlStreamReader xmlReader(&xmlFile); while (!xmlReader.atEnd()) { xmlReader.readNext(); if (xmlReader.isStartElement()) { if (xmlReader.name() == "bookmarks" && (xmlReader.attributes().value("version") != "1.1" && xmlReader.attributes().value("version") != "2.0")) { xmlReader.raiseError(i18n("The format of %1 is not supported.", xmlFile.fileName())); break; } else { if (xmlReader.name() == "bookmark") { QString profile = xmlReader.attributes().value("profile").toString(); BookmarkPtr bookmark = BookmarkPtr(new Smb4KBookmark()); bookmark->setProfile(profile); bookmark->setGroupName(xmlReader.attributes().value("group").toString()); while (!(xmlReader.isEndElement() && xmlReader.name() == "bookmark")) { xmlReader.readNext(); if (xmlReader.isStartElement()) { if (xmlReader.name() == "workgroup") { bookmark->setWorkgroupName(xmlReader.readElementText()); } else if (xmlReader.name() == "unc") { bookmark->setUrl(xmlReader.readElementText()); } else if (xmlReader.name() == "url") { bookmark->setUrl(QUrl(xmlReader.readElementText())); } else if (xmlReader.name() == "login") { bookmark->setLogin(xmlReader.readElementText()); } else if (xmlReader.name() == "ip") { bookmark->setHostIpAddress(xmlReader.readElementText()); } else if (xmlReader.name() == "label") { bookmark->setLabel(xmlReader.readElementText()); } - else - { - // Do nothing - } continue; } else { continue; } } d->bookmarks << bookmark; } else { continue; } } } else { continue; } } xmlFile.close(); if (xmlReader.hasError()) { Smb4KNotification::readingFileFailed(xmlFile, xmlReader.errorString()); } - else - { - // Do nothing - } } else { if (xmlFile.exists()) { Smb4KNotification::openingFileFailed(xmlFile); } - else - { - // Do nothing - } } emit updated(); } BookmarkPtr Smb4KBookmarkHandler::findBookmarkByUrl(const QUrl &url) { // Update the bookmarks: update(); // Find the bookmark: BookmarkPtr bookmark; if (!url.isEmpty() && url.isValid() && !bookmarksList().isEmpty()) { for (const BookmarkPtr &b : bookmarksList()) { if (QString::compare(b->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), url.toString(QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0) { bookmark = b; break; } - else - { - // Do nothing - } } } - else - { - // Do nothing - } return bookmark; } BookmarkPtr Smb4KBookmarkHandler::findBookmarkByLabel(const QString &label) { // Update the bookmarks: update(); // Find the bookmark: BookmarkPtr bookmark; for (const BookmarkPtr &b : bookmarksList()) { if (QString::compare(b->label().toUpper(), label.toUpper()) == 0) { bookmark = b; break; } else { continue; } } return bookmark; } QList Smb4KBookmarkHandler::bookmarksList() const { // Update the bookmarks: update(); // Get this list of the bookmarks if (Smb4KSettings::useProfiles()) { QList bookmarks; for (const BookmarkPtr &b : d->bookmarks) { if (b->profile() == Smb4KSettings::activeProfile()) { bookmarks << b; } - else - { - // Do nothing - } } return bookmarks; } - else - { - // Do nothing - } // Return the list of bookmarks: return d->bookmarks; } QList Smb4KBookmarkHandler::bookmarksList(const QString &group) const { // Update bookmarks update(); // Get the list of bookmarks organized in the given group QList bookmarks; for (const BookmarkPtr &bookmark : bookmarksList()) { if (QString::compare(group, bookmark->groupName(), Qt::CaseInsensitive) == 0) { bookmarks << bookmark; } - else - { - // Do nothing - } } return bookmarks; } QStringList Smb4KBookmarkHandler::groupsList() const { QStringList groups; for (const BookmarkPtr &b : bookmarksList()) { if (!groups.contains(b->groupName())) { groups << b->groupName(); } - else - { - // Do nothing - } } return groups; } void Smb4KBookmarkHandler::resetBookmarks() { readBookmarkList(); } bool Smb4KBookmarkHandler::isBookmarked(const SharePtr& share) { if (findBookmarkByUrl(share->url())) { return true; } - else - { - // Do nothing - } return false; } void Smb4KBookmarkHandler::editBookmarks() { // // Only allow one instance of the bookmark editor // if (!d->editor) { d->editor = new Smb4KBookmarkEditor(d->bookmarks, QApplication::activeWindow()); } else { d->editor->raise(); } if (d->editor->exec() == QDialog::Accepted) { addBookmarks(d->editor->editedBookmarks(), true); } else { resetBookmarks(); } // // Delete the editor after use // delete d->editor; d->editor = 0; } void Smb4KBookmarkHandler::update() const { // Get new IP addresses. for (const BookmarkPtr &bookmark : d->bookmarks) { HostPtr host = findHost(bookmark->hostName(), bookmark->workgroupName()); if (host) { if (host->hasIpAddress() && bookmark->hostIpAddress() != host->ipAddress()) { bookmark->setHostIpAddress(host->ipAddress()); } - else - { - // Do nothing - } - } - else - { - // Do nothing } } } void Smb4KBookmarkHandler::migrateProfile(const QString& from, const QString& to) { // Replace the old profile name with the new one. for (const BookmarkPtr &bookmark : d->bookmarks) { if (QString::compare(bookmark->profile(), from, Qt::CaseSensitive) == 0) { bookmark->setProfile(to); } - else - { - // Do nothing - } } // Write the new list to the file. writeBookmarkList(); } void Smb4KBookmarkHandler::removeProfile(const QString& name) { QMutableListIterator it(d->bookmarks); while (it.hasNext()) { const BookmarkPtr &bookmark = it.next(); if (QString::compare(bookmark->profile(), name, Qt::CaseSensitive) == 0) { it.remove(); } - else - { - // Do nothing - } } // Write the new list to the file. writeBookmarkList(); } diff --git a/core/smb4kbookmarkhandler_p.cpp b/core/smb4kbookmarkhandler_p.cpp index 252a7ad..ce25f1d 100644 --- a/core/smb4kbookmarkhandler_p.cpp +++ b/core/smb4kbookmarkhandler_p.cpp @@ -1,1093 +1,993 @@ /*************************************************************************** Private classes for the bookmark handler ------------------- begin : Sun Mar 20 2011 copyright : (C) 2011-2018 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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, 51 Franklin Street, Suite 500, Boston, * * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kbookmarkhandler_p.h" #include "smb4ksettings.h" #include "smb4kbookmark.h" // Qt includes #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include #include #include Smb4KBookmarkDialog::Smb4KBookmarkDialog(const QList &bookmarks, const QStringList &groups, QWidget *parent) : QDialog(parent) { setWindowTitle(i18n("Add Bookmarks")); setupView(); loadLists(bookmarks, groups); KConfigGroup group(Smb4KSettings::self()->config(), "BookmarkDialog"); KWindowConfig::restoreWindowSize(windowHandle(), group); m_label_edit->completionObject()->setItems(group.readEntry("LabelCompletion", QStringList())); m_group_combo->completionObject()->setItems(group.readEntry("GroupCompletion", m_groups)); connect(KIconLoader::global(), SIGNAL(iconChanged(int)), SLOT(slotIconSizeChanged(int))); } Smb4KBookmarkDialog::~Smb4KBookmarkDialog() { while (!m_bookmarks.isEmpty()) { m_bookmarks.takeFirst().clear(); } } const QList &Smb4KBookmarkDialog::bookmarks() { return m_bookmarks; } void Smb4KBookmarkDialog::setupView() { QVBoxLayout *layout = new QVBoxLayout(this); layout->setSpacing(5); QWidget *description = new QWidget(this); QHBoxLayout *desc_layout = new QHBoxLayout(description); desc_layout->setSpacing(5); desc_layout->setMargin(0); QLabel *pixmap = new QLabel(description); QPixmap sync_pix = KDE::icon("bookmark-new").pixmap(KIconLoader::SizeHuge); pixmap->setPixmap(sync_pix); pixmap->setAlignment(Qt::AlignBottom); QLabel *label = new QLabel(i18n("All listed shares will be bookmarked. To edit the label " "or group, click the respective bookmark entry."), description); label->setWordWrap(true); label->setAlignment(Qt::AlignBottom); desc_layout->addWidget(pixmap, 0); desc_layout->addWidget(label, Qt::AlignBottom); m_widget = new QListWidget(this); m_widget->setSortingEnabled(true); m_widget->setSelectionMode(QAbstractItemView::SingleSelection); int icon_size = KIconLoader::global()->currentSize(KIconLoader::Small); m_widget->setIconSize(QSize(icon_size, icon_size)); m_editors = new QWidget(this); m_editors->setEnabled(false); QGridLayout *editors_layout = new QGridLayout(m_editors); editors_layout->setSpacing(5); editors_layout->setMargin(0); QLabel *l_label = new QLabel(i18n("Label:"), m_editors); m_label_edit = new KLineEdit(m_editors); m_label_edit->setClearButtonEnabled(true); QLabel *g_label = new QLabel(i18n("Group:"), m_editors); m_group_combo = new KComboBox(true, m_editors); editors_layout->addWidget(l_label, 0, 0, 0); editors_layout->addWidget(m_label_edit, 0, 1, 0); editors_layout->addWidget(g_label, 1, 0, 0); editors_layout->addWidget(m_group_combo, 1, 1, 0); QDialogButtonBox *buttonBox = new QDialogButtonBox(Qt::Horizontal, this); m_ok_button = buttonBox->addButton(QDialogButtonBox::Ok); m_cancel_button = buttonBox->addButton(QDialogButtonBox::Cancel); m_ok_button->setShortcut(Qt::CTRL|Qt::Key_Return); m_cancel_button->setShortcut(Qt::Key_Escape); m_ok_button->setDefault(true); layout->addWidget(description, 0); layout->addWidget(m_widget, 0); layout->addWidget(m_editors, 0); layout->addWidget(buttonBox, 0); setMinimumWidth(sizeHint().width() > 350 ? sizeHint().width() : 350); connect(m_widget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(slotBookmarkClicked(QListWidgetItem*))); connect(m_label_edit, SIGNAL(editingFinished()), this, SLOT(slotLabelEdited())); connect(m_group_combo->lineEdit(), SIGNAL(editingFinished()), this, SLOT(slotGroupEdited())); connect(m_ok_button, SIGNAL(clicked()), this, SLOT(slotDialogAccepted())); connect(m_cancel_button, SIGNAL(clicked()), this, SLOT(reject())); } void Smb4KBookmarkDialog::loadLists(const QList &bookmarks, const QStringList &groups) { // Copy the bookmarks to the internal list and add them to // the list widget afterwards. for (const BookmarkPtr &b : bookmarks) { QListWidgetItem *item = new QListWidgetItem(b->icon(), b->displayString(), m_widget); item->setData(Qt::UserRole, static_cast(b->url())); m_bookmarks << b; } m_groups = groups; m_group_combo->addItems(m_groups); } BookmarkPtr Smb4KBookmarkDialog::findBookmark(const QUrl &url) { BookmarkPtr bookmark; for (const BookmarkPtr &b : m_bookmarks) { if (b->url() == url) { bookmark = b; break; } else { continue; } } return bookmark; } void Smb4KBookmarkDialog::slotBookmarkClicked(QListWidgetItem *bookmark_item) { if (bookmark_item) { // Enable the editor widgets if necessary if (!m_editors->isEnabled()) { m_editors->setEnabled(true); } - else - { - // Do nothing - } QUrl url = bookmark_item->data(Qt::UserRole).toUrl(); BookmarkPtr bookmark = findBookmark(url); if (bookmark) { m_label_edit->setText(bookmark->label()); m_group_combo->setCurrentItem(bookmark->groupName()); } else { m_label_edit->clear(); m_group_combo->clearEditText(); m_editors->setEnabled(false); } } else { m_label_edit->clear(); m_group_combo->clearEditText(); m_editors->setEnabled(false); } } void Smb4KBookmarkDialog::slotLabelEdited() { // Set the label QUrl url = m_widget->currentItem()->data(Qt::UserRole).toUrl(); BookmarkPtr bookmark = findBookmark(url); if (bookmark) { bookmark->setLabel(m_label_edit->userText()); } - else - { - // Do nothing - } // Add label to completion object KCompletion *completion = m_label_edit->completionObject(); if (!m_label_edit->userText().isEmpty()) { completion->addItem(m_label_edit->userText()); } - else - { - // Do nothing - } } void Smb4KBookmarkDialog::slotGroupEdited() { // Set the group QUrl url = m_widget->currentItem()->data(Qt::UserRole).toUrl(); BookmarkPtr bookmark = findBookmark(url); if (bookmark) { bookmark->setGroupName(m_group_combo->currentText()); } - else - { - // Do nothing - } // Add the group name to the combo box if (m_group_combo->findText(m_group_combo->currentText()) == -1) { m_group_combo->addItem(m_group_combo->currentText()); } - else - { - // Do nothing - } // Add group to completion object KCompletion *completion = m_group_combo->completionObject(); if (!m_group_combo->currentText().isEmpty()) { completion->addItem(m_group_combo->currentText()); } - else - { - // Do nothing - } } void Smb4KBookmarkDialog::slotDialogAccepted() { KConfigGroup group(Smb4KSettings::self()->config(), "BookmarkDialog"); KWindowConfig::saveWindowSize(windowHandle(), group); group.writeEntry("LabelCompletion", m_label_edit->completionObject()->items()); group.writeEntry("GroupCompletion", m_group_combo->completionObject()->items()); accept(); } void Smb4KBookmarkDialog::slotIconSizeChanged(int group) { switch (group) { case KIconLoader::Small: { int icon_size = KIconLoader::global()->currentSize(KIconLoader::Small); m_widget->setIconSize(QSize(icon_size, icon_size)); break; } default: { break; } } } Smb4KBookmarkEditor::Smb4KBookmarkEditor(const QList &bookmarks, QWidget *parent) : QDialog(parent), m_bookmarks(bookmarks) { // // Set the window title // setWindowTitle(i18n("Edit Bookmarks")); // // Setup the view // setupView(); // // Load the bookmarks into the editor // loadBookmarks(); // // Set the editor's minimum width // setMinimumWidth(sizeHint().height() > sizeHint().width() ? sizeHint().height() : sizeHint().width()); // // Load some other settings // KConfigGroup group(Smb4KSettings::self()->config(), "BookmarkEditor"); KWindowConfig::restoreWindowSize(windowHandle(), group); m_label_edit->completionObject()->setItems(group.readEntry("LabelCompletion", QStringList())); m_login_edit->completionObject()->setItems(group.readEntry("LoginCompletion", QStringList())); m_ip_edit->completionObject()->setItems(group.readEntry("IPCompletion", QStringList())); m_group_combo->completionObject()->setItems(group.readEntry("GroupCompletion", m_groups)); // // Connections // connect(KIconLoader::global(), SIGNAL(iconChanged(int)), SLOT(slotIconSizeChanged(int))); } Smb4KBookmarkEditor::~Smb4KBookmarkEditor() { while (!m_bookmarks.isEmpty()) { m_bookmarks.takeFirst().clear(); } } bool Smb4KBookmarkEditor::eventFilter(QObject *obj, QEvent *e) { if (obj == m_tree_widget->viewport()) { switch (e->type()) { case QEvent::DragEnter: { QDragEnterEvent *ev = static_cast(e); if (ev->source() == m_tree_widget->viewport()) { e->accept(); } else { e->ignore(); } break; } case QEvent::DragLeave: { e->ignore(); break; } case QEvent::Drop: { QTimer::singleShot(50, this, SLOT(slotAdjust())); break; } default: { break; } } } return QDialog::eventFilter(obj, e); } void Smb4KBookmarkEditor::setupView() { QVBoxLayout *layout = new QVBoxLayout(this); layout->setSpacing(5); m_tree_widget = new QTreeWidget(this); m_tree_widget->setColumnCount(2); m_tree_widget->hideColumn((m_tree_widget->columnCount() - 1)); // for sorting purposes m_tree_widget->headerItem()->setHidden(true); m_tree_widget->setRootIsDecorated(true); m_tree_widget->setSelectionMode(QAbstractItemView::SingleSelection); m_tree_widget->setContextMenuPolicy(Qt::CustomContextMenu); m_tree_widget->header()->setSectionResizeMode(QHeaderView::ResizeToContents); m_tree_widget->setDragDropMode(QTreeWidget::InternalMove); int icon_size = KIconLoader::global()->currentSize(KIconLoader::Small); m_tree_widget->setIconSize(QSize(icon_size, icon_size)); m_tree_widget->viewport()->installEventFilter(this); m_add_group = new QAction(KDE::icon("bookmark-add-folder"), i18n("Add Group"), m_tree_widget); m_delete = new QAction(KDE::icon("edit-delete"), i18n("Remove"), m_tree_widget); m_clear = new QAction(KDE::icon("edit-clear"), i18n("Clear"), m_tree_widget); m_menu = new KActionMenu(m_tree_widget); m_menu->addAction(m_add_group); m_menu->addAction(m_delete); m_menu->addAction(m_clear); m_editors = new QWidget(this); m_editors->setEnabled(false); QGridLayout *editors_layout = new QGridLayout(m_editors); editors_layout->setSpacing(5); editors_layout->setMargin(0); QLabel *l_label = new QLabel(i18n("Label:"), m_editors); m_label_edit = new KLineEdit(m_editors); m_label_edit->setClearButtonEnabled(true); QLabel *lg_label = new QLabel(i18n("Login:"), m_editors); m_login_edit = new KLineEdit(m_editors); m_login_edit->setClearButtonEnabled(true); QLabel *i_label = new QLabel(i18n("IP Address:"), m_editors); m_ip_edit = new KLineEdit(m_editors); m_ip_edit->setClearButtonEnabled(true); QLabel *g_label = new QLabel(i18n("Group:"), m_editors); m_group_combo = new KComboBox(true, m_editors); m_group_combo->setDuplicatesEnabled(false); editors_layout->addWidget(l_label, 0, 0, 0); editors_layout->addWidget(m_label_edit, 0, 1, 0); editors_layout->addWidget(lg_label, 1, 0, 0); editors_layout->addWidget(m_login_edit, 1, 1, 0); editors_layout->addWidget(i_label, 2, 0, 0); editors_layout->addWidget(m_ip_edit, 2, 1, 0); editors_layout->addWidget(g_label, 3, 0, 0); editors_layout->addWidget(m_group_combo, 3, 1, 0); QDialogButtonBox *buttonBox = new QDialogButtonBox(Qt::Horizontal, this); m_ok_button = buttonBox->addButton(QDialogButtonBox::Ok); m_cancel_button = buttonBox->addButton(QDialogButtonBox::Cancel); m_ok_button->setShortcut(Qt::CTRL|Qt::Key_Return); m_cancel_button->setShortcut(Qt::Key_Escape); m_ok_button->setDefault(true); layout->addWidget(m_tree_widget); layout->addWidget(m_editors); layout->addWidget(buttonBox); connect(m_tree_widget, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(slotItemClicked(QTreeWidgetItem*,int))); connect(m_tree_widget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotContextMenuRequested(QPoint))); connect(m_label_edit, SIGNAL(editingFinished()), this, SLOT(slotLabelEdited())); connect(m_ip_edit, SIGNAL(editingFinished()), this, SLOT(slotIPEdited())); connect(m_login_edit, SIGNAL(editingFinished()), this, SLOT(slotLoginEdited())); connect(m_group_combo->lineEdit(), SIGNAL(editingFinished()), this, SLOT(slotGroupEdited())); connect(m_add_group, SIGNAL(triggered(bool)), this, SLOT(slotAddGroupTriggered(bool))); connect(m_delete, SIGNAL(triggered(bool)), this, SLOT(slotDeleteTriggered(bool))); connect(m_clear, SIGNAL(triggered(bool)), this, SLOT(slotClearTriggered(bool))); connect(m_ok_button, SIGNAL(clicked()), this, SLOT(slotDialogAccepted())); connect(m_cancel_button, SIGNAL(clicked()), this, SLOT(slotDialogRejected())); } void Smb4KBookmarkEditor::loadBookmarks() { // // Clear the tree widget and the group combo box // m_tree_widget->clear(); m_group_combo->clear(); // // Copy the groups into the internal list // m_groups.clear(); for (const BookmarkPtr &bookmark : m_bookmarks) { if (!m_groups.contains(bookmark->groupName())) { m_groups << bookmark->groupName(); } - else - { - // Do nothing - } } // // Insert the groups into the tree widget // for (const QString &group : m_groups) { if (!group.isEmpty()) { QTreeWidgetItem *groupItem = new QTreeWidgetItem(QTreeWidgetItem::UserType); groupItem->setIcon(0, KDE::icon("folder-bookmark")); groupItem->setText(0, group); groupItem->setText((m_tree_widget->columnCount() - 1), QString("00_%1").arg(group)); groupItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt::ItemIsDropEnabled); m_tree_widget->addTopLevelItem(groupItem); } - else - { - // Do nothing - } } // // Insert the bookmarks info the tree widget // for (const BookmarkPtr &bookmark : m_bookmarks) { QTreeWidgetItem *bookmarkItem = new QTreeWidgetItem(QTreeWidgetItem::UserType); bookmarkItem->setData(0, QTreeWidgetItem::UserType, static_cast(bookmark->url())); bookmarkItem->setIcon(0, bookmark->icon()); bookmarkItem->setText(0, bookmark->displayString()); bookmarkItem->setText((m_tree_widget->columnCount() - 1), QString("01_%1").arg(bookmark->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort))); bookmarkItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt::ItemIsDragEnabled); if (!bookmark->groupName().isEmpty()) { QList items = m_tree_widget->findItems(bookmark->groupName(), Qt::MatchFixedString|Qt::MatchCaseSensitive, 0); if (!items.isEmpty()) { items.first()->addChild(bookmarkItem); items.first()->setExpanded(true); } - else - { - // Do nothing - } } else { m_tree_widget->addTopLevelItem(bookmarkItem); } } // // Sort // for (int i = 0; i < m_tree_widget->topLevelItemCount(); ++i) { m_tree_widget->topLevelItem(i)->sortChildren((m_tree_widget->columnCount() - 1), Qt::AscendingOrder); } m_tree_widget->sortItems((m_tree_widget->columnCount() - 1), Qt::AscendingOrder); // // Check that an empty group entry is also present. If it is not there, // add it now and insert the groups to the group combo box afterwards. // if (!m_groups.contains("") && !m_groups.contains(QString())) { m_groups << ""; } - else - { - // Do nothing - } m_group_combo->addItems(m_groups); m_group_combo->setCurrentItem(""); } QList Smb4KBookmarkEditor::editedBookmarks() { return m_bookmarks; } BookmarkPtr Smb4KBookmarkEditor::findBookmark(const QUrl &url) { BookmarkPtr bookmark; for (const BookmarkPtr &b : m_bookmarks) { if (b->url() == url) { bookmark = b; break; } else { continue; } } return bookmark; } void Smb4KBookmarkEditor::slotItemClicked(QTreeWidgetItem *item, int /*col*/) { if (item) { if (m_tree_widget->indexOfTopLevelItem(item) != -1) { // This is a top-level item, i.e. it is either a bookmark without // group or a group entry. // Bookmarks have an URL stored, group folders not. if (!item->data(0, QTreeWidgetItem::UserType).toUrl().isEmpty()) { BookmarkPtr bookmark = findBookmark(item->data(0, QTreeWidgetItem::UserType).toUrl()); if (bookmark) { m_label_edit->setText(bookmark->label()); m_login_edit->setText(bookmark->login()); m_ip_edit->setText(bookmark->hostIpAddress()); m_group_combo->setCurrentItem(bookmark->groupName()); m_editors->setEnabled(true); } else { m_label_edit->clear(); m_login_edit->clear(); m_ip_edit->clear(); m_group_combo->clearEditText(); m_editors->setEnabled(false); } } else { m_label_edit->clear(); m_login_edit->clear(); m_ip_edit->clear(); m_group_combo->clearEditText(); m_editors->setEnabled(false); } } else { // This can only be a bookmark. BookmarkPtr bookmark = findBookmark(item->data(0, QTreeWidgetItem::UserType).toUrl()); if (bookmark) { m_label_edit->setText(bookmark->label()); m_login_edit->setText(bookmark->login()); m_ip_edit->setText(bookmark->hostIpAddress()); m_group_combo->setCurrentItem(bookmark->groupName()); m_editors->setEnabled(true); } else { m_label_edit->clear(); m_login_edit->clear(); m_ip_edit->clear(); m_group_combo->clearEditText(); m_editors->setEnabled(false); } } } else { m_label_edit->clear(); m_login_edit->clear(); m_ip_edit->clear(); m_group_combo->clearEditText(); m_editors->setEnabled(false); } } void Smb4KBookmarkEditor::slotContextMenuRequested(const QPoint &pos) { QTreeWidgetItem *item = m_tree_widget->itemAt(pos); m_delete->setEnabled((item)); m_menu->menu()->popup(m_tree_widget->viewport()->mapToGlobal(pos)); } void Smb4KBookmarkEditor::slotLabelEdited() { // Set the label QUrl url = m_tree_widget->currentItem()->data(0, QTreeWidgetItem::UserType).toUrl(); BookmarkPtr bookmark = findBookmark(url); if (bookmark) { bookmark->setLabel(m_label_edit->userText()); } - else - { - // Do nothing - } // Add label to completion object KCompletion *completion = m_label_edit->completionObject(); if (!m_label_edit->userText().isEmpty()) { completion->addItem(m_label_edit->userText()); } - else - { - // Do nothing - } } void Smb4KBookmarkEditor::slotLoginEdited() { // Set the login QUrl url = m_tree_widget->currentItem()->data(0, QTreeWidgetItem::UserType).toUrl(); BookmarkPtr bookmark = findBookmark(url); if (bookmark) { bookmark->setLogin(m_login_edit->userText()); } - else - { - // Do nothing - } // Add login to completion object KCompletion *completion = m_login_edit->completionObject(); if (!m_login_edit->userText().isEmpty()) { completion->addItem(m_login_edit->userText()); } - else - { - // Do nothing - } } void Smb4KBookmarkEditor::slotIPEdited() { // Set the ip address QUrl url = m_tree_widget->currentItem()->data(0, QTreeWidgetItem::UserType).toUrl(); BookmarkPtr bookmark = findBookmark(url); if (bookmark) { bookmark->setHostIpAddress(m_ip_edit->userText()); } - else - { - // Do nothing - } // Add login to completion object KCompletion *completion = m_ip_edit->completionObject(); if (!m_ip_edit->userText().isEmpty()) { completion->addItem(m_ip_edit->userText()); } - else - { - // Do nothing - } } void Smb4KBookmarkEditor::slotGroupEdited() { // // Get the URL of the current item. // QUrl url = m_tree_widget->currentItem()->data(0, QTreeWidgetItem::UserType).toUrl(); // // Return here, if the current item is a group // if (url.isEmpty()) { return; } - else - { - // Do nothing - } // // Set the group name to the bookmark // BookmarkPtr bookmark = findBookmark(url); if (bookmark) { bookmark->setGroupName(m_group_combo->currentText()); } - else - { - // Do nothing - } // // Reload the bookmarks (The current item is cleared by this!) // loadBookmarks(); // // Reset the current item // QTreeWidgetItemIterator it(m_tree_widget); while (*it) { if ((*it)->data(0, QTreeWidgetItem::UserType).toUrl() == url) { m_tree_widget->setCurrentItem(*it); slotItemClicked(*it, 0); break; } - else - { - // Do nothing - } ++it; } // // Add the group to the completion object // KCompletion *completion = m_group_combo->completionObject(); if (!m_group_combo->currentText().isEmpty()) { completion->addItem(m_group_combo->currentText()); } - else - { - // Do nothing - } } void Smb4KBookmarkEditor::slotAddGroupTriggered(bool /*checked*/) { bool ok = false; QString group_name = QInputDialog::getText(this, i18n("Add Group"), i18n("Group name:"), QLineEdit::Normal, QString(), &ok); if (ok && !group_name.isEmpty() && m_tree_widget->findItems(group_name, Qt::MatchFixedString|Qt::MatchCaseSensitive, 0).isEmpty()) { // Create a new group item and add it to the widget QTreeWidgetItem *group = new QTreeWidgetItem(QTreeWidgetItem::UserType); group->setIcon(0, KDE::icon("folder-bookmark")); group->setText(0, group_name); group->setText((m_tree_widget->columnCount() - 1), QString("00_%1").arg(group_name)); group->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt::ItemIsDropEnabled) ; m_tree_widget->addTopLevelItem(group); m_tree_widget->sortItems((m_tree_widget->columnCount() - 1), Qt::AscendingOrder); // Add the group to the combo box m_group_combo->addItem(group_name); m_group_combo->completionObject()->addItem(group_name); } - else - { - // Do nothing - } } void Smb4KBookmarkEditor::slotDeleteTriggered(bool /*checked*/) { // // Remove the bookmarks from the view and the internal list // QList selected = m_tree_widget->selectedItems(); while (!selected.isEmpty()) { QTreeWidgetItem *item = selected.takeFirst(); QUrl url = item->data(0, QTreeWidgetItem::UserType).toUrl(); QMutableListIterator it(m_bookmarks); while (it.hasNext()) { BookmarkPtr bookmark = it.next(); if (bookmark->url() == url) { it.remove(); break; } - else - { - // Do nothing - } } delete item; } } void Smb4KBookmarkEditor::slotClearTriggered(bool /*checked*/) { m_tree_widget->clear(); m_bookmarks.clear(); m_groups.clear(); } void Smb4KBookmarkEditor::slotDialogAccepted() { // // Write the dialog properties to the config file // KConfigGroup group(Smb4KSettings::self()->config(), "BookmarkEditor"); KWindowConfig::saveWindowSize(windowHandle(), group); group.writeEntry("LabelCompletion", m_label_edit->completionObject()->items()); group.writeEntry("LoginCompletion", m_login_edit->completionObject()->items()); group.writeEntry("IPCompletion", m_ip_edit->completionObject()->items()); group.writeEntry("GroupCompletion", m_group_combo->completionObject()->items()); // // Accept the dialog // accept(); } void Smb4KBookmarkEditor::slotDialogRejected() { // // Reject the dialog // reject(); } void Smb4KBookmarkEditor::slotIconSizeChanged(int group) { switch (group) { case KIconLoader::Small: { int icon_size = KIconLoader::global()->currentSize(KIconLoader::Small); m_tree_widget->setIconSize(QSize(icon_size, icon_size)); break; } default: { break; } } } void Smb4KBookmarkEditor::slotAdjust() { // Do the necessary adjustments: QTreeWidgetItemIterator it(m_tree_widget); while (*it) { if (!(*it)->parent()) { if ((*it)->data(0, QTreeWidgetItem::UserType).toUrl().isEmpty()) { if ((*it)->childCount() == 0) { delete *it; } - else - { - // Do nothing - } } else { BookmarkPtr bookmark = findBookmark((*it)->data(0, QTreeWidgetItem::UserType).toUrl()); if (bookmark) { bookmark->setGroupName(""); } - else - { - // Do nothing - } } } else { BookmarkPtr bookmark = findBookmark((*it)->data(0, QTreeWidgetItem::UserType).toUrl()); if (bookmark) { bookmark->setGroupName((*it)->parent()->text(0)); } - else - { - // Do nothing - } } ++it; } } diff --git a/core/smb4kclient.cpp b/core/smb4kclient.cpp index 950b763..54047a4 100644 --- a/core/smb4kclient.cpp +++ b/core/smb4kclient.cpp @@ -1,1164 +1,1028 @@ /*************************************************************************** This class provides the interface to the libsmbclient library. ------------------- begin : Sa Oct 20 2018 copyright : (C) 2018-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kclient.h" #include "smb4kclient_p.h" #include "smb4khardwareinterface.h" #include "smb4ksettings.h" #include "smb4kcustomoptionsmanager.h" #include "smb4kcustomoptions.h" #include "smb4kbasicnetworkitem.h" #include "smb4kglobal.h" #include "smb4khomesshareshandler.h" #include "smb4kwalletmanager.h" #include "smb4knotification.h" // Qt includes #include #include #include #include using namespace Smb4KGlobal; Q_GLOBAL_STATIC(Smb4KClientStatic, p); Smb4KClient::Smb4KClient(QObject* parent) : KCompositeJob(parent), d(new Smb4KClientPrivate) { // // Connections // (QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(slotAboutToQuit())); } Smb4KClient::~Smb4KClient() { } Smb4KClient *Smb4KClient::self() { return &p->instance; } void Smb4KClient::start() { // // Check the network configurations // Smb4KHardwareInterface::self()->updateNetworkConfig(); // // Connect to Smb4KHardwareInterface to be able to get the response // connect(Smb4KHardwareInterface::self(), SIGNAL(networkConfigUpdated()), this, SLOT(slotStartJobs())); } bool Smb4KClient::isRunning() { return hasSubjobs(); } void Smb4KClient::abort() { QListIterator it(subjobs()); while (it.hasNext()) { it.next()->kill(KJob::EmitResult); } } void Smb4KClient::lookupDomains() { // // Send Wakeup-On-LAN packages // if (Smb4KSettings::enableWakeOnLAN()) { QList wakeOnLanEntries = Smb4KCustomOptionsManager::self()->wakeOnLanEntries(); if (!wakeOnLanEntries.isEmpty()) { NetworkItemPtr item = NetworkItemPtr(new Smb4KBasicNetworkItem()); emit aboutToStart(item, WakeUp); QUdpSocket *socket = new QUdpSocket(this); for (int i = 0; i < wakeOnLanEntries.size(); ++i) { if (wakeOnLanEntries.at(i)->wolSendBeforeNetworkScan()) { QHostAddress addr; if (wakeOnLanEntries.at(i)->hasIpAddress()) { addr.setAddress(wakeOnLanEntries.at(i)->ipAddress()); } else { addr.setAddress("255.255.255.255"); } // Construct magic sequence QByteArray sequence; // 6 times 0xFF for (int j = 0; j < 6; ++j) { sequence.append(QChar(0xFF).toLatin1()); } // 16 times the MAC address QStringList parts = wakeOnLanEntries.at(i)->macAddress().split(':', QString::SkipEmptyParts); for (int j = 0; j < 16; ++j) { for (int k = 0; k < parts.size(); ++k) { sequence.append(QChar(QString("0x%1").arg(parts.at(k)).toInt(0, 16)).toLatin1()); } } socket->writeDatagram(sequence, addr, 9); } - else - { - // Do nothing - } } delete socket; // Wait the defined time int stop = 1000 * Smb4KSettings::wakeOnLANWaitingTime() / 250; int i = 0; while (i++ < stop) { QTest::qWait(250); } emit finished(item, WakeUp); item.clear(); } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // Emit the aboutToStart() signal // NetworkItemPtr item = NetworkItemPtr(new Smb4KBasicNetworkItem(Network)); item->setUrl(QUrl("smb://")); emit aboutToStart(item, LookupDomains); // // Create the job // Smb4KClientJob *job = new Smb4KClientJob(this); job->setNetworkItem(item); job->setProcess(LookupDomains); // // Clear the pointer // item.clear(); // // Set the busy cursor // if (!hasSubjobs() && modifyCursor()) { QApplication::setOverrideCursor(Qt::BusyCursor); } - else - { - // Do nothing - } // // Add the job to the subjobs // addSubjob(job); // // Start the job // job->start(); } void Smb4KClient::lookupDomainMembers(const WorkgroupPtr &workgroup) { // // Emit the aboutToStart() signal // emit aboutToStart(workgroup, LookupDomainMembers); // // Create the job // Smb4KClientJob *job = new Smb4KClientJob(this); job->setNetworkItem(workgroup); job->setProcess(LookupDomainMembers); // // Set the busy cursor // if (!hasSubjobs() && modifyCursor()) { QApplication::setOverrideCursor(Qt::BusyCursor); } - else - { - // Do nothing - } // // Add the job to the subjobs // addSubjob(job); // // Start the job // job->start(); } void Smb4KClient::lookupShares(const HostPtr &host) { // // Emit the aboutToStart() signal // emit aboutToStart(host, LookupShares); // // Create the job // Smb4KClientJob *job = new Smb4KClientJob(this); job->setNetworkItem(host); job->setProcess(LookupShares); // // Set the busy cursor // if (!hasSubjobs() && modifyCursor()) { QApplication::setOverrideCursor(Qt::BusyCursor); } - else - { - // Do nothing - } // // Add the job to the subjobs // addSubjob(job); // // Start the job // job->start(); } void Smb4KClient::lookupFiles(const NetworkItemPtr &item) { // // Check that the network item has the correct type and process it. // if (item->type() == Share || item->type() == Directory) { // // Emit the aboutToStart() signal // emit aboutToStart(item, LookupFiles); // // Create the job // Smb4KClientJob *job = new Smb4KClientJob(this); job->setNetworkItem(item); job->setProcess(LookupFiles); // // Set the busy cursor // if (!hasSubjobs() && modifyCursor()) { QApplication::setOverrideCursor(Qt::BusyCursor); } - else - { - // Do nothing - } // // Add the job to the subjobs // addSubjob(job); // // Start the job // job->start(); } - else - { - // Do nothing - } } void Smb4KClient::printFile(const SharePtr& share, const KFileItem& fileItem, int copies) { // // Emit the aboutToStart() signal // emit aboutToStart(share, PrintFile); // // Create the job // Smb4KClientJob *job = new Smb4KClientJob(this); job->setNetworkItem(share); job->setPrintFileItem(fileItem); job->setPrintCopies(copies); job->setProcess(PrintFile); // // Set the busy cursor // if (!hasSubjobs() && modifyCursor()) { QApplication::setOverrideCursor(Qt::BusyCursor); } - else - { - // Do nothing - } // // Add the job to the subjobs // addSubjob(job); // // Start the job // job->start(); } void Smb4KClient::search(const QString& item) { // // Create empty basic network item // NetworkItemPtr networkItem = NetworkItemPtr(new Smb4KBasicNetworkItem()); // // Emit the aboutToStart() signal // emit aboutToStart(networkItem, NetworkSearch); // // Before doing the search, lookup all domains, servers and shares in the // network neighborhood. // lookupDomains(); while(isRunning()) { QTest::qWait(50); } for (const WorkgroupPtr &workgroup : workgroupsList()) { lookupDomainMembers(workgroup); while(isRunning()) { QTest::qWait(50); } } for (const HostPtr &host : hostsList()) { lookupShares(host); while(isRunning()) { QTest::qWait(50); } } // // Do the actual search // QList results; for (const SharePtr &share : sharesList()) { if (share->shareName().contains(item, Qt::CaseInsensitive)) { results << share; } - else - { - // Do nothing - } } // // Emit the search results // emit searchResults(results); // // Emit the finished() signal // emit finished(networkItem, NetworkSearch); } void Smb4KClient::openPreviewDialog(const SharePtr &share) { // // Printer share check // if (share->isPrinter()) { return; } - else - { - // Do nothing - } // // 'homes' share check // if (share->isHomesShare()) { Smb4KHomesSharesHandler::self()->specifyUser(share, true); } - else - { - // Do nothing - } // // Start the preview dialog // // First, check if a preview dialog has already been set up for this share // and reuse it, if possible. // QPointer dlg = 0; for (Smb4KPreviewDialog *p : d->previewDialogs) { if (share == p->share()) { dlg = p; } - else - { - // Do nothing - } } // // If there was no preview dialog present, create a new one // if (!dlg) { dlg = new Smb4KPreviewDialog(share, QApplication::activeWindow()); d->previewDialogs << dlg; // // Connections // connect(dlg, SIGNAL(requestPreview(NetworkItemPtr)), this, SLOT(slotStartNetworkQuery(NetworkItemPtr))); connect(dlg, SIGNAL(aboutToClose(Smb4KPreviewDialog *)), this, SLOT(slotPreviewDialogClosed(Smb4KPreviewDialog *))); connect(dlg, SIGNAL(requestAbort()), this, SLOT(slotAbort())); connect(this, SIGNAL(files(QList)), dlg, SLOT(slotPreviewResults(QList))); connect(this, SIGNAL(aboutToStart(NetworkItemPtr,int)), dlg, SLOT(slotAboutToStart(NetworkItemPtr,int))); connect(this, SIGNAL(finished(NetworkItemPtr,int)), dlg, SLOT(slotFinished(NetworkItemPtr,int))); } - else - { - // Do nothing - } // // Show the preview dialog // if (!dlg->isVisible()) { dlg->setVisible(true); } - else - { - // Do nothing - } } void Smb4KClient::openPrintDialog(const SharePtr& share) { // // Printer share check // if (!share->isPrinter()) { return; } - else - { - // Do nothing - } // // Start the print dialog // // First, check if a print dialog has already been set up for this share // and reuse it, if possible. // QPointer dlg = 0; for (Smb4KPrintDialog *p : d->printDialogs) { if (share == p->share()) { dlg = p; } - else - { - // Do nothing - } } // // If there was no print dialog present, create a new one // if (!dlg) { Smb4KWalletManager::self()->readAuthInfo(share); dlg = new Smb4KPrintDialog(share, QApplication::activeWindow()); d->printDialogs << dlg; connect(dlg, SIGNAL(printFile(SharePtr, KFileItem, int)), this, SLOT(slotStartPrinting(SharePtr, KFileItem, int))); connect(dlg, SIGNAL(aboutToClose(Smb4KPrintDialog *)), this, SLOT(slotPrintDialogClosed(Smb4KPrintDialog *))); } - else - { - // Do nothing - } // // Show the preview dialog // if (!dlg->isVisible()) { dlg->setVisible(true); } - else - { - // Do nothing - } } void Smb4KClient::processErrors(Smb4KClientJob *job) { switch (job->error()) { case Smb4KClientJob::AccessDeniedError: { switch (job->networkItem()->type()) { case Host: { if (Smb4KWalletManager::self()->showPasswordDialog(job->networkItem())) { lookupShares(job->networkItem().staticCast()); } - else - { - // Do nothing - } break; } case Share: { if (Smb4KWalletManager::self()->showPasswordDialog(job->networkItem())) { lookupFiles(job->networkItem().staticCast()); } - else - { - // Do nothing - } break; } case Directory: case File: { FilePtr file = job->networkItem().staticCast(); SharePtr share = SharePtr(new Smb4KShare()); share->setWorkgroupName(file->workgroupName()); share->setHostName(file->hostName()); share->setShareName(file->shareName()); share->setLogin(file->login()); share->setPassword(file->password()); if (Smb4KWalletManager::self()->showPasswordDialog(share)) { file->setLogin(share->login()); file->setPassword(share->password()); lookupFiles(file); } - else - { - // Do nothing - } break; } default: { qDebug() << "Authentication error. URL:" << job->networkItem()->url(); break; } } break; } default: { Smb4KNotification::networkCommunicationFailed(job->errorText()); break; } } } void Smb4KClient::processWorkgroups(Smb4KClientJob *job) { // // Remove obsolete workgroups and their members // QListIterator wIt(workgroupsList()); while (wIt.hasNext()) { WorkgroupPtr workgroup = wIt.next(); bool found = false; for (const WorkgroupPtr &w : job->workgroups()) { if (w->workgroupName() == workgroup->workgroupName()) { found = true; break; } else { continue; } } if (!found) { QList obsoleteHosts = workgroupMembers(workgroup); QListIterator hIt(obsoleteHosts); while (hIt.hasNext()) { removeHost(hIt.next()); } removeWorkgroup(workgroup); } - else - { - // Do nothing - } } // // Add new workgroups and update existing ones. // for (const WorkgroupPtr &workgroup : job->workgroups()) { if (!findWorkgroup(workgroup->workgroupName())) { addWorkgroup(workgroup); // Since this is a new workgroup, no master browser is present. HostPtr masterBrowser = HostPtr(new Smb4KHost()); masterBrowser->setWorkgroupName(workgroup->workgroupName()); masterBrowser->setHostName(workgroup->masterBrowserName()); masterBrowser->setIpAddress(workgroup->masterBrowserIpAddress()); masterBrowser->setIsMasterBrowser(true); addHost(masterBrowser); } else { updateWorkgroup(workgroup); // Check if the master browser changed QList members = workgroupMembers(workgroup); for (const HostPtr &host : members) { if (workgroup->masterBrowserName() == host->hostName()) { host->setIsMasterBrowser(true); if (!host->hasIpAddress() && workgroup->hasMasterBrowserIpAddress()) { host->setIpAddress(workgroup->masterBrowserIpAddress()); } - else - { - // Do nothing - } } else { host->setIsMasterBrowser(false); } } } } emit workgroups(); } void Smb4KClient::processHosts(Smb4KClientJob *job) { // // Get the workgroup pointer // WorkgroupPtr workgroup = job->networkItem().staticCast(); // // Remove obsolete workgroup members // QList members = workgroupMembers(workgroup); QListIterator hIt(members); while (hIt.hasNext()) { HostPtr host = hIt.next(); bool found = false; for (const HostPtr &h : job->hosts()) { if (h->workgroupName() == host->workgroupName() && h->hostName() == host->hostName()) { found = true; break; } else { continue; } } if (!found) { QList obsoleteShares = sharedResources(host); QListIterator sIt(obsoleteShares); while (sIt.hasNext()) { removeShare(sIt.next()); } removeHost(host); } - else - { - // Do nothing - } } // // Add new hosts and update existing ones // for (const HostPtr &host : job->hosts()) { if (host->hostName() == workgroup->masterBrowserName()) { host->setIsMasterBrowser(true); } else { host->setIsMasterBrowser(false); } if (!findHost(host->hostName(), host->workgroupName())) { addHost(host); } else { updateHost(host); } } emit hosts(workgroup); } void Smb4KClient::processShares(Smb4KClientJob *job) { // // Get the host pointer // HostPtr host = job->networkItem().staticCast(); // // Remove obsolete shares // QList sharedRes = sharedResources(host); QListIterator sIt(sharedRes); while (sIt.hasNext()) { SharePtr share = sIt.next(); bool found = false; for (const SharePtr &s : job->shares()) { if (s->workgroupName() == share->workgroupName() && s->url().matches(share->url(), QUrl::RemoveUserInfo|QUrl::RemovePort)) { found = true; break; } else { continue; } } if (!found || (share->isHidden() && !Smb4KSettings::detectHiddenShares()) || (share->isPrinter() && !Smb4KSettings::detectPrinterShares())) { removeShare(share); } - else - { - // Do nothing - } } // // Add new shares and update existing ones // for (const SharePtr &share : job->shares()) { // // Process only those shares that the user wants to see // if (share->isHidden() && !Smb4KSettings::detectHiddenShares()) { continue; } - else - { - // Do nothing - } if (share->isPrinter() && !Smb4KSettings::detectPrinterShares()) { continue; } - else - { - // Do nothing - } // // Add or update the shares // if (!findShare(share->url(), share->workgroupName())) { addShare(share); } else { updateShare(share); } } emit shares(host); } void Smb4KClient::processFiles(Smb4KClientJob *job) { QList list; for (const FilePtr &f : job->files()) { if (f->isHidden() && !Smb4KSettings::previewHiddenItems()) { continue; } - else - { - // Do nothing - } list << f; } emit files(list); } void Smb4KClient::slotStartJobs() { if (Smb4KHardwareInterface::self()->isOnline()) { // // Disconnect from Smb4KHardwareInterface::networkConfigUpdated() signal, // otherwise we get unwanted periodic scanning. // disconnect(Smb4KHardwareInterface::self(), SIGNAL(networkConfigUpdated()), this, SLOT(slotStartJobs())); // // Lookup domains as the first step // lookupDomains(); } - else - { - // Do nothing - } } void Smb4KClient::slotResult(KJob *job) { // // Get the client job // Smb4KClientJob *clientJob = qobject_cast(job); // // Define a network item pointer and the process value for the // finished() signal. // NetworkItemPtr item = clientJob->networkItem(); Smb4KGlobal::Process process = clientJob->process(); // // Get the result from the query and process it // if (clientJob) { if (clientJob->error() == 0) { switch (clientJob->networkItem()->type()) { case Network: { // Process the discovered workgroups processWorkgroups(clientJob); break; } case Workgroup: { // Process the discovered workgroup members processHosts(clientJob); break; } case Host: { // Process the discovered shares processShares(clientJob); break; } case Share: case Directory: { // Process the discoveres files and directories processFiles(clientJob); break; } default: { break; } } } else { processErrors(clientJob); } } - else - { - // Do nothing - } // // Remove the job // removeSubjob(job); // // Emit the finished signal // finished(item, process); // // Clear the network item pointer // item.clear(); // // Restore the cursor // if (!hasSubjobs() && modifyCursor()) { QApplication::restoreOverrideCursor(); } - else - { - // Do nothing - } } void Smb4KClient::slotAboutToQuit() { abort(); } void Smb4KClient::slotStartNetworkQuery(NetworkItemPtr item) { // // Look up files // lookupFiles(item); } void Smb4KClient::slotPreviewDialogClosed(Smb4KPreviewDialog *dialog) { // // Remove the preview dialog from the list // if (dialog) { // Find the dialog in the list and take it from the list. // It will automatically be deleted on close, so there is // no need to delete the dialog here. int i = d->previewDialogs.indexOf(dialog); d->previewDialogs.takeAt(i); } - else - { - // Do nothing - } } void Smb4KClient::slotAbort() { abort(); } void Smb4KClient::slotStartPrinting(const SharePtr& printer, const KFileItem& fileItem, int copies) { // // Start printing // printFile(printer, fileItem, copies); } void Smb4KClient::slotPrintDialogClosed(Smb4KPrintDialog* dialog) { // // Remove the print dialog from the list // if (dialog) { // Find the dialog in the list and take it from the list. // It will automatically be deleted on close, so there is // no need to delete the dialog here. int i = d->printDialogs.indexOf(dialog); d->printDialogs.takeAt(i); } - else - { - // Do nothing - } } diff --git a/core/smb4kclient_p.cpp b/core/smb4kclient_p.cpp index ee0507c..8a00db3 100644 --- a/core/smb4kclient_p.cpp +++ b/core/smb4kclient_p.cpp @@ -1,2134 +1,2026 @@ /*************************************************************************** Private classes for the SMB client ------------------- begin : So Oct 21 2018 copyright : (C) 2018-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kclient_p.h" #include "smb4ksettings.h" #include "smb4kwalletmanager.h" #include "smb4kcustomoptions.h" #include "smb4kcustomoptionsmanager.h" #include "smb4knotification.h" // System includes #include // #include #include // #include // Qt includes #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // KDE includes #include #include #include #include #include #include #include #include #define SMBC_DEBUG 1 using namespace Smb4KGlobal; // // Authentication function for libsmbclient // static void get_auth_data_with_context_fn(SMBCCTX *context, const char *server, const char *share, char *workgroup, int maxLenWorkgroup, char *username, int maxLenUsername, char *password, int maxLenPassword) { if (context != nullptr) { Smb4KClientJob *job = static_cast(smbc_getOptionUserData(context)); if (job) { job->get_auth_data_fn(server, share, workgroup, maxLenWorkgroup, username, maxLenUsername, password, maxLenPassword); } - else - { - // Do nothing - } } } // // Client job // Smb4KClientJob::Smb4KClientJob(QObject* parent) : KJob(parent), m_process(Smb4KGlobal::NoProcess) { } Smb4KClientJob::~Smb4KClientJob() { // // Clear the list of workgroups // while (!m_workgroups.isEmpty()) { m_workgroups.takeFirst().clear(); } // // Clear the list of hosts // while (!m_hosts.isEmpty()) { m_hosts.takeFirst().clear(); } // // Clear the list of shares // while (!m_shares.isEmpty()) { m_shares.takeFirst().clear(); } // // Clear the list of files and directories // while (!m_files.isEmpty()) { m_files.takeFirst().clear(); } } void Smb4KClientJob::start() { QTimer::singleShot(50, this, SLOT(slotStartJob())); } void Smb4KClientJob::setNetworkItem(NetworkItemPtr item) { m_item = item; } NetworkItemPtr Smb4KClientJob::networkItem() const { return m_item; } void Smb4KClientJob::setProcess(Smb4KGlobal::Process process) { m_process = process; } Smb4KGlobal::Process Smb4KClientJob::process() const { return m_process; } void Smb4KClientJob::setPrintFileItem(const KFileItem& item) { m_fileItem = item; } void Smb4KClientJob::setPrintCopies(int copies) { m_copies = copies; } void Smb4KClientJob::get_auth_data_fn(const char* server, const char* share, char* workgroup, int maxLenWorkgroup, char* username, int maxLenUsername, char* password, int maxLenPassword) { // // Authentication // switch (m_item->type()) { case Network: { // // No authentication needed // break; } case Workgroup: { // // Only request authentication data, if the master browsers require // authentication data. // if (Smb4KSettings::masterBrowsersRequireAuth()) { if (QString::fromUtf8(server).toUpper() != QString::fromUtf8(workgroup).toUpper()) { // // This is the master browser. Create a host object for it. // HostPtr h = HostPtr(new Smb4KHost()); h->setWorkgroupName(QString::fromUtf8(workgroup)); h->setHostName(QString::fromUtf8(server)); // // Get the authentication data // Smb4KWalletManager::self()->readAuthInfo(h); // // Copy the authentication data // qstrncpy(username, h->login().toUtf8().data(), maxLenUsername); qstrncpy(password, h->password().toUtf8().data(), maxLenPassword); } - else - { - // Do nothing - } - } - else - { - // Do nothing } break; } case Host: { // // The host object // HostPtr h = m_item.staticCast(); // // Get the authentication data // Smb4KWalletManager::self()->readAuthInfo(h); // // Copy the authentication data // qstrncpy(username, h->login().toUtf8().data(), maxLenUsername); qstrncpy(password, h->password().toUtf8().data(), maxLenPassword); break; } case Share: { // // The share object // SharePtr s = m_item.staticCast(); // // Get the authentication data // Smb4KWalletManager::self()->readAuthInfo(s); // // Copy the authentication data // qstrncpy(username, s->login().toUtf8().data(), maxLenUsername); qstrncpy(password, s->password().toUtf8().data(), maxLenPassword); break; } case Directory: { // // The file object // FilePtr f = m_item.staticCast(); // // Create a share object // SharePtr s = SharePtr(new Smb4KShare()); s->setWorkgroupName(f->workgroupName()); s->setHostName(f->hostName()); s->setShareName(f->shareName()); s->setLogin(f->login()); s->setPassword(f->password()); // // Get the authentication data // Smb4KWalletManager::self()->readAuthInfo(s); // // Copy the authentication data // qstrncpy(username, s->login().toUtf8().data(), maxLenUsername); qstrncpy(password, s->password().toUtf8().data(), maxLenPassword); break; } default: { break; } } } QList Smb4KClientJob::workgroups() { return m_workgroups; } QList Smb4KClientJob::hosts() { return m_hosts; } QList Smb4KClientJob::shares() { return m_shares; } QList Smb4KClientJob::files() { return m_files; } QString Smb4KClientJob::workgroup() { QString workgroup; switch (m_item->type()) { case Network: { break; } case Workgroup: { workgroup = m_item->url().host().toUpper(); break; } case Host: { workgroup = m_item.staticCast()->workgroupName(); break; } case Share: { workgroup = m_item.staticCast()->workgroupName(); break; } case Directory: case File: { workgroup = m_item.staticCast()->workgroupName(); break; } default: { break; } } return workgroup; } void Smb4KClientJob::doLookups() { // // Read the given URL // int dirfd; struct smbc_dirent *dirp = nullptr; dirfd = smbc_opendir(m_item->url().toString().toUtf8().data()); if (dirfd < 0) { int errorCode = errno; switch (errorCode) { case ENOMEM: { setError(OutOfMemoryError); setErrorText(i18n("Out of memory")); break; } case EACCES: { setError(AccessDeniedError); setErrorText(i18n("Permission denied")); break; } case EINVAL: { setError(InvalidUrlError); setErrorText(i18n("An invalid URL was passed")); break; } case ENOENT: { setError(NonExistentUrlError); setErrorText(i18n("The URL does not exist")); break; } case ENOTDIR: { setError(NoDirectoryError); setErrorText(i18n("Name is not a directory")); break; } case EPERM: { setError(NotPermittedError); // Is the error message correct? setErrorText(i18n("Operation not permitted")); break; } case ENODEV: { setError(NotFoundError); setErrorText(i18n("The workgroup or server could not be found")); break; } default: { setError(UnknownError); setErrorText(i18n("Unknown error")); } } emitResult(); return; } else { // // Get the entries of the "directory" // while ((dirp = smbc_readdir(dirfd)) != nullptr) { switch (dirp->smbc_type) { case SMBC_WORKGROUP: { // // Create a workgroup pointer // WorkgroupPtr workgroup = WorkgroupPtr(new Smb4KWorkgroup()); // // Set the workgroup name // QString workgroupName = QString::fromUtf8(dirp->name); workgroup->setWorkgroupName(workgroupName); // // Set the master browser // QString masterBrowserName = QString::fromUtf8(dirp->comment); workgroup->setMasterBrowserName(masterBrowserName); // // Lookup IP address // QHostAddress address = lookupIpAddress(masterBrowserName); // // Process the IP address. // If the address is null, the server most likely went offline. So, skip the // workgroup and delete the pointer. // if (!address.isNull()) { workgroup->setMasterBrowserIpAddress(address); m_workgroups << workgroup; } else { workgroup.clear(); } break; } case SMBC_SERVER: { // // Create a host pointer // HostPtr host = HostPtr(new Smb4KHost()); // // Set the workgroup name // host->setWorkgroupName(m_item->url().host()); // // Set the host name // QString hostName = QString::fromUtf8(dirp->name); host->setHostName(hostName); // // Set the comment // QString comment = QString::fromUtf8(dirp->comment); host->setComment(comment); // // Lookup IP address // QHostAddress address = lookupIpAddress(hostName); // // Process the IP address. // If the address is null, the server most likely went offline. So, skip it // and delete the pointer. // if (!address.isNull()) { host->setIpAddress(address); m_hosts << host; } else { host.clear(); } break; } case SMBC_FILE_SHARE: { // // Create a share pointer // SharePtr share = SharePtr(new Smb4KShare()); // // Set the workgroup name // share->setWorkgroupName(m_item.staticCast()->workgroupName()); // // Set the host name // share->setHostName(m_item->url().host()); // // Set the share name // share->setShareName(QString::fromUtf8(dirp->name)); // // Set the comment // share->setComment(QString::fromUtf8(dirp->comment)); // // Set share type // share->setShareType(FileShare); // // Set the authentication data // share->setLogin(m_item->url().userName()); share->setPassword(m_item->url().password()); // // Lookup IP address // QHostAddress address = lookupIpAddress(m_item->url().host()); // // Process the IP address. // If the address is null, the server most likely went offline. So, skip it // and delete the pointer. // if (!address.isNull()) { share->setHostIpAddress(address); m_shares << share; } else { share.clear(); } break; } case SMBC_PRINTER_SHARE: { // // Create a share pointer // SharePtr share = SharePtr(new Smb4KShare()); // // Set the workgroup name // share->setWorkgroupName(m_item.staticCast()->workgroupName()); // // Set the host name // share->setHostName(m_item->url().host()); // // Set the share name // share->setShareName(QString::fromUtf8(dirp->name)); // // Set the comment // share->setComment(QString::fromUtf8(dirp->comment)); // // Set share type // share->setShareType(PrinterShare); // // Set the authentication data // share->setLogin(m_item->url().userName()); share->setPassword(m_item->url().password()); // // Lookup IP address // QHostAddress address = lookupIpAddress(m_item->url().host()); // // Process the IP address. // If the address is null, the server most likely went offline. So, skip it // and delete the pointer. // if (!address.isNull()) { share->setHostIpAddress(address); m_shares << share; } else { share.clear(); } break; } case SMBC_IPC_SHARE: { // // Create a share pointer // SharePtr share = SharePtr(new Smb4KShare()); // // Set the workgroup name // share->setWorkgroupName(m_item.staticCast()->workgroupName()); // // Set the host name // share->setHostName(m_item->url().host()); // // Set the share name // share->setShareName(QString::fromUtf8(dirp->name)); // // Set the comment // share->setComment(QString::fromUtf8(dirp->comment)); // // Set share type // share->setShareType(IpcShare); // // Set the authentication data // share->setLogin(m_item->url().userName()); share->setPassword(m_item->url().password()); // // Lookup IP address // QHostAddress address = lookupIpAddress(m_item->url().host()); // // Process the IP address. // If the address is null, the server most likely went offline. So, skip it // and delete the pointer. // if (!address.isNull()) { share->setHostIpAddress(address); m_shares << share; } else { share.clear(); } break; } case SMBC_DIR: { // // Do not process '.' and '..' directories // QString name = QString::fromUtf8(dirp->name); if (name != "." && name != "..") { // // Create the URL for the discovered item // QUrl u = m_item->url(); u.setPath(m_item->url().path()+QDir::separator()+QString::fromUtf8(dirp->name)); // // We do not stat directories. Directly create the directory object // FilePtr dir = FilePtr(new Smb4KFile(u, Directory)); // // Set the workgroup name // dir->setWorkgroupName(m_item.staticCast()->workgroupName()); // // Set the authentication data // dir->setLogin(m_item->url().userName()); dir->setPassword(m_item->url().password()); // // Lookup IP address // QHostAddress address = lookupIpAddress(m_item->url().host()); // // Process the IP address. // If the address is null, the server most likely went offline. So, skip it // and delete the pointer. // if (!address.isNull()) { dir->setHostIpAddress(address); m_files << dir; } else { dir.clear(); } } - else - { - // Do nothing - } break; } case SMBC_FILE: { // // Create the URL for the discovered item // QUrl u = m_item->url(); u.setPath(m_item->url().path()+QDir::separator()+QString::fromUtf8(dirp->name)); // // Create the directory object // FilePtr dir = FilePtr(new Smb4KFile(u, File)); // // Set the workgroup name // dir->setWorkgroupName(m_item.staticCast()->workgroupName()); // // Stat the file // // FIXME // // Set the authentication data // dir->setLogin(m_item->url().userName()); dir->setPassword(m_item->url().password()); // // Lookup IP address // QHostAddress address = lookupIpAddress(m_item->url().host()); // // Process the IP address. // If the address is null, the server most likely went offline. So, skip it // and delete the pointer. // if (!address.isNull()) { dir->setHostIpAddress(address); m_files << dir; } else { dir.clear(); } break; } case SMBC_LINK: { qDebug() << "Processing links is not implemented."; qDebug() << dirp->name; qDebug() << dirp->comment; break; } default: { qDebug() << "Need to process network item " << dirp->name; break; } } } smbc_closedir(dirfd); } } void Smb4KClientJob::doPrinting() { // // The URL that is to be printed // QUrl fileUrl; // // Set the temporary directory // QTemporaryDir tempDir; // // Check if we can directly print the file // if (m_fileItem.mimetype() == "application/postscript" || m_fileItem.mimetype() == "application/pdf" || m_fileItem.mimetype().startsWith(QLatin1String("image"))) { // // Set the URL to the incoming file // fileUrl = m_fileItem.url(); } else if (m_fileItem.mimetype() == "application/x-shellscript" || m_fileItem.mimetype().startsWith(QLatin1String("text")) || m_fileItem.mimetype().startsWith(QLatin1String("message"))) { // // Set a printer object // QPrinter printer(QPrinter::HighResolution); printer.setCreator("Smb4K"); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(QString("%1/smb4k_print.pdf").arg(tempDir.path())); // // Open the file that is to be printed and read it // QStringList contents; QFile file(m_fileItem.url().path()); if (file.open(QFile::ReadOnly|QFile::Text)) { QTextStream ts(&file); while (!ts.atEnd()) { contents << ts.readLine(); } } else { return; } // // Convert the file to PDF // QTextDocument doc; if (m_fileItem.mimetype().endsWith(QLatin1String("html"))) { doc.setHtml(contents.join(" ")); } else { doc.setPlainText(contents.join("\n")); } doc.print(&printer); // // Set the URL to the converted file // fileUrl.setUrl(printer.outputFileName()); fileUrl.setScheme("file"); } else { Smb4KNotification::mimetypeNotSupported(m_fileItem.mimetype()); return; } // // Get the open function for the printer // smbc_open_print_job_fn openPrinter = smbc_getFunctionOpenPrintJob(m_context); if (!openPrinter) { if (errno != 0) qDebug() << "errno is set:" << errno; setError(OpenPrintJobError); setErrorText(i18n("The print job could not be set up (step 1)")); emitResult(); return; } - else - { - // Do nothing - } // // Open the printer for printing // SMBCFILE *printer = openPrinter(m_context, m_item->url().toString().toUtf8().data()); if (!printer) { if (errno != 0) qDebug() << "errno is set:" << errno; setError(OpenPrintJobError); setErrorText(i18n("The print job could not be set up (step 2)")); emitResult(); return; } - else - { - // Do nothing - } // // Open the file // QFile file(fileUrl.path()); if (!file.open(QFile::ReadOnly)) { setError(FileAccessError); setErrorText(i18n("The file %1 could not be read", fileUrl.path())); emitResult(); return; } - else - { - // Do nothing - } // // Write X copies of the file to the printer // char buffer[4096]; qint64 bytes = 0; int copy = 0; while (copy < m_copies) { while ((bytes = file.read(buffer, sizeof(buffer))) > 0) { smbc_write_fn writeFile = smbc_getFunctionWrite(m_context); if (writeFile(m_context, printer, buffer, bytes) < 0) { setError(PrintFileError); setErrorText(i18n("The file %1 could not be printed to %2", fileUrl.path(), m_item.staticCast()->displayString())); smbc_close_fn closePrinter = smbc_getFunctionClose(m_context); closePrinter(m_context, printer); } - else - { - // Do nothing - } } copy++; } // // Close the printer // smbc_close_fn closePrinter = smbc_getFunctionClose(m_context); closePrinter(m_context, printer); } QHostAddress Smb4KClientJob::lookupIpAddress(const QString& name) { // // The IP address object // QHostAddress ipAddress; // If the IP address is not to be determined for the local machine, we can use QHostInfo to // determine it. Otherwise we need to use QNetworkInterface for it. if (name.toUpper() == QHostInfo::localHostName().toUpper() || name.toUpper() == globalSambaOptions()["netbios name"].toUpper() || name.toUpper() == Smb4KSettings::netBIOSName().toUpper()) { // FIXME: Do we need to honor 'interfaces' here? QList addresses = QNetworkInterface::allAddresses(); // Get the IP address for the host. For the time being, prefer the // IPv4 address over the IPv6 address. for (const QHostAddress &addr : addresses) { // We only use global addresses. #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) if (addr.isGlobal()) #else if (!addr.isLoopback() && !addr.isMulticast()) #endif { if (addr.protocol() == QAbstractSocket::IPv4Protocol) { ipAddress = addr; break; } else if (addr.protocol() == QAbstractSocket::IPv6Protocol) { // FIXME: Use the right address here. ipAddress = addr; } - else - { - // Do nothing - } } - else - { - // Do nothing - } } } else { // Get the IP address QHostInfo hostInfo = QHostInfo::fromName(name); if (hostInfo.error() == QHostInfo::NoError) { // Get the IP address for the host. For the time being, prefer the // IPv4 address over the IPv6 address. for (const QHostAddress &addr : hostInfo.addresses()) { // We only use global addresses. #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) if (addr.isGlobal()) #else if (!addr.isLoopback() && !addr.isMulticast()) #endif { if (addr.protocol() == QAbstractSocket::IPv4Protocol) { ipAddress = addr; break; } else if (addr.protocol() == QAbstractSocket::IPv6Protocol) { // FIXME: Use the right address here. ipAddress = addr; } - else - { - // Do nothing - } - } - else - { - // Do nothing } } } - else - { - // Do nothing - } } return ipAddress; } void Smb4KClientJob::slotStartJob() { // // Allocate new context // m_context = smbc_new_context(); if (!m_context) { int errorCode = errno; switch (errorCode) { case ENOMEM: { setError(OutOfMemoryError); setErrorText(i18n("Out of memory")); break; } default: { setError(UnknownError); setErrorText(i18n("Unknown error")); break; } } emitResult(); return; } // // Get the custom options // OptionsPtr options = Smb4KCustomOptionsManager::self()->findOptions(m_item); // // Set debug level // smbc_setDebug(m_context, SMBC_DEBUG); // // Set the NetBIOS name and the workgroup to make connections // switch (m_item->type()) { case Network: { // // We do not know about the servers and the domains/workgroups // present. So, do not set anything and use the default. // break; } case Workgroup: { // // Set the NetBIOS name of the master browser and the workgroup to be queried // WorkgroupPtr workgroup = m_item.staticCast(); smbc_setNetbiosName(m_context, workgroup->masterBrowserName().toUtf8().data()); smbc_setWorkgroup(m_context, workgroup->workgroupName().toUtf8().data()); break; } case Host: { // // Set both the NetBIOS name of the server and the workgroup to be queried // HostPtr host = m_item.staticCast(); smbc_setNetbiosName(m_context, host->hostName().toUtf8().data()); smbc_setWorkgroup(m_context, host->workgroupName().toUtf8().data()); break; } case Share: { // // Set both the NetBIOS name of the server and the workgroup to be queried // SharePtr share = m_item.staticCast(); smbc_setNetbiosName(m_context, share->hostName().toUtf8().data()); smbc_setWorkgroup(m_context, share->workgroupName().toUtf8().data()); break; } case Directory: { // // Set both the NetBIOS name of the server and the workgroup to be queried // FilePtr file = m_item.staticCast(); smbc_setNetbiosName(m_context, file->hostName().toUtf8().data()); smbc_setWorkgroup(m_context, file->workgroupName().toUtf8().data()); break; } default: { break; } } // // Set the user for making the connection // if (!m_item->url().userName().isEmpty()) { smbc_setUser(m_context, m_item->url().userName().toUtf8().data()); } - else - { - // Do nothing - } // // Set the port // if (options) { if (options->useSmbPort()) { smbc_setPort(m_context, options->smbPort()); } else { smbc_setPort(m_context, 0 /* use the default */); } } else { if (Smb4KSettings::useRemoteSmbPort()) { smbc_setPort(m_context, Smb4KSettings::remoteSmbPort()); } else { smbc_setPort(m_context, 0 /* use the default */); } } // // Set the user data (this class) // smbc_setOptionUserData(m_context, this); // // Set number of master browsers to be used // if (Smb4KSettings::largeNetworkNeighborhood()) { smbc_setOptionBrowseMaxLmbCount(m_context, 3); } else { smbc_setOptionBrowseMaxLmbCount(m_context, 0 /* all master browsers */); } // // Set the encryption level // if (Smb4KSettings::useEncryptionLevel()) { switch (Smb4KSettings::encryptionLevel()) { case Smb4KSettings::EnumEncryptionLevel::None: { smbc_setOptionSmbEncryptionLevel(m_context, SMBC_ENCRYPTLEVEL_NONE); break; } case Smb4KSettings::EnumEncryptionLevel::Request: { smbc_setOptionSmbEncryptionLevel(m_context, SMBC_ENCRYPTLEVEL_REQUEST); break; } case Smb4KSettings::EnumEncryptionLevel::Require: { smbc_setOptionSmbEncryptionLevel(m_context, SMBC_ENCRYPTLEVEL_REQUIRE); break; } default: { break; } } } - else - { - // Do nothing - } // // Set the usage of anonymous login // smbc_setOptionNoAutoAnonymousLogin(m_context, false); // // Set the usage of the winbind ccache // smbc_setOptionUseCCache(m_context, Smb4KSettings::useWinbindCCache()); // // Set usage of Kerberos // if (options) { smbc_setOptionUseKerberos(m_context, options->useKerberos()); } else { smbc_setOptionUseKerberos(m_context, Smb4KSettings::useKerberos()); } smbc_setOptionFallbackAfterKerberos(m_context, 1); // // Set the channel for debug output // smbc_setOptionDebugToStderr(m_context, 1); // // Set auth callback function // smbc_setFunctionAuthDataWithContext(m_context, get_auth_data_with_context_fn); // // Initialize context with the previously defined options // if (!smbc_init_context(m_context)) { int errorCode = errno; switch (errorCode) { case ENOMEM: { setError(OutOfMemoryError); setErrorText(i18n("Out of memory")); break; } case EBADF: { setError(NullContextError); setErrorText(i18n("NULL context given")); break; } case ENOENT: { setError(SmbConfError); setErrorText(i18n("The smb.conf file would not load")); break; } default: { setError(UnknownError); setErrorText(i18n("Unknown error")); } } smbc_free_context(m_context, 0); emitResult(); return; } // // Set the new context // (void)smbc_set_context(m_context); // // Process the given URL according to the passed process // switch (m_process) { case LookupDomains: case LookupDomainMembers: case LookupShares: case LookupFiles: { doLookups(); break; } case PrintFile: { doPrinting(); break; } default: { break; } } // // Free the context // smbc_free_context(m_context, 0); // // Emit the result // emitResult(); } Smb4KPreviewDialog::Smb4KPreviewDialog(const SharePtr& share, QWidget* parent) : QDialog(parent), m_share(share) { // // Dialog title // setWindowTitle(i18n("Preview of %1", share->displayString())); // // Attributes // setAttribute(Qt::WA_DeleteOnClose, true); // // Layout // QVBoxLayout *layout = new QVBoxLayout(this); setLayout(layout); // // The list widget // QListWidget *listWidget = new QListWidget(this); listWidget->setSelectionMode(QAbstractItemView::SingleSelection); connect(listWidget, SIGNAL(itemActivated(QListWidgetItem *)), SLOT(slotItemActivated(QListWidgetItem *))); layout->addWidget(listWidget, 0); // // Toolbar // Use QToolBar here with the settings suggested by the note provided in the 'Detailed Description' // section of KToolBar (https://api.kde.org/frameworks/kxmlgui/html/classKToolBar.html) // QToolBar *toolBar = new QToolBar(this); toolBar->setToolButtonStyle(Qt::ToolButtonFollowStyle); toolBar->setProperty("otherToolbar", true); // // Reload / cancel action // KDualAction *reloadAction = new KDualAction(toolBar); reloadAction->setObjectName("reload_action"); reloadAction->setInactiveText(i18n("Reload")); reloadAction->setInactiveIcon(KDE::icon("view-refresh")); reloadAction->setActiveText(i18n("Abort")); reloadAction->setActiveIcon(KDE::icon("process-stop")); reloadAction->setActive(false); reloadAction->setAutoToggle(false); connect(reloadAction, SIGNAL(toggled(bool)), this, SLOT(slotReloadActionTriggered())); toolBar->addAction(reloadAction); // // Up action // QAction *upAction =toolBar->addAction(KDE::icon("go-up"), i18n("Up"), this, SLOT(slotUpActionTriggered())); upAction->setObjectName("up_action"); upAction->setEnabled(false); toolBar->addSeparator(); // // URL combo box // KUrlComboBox *urlCombo = new KUrlComboBox(KUrlComboBox::Directories, toolBar); urlCombo->setEditable(false); toolBar->addWidget(urlCombo); connect(urlCombo, SIGNAL(urlActivated(QUrl)), this, SLOT(slotUrlActivated(QUrl))); layout->addWidget(toolBar, 0); // // Dialog button box // QDialogButtonBox *buttonBox = new QDialogButtonBox(this); buttonBox->setOrientation(Qt::Horizontal); QPushButton *closeButton = buttonBox->addButton(QDialogButtonBox::Close); connect(closeButton, SIGNAL(clicked()), this, SLOT(slotClosingDialog())); layout->addWidget(buttonBox, 0); // // Set the minimum width // setMinimumWidth(sizeHint().width() > 350 ? sizeHint().width() : 350); // // Set the dialog size // create(); KConfigGroup group(Smb4KSettings::self()->config(), "PreviewDialog"); KWindowConfig::restoreWindowSize(windowHandle(), group); resize(windowHandle()->size()); // workaround for QTBUG-40584 // // Start the preview // m_currentItem = m_share; QTimer::singleShot(0, this, SLOT(slotInitializePreview())); } Smb4KPreviewDialog::~Smb4KPreviewDialog() { // // Clear the share // m_share.clear(); // // Clear the current item // m_currentItem.clear(); // // Clear the listing // while (!m_listing.isEmpty()) { m_listing.takeFirst().clear(); } } SharePtr Smb4KPreviewDialog::share() const { return m_share; } void Smb4KPreviewDialog::slotClosingDialog() { // // Save the dialog size // KConfigGroup group(Smb4KSettings::self()->config(), "PreviewDialog"); KWindowConfig::saveWindowSize(windowHandle(), group); // // Emit the aboutToClose() signal // emit aboutToClose(this); // // Close the dialog // accept(); } void Smb4KPreviewDialog::slotReloadActionTriggered() { KDualAction *reloadAction = findChild(); if (reloadAction->isActive()) { emit requestAbort(); } else { emit requestPreview(m_currentItem); } } void Smb4KPreviewDialog::slotUpActionTriggered() { // // Get the new URL // QUrl u = KIO::upUrl(m_currentItem->url()); // // Create a new network item object, if necessary and set the new current // item. Also, disable the "Up" action, if necessary. // if (m_share->url().matches(u, QUrl::StripTrailingSlash)) { findChild("up_action")->setEnabled(false); m_currentItem = m_share; } else if (m_share->url().path().length() < u.path().length()) { FilePtr file = FilePtr(new Smb4KFile(u, Directory)); file->setWorkgroupName(m_share->workgroupName()); m_currentItem = file; } else { return; } // // Emit the requestPreview() signal // emit requestPreview(m_currentItem); } void Smb4KPreviewDialog::slotUrlActivated(const QUrl &url) { // // Get the full authentication information. This is needed, since the combo // box only returns sanitized URLs, i.e. without password, etc. // QUrl u = url; u.setUserName(m_share->login()); u.setPassword(m_share->password()); // // Create a new network item object, if necessary and set the new current // item. // if (m_share->url().matches(u, QUrl::StripTrailingSlash)) { m_currentItem = m_share; } else { FilePtr file = FilePtr(new Smb4KFile(u, Directory)); file->setWorkgroupName(m_share->workgroupName()); m_currentItem = file; } // // Emit the requestPreview() signal // emit requestPreview(m_currentItem); } void Smb4KPreviewDialog::slotItemActivated(QListWidgetItem *item) { // // Only process the item if it represents a directory // if (item && item->type() == Directory) { // // Find the file item, make it the current one and emit the requestPreview() // signal. // for (const FilePtr &f : m_listing) { if (item->data(Qt::UserRole).toUrl().matches(f->url(), QUrl::None)) { m_currentItem = f; emit requestPreview(m_currentItem); break; } - else - { - // Do nothing - } } } - else - { - // Do nothing - } } void Smb4KPreviewDialog::slotInitializePreview() { emit requestPreview(m_currentItem); } void Smb4KPreviewDialog::slotPreviewResults(const QList &list) { // // Only process data the belongs to this dialog // if (m_share->workgroupName() == list.first()->workgroupName() && m_share->hostName() == list.first()->hostName() && list.first()->url().path().startsWith(m_share->url().path())) { // // Clear the internal listing // while (!m_listing.isEmpty()) { m_listing.takeFirst().clear(); } // // Copy the list into the private variable // m_listing = list; // // Get the list widget // QListWidget *listWidget = findChild(); // // Clear the list widget // listWidget->clear(); // // Insert the new listing // if (listWidget) { for (const FilePtr &f : list) { QListWidgetItem *item = new QListWidgetItem(f->icon(), f->name(), listWidget, f->isDirectory() ? Directory : File); item->setData(Qt::UserRole, f->url()); } } - else - { - // Do nothing - } // // Sort the list widget // listWidget->sortItems(); // // Add the URL to the combo box and show it. Omit duplicates. // KUrlComboBox *urlCombo = findChild(); QStringList urls = urlCombo->urls(); urls << m_currentItem->url().toString(); urlCombo->setUrls(urls); urlCombo->setUrl(m_currentItem->url()); // // Enable / disable the "Up" action // findChild("up_action")->setEnabled(!m_share->url().matches(m_currentItem->url(), QUrl::StripTrailingSlash)); } - else - { - // Do nothing - } } void Smb4KPreviewDialog::slotAboutToStart(const NetworkItemPtr &item, int type) { if (type == LookupFiles) { switch (item->type()) { case Share: { SharePtr s = item.staticCast(); if (m_share->workgroupName() == s->workgroupName() && m_share->hostName() == s->hostName() && s->url().path().startsWith(m_share->url().path())) { KDualAction *reloadAction = findChild(); reloadAction->setActive(true); } - else - { - // Do nothing - } break; } case Directory: { FilePtr f = item.staticCast(); if (m_share->workgroupName() == f->workgroupName() && m_share->hostName() == f->hostName() && f->url().path().startsWith(m_share->url().path())) { KDualAction *reloadAction = findChild(); reloadAction->setActive(true); } - else - { - // Do nothing - } break; } default: { break; } } } - else - { - // Do nothing - } } void Smb4KPreviewDialog::slotFinished(const NetworkItemPtr &item, int type) { if (type == LookupFiles) { switch (item->type()) { case Share: { SharePtr s = item.staticCast(); if (m_share->workgroupName() == s->workgroupName() && m_share->hostName() == s->hostName() && s->url().path().startsWith(m_share->url().path())) { KDualAction *reloadAction = findChild(); reloadAction->setActive(false); } - else - { - // Do nothing - } break; } case Directory: { FilePtr f = item.staticCast(); if (m_share->workgroupName() == f->workgroupName() && m_share->hostName() == f->hostName() && f->url().path().startsWith(m_share->url().path())) { KDualAction *reloadAction = findChild(); reloadAction->setActive(false); } - else - { - // Do nothing - } break; } default: { break; } } } - else - { - // Do nothing - } } Smb4KPrintDialog::Smb4KPrintDialog(const SharePtr& share, QWidget* parent) : QDialog(parent), m_share(share) { // // Dialog title // setWindowTitle(i18n("Print File")); // // Attributes // setAttribute(Qt::WA_DeleteOnClose, true); // // Layout // QVBoxLayout *layout = new QVBoxLayout(this); setLayout(layout); // // Information group box // QGroupBox *informationBox = new QGroupBox(i18n("Information"), this); QGridLayout *informationBoxLayout = new QGridLayout(informationBox); // Printer name QLabel *printerNameLabel = new QLabel(i18n("Printer:"), informationBox); QLabel *printerName = new QLabel(share->displayString(), informationBox); informationBoxLayout->addWidget(printerNameLabel, 0, 0, 0); informationBoxLayout->addWidget(printerName, 0, 1, 0); // IP address QLabel *ipAddressLabel = new QLabel(i18n("IP Address:"), informationBox); QLabel *ipAddress = new QLabel(share->hostIpAddress(), informationBox); informationBoxLayout->addWidget(ipAddressLabel, 1, 0, 0); informationBoxLayout->addWidget(ipAddress, 1, 1, 0); // Workgroup QLabel *workgroupNameLabel = new QLabel(i18n("Domain:"), informationBox); QLabel *workgroupName = new QLabel(share->workgroupName(), informationBox); informationBoxLayout->addWidget(workgroupNameLabel, 2, 0, 0); informationBoxLayout->addWidget(workgroupName, 2, 1, 0); layout->addWidget(informationBox); // // File and settings group box // QGroupBox *fileBox = new QGroupBox(i18n("File and Settings"), this); QGridLayout *fileBoxLayout = new QGridLayout(fileBox); // File QLabel *fileLabel = new QLabel(i18n("File:"), fileBox); KUrlRequester *file = new KUrlRequester(fileBox); file->setMode(KFile::File|KFile::LocalOnly|KFile::ExistingOnly); file->setUrl(QUrl::fromLocalFile(QDir::homePath())); file->setWhatsThis(i18n("This is the file you want to print on the remote printer. " "Currently only a few mimetypes are supported such as PDF, Postscript, plain text, and " "images. If the file's mimetype is not supported, you need to convert it.")); connect(file, SIGNAL(textChanged(QString)), this, SLOT(slotUrlChanged())); fileBoxLayout->addWidget(fileLabel, 0, 0, 0); fileBoxLayout->addWidget(file, 0, 1, 0); // Copies QLabel *copiesLabel = new QLabel(i18n("Copies:"), fileBox); QSpinBox *copies = new QSpinBox(fileBox); copies->setValue(1); copies->setMinimum(1); copies->setWhatsThis(i18n("This is the number of copies you want to print.")); fileBoxLayout->addWidget(copiesLabel, 1, 0, 0); fileBoxLayout->addWidget(copies, 1, 1, 0); layout->addWidget(fileBox); // // Buttons // QDialogButtonBox *buttonBox = new QDialogButtonBox(this); QPushButton *printButton = buttonBox->addButton(i18n("Print"), QDialogButtonBox::ActionRole); printButton->setObjectName("print_button"); printButton->setShortcut(Qt::CTRL|Qt::Key_P); connect(printButton, SIGNAL(clicked(bool)), this, SLOT(slotPrintButtonClicked())); QPushButton *cancelButton = buttonBox->addButton(QDialogButtonBox::Cancel); cancelButton->setObjectName("cancel_button"); cancelButton->setShortcut(Qt::Key_Escape); cancelButton->setDefault(true); connect(cancelButton, SIGNAL(clicked(bool)), this, SLOT(slotCancelButtonClicked())); layout->addWidget(buttonBox); // // Set the minimum width // setMinimumWidth(sizeHint().width() > 350 ? sizeHint().width() : 350); // // Set the dialog size // create(); KConfigGroup group(Smb4KSettings::self()->config(), "PrintDialog"); KWindowConfig::restoreWindowSize(windowHandle(), group); resize(windowHandle()->size()); // workaround for QTBUG-40584 // // Set the buttons // slotUrlChanged(); } Smb4KPrintDialog::~Smb4KPrintDialog() { } SharePtr Smb4KPrintDialog::share() const { return m_share; } KFileItem Smb4KPrintDialog::fileItem() const { return m_fileItem; } void Smb4KPrintDialog::slotUrlChanged() { // // Take the focus from the URL requester and give it to the dialog's // button box // QDialogButtonBox *buttonBox = findChild(); buttonBox->setFocus(); // // Get the URL from the URL requester // KUrlRequester *file = findChild(); KFileItem fileItem = KFileItem(file->url()); // // Apply the settings to the buttons of the dialog's button box // QPushButton *printButton = findChild("print_button"); printButton->setEnabled(fileItem.url().isValid() && fileItem.isFile()); printButton->setDefault(fileItem.url().isValid() && fileItem.isFile()); QPushButton *cancelButton = findChild("cancel_button"); cancelButton->setDefault(!fileItem.url().isValid() || !fileItem.isFile()); } void Smb4KPrintDialog::slotPrintButtonClicked() { // // Get the file item that is to be printed // KUrlRequester *file = findChild(); m_fileItem = KFileItem(file->url()); if (m_fileItem.url().isValid()) { // // Check if the mime type is supported or if the file can be // converted into a supported mimetype // if (m_fileItem.mimetype() != "application/postscript" && m_fileItem.mimetype() != "application/pdf" && m_fileItem.mimetype() != "application/x-shellscript" && !m_fileItem.mimetype().startsWith(QLatin1String("text")) && !m_fileItem.mimetype().startsWith(QLatin1String("message")) && !m_fileItem.mimetype().startsWith(QLatin1String("image"))) { Smb4KNotification::mimetypeNotSupported(m_fileItem.mimetype()); return; } - else - { - // Do nothing. Mimetype is supported - } // // Save the window size // KConfigGroup group(Smb4KSettings::self()->config(), "PrintDialog"); KWindowConfig::saveWindowSize(windowHandle(), group); // // Emit the printFile() signal // QSpinBox *copies = findChild(); emit printFile(m_share, m_fileItem, copies->value()); // // Emit the aboutToClose() signal // emit aboutToClose(this); // // Close the print dialog // accept(); } - else - { - // Do nothing - } } void Smb4KPrintDialog::slotCancelButtonClicked() { // // Abort the printing // Smb4KClient::self()->abort(); // // Emit the aboutToClose() signal // emit aboutToClose(this); // // Reject the dialog // reject(); } diff --git a/core/smb4kcustomoptions.cpp b/core/smb4kcustomoptions.cpp index 78e40e6..cd88d81 100644 --- a/core/smb4kcustomoptions.cpp +++ b/core/smb4kcustomoptions.cpp @@ -1,1110 +1,1002 @@ /*************************************************************************** This class carries custom options ------------------- begin : Fr 29 Apr 2011 - copyright : (C) 2011-2018 by Alexander Reinholdt + copyright : (C) 2011-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kcustomoptions.h" #include "smb4ksettings.h" #if defined(Q_OS_LINUX) #include "smb4kmountsettings_linux.h" #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) #include "smb4kmountsettings_bsd.h" #endif // Qt includes #include #include // KDE includes #include #include class Smb4KCustomOptionsPrivate { public: QString workgroup; QUrl url; QHostAddress ip; NetworkItem type; #if !defined(SMB4K_UNSUPPORTED_PLATFORM) Smb4KCustomOptions::Remount remount; bool useUser; KUser user; bool useGroup; KUserGroup group; bool useFileMode; QString fileMode; bool useDirectoryMode; QString directoryMode; #endif #if defined(Q_OS_LINUX) bool cifsUnixExtensionsSupport; bool useFileSystemPort; int fileSystemPort; bool useSecurityMode; int securityMode; bool useWriteAccess; int writeAccess; #endif QString profile; bool useSmbPort; int smbPort; bool useKerberos; QString mac; bool wakeOnLanBeforeFirstScan; bool wakeOnLanBeforeMount; }; Smb4KCustomOptions::Smb4KCustomOptions(Smb4KHost *host) : d(new Smb4KCustomOptionsPrivate) { d->workgroup = host->workgroupName(); d->url = host->url(); d->type = Host; #if !defined(SMB4K_UNSUPPORTED_PLATFORM) d->remount = UndefinedRemount; d->useUser = Smb4KMountSettings::useUserId(); d->user = KUser(Smb4KMountSettings::userId()); d->useGroup = Smb4KMountSettings::useGroupId(); d->group = KUserGroup(Smb4KMountSettings::groupId()); d->useFileMode = Smb4KMountSettings::useFileMode(); d->fileMode = Smb4KMountSettings::fileMode(); d->useDirectoryMode = Smb4KMountSettings::useDirectoryMode(); d->directoryMode = Smb4KMountSettings::directoryMode(); #endif #if defined(Q_OS_LINUX) d->cifsUnixExtensionsSupport = Smb4KMountSettings::cifsUnixExtensionsSupport(); d->useFileSystemPort = Smb4KMountSettings::useRemoteFileSystemPort(); d->fileSystemPort = Smb4KMountSettings::remoteFileSystemPort(); d->useSecurityMode = Smb4KMountSettings::useSecurityMode(); d->securityMode = Smb4KMountSettings::securityMode(); d->useWriteAccess = Smb4KMountSettings::useWriteAccess(); d->writeAccess = Smb4KMountSettings::writeAccess(); #endif d->useSmbPort = Smb4KSettings::useRemoteSmbPort(); d->smbPort = host->port() != -1 ? host->port() : Smb4KSettings::remoteSmbPort(); d->useKerberos = Smb4KSettings::useKerberos(); d->ip.setAddress(host->ipAddress()); d->wakeOnLanBeforeFirstScan = false; d->wakeOnLanBeforeMount = false; } Smb4KCustomOptions::Smb4KCustomOptions(Smb4KShare *share) : d(new Smb4KCustomOptionsPrivate) { d->url = share->url(); d->workgroup = share->workgroupName(); d->type = Share; #if !defined(SMB4K_UNSUPPORTED_PLATFORM) d->remount = UndefinedRemount; d->useUser = Smb4KMountSettings::useUserId(); d->user = share->user(); d->useGroup = Smb4KMountSettings::useGroupId(); d->group = share->group(); d->useFileMode = Smb4KMountSettings::useFileMode(); d->fileMode = Smb4KMountSettings::fileMode(); d->useDirectoryMode = Smb4KMountSettings::useDirectoryMode(); d->directoryMode = Smb4KMountSettings::directoryMode(); #endif #if defined(Q_OS_LINUX) d->cifsUnixExtensionsSupport = Smb4KMountSettings::cifsUnixExtensionsSupport(); d->useFileSystemPort = Smb4KMountSettings::useRemoteFileSystemPort(); d->fileSystemPort = share->port() != -1 ? share->port() : Smb4KMountSettings::remoteFileSystemPort(); d->useSecurityMode = Smb4KMountSettings::useSecurityMode(); d->securityMode = Smb4KMountSettings::securityMode(); d->useWriteAccess = Smb4KMountSettings::useWriteAccess(); d->writeAccess = Smb4KMountSettings::writeAccess(); #endif d->useSmbPort = Smb4KSettings::useRemoteSmbPort(); d->smbPort = Smb4KSettings::remoteSmbPort(); d->useKerberos = Smb4KSettings::useKerberos(); d->ip.setAddress(share->hostIpAddress()); d->wakeOnLanBeforeFirstScan = false; d->wakeOnLanBeforeMount = false; } Smb4KCustomOptions::Smb4KCustomOptions(const Smb4KCustomOptions &o) : d(new Smb4KCustomOptionsPrivate) { *d = *o.d; } Smb4KCustomOptions::Smb4KCustomOptions() : d(new Smb4KCustomOptionsPrivate) { d->type = UnknownNetworkItem; #if !defined(SMB4K_UNSUPPORTED_PLATFORM) d->remount = UndefinedRemount; d->useUser = Smb4KMountSettings::useUserId(); d->user = KUser(Smb4KMountSettings::userId()); d->useGroup = Smb4KMountSettings::useGroupId(); d->group = KUserGroup(Smb4KMountSettings::groupId()); d->useFileMode = Smb4KMountSettings::useFileMode(); d->fileMode = Smb4KMountSettings::fileMode(); d->useDirectoryMode = Smb4KMountSettings::useDirectoryMode(); d->directoryMode = Smb4KMountSettings::directoryMode(); #endif #if defined(Q_OS_LINUX) d->cifsUnixExtensionsSupport = Smb4KMountSettings::cifsUnixExtensionsSupport(); d->useFileSystemPort = Smb4KMountSettings::useRemoteFileSystemPort(); d->fileSystemPort = Smb4KMountSettings::remoteFileSystemPort(); d->useSecurityMode = Smb4KMountSettings::useSecurityMode(); d->securityMode = Smb4KMountSettings::securityMode(); d->useWriteAccess = Smb4KMountSettings::useWriteAccess(); d->writeAccess = Smb4KMountSettings::writeAccess(); #endif d->useSmbPort = Smb4KSettings::useRemoteSmbPort(); d->smbPort = Smb4KSettings::remoteSmbPort(); d->useKerberos = Smb4KSettings::useKerberos(); d->wakeOnLanBeforeFirstScan = false; d->wakeOnLanBeforeMount = false; } Smb4KCustomOptions::~Smb4KCustomOptions() { } void Smb4KCustomOptions::setHost(Smb4KHost *host) { // // Set all variables that can be extracted from the host item // if (host) { switch (d->type) { case UnknownNetworkItem: { d->workgroup = host->workgroupName(); d->url = host->url(); d->type = Host; d->smbPort = host->port() != -1 ? host->port() : d->smbPort; d->ip.setAddress(host->ipAddress()); break; } default: { break; } } } - else - { - // Do nothing - } } void Smb4KCustomOptions::setShare(Smb4KShare *share) { // // Set all variables that can be extracted from the share item // if (share) { switch (d->type) { case UnknownNetworkItem: { d->url = share->url(); d->workgroup = share->workgroupName(); d->type = Share; #if defined(Q_OS_LINUX) d->fileSystemPort = share->port() != -1 ? share->port() : d->fileSystemPort; #endif #if !defined(SMB4K_UNSUPPORTED_PLATFORM) d->user = share->user(); d->group = share->group(); #endif d->ip.setAddress(share->hostIpAddress()); break; } case Host: { if (QString::compare(d->url.toString(QUrl::RemoveUserInfo|QUrl::RemovePort|QUrl::RemovePath), share->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort|QUrl::RemovePath), Qt::CaseInsensitive) == 0) { d->url = share->url(); d->type = Share; #if defined(Q_OS_LINUX) d->fileSystemPort = share->port() != -1 ? share->port() : d->fileSystemPort; #endif #if !defined(SMB4K_UNSUPPORTED_PLATFORM) d->user = share->user(); d->group = share->group(); #endif d->ip.setAddress(share->hostIpAddress()); } - else - { - // Do nothing - } break; } default: { break; } } } - else - { - // Do nothing - } } Smb4KGlobal::NetworkItem Smb4KCustomOptions::type() const { return d->type; } void Smb4KCustomOptions::setWorkgroupName(const QString &workgroup) { d->workgroup = workgroup; } QString Smb4KCustomOptions::workgroupName() const { return d->workgroup; } void Smb4KCustomOptions::setUrl(const QUrl &url) { d->url = url; } QUrl Smb4KCustomOptions::url() const { return d->url; } QString Smb4KCustomOptions::hostName() const { return d->url.host().toUpper(); } QString Smb4KCustomOptions::shareName() const { if (d->url.path().startsWith('/')) { return d->url.path().remove(0, 1); } - else - { - // Do nothing - } return d->url.path(); } void Smb4KCustomOptions::setIpAddress(const QString &ip) { d->ip.setAddress(ip); } QString Smb4KCustomOptions::ipAddress() const { return d->ip.toString(); } bool Smb4KCustomOptions::hasIpAddress() const { return !d->ip.isNull(); } QString Smb4KCustomOptions::displayString() const { QString string; switch (d->type) { case Host: { string = hostName(); break; } case Share: { string = i18n("%1 on %2", shareName(), hostName()); break; } default: { break; } } return string; } #if !defined(SMB4K_UNSUPPORTED_PLATFORM) void Smb4KCustomOptions::setRemount(Smb4KCustomOptions::Remount remount) { switch (d->type) { case Share: { d->remount = remount; break; } default: { d->remount = UndefinedRemount; break; } } } Smb4KCustomOptions::Remount Smb4KCustomOptions::remount() const { return d->remount; } void Smb4KCustomOptions::setUseUser(bool use) { d->useUser = use; } bool Smb4KCustomOptions::useUser() const { return d->useUser; } void Smb4KCustomOptions::setUser(const KUser &user) { d->user = user; } KUser Smb4KCustomOptions::user() const { return d->user; } void Smb4KCustomOptions::setUseGroup(bool use) { d->useGroup = use; } bool Smb4KCustomOptions::useGroup() const { return d->useGroup; } void Smb4KCustomOptions::setGroup(const KUserGroup& group) { d->group = group; } KUserGroup Smb4KCustomOptions::group() const { return d->group; } void Smb4KCustomOptions::setUseFileMode(bool use) { d->useFileMode = use; } bool Smb4KCustomOptions::useFileMode() const { return d->useFileMode; } void Smb4KCustomOptions::setFileMode(const QString& mode) { d->fileMode = mode; } QString Smb4KCustomOptions::fileMode() const { return d->fileMode; } void Smb4KCustomOptions::setUseDirectoryMode(bool use) { d->useDirectoryMode = use; } bool Smb4KCustomOptions::useDirectoryMode() const { return d->useDirectoryMode; } void Smb4KCustomOptions::setDirectoryMode(const QString& mode) { d->directoryMode = mode; } QString Smb4KCustomOptions::directoryMode() const { return d->directoryMode; } #endif #if defined(Q_OS_LINUX) void Smb4KCustomOptions::setCifsUnixExtensionsSupport(bool support) { d->cifsUnixExtensionsSupport = support; } bool Smb4KCustomOptions::cifsUnixExtensionsSupport() const { return d->cifsUnixExtensionsSupport; } void Smb4KCustomOptions::setUseFileSystemPort(bool use) { d->useFileSystemPort = use; } bool Smb4KCustomOptions::useFileSystemPort() const { return d->useFileSystemPort; } void Smb4KCustomOptions::setFileSystemPort(int port) { d->fileSystemPort = port; switch (d->type) { case Share: { d->url.setPort(port); break; } default: { break; } } } int Smb4KCustomOptions::fileSystemPort() const { return d->fileSystemPort; } void Smb4KCustomOptions::setUseSecurityMode(bool use) { d->useSecurityMode = use; } bool Smb4KCustomOptions::useSecurityMode() const { return d->useSecurityMode; } void Smb4KCustomOptions::setSecurityMode(int mode) { d->securityMode = mode; } int Smb4KCustomOptions::securityMode() const { return d->securityMode; } void Smb4KCustomOptions::setUseWriteAccess(bool use) { d->useWriteAccess = use; } bool Smb4KCustomOptions::useWriteAccess() const { return d->useWriteAccess; } void Smb4KCustomOptions::setWriteAccess(int access) { d->writeAccess = access; } int Smb4KCustomOptions::writeAccess() const { return d->writeAccess; } #endif void Smb4KCustomOptions::setProfile(const QString &profile) { d->profile = profile; } QString Smb4KCustomOptions::profile() const { return d->profile; } void Smb4KCustomOptions::setUseSmbPort(bool use) { d->useSmbPort = use; } bool Smb4KCustomOptions::useSmbPort() const { return d->useSmbPort; } void Smb4KCustomOptions::setSmbPort(int port) { d->smbPort = port; switch (d->type) { case Host: { d->url.setPort(port); break; } default: { break; } } } int Smb4KCustomOptions::smbPort() const { return d->smbPort; } void Smb4KCustomOptions::setUseKerberos(bool use) { d->useKerberos = use; } bool Smb4KCustomOptions::useKerberos() const { return d->useKerberos; } void Smb4KCustomOptions::setMACAddress(const QString &macAddress) { QRegExp exp("..\\:..\\:..\\:..\\:..\\:.."); if (exp.exactMatch(macAddress)) { d->mac = macAddress; } - else - { - // Do nothing - } } QString Smb4KCustomOptions::macAddress() const { return d->mac; } void Smb4KCustomOptions::setWOLSendBeforeNetworkScan(bool send) { d->wakeOnLanBeforeFirstScan = send; } bool Smb4KCustomOptions::wolSendBeforeNetworkScan() const { return d->wakeOnLanBeforeFirstScan; } void Smb4KCustomOptions::setWOLSendBeforeMount(bool send) { d->wakeOnLanBeforeMount = send; } bool Smb4KCustomOptions::wolSendBeforeMount() const { return d->wakeOnLanBeforeMount; } QMap Smb4KCustomOptions::customOptions() const { QMap entries; #if !defined(SMB4K_UNSUPPORTED_PLATFORM) switch (d->remount) { case RemountOnce: { entries.insert("remount", "once"); break; } case RemountAlways: { entries.insert("remount", "always"); break; } case RemountNever: { entries.insert("remount", "never"); break; } case UndefinedRemount: { entries.insert("remount", QString()); break; } default: { break; } } entries.insert("use_user", d->useUser ? "true" : "false"); entries.insert("uid", QString("%1").arg(d->user.userId().toString())); entries.insert("owner", d->user.loginName()); entries.insert("use_group", d->useGroup ? "true" : "false"); entries.insert("gid", QString("%1").arg(d->group.groupId().toString())); entries.insert("group", d->group.name()); entries.insert("use_file_mode", d->useFileMode ? "true" : "false"); entries.insert("file_mode", d->fileMode); entries.insert("use_directory_mode", d->useDirectoryMode ? "true" : "false"); entries.insert("directory_mode", d->directoryMode); #endif #if defined(Q_OS_LINUX) entries.insert("cifs_unix_extensions_support", d->cifsUnixExtensionsSupport ? "true" : "false"); entries.insert("use_filesystem_port", d->useFileSystemPort ? "true" : "false"); entries.insert("filesystem_port", QString("%1").arg(fileSystemPort())); entries.insert("use_security_mode", d->useSecurityMode ? "true" : "false"); switch (d->securityMode) { case Smb4KMountSettings::EnumSecurityMode::None: { entries.insert("security_mode", "none"); break; } case Smb4KMountSettings::EnumSecurityMode::Krb5: { entries.insert("security_mode", "krb5"); break; } case Smb4KMountSettings::EnumSecurityMode::Krb5i: { entries.insert("security_mode", "krb5i"); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlm: { entries.insert("security_mode", "ntlm"); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmi: { entries.insert("security_mode", "ntlmi"); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmv2: { entries.insert("security_mode", "ntlmv2"); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmv2i: { entries.insert("security_mode", "ntlmv2i"); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmssp: { entries.insert("security_mode", "ntlmssp"); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmsspi: { entries.insert("security_mode", "ntlmsspi"); break; } default: { break; } } entries.insert("use_write_access", d->useWriteAccess ? "true" : "false"); switch (d->writeAccess) { case Smb4KMountSettings::EnumWriteAccess::ReadWrite: { entries.insert("write_access", "true"); break; } case Smb4KMountSettings::EnumWriteAccess::ReadOnly: { entries.insert("write_access", "false"); break; } default: { break; } } #endif entries.insert("use_smb_port", d->useSmbPort ? "true" : "false"); entries.insert("smb_port", QString("%1").arg(smbPort())); entries.insert("kerberos", d->useKerberos ? "true" : "false"); entries.insert("mac_address", d->mac); entries.insert("wol_send_before_first_scan", d->wakeOnLanBeforeFirstScan ? "true" : "false"); entries.insert("wol_send_before_mount", d->wakeOnLanBeforeMount ? "true" : "false"); return entries; } bool Smb4KCustomOptions::hasOptions() const { // // NOTE: This function does not honor the workgroup, the url, // the ip address, the type and the profile, because these things // are not custom options. // #if !defined(SMB4K_UNSUPPORTED_PLATFORM) // Perform remount if (d->remount != Smb4KCustomOptions::UndefinedRemount) { return true; } - else - { - // Do nothing - } // Use user information if (d->useUser != Smb4KMountSettings::useUserId()) { return true; } - else - { - // Do nothing - } // User information if (d->user.userId() != KUser(Smb4KMountSettings::userId()).userId()) { return true; } - else - { - // Do nothing - } // Use group information if (d->useGroup != Smb4KMountSettings::useGroupId()) { return true; } - else - { - // Do nothing - } // Group information if (d->group.groupId() != KUserGroup(Smb4KMountSettings::groupId()).groupId()) { return true; } - else - { - // Do nothing - } // Use file mask if (d->useFileMode != Smb4KMountSettings::useFileMode()) { return true; } - else - { - // Do nothing - } if (d->fileMode != Smb4KMountSettings::fileMode()) { return true; } - else - { - // Do nothing - } if (d->useDirectoryMode != Smb4KMountSettings::useDirectoryMode()) { return true; } - else - { - // Do nothing - } if (d->directoryMode != Smb4KMountSettings::directoryMode()) { return true; } - else - { - // Do nothing - } #endif #if defined(Q_OS_LINUX) // CIFS Unix extension support if (d->cifsUnixExtensionsSupport != Smb4KMountSettings::cifsUnixExtensionsSupport()) { return true; } - else - { - // Do nothing - } // Use filesystem port if (d->useFileSystemPort != Smb4KMountSettings::useRemoteFileSystemPort()) { return true; } - else - { - // Do nothing - } // File system port (used for mounting) if (d->fileSystemPort != Smb4KMountSettings::remoteFileSystemPort()) { return true; } - else - { - // Do nothing - } // Use security mode if (d->useSecurityMode != Smb4KMountSettings::useSecurityMode()) { return true; } - else - { - // Do nothing - } // Security mode if (d->securityMode != Smb4KMountSettings::securityMode()) { return true; } - else - { - // Do nothing - } // Use write access if (d->useWriteAccess != Smb4KMountSettings::useWriteAccess()) { return true; } - else - { - // Do nothing - } // Write access if (d->writeAccess != Smb4KMountSettings::writeAccess()) { return true; } - else - { - // Do nothing - } #endif // Use SMB port if (d->useSmbPort != Smb4KSettings::useRemoteSmbPort()) { return true; } - else - { - // Do nothing - } // SMB port if (d->smbPort != Smb4KSettings::remoteSmbPort()) { return true; } - else - { - // Do nothing - } // Kerberos if (d->useKerberos != Smb4KSettings::useKerberos()) { return true; } - else - { - // Do nothing - } // MAC address if (!d->mac.isEmpty()) { return true; } - else - { - // Do nothing - } // Send WOL packages before first scan if (d->wakeOnLanBeforeFirstScan) { return true; } - else - { - // Do nothing - } // Send WOL packages before mount if (d->wakeOnLanBeforeMount) { return true; } - else - { - // Do nothing - } return false; } void Smb4KCustomOptions::update(Smb4KCustomOptions *options) { d->ip.setAddress(options->ipAddress()); #if !defined(SMB4K_UNSUPPORTED_PLATFORM) d->remount = options->remount(); d->useUser = options->useUser(); d->user = options->user(); d->useGroup = options->useGroup(); d->group = options->group(); d->useFileMode = options->useFileMode(); d->fileMode = options->fileMode(); d->useDirectoryMode = options->useDirectoryMode(); d->directoryMode = options->directoryMode(); #endif #if defined(Q_OS_LINUX) d->cifsUnixExtensionsSupport = options->cifsUnixExtensionsSupport(); d->useFileSystemPort = options->useFileSystemPort(); d->fileSystemPort = options->fileSystemPort(); d->useSecurityMode = options->useSecurityMode(); d->securityMode = options->securityMode(); d->useWriteAccess = options->useWriteAccess(); d->writeAccess = options->writeAccess(); #endif d->profile = options->profile(); d->useSmbPort = options->useSmbPort(); d->smbPort = options->smbPort(); d->useKerberos = options->useKerberos(); d->mac = options->macAddress(); d->wakeOnLanBeforeFirstScan = options->wolSendBeforeNetworkScan(); d->wakeOnLanBeforeMount = options->wolSendBeforeMount(); } diff --git a/core/smb4kcustomoptions.h b/core/smb4kcustomoptions.h index c5140a8..b847afe 100644 --- a/core/smb4kcustomoptions.h +++ b/core/smb4kcustomoptions.h @@ -1,577 +1,577 @@ /*************************************************************************** This class carries custom options ------------------- begin : Fr 29 Apr 2011 - copyright : (C) 2011-2018 by Alexander Reinholdt + copyright : (C) 2011-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifndef SMB4KCUSTOMOPTIONS_H #define SMB4KCUSTOMOPTIONS_H // application specific includes #include "smb4khost.h" #include "smb4kshare.h" #include "smb4kglobal.h" // Qt includes #include #include // KDE includes #include // forward declarations class Smb4KCustomOptionsPrivate; using namespace Smb4KGlobal; /** * This class stores the custom options defined for a certain host * or share. * * @author Alexander Reinholdt * @since 1.0.0 */ class Q_DECL_EXPORT Smb4KCustomOptions { friend class Smb4KCustomOptionsPrivate; public: /** * Constructor for a host */ explicit Smb4KCustomOptions(Smb4KHost *host); /** * Constructor for a share */ explicit Smb4KCustomOptions(Smb4KShare *share); /** * Copy constructor */ Smb4KCustomOptions(const Smb4KCustomOptions &options); /** * Empty constructor */ Smb4KCustomOptions(); /** * Destructor */ ~Smb4KCustomOptions(); /** * Sets the host object. If you already set a network item before, * this function will do nothing. * * @param host The host object */ void setHost(Smb4KHost *host); /** * Sets the share object. If you already set a host item before, * you can overwrite it with this function if the host names and * workgroup names match. This way you can propagate options that * were defined for a host to one of its shares. * * @param share The host object */ void setShare(Smb4KShare *share); /** * Returns the type of the network item for that the options * are defined * * @returns the type of the network item */ Smb4KGlobal::NetworkItem type() const; /** * Sets the workgroup name. * * @param workgroup The workgroup name */ void setWorkgroupName(const QString &workgroup); /** * Returns the workgroup name. * * @returns the workgroup name. */ QString workgroupName() const; /** * Sets the URL of the network item * * @param url The URL */ void setUrl(const QUrl &url); /** * Returns the URL of the network item * * @returns the URL */ QUrl url() const; /** * Returns the host name. * * @returns the host name. */ QString hostName() const; /** * Returns the share name, if appropriate, or an empty string. * * @returns the share name */ QString shareName() const; /** * Sets the IP address for the network item * * @param ip The IP address */ void setIpAddress(const QString &ip); /** * Returns the IP address of the network item * * @returns the IP address */ QString ipAddress() const; /** * Returns TRUE if the IP address is set and FALSE otherwise. * * @returns TRUE if the IP address is known. */ bool hasIpAddress() const; /** * Returns the display string. Prefer this over all other alternatives in your * GUI. * @returns the display string. */ QString displayString() const; #if !defined(SMB4K_UNSUPPORTED_PLATFORM) /** * Remount enumeration * * @param RemountOnce Remount the share only next time the application * is started. * @param RemountAlways Remount the share every time the application is * started. * @param RemountNever Never remount the share. * @param UndefinedRemount No remount option is defined. */ enum Remount { RemountOnce, RemountAlways, RemountNever, UndefinedRemount }; /** * If the network item is of type Share, set if it should be remounted. * If the network item is not of type Share, this function does nothing. * * @param remount One entry of the Remount enumeration */ void setRemount(Remount remount); /** * Returns if the network item should be remounted. * * @returns if the network item should be remounted. */ Remount remount() const; /** * Set if the information about the user that is to be owner of the share * should be used when mounting or not. * * @param usage Boolean that determines whether the uid should be * used. */ void setUseUser(bool use); /** * Use the information about the user that is to be owner of the share. * * @returns TRUE if the uid should be used when mounting. */ bool useUser() const; /** * Set the user who owns the share. * @param user The user */ void setUser(const KUser &user); /** * Returns the user who owns the share. * @returns the user */ KUser user() const; /** * Set if the information about the group that is to be owner of the share * should be used when mounting or not. * * @param use Boolean that determines whether the gid should be used. */ void setUseGroup(bool use); /** * Use the information about the group that is to be owner of the share. * * @returns TRUE if the gid should be used when mounting. */ bool useGroup() const; /** * Set the group that owns the share. * * @param group The group */ void setGroup(const KUserGroup &group); /** * Returns the group that owns the share. * * @returns the group */ KUserGroup group() const; /** * Set if the file mode should be used. * * @param use Boolean that determines whether the file mode should be used. */ void setUseFileMode(bool use); /** * Returns if the file mode should be used. * * @return TRUE if the file mode should be used */ bool useFileMode() const; /** * Set the file mode that should be used. The value must be defined in octal. * * @param mode The file mode */ void setFileMode(const QString &mode); /** * Returns the file mode that should be used. The value is returned in octal. * * @returns the file mode */ QString fileMode() const; /** * Set if the directory mode should be used. * * @param use Boolean that determines whether the directory mode should be used. */ void setUseDirectoryMode(bool use); /** * Returns if the directory mode should be used. * * @return TRUE if the file directory should be used */ bool useDirectoryMode() const; /** * Set the directory mode that should be used. The value must be defined in octal. * * @param mode The directory mode */ void setDirectoryMode(const QString &mode); /** * Returns the directory mode that should be used. The value is returned in octal. * * @returns the directory mode */ QString directoryMode() const; #endif #if defined(Q_OS_LINUX) /** * Set if the server supports the CIFS Unix Extensions. If this setting is set, * the parameters that are not needed in the case of support are cleared. * * @param supports Boolean that determines if the server supports * the CIFS Unix extensions. */ void setCifsUnixExtensionsSupport(bool support); /** * The server supports the CIFS Unix extensions. * * @returns TRUE if the server supports the CIFS Unix Extensions. */ bool cifsUnixExtensionsSupport() const; /** * Set if the filesystem port should be used * * @param use Boolean that determines if the filesystem port should * be used */ void setUseFileSystemPort(bool use); /** * Returns if the filesystem port should be used. * * @returns TRUE if the filesystem port should be used */ bool useFileSystemPort() const; /** * Set the port that is to be used with mounting for a single share or all * shares of a host. * * @param port The file system port */ void setFileSystemPort(int port); /** * Returns the file system port. The default value is 445. * * @returns the file system port */ int fileSystemPort() const; /** * Set if the security mode should be used. * * @param use Boolean that determines if the security mode should * be used */ void setUseSecurityMode(bool use); /** * Returns if the security mode should be used * * @returns TRUE if the security mode should be used */ bool useSecurityMode() const; /** * Set the security mode for mounting. * * @param mode The security mode */ void setSecurityMode(int mode); /** * Returns the security mode for mounting a specific share. * * @returns the security mode */ int securityMode() const; /** * Set if the write access setting should be used. * * @param use Boolean that determines if the write access setting * should be used */ void setUseWriteAccess(bool use); /** * Returns if the write access setting should be used * * @returns TRUE if the write access setting should be used */ bool useWriteAccess() const; /** * Set the write access for either a single share or all shares of a host. * * @param access The write access */ void setWriteAccess(int access); /** * Returns the write access for the share. * * @returns the write access */ int writeAccess() const; #endif /** * Set the profile this custom options object belongs to. The profile is * meant to distinguish between several network environments, like home * and work. * * @param profile The profile name */ void setProfile(const QString &profile); /** * Returns the name of the profile this custom options object belongs to. * * @returns the profile name */ QString profile() const; /** * Set whether the SMB port should be used. * * @param use True, if the SMB port should be used */ void setUseSmbPort(bool use); /** * Returns whether the SMB port should be used. * * @returns TRUE if the SMB port should be used. */ bool useSmbPort() const; /** * Set the SMB port to use with this host or share. * * @param port The SMB port */ void setSmbPort(int port); /** * Returns the SMB port. The default value is 139. * * @returns the SMB port */ int smbPort() const; /** * Sets the useage of Kerberos for this network item. * * @param use Boolean that determines the useage of Kerberos */ void setUseKerberos(bool use); /** * Returns the usage of Kerberos for this network item. * * @returns the usage of Kerberos */ bool useKerberos() const; /** * This function sets the MAC address of a host. In case the options * represent a share this is the MAC address of the host that shares * the resource. * * @param macAddress The MAC address of the host */ void setMACAddress(const QString &macAddress); /** * This function returns the MAC address of the host or an empty string if * no MAC address was defined. * * @returns the MAC address of the host. */ QString macAddress() const; /** * Set whether a magic WOL package should be send to the host that this * network item represents or where this network item is located before scanning * the entire network. * * @param send Boolean that determines if a magic WOL package * is to be sent. */ void setWOLSendBeforeNetworkScan(bool send); /** * Send a magic WOL package to the host that this network item represents * or where this network item is located before scanning the entire network. * * @returns TRUE if a magic WOL package should be send on first network * scan. */ bool wolSendBeforeNetworkScan() const; /** * Set whether a magic WOL package should be send to the host that this * network item represents or where this network item is located before a * mount attempt. * * @param send Boolean that determines if a magic WOL package * is to be sent. */ void setWOLSendBeforeMount(bool send); /** * Send a magic WOL package to the host that this network item represents * or where this network item is located before a mount attempt. * * @returns TRUE if a magic WOL package should be send on first network * scan. */ bool wolSendBeforeMount() const; /** * This function returns all custom options in a sorted map. The URL, * workgroup and IP address must be retrieved separately if needed. * * Note that all entries that are set and valid are returned here. This * also comprises default values (e.g. the default SMB port). If you need * to check if a certain value is a custom option or not, you need to implement * this check. * * @returns all valid entries. */ QMap customOptions() const; /** * Check if there are options defined * * @returns TRUE if there are options defined and FALSE otherwise */ bool hasOptions() const; /** * Update this custom options object. You cannot change the workgroup, * URL and type with this function. * * @param options The options that are used to update this object */ void update(Smb4KCustomOptions *options); private: const QScopedPointer d; }; #endif diff --git a/core/smb4kcustomoptionsmanager.cpp b/core/smb4kcustomoptionsmanager.cpp index 3c99c15..a433d13 100644 --- a/core/smb4kcustomoptionsmanager.cpp +++ b/core/smb4kcustomoptionsmanager.cpp @@ -1,1176 +1,1175 @@ /*************************************************************************** Manage custom options ------------------- begin : Fr 29 Apr 2011 copyright : (C) 2011-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kcustomoptionsmanager.h" #include "smb4kcustomoptionsmanager_p.h" #include "smb4kcustomoptions.h" #include "smb4khomesshareshandler.h" #include "smb4knotification.h" #include "smb4khost.h" #include "smb4kshare.h" #include "smb4ksettings.h" #include "smb4kglobal.h" #include "smb4kprofilemanager.h" #if defined(Q_OS_LINUX) #include "smb4kmountsettings_linux.h" #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) #include "smb4kmountsettings_bsd.h" #endif // Qt includes #include #include #include #include #include // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include using namespace Smb4KGlobal; Q_GLOBAL_STATIC(Smb4KCustomOptionsManagerStatic, p); Smb4KCustomOptionsManager::Smb4KCustomOptionsManager(QObject *parent) : QObject(parent), d(new Smb4KCustomOptionsManagerPrivate) { // First we need the directory. QString path = dataLocation(); QDir dir; if (!dir.exists(path)) { dir.mkpath(path); } readCustomOptions(); // Connections - connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), - this, SLOT(slotAboutToQuit())); + connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(slotAboutToQuit())); } Smb4KCustomOptionsManager::~Smb4KCustomOptionsManager() { } Smb4KCustomOptionsManager *Smb4KCustomOptionsManager::self() { return &p->instance; } #if !defined(SMB4K_UNSUPPORTED_PLATFORM) void Smb4KCustomOptionsManager::addRemount(const SharePtr &share, bool always) { if (share) { OptionsPtr options = findOptions(share, true); if (options) { // If the options are already in the list, check if the share is // always to be remounted. If so, ignore the 'always' argument // and leave that option untouched. if (options->remount() != Smb4KCustomOptions::RemountAlways) { options->setRemount(always ? Smb4KCustomOptions::RemountAlways : Smb4KCustomOptions::RemountOnce); } } else { options = OptionsPtr(new Smb4KCustomOptions(share.data())); options->setProfile(Smb4KProfileManager::self()->activeProfile()); options->setRemount(always ? Smb4KCustomOptions::RemountAlways : Smb4KCustomOptions::RemountOnce); d->options << options; } writeCustomOptions(); } } void Smb4KCustomOptionsManager::removeRemount(const SharePtr &share, bool force) { if (share) { OptionsPtr options = findOptions(share, true); if (options) { if (options->remount() == Smb4KCustomOptions::RemountOnce) { options->setRemount(Smb4KCustomOptions::RemountNever); } else if (options->remount() == Smb4KCustomOptions::RemountAlways && force) { options->setRemount(Smb4KCustomOptions::RemountNever); } } writeCustomOptions(); } } void Smb4KCustomOptionsManager::clearRemounts(bool force) { // // List of relevant custom options // QList options = customOptions(false); // // Remove the remount flags // for (const OptionsPtr &o : options) { if (o->type() == Share) { if (o->remount() == Smb4KCustomOptions::RemountOnce) { o->setRemount(Smb4KCustomOptions::RemountNever); } else if (o->remount() == Smb4KCustomOptions::RemountAlways && force) { o->setRemount(Smb4KCustomOptions::RemountNever); } } } // // Write the options // writeCustomOptions(); } QList Smb4KCustomOptionsManager::sharesToRemount() { // // List of relevant custom options // QList options = customOptions(false); // // List of remounts // QList remounts; // // Get the list of remounts // for (const OptionsPtr &o : options) { if (o->remount() == Smb4KCustomOptions::RemountOnce) { remounts << o; } else if (o->remount() == Smb4KCustomOptions::RemountAlways) { remounts << o; } } // // Return relevant options // return remounts; } #endif OptionsPtr Smb4KCustomOptionsManager::findOptions(const NetworkItemPtr &networkItem, bool exactMatch) { // // The options that are to be returned // OptionsPtr options; // // Get the list of options // QList optionsList = customOptions(false); // // Only do something if the list of options is not empty. // if (!optionsList.isEmpty()) { switch (networkItem->type()) { case Host: { HostPtr host = networkItem.staticCast(); if (host) { for (const OptionsPtr &o : optionsList) { // In case of a host, there can only be an exact match. if (QString::compare(host->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), o->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0 || (host->url().isEmpty() && host->ipAddress() == o->ipAddress())) { options = o; break; } } } break; } case Share: { SharePtr share = networkItem.staticCast(); if (share) { for (const OptionsPtr &o : optionsList) { if (QString::compare(share->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), o->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0) { options = o; break; } else if (!exactMatch && o->type() == Host && QString::compare(share->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort|QUrl::RemovePath), o->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort|QUrl::RemovePath), Qt::CaseInsensitive) == 0) { options = o; } } } break; } default: { break; } } } return options; } OptionsPtr Smb4KCustomOptionsManager::findOptions(const QUrl &url) { // // The options that are to be returned // OptionsPtr options; // // Search the options for the given URL // if (url.isValid() && url.scheme() == "smb") { // // Get the relevant options // QList optionsList = customOptions(false); // // Get the options // for (const OptionsPtr &o : optionsList) { if (o->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort|QUrl::StripTrailingSlash) == url.toString(QUrl::RemoveUserInfo|QUrl::RemovePort|QUrl::StripTrailingSlash)) { options = o; break; } } } // // Return the options // return options; } void Smb4KCustomOptionsManager::readCustomOptions() { // // Clear the list of options // while (!d->options.isEmpty()) { d->options.takeFirst().clear(); } // // Set the XML file // QFile xmlFile(dataLocation()+QDir::separator()+"custom_options.xml"); if (xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QXmlStreamReader xmlReader(&xmlFile); while (!xmlReader.atEnd()) { xmlReader.readNext(); if (xmlReader.isStartElement()) { if (xmlReader.name() == "custom_options" && (xmlReader.attributes().value("version") != "1.2" && xmlReader.attributes().value("version") != "2.0")) { xmlReader.raiseError(i18n("The format of %1 is not supported.", xmlFile.fileName())); break; } else { if (xmlReader.name() == "options") { OptionsPtr options = OptionsPtr(new Smb4KCustomOptions()); options->setProfile(xmlReader.attributes().value("profile").toString()); // // Initialize the options // if (QString::compare(xmlReader.attributes().value("type").toString(), "host", Qt::CaseInsensitive) == 0) { options->setHost(new Smb4KHost()); } else { options->setShare(new Smb4KShare()); } while (!(xmlReader.isEndElement() && xmlReader.name() == "options")) { xmlReader.readNext(); if (xmlReader.isStartElement()) { if (xmlReader.name() == "workgroup") { options->setWorkgroupName(xmlReader.readElementText()); } else if (xmlReader.name() == "url") { QUrl url(xmlReader.readElementText()); options->setUrl(url); } else if (xmlReader.name() == "unc") { QUrl url = QUrl::fromUserInput(xmlReader.readElementText()); url.setScheme("smb"); options->setUrl(url); } else if (xmlReader.name() == "ip") { options->setIpAddress(xmlReader.readElementText()); } else if (xmlReader.name() == "custom") { while (!(xmlReader.isEndElement() && xmlReader.name() == "custom")) { xmlReader.readNext(); if (xmlReader.isStartElement()) { if (xmlReader.name() == "smb_port") { bool ok = false; int portNumber = xmlReader.readElementText().toInt(&ok); if (ok) { options->setSmbPort(portNumber); } } else if (xmlReader.name() == "use_smb_port") { QString useSmbPort = xmlReader.readElementText(); if (useSmbPort == "true") { options->setUseSmbPort(true); } else { options->setUseSmbPort(false); } } else if (xmlReader.name() == "kerberos") { QString useKerberos = xmlReader.readElementText(); if (useKerberos == "true") { options->setUseKerberos(true); } else { options->setUseKerberos(false); } } else if (xmlReader.name() == "mac_address") { QString macAddress = xmlReader.readElementText(); QRegExp exp("..\\:..\\:..\\:..\\:..\\:.."); if (exp.exactMatch(macAddress)) { options->setMACAddress(macAddress); } } else if (xmlReader.name() == "wol_send_before_first_scan") { QString send = xmlReader.readElementText(); if (send == "true") { options->setWOLSendBeforeNetworkScan(true); } else { options->setWOLSendBeforeNetworkScan(false); } } else if (xmlReader.name() == "wol_send_before_mount") { QString send = xmlReader.readElementText(); if (send == "true") { options->setWOLSendBeforeMount(true); } else { options->setWOLSendBeforeMount(false); } } #if !defined(SMB4K_UNSUPPORTED_PLATFORM) else if (xmlReader.name() == "remount") { QString remount = xmlReader.readElementText(); if (remount == "once") { options->setRemount(Smb4KCustomOptions::RemountOnce); } else if (remount == "always") { options->setRemount(Smb4KCustomOptions::RemountAlways); } else if (remount == "never") { options->setRemount(Smb4KCustomOptions::RemountNever); } else { options->setRemount(Smb4KCustomOptions::UndefinedRemount); } } else if (xmlReader.name() == "use_user") { QString useUser = xmlReader.readElementText(); if (useUser == "true") { options->setUseUser(true); } else { options->setUseUser(false); } } else if (xmlReader.name() == "uid") { KUser user((K_UID)xmlReader.readElementText().toInt()); if (user.isValid()) { options->setUser(user); } } else if (xmlReader.name() == "use_group") { QString useGroup = xmlReader.readElementText(); if (useGroup == "true") { options->setUseGroup(true); } else { options->setUseGroup(false); } } else if (xmlReader.name() == "gid") { KUserGroup group((K_GID)xmlReader.readElementText().toInt()); if (group.isValid()) { options->setGroup(group); } } else if (xmlReader.name() == "use_file_mode") { QString useFileMode = xmlReader.readElementText(); if (useFileMode == "true") { options->setUseFileMode(true); } else { options->setUseFileMode(false); } } else if (xmlReader.name() == "file_mode") { options->setFileMode(xmlReader.readElementText()); } else if (xmlReader.name() == "use_directory_mode") { QString useDirectoryMode = xmlReader.readElementText(); if (useDirectoryMode == "true") { options->setUseDirectoryMode(true); } else { options->setUseDirectoryMode(false); } } else if (xmlReader.name() == "directory_mode") { options->setDirectoryMode(xmlReader.readElementText()); } #endif #if defined(Q_OS_LINUX) else if (xmlReader.name() == "cifs_unix_extensions_support") { QString support = xmlReader.readElementText(); if (support == "true") { options->setCifsUnixExtensionsSupport(true); } else { options->setCifsUnixExtensionsSupport(false); } } else if (xmlReader.name() == "use_filesystem_port") { QString useFilesystemPort = xmlReader.readElementText(); if (useFilesystemPort == "true") { options->setUseFileSystemPort(true); } else { options->setUseFileSystemPort(false); } } else if (xmlReader.name() == "filesystem_port") { bool ok = false; int portNumber = xmlReader.readElementText().toInt(&ok); if (ok) { options->setFileSystemPort(portNumber); } } else if (xmlReader.name() == "use_security_mode") { QString useSecurityMode = xmlReader.readElementText(); if (useSecurityMode == "true") { options->setUseSecurityMode(true); } else { options->setUseSecurityMode(false); } } else if (xmlReader.name() == "security_mode") { QString securityMode = xmlReader.readElementText(); if (securityMode == "none") { options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::None); } else if (securityMode == "krb5") { options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Krb5); } else if (securityMode == "krb5i") { options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Krb5i); } else if (securityMode == "ntlm") { options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Ntlm); } else if (securityMode == "ntlmi") { options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Ntlmi); } else if (securityMode == "ntlmv2") { options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Ntlmv2); } else if (securityMode == "ntlmv2i") { options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Ntlmv2i); } else if (securityMode == "ntlmssp") { options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Ntlmssp); } else if (securityMode == "ntlmsspi") { options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Ntlmsspi); } } else if (xmlReader.name() == "use_write_access") { QString useWriteAccess = xmlReader.readElementText(); if (useWriteAccess == "true") { options->setUseWriteAccess(true); } else { options->setUseWriteAccess(false); } } else if (xmlReader.name() == "write_access") { QString writeAccess = xmlReader.readElementText(); if (writeAccess == "true") { options->setWriteAccess(Smb4KMountSettings::EnumWriteAccess::ReadWrite); } else if (writeAccess == "false") { options->setWriteAccess(Smb4KMountSettings::EnumWriteAccess::ReadWrite); } } #endif } } } continue; } else { continue; } } d->options << options; } } } } xmlFile.close(); if (xmlReader.hasError()) { Smb4KNotification::readingFileFailed(xmlFile, xmlReader.errorString()); } } else { if (xmlFile.exists()) { Smb4KNotification::openingFileFailed(xmlFile); } } } void Smb4KCustomOptionsManager::writeCustomOptions() { // // Set the XML file // QFile xmlFile(dataLocation()+QDir::separator()+"custom_options.xml"); // // Write the options to the file // if (!d->options.isEmpty()) { if (xmlFile.open(QIODevice::WriteOnly|QIODevice::Text)) { QXmlStreamWriter xmlWriter(&xmlFile); xmlWriter.setAutoFormatting(true); xmlWriter.writeStartDocument(); xmlWriter.writeStartElement("custom_options"); xmlWriter.writeAttribute("version", "2.0"); for (const OptionsPtr &options : d->options) { #if !defined(SMB4K_UNSUPPORTED_PLATFORM) if (options->hasOptions() || options->remount() == Smb4KCustomOptions::RemountOnce) #else if (options->hasOptions()) #endif { xmlWriter.writeStartElement("options"); xmlWriter.writeAttribute("type", options->type() == Host ? "host" : "share"); xmlWriter.writeAttribute("profile", options->profile()); xmlWriter.writeTextElement("workgroup", options->workgroupName()); xmlWriter.writeTextElement("url", options->url().toDisplayString()); xmlWriter.writeTextElement("ip", options->ipAddress()); xmlWriter.writeStartElement("custom"); QMap map = options->customOptions(); QMapIterator it(map); while (it.hasNext()) { it.next(); if (!it.value().isEmpty()) { xmlWriter.writeTextElement(it.key(), it.value()); } } xmlWriter.writeEndElement(); xmlWriter.writeEndElement(); } } xmlWriter.writeEndDocument(); xmlFile.close(); } else { Smb4KNotification::openingFileFailed(xmlFile); } } else { xmlFile.remove(); } // FIXME: Flush the list of custom options and reload it? } QList Smb4KCustomOptionsManager::customOptions(bool optionsOnly) { // // Options list // QList options; // // Get this list of options // for (const OptionsPtr &o : d->options) { if (Smb4KSettings::useProfiles() && o->profile() != Smb4KProfileManager::self()->activeProfile()) { continue; } #if !defined(SMB4K_UNSUPPORTED_PLATFORM) if (o->hasOptions() || (!optionsOnly && o->remount() == Smb4KCustomOptions::RemountOnce)) #else if (o->hasOptions()) #endif { options << o; } } // // Return the list of relevant options // return options; } void Smb4KCustomOptionsManager::replaceCustomOptions(const QList &optionsList) { // // Clear the list of options. Honor profiles. // QMutableListIterator it(d->options); while (it.hasNext()) { OptionsPtr options = it.next(); if (Smb4KSettings::useProfiles() && options->profile() != Smb4KProfileManager::self()->activeProfile()) { continue; } it.remove(); } // // Append the new list // if (!optionsList.isEmpty()) { for (const OptionsPtr &options : optionsList) { if (Smb4KSettings::useProfiles()) { options->setProfile(Smb4KProfileManager::self()->activeProfile()); } #if !defined(SMB4K_UNSUPPORTED_PLATFORM) if (options->hasOptions() || options->remount() == Smb4KCustomOptions::RemountOnce) #else if (options->hasOptions()) #endif { d->options << options; } } } writeCustomOptions(); } void Smb4KCustomOptionsManager::openCustomOptionsDialog(const NetworkItemPtr &item) { if (item) { OptionsPtr options; switch (item->type()) { case Host: { HostPtr host = item.staticCast(); if (host) { options = findOptions(host); if (!options) { options = OptionsPtr(new Smb4KCustomOptions(host.data())); options->setProfile(Smb4KProfileManager::self()->activeProfile()); } } break; } case Share: { SharePtr share = item.staticCast(); if (share && !share->isPrinter()) { if (share->isHomesShare()) { if (!Smb4KHomesSharesHandler::self()->specifyUser(share, true)) { return; } } options = findOptions(share); if (!options) { options = OptionsPtr(new Smb4KCustomOptions(share.data())); options->setProfile(Smb4KProfileManager::self()->activeProfile()); // Get rid of the 'homes' share if (share->isHomesShare()) { options->setUrl(share->homeUrl()); } } else { // In case the custom options object for the host has been // returned, change its internal network item, otherwise we // will change the host's custom options... options->setShare(share.data()); } } break; } default: { break; } } if (options) { QPointer dlg = new Smb4KCustomOptionsDialog(options, QApplication::activeWindow()); if (dlg->exec() == QDialog::Accepted) { if (options->hasOptions()) { addCustomOptions(options); } else { removeCustomOptions(options); } } else { resetCustomOptions(); } delete dlg; } } } void Smb4KCustomOptionsManager::addCustomOptions(const OptionsPtr &options) { if (options) { // // Check if options for the URL already exist // OptionsPtr knownOptions = findOptions(options->url()); if (knownOptions) { // // Update the options // knownOptions->update(options.data()); } else { // // Add the options // if (options->profile().isEmpty()) { options->setProfile(Smb4KProfileManager::self()->activeProfile()); } d->options << options; } // // In case the options are defined for a host, propagate them // to the options of shares belonging to that host. Overwrite // the settings // if (options->type() == Host) { for (const OptionsPtr &o : d->options) { if (o->type() == Share && o->hostName() == options->hostName() && o->workgroupName() == options->workgroupName()) { o->setIpAddress(options->ipAddress()); #if !defined(SMB4K_UNSUPPORTED_PLATFORM) o->setUseUser(options->useUser()); o->setUser(options->user()); o->setUseGroup(options->useGroup()); o->setGroup(options->group()); o->setUseFileMode(options->useFileMode()); o->setFileMode(options->fileMode()); o->setUseDirectoryMode(options->useDirectoryMode()); o->setDirectoryMode(options->directoryMode()); #endif #if defined(Q_OS_LINUX) o->setCifsUnixExtensionsSupport(options->cifsUnixExtensionsSupport()); o->setUseFileSystemPort(options->useFileSystemPort()); o->setFileSystemPort(options->fileSystemPort()); o->setUseSecurityMode(options->useSecurityMode()); o->setSecurityMode(options->securityMode()); o->setUseWriteAccess(options->useWriteAccess()); o->setWriteAccess(options->writeAccess()); #endif o->setUseSmbPort(options->useSmbPort()); o->setSmbPort(options->smbPort()); o->setUseKerberos(options->useKerberos()); o->setMACAddress(options->macAddress()); o->setWOLSendBeforeNetworkScan(options->wolSendBeforeNetworkScan()); o->setWOLSendBeforeMount(options->wolSendBeforeMount()); } } } // // Write the custom options to the file // writeCustomOptions(); } } void Smb4KCustomOptionsManager::removeCustomOptions(const OptionsPtr &options) { if (options) { // // Find the custom options and remove them // for (int i = 0; i < d->options.size(); ++i) { if ((!Smb4KSettings::useProfiles() || Smb4KProfileManager::self()->activeProfile() == d->options.at(i)->profile()) && d->options.at(i)->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort|QUrl::StripTrailingSlash) == options->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort|QUrl::StripTrailingSlash)) { d->options.takeAt(i).clear(); break; } } // // Write the custom options to the file // writeCustomOptions(); } } QList Smb4KCustomOptionsManager::wakeOnLanEntries() const { QList list; // // Get the Wake-On-LAN entries // for (const OptionsPtr &options : d->options) { if (!options->macAddress().isEmpty() && (options->wolSendBeforeNetworkScan() || options->wolSendBeforeMount())) { list << options; } } // // Return them // return list; } void Smb4KCustomOptionsManager::resetCustomOptions() { readCustomOptions(); } void Smb4KCustomOptionsManager::migrateProfile(const QString& from, const QString& to) { // // Replace the old with the new profile // for (const OptionsPtr &options : d->options) { if (options->profile() == from) { options->setProfile(to); } } // // Write all custom options to the file. // writeCustomOptions(); } void Smb4KCustomOptionsManager::removeProfile(const QString& name) { // // Remove all entries belonging to the profile // QMutableListIterator it(d->options); while (it.hasNext()) { OptionsPtr options = it.next(); if (QString::compare(options->profile(), name, Qt::CaseSensitive) == 0) { it.remove(); } } // // Write all custom options to the file. // writeCustomOptions(); } ///////////////////////////////////////////////////////////////////////////// // SLOT IMPLEMENTATIONS ///////////////////////////////////////////////////////////////////////////// void Smb4KCustomOptionsManager::slotAboutToQuit() { writeCustomOptions(); } diff --git a/core/smb4kcustomoptionsmanager_p.cpp b/core/smb4kcustomoptionsmanager_p.cpp index 0e383b5..25940d3 100644 --- a/core/smb4kcustomoptionsmanager_p.cpp +++ b/core/smb4kcustomoptionsmanager_p.cpp @@ -1,2459 +1,2019 @@ /*************************************************************************** Private helper classes for Smb4KCustomOptionsManagerPrivate class ------------------- begin : Fr 29 Apr 2011 copyright : (C) 2011-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kcustomoptionsmanager_p.h" #include "smb4ksettings.h" #if defined(Q_OS_LINUX) #include "smb4kmountsettings_linux.h" #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) #include "smb4kmountsettings_bsd.h" #endif // Qt includes #include #include #include #include #include #include #include #include #include #include #include #include // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include #include #include #include #include #include Smb4KCustomOptionsDialog::Smb4KCustomOptionsDialog(const OptionsPtr &options, QWidget *parent) : QDialog(parent), m_options(options) { // // Set the title // setWindowTitle(i18n("Custom Options")); // // Set up the layout // QVBoxLayout *layout = new QVBoxLayout(this); layout->setSpacing(5); setLayout(layout); // Header QWidget *header = new QWidget(this); QHBoxLayout *headerLayout = new QHBoxLayout(header); headerLayout->setSpacing(5); headerLayout->setMargin(0); QLabel *pixmap = new QLabel(header); QPixmap preferencesPixmap = KDE::icon("preferences-system-network").pixmap(KIconLoader::SizeHuge); pixmap->setPixmap(preferencesPixmap); pixmap->setAlignment(Qt::AlignCenter); QLabel *description = 0; switch (m_options->type()) { case Host: { description = new QLabel(i18n("

Define custom options for host %1 and all the shares it provides.

", m_options->displayString()), header); break; } case Share: { description = new QLabel(i18n("

Define custom options for share %1.

", m_options->displayString()), header); break; } default: { description = new QLabel(); break; } } description->setWordWrap(true); description->setAlignment(Qt::AlignVCenter); headerLayout->addWidget(pixmap, 0); headerLayout->addWidget(description, Qt::AlignVCenter); layout->addWidget(header, 0); // // Set up the operating system dependent stuff // setupView(); // // Finish the layout // QDialogButtonBox *buttonBox = new QDialogButtonBox(Qt::Horizontal, this); QPushButton *restoreButton = buttonBox->addButton(QDialogButtonBox::RestoreDefaults); QPushButton *okButton = buttonBox->addButton(QDialogButtonBox::Ok); okButton->setShortcut(Qt::CTRL|Qt::Key_Return); okButton->setDefault(true); QPushButton *cancelButton = buttonBox->addButton(QDialogButtonBox::Cancel); cancelButton->setShortcut(Qt::Key_Escape); layout->addWidget(buttonBox, 0); // // Connections // connect(restoreButton, SIGNAL(clicked()), SLOT(slotSetDefaultValues())); connect(okButton, SIGNAL(clicked()), SLOT(slotOKClicked())); connect(cancelButton, SIGNAL(clicked()), SLOT(reject())); // // Load settings // create(); KConfigGroup group(Smb4KSettings::self()->config(), "CustomOptionsDialog"); KWindowConfig::restoreWindowSize(windowHandle(), group); resize(windowHandle()->size()); // workaround for QTBUG-40584 // // Enable/disable buttons // restoreButton->setEnabled(!checkDefaultValues()); } Smb4KCustomOptionsDialog::~Smb4KCustomOptionsDialog() { } #if defined(Q_OS_LINUX) // // Linux // void Smb4KCustomOptionsDialog::setupView() { // // Tab widget with settings // QTabWidget *tabWidget = new QTabWidget(this); QVBoxLayout *dialogLayout = qobject_cast(layout()); dialogLayout->addWidget(tabWidget, 0); // // Custom options for mounting // QWidget *mountingTab = new QWidget(tabWidget); QVBoxLayout *mountingTabLayout = new QVBoxLayout(mountingTab); mountingTabLayout->setSpacing(5); // // Common options // QGroupBox *commonBox = new QGroupBox(i18n("Common Options"), mountingTab); QGridLayout *commonBoxLayout = new QGridLayout(commonBox); commonBoxLayout->setSpacing(5); QCheckBox *remountAlways = new QCheckBox(i18n("Always remount this share"), commonBox); remountAlways->setObjectName("RemountAlways"); remountAlways->setEnabled(m_options->type() == Share); connect(remountAlways, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); commonBoxLayout->addWidget(remountAlways, 0, 0, 1, 2, 0); // Write access QCheckBox *useWriteAccess = new QCheckBox(Smb4KMountSettings::self()->useWriteAccessItem()->label(), commonBox); useWriteAccess->setObjectName("UseWriteAccess"); KComboBox *writeAccess = new KComboBox(commonBox); writeAccess->setObjectName("WriteAccess"); QString readWriteText = Smb4KMountSettings::self()->writeAccessItem()->choices().value(Smb4KMountSettings::EnumWriteAccess::ReadWrite).label; QString readOnlyText = Smb4KMountSettings::self()->writeAccessItem()->choices().value(Smb4KMountSettings::EnumWriteAccess::ReadOnly).label; writeAccess->addItem(readWriteText); writeAccess->addItem(readOnlyText); connect(useWriteAccess, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); connect(writeAccess, SIGNAL(currentIndexChanged(int)), SLOT(slotCheckValues())); commonBoxLayout->addWidget(useWriteAccess, 1, 0, 0); commonBoxLayout->addWidget(writeAccess, 1, 1, 0); // Remote file system port QCheckBox *useFilesystemPort = new QCheckBox(Smb4KMountSettings::self()->useRemoteFileSystemPortItem()->label(), commonBox); useFilesystemPort->setObjectName("UseFilesystemPort"); QSpinBox *filesystemPort = new QSpinBox(commonBox); filesystemPort->setObjectName("FileSystemPort"); filesystemPort->setMinimum(Smb4KMountSettings::self()->remoteFileSystemPortItem()->minValue().toInt()); filesystemPort->setMaximum(Smb4KMountSettings::self()->remoteFileSystemPortItem()->maxValue().toInt()); // filesystemPort->setSliderEnabled(true); connect(useFilesystemPort, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); connect(filesystemPort, SIGNAL(valueChanged(int)), SLOT(slotCheckValues())); commonBoxLayout->addWidget(useFilesystemPort, 2, 0, 0); commonBoxLayout->addWidget(filesystemPort, 2, 1, 0); mountingTabLayout->addWidget(commonBox, 0); // // CIFS Unix Extensions Support // QGroupBox *extensionsSupportBox = new QGroupBox(i18n("CIFS Unix Extensions Support"), mountingTab); QGridLayout *extensionsSupportBoxLayout = new QGridLayout(extensionsSupportBox); extensionsSupportBoxLayout->setSpacing(5); QCheckBox *cifsExtensionsSupport = new QCheckBox(i18n("This server supports the CIFS Unix extensions"), extensionsSupportBox); cifsExtensionsSupport->setObjectName("CifsExtensionsSupport"); connect(cifsExtensionsSupport, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); connect(cifsExtensionsSupport, SIGNAL(toggled(bool)), SLOT(slotCifsExtensionsSupport(bool))); extensionsSupportBoxLayout->addWidget(cifsExtensionsSupport, 0, 0, 1, 4, 0); // User Id QCheckBox *useUserId = new QCheckBox(Smb4KMountSettings::self()->useUserIdItem()->label(), extensionsSupportBox); useUserId->setObjectName("UseUserId"); KComboBox *userId = new KComboBox(extensionsSupportBox); userId->setObjectName("UserId"); QList allUsers = KUser::allUsers(); for (const KUser &u : allUsers) { userId->addItem(QString("%1 (%2)").arg(u.loginName()).arg(u.userId().nativeId()), QVariant::fromValue(u.groupId().nativeId())); } connect(useUserId, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); connect(userId, SIGNAL(currentIndexChanged(int)), SLOT(slotCheckValues())); extensionsSupportBoxLayout->addWidget(useUserId, 1, 0, 0); extensionsSupportBoxLayout->addWidget(userId, 1, 1, 0); // Group Id QCheckBox *useGroupId = new QCheckBox(Smb4KMountSettings::self()->useGroupIdItem()->label(), extensionsSupportBox); useGroupId->setObjectName("UseGroupId"); KComboBox *groupId = new KComboBox(extensionsSupportBox); groupId->setObjectName("GroupId"); QList allGroups = KUserGroup::allGroups(); for (const KUserGroup &g : allGroups) { groupId->addItem(QString("%1 (%2)").arg(g.name()).arg(g.groupId().nativeId()), QVariant::fromValue(g.groupId().nativeId())); } connect(useGroupId, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); connect(groupId, SIGNAL(currentIndexChanged(int)), SLOT(slotCheckValues())); extensionsSupportBoxLayout->addWidget(useGroupId, 2, 0, 0); extensionsSupportBoxLayout->addWidget(groupId, 2, 1, 0); // File mode QCheckBox *useFileMode = new QCheckBox(Smb4KMountSettings::self()->useFileModeItem()->label(), extensionsSupportBox); useFileMode->setObjectName("UseFileMode"); KLineEdit *fileMode = new KLineEdit(extensionsSupportBox); fileMode->setObjectName("FileMode"); fileMode->setClearButtonEnabled(true); fileMode->setAlignment(Qt::AlignRight); connect(useFileMode, SIGNAL(toggled(bool)), this, SLOT(slotCheckValues())); connect(fileMode, SIGNAL(textEdited(QString)), this, SLOT(slotCheckValues())); extensionsSupportBoxLayout->addWidget(useFileMode, 3, 0, 0); extensionsSupportBoxLayout->addWidget(fileMode, 3, 1, 0); // Directory mode QCheckBox *useDirectoryMode = new QCheckBox(Smb4KMountSettings::self()->useDirectoryModeItem()->label(), extensionsSupportBox); useDirectoryMode->setObjectName("UseDirectoryMode"); KLineEdit *directoryMode = new KLineEdit(extensionsSupportBox); directoryMode->setObjectName("DirectoryMode"); directoryMode->setClearButtonEnabled(true); directoryMode->setAlignment(Qt::AlignRight); connect(useDirectoryMode, SIGNAL(toggled(bool)), this, SLOT(slotCheckValues())); connect(directoryMode, SIGNAL(textEdited(QString)), this, SLOT(slotCheckValues())); extensionsSupportBoxLayout->addWidget(useDirectoryMode, 4, 0, 0); extensionsSupportBoxLayout->addWidget(directoryMode, 4, 1, 0); mountingTabLayout->addWidget(extensionsSupportBox, 0); // // Advanced options // QGroupBox *advancedOptionsBox = new QGroupBox(i18n("Advanced Options"), mountingTab); QGridLayout *advancedOptionsBoxLayout = new QGridLayout(advancedOptionsBox); advancedOptionsBoxLayout->setSpacing(5); // Security mode QCheckBox *useSecurityMode = new QCheckBox(Smb4KMountSettings::self()->useSecurityModeItem()->label(), advancedOptionsBox); useSecurityMode->setObjectName("UseSecurityMode"); KComboBox *securityMode = new KComboBox(advancedOptionsBox); securityMode->setObjectName("SecurityMode"); QString noneText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::None).label; QString krb5Text = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Krb5).label; QString krb5iText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Krb5i).label; QString ntlmText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlm).label; QString ntlmiText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmi).label; QString ntlmv2Text = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmv2).label; QString ntlmv2iText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmv2i).label; QString ntlmsspText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmssp).label; QString ntlmsspiText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmsspi).label; securityMode->addItem(noneText); securityMode->addItem(krb5Text); securityMode->addItem(krb5iText); securityMode->addItem(ntlmText); securityMode->addItem(ntlmiText); securityMode->addItem(ntlmv2Text); securityMode->addItem(ntlmv2iText); securityMode->addItem(ntlmsspText); connect(useSecurityMode, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); connect(securityMode, SIGNAL(currentIndexChanged(int)), SLOT(slotCheckValues())); advancedOptionsBoxLayout->addWidget(useSecurityMode, 0, 0, 0); advancedOptionsBoxLayout->addWidget(securityMode, 0, 1, 0); mountingTabLayout->addWidget(advancedOptionsBox, 0); mountingTabLayout->addStretch(100); tabWidget->addTab(mountingTab, i18n("Mounting")); // // Custom options for Samba // QWidget *sambaTab = new QWidget(tabWidget); QVBoxLayout *sambaTabLayout = new QVBoxLayout(sambaTab); sambaTabLayout->setSpacing(5); // // Common Options // QGroupBox *commonSambaOptionsBox = new QGroupBox(i18n("Common Options"), sambaTab); QGridLayout *commonSambaOptionsBoxLayout = new QGridLayout(commonSambaOptionsBox); commonSambaOptionsBoxLayout->setSpacing(5); // SMB port QCheckBox *useSmbPort = new QCheckBox(Smb4KSettings::self()->useRemoteSmbPortItem()->label(), commonSambaOptionsBox); useSmbPort->setObjectName("UseSmbPort"); QSpinBox *smbPort = new QSpinBox(commonSambaOptionsBox); smbPort->setObjectName("SmbPort"); smbPort->setMinimum(Smb4KSettings::self()->remoteSmbPortItem()->minValue().toInt()); smbPort->setMaximum(Smb4KSettings::self()->remoteSmbPortItem()->maxValue().toInt()); // smbPort->setSliderEnabled(true); connect(useSmbPort, SIGNAL(toggled(bool)), this, SLOT(slotCheckValues())); connect(smbPort, SIGNAL(valueChanged(int)), this, SLOT(slotCheckValues())); commonSambaOptionsBoxLayout->addWidget(useSmbPort, 0, 0, 0); commonSambaOptionsBoxLayout->addWidget(smbPort, 0, 1, 0); sambaTabLayout->addWidget(commonSambaOptionsBox, 0); // // Authentication // QGroupBox *authenticationBox = new QGroupBox(i18n("Authentication"), sambaTab); QVBoxLayout *authenticationBoxLayout = new QVBoxLayout(authenticationBox); authenticationBoxLayout->setSpacing(5); // Kerberos QCheckBox *useKerberos = new QCheckBox(Smb4KSettings::self()->useKerberosItem()->label(), authenticationBox); useKerberos->setObjectName("UseKerberos"); connect(useKerberos, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); authenticationBoxLayout->addWidget(useKerberos, 0); sambaTabLayout->addWidget(authenticationBox, 0); sambaTabLayout->addStretch(100); tabWidget->addTab(sambaTab, i18n("Samba")); // // Custom options for Wake-On-LAN // // NOTE: If you change the texts here, also alter them in the respective // config page. // QWidget *wakeOnLanTab = new QWidget(tabWidget); QVBoxLayout *wakeOnLanTabLayout = new QVBoxLayout(wakeOnLanTab); wakeOnLanTabLayout->setSpacing(5); // // MAC address // QGroupBox *macAddressBox = new QGroupBox(i18n("MAC Address"), wakeOnLanTab); QGridLayout *macAddressBoxLayout = new QGridLayout(macAddressBox); macAddressBoxLayout->setSpacing(5); // MAC address QLabel *macAddressLabel = new QLabel(i18n("MAC Address:"), macAddressBox); KLineEdit *macAddress = new KLineEdit(macAddressBox); macAddress->setObjectName("MACAddress"); macAddress->setClearButtonEnabled(true); macAddress->setInputMask("HH:HH:HH:HH:HH:HH;_"); // MAC address, see QLineEdit doc macAddressLabel->setBuddy(macAddress); connect(macAddress, SIGNAL(textEdited(QString)), SLOT(slotCheckValues())); connect(macAddress, SIGNAL(textEdited(QString)), SLOT(slotEnableWOLFeatures(QString))); macAddressBoxLayout->addWidget(macAddressLabel, 0, 0, 0); macAddressBoxLayout->addWidget(macAddress, 0, 1, 0); wakeOnLanTabLayout->addWidget(macAddressBox, 0); // // Wake-On-LAN Actions // QGroupBox *wakeOnLANActionsBox = new QGroupBox(i18n("Actions"), wakeOnLanTab); QVBoxLayout *wakeOnLANActionsBoxLayout = new QVBoxLayout(wakeOnLANActionsBox); wakeOnLANActionsBoxLayout->setSpacing(5); // Send magic package before network scan QCheckBox *sendPackageBeforeScan = new QCheckBox(i18n("Send magic package before scanning the network neighborhood"), wakeOnLANActionsBox); sendPackageBeforeScan->setObjectName("SendPackageBeforeScan"); connect(sendPackageBeforeScan, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); wakeOnLANActionsBoxLayout->addWidget(sendPackageBeforeScan, 0); // Send magic package before mount QCheckBox *sendPackageBeforeMount = new QCheckBox(i18n("Send magic package before mounting a share"), wakeOnLanTab); sendPackageBeforeMount->setObjectName("SendPackageBeforeMount"); connect(sendPackageBeforeMount, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); wakeOnLANActionsBoxLayout->addWidget(sendPackageBeforeMount, 0); wakeOnLanTabLayout->addWidget(wakeOnLANActionsBox, 0); wakeOnLanTabLayout->addStretch(100); tabWidget->addTab(wakeOnLanTab, i18n("Wake-On-LAN")); // // Load settings // if (m_options->hasOptions()) { if (m_options->type() == Share) { remountAlways->setChecked((m_options->remount() == Smb4KCustomOptions::RemountAlways)); } - else - { - // Do nothing - } // CIFS Unix extensions support cifsExtensionsSupport->setChecked(m_options->cifsUnixExtensionsSupport()); // User information useUserId->setChecked(m_options->useUser()); userId->setCurrentText(QString("%1 (%2)").arg(m_options->user().loginName()).arg(m_options->user().userId().nativeId())); // Group information useGroupId->setChecked(m_options->useGroup()); groupId->setCurrentText(QString("%1 (%2)").arg(m_options->group().name()).arg(m_options->group().groupId().nativeId())); // File mode useFileMode->setChecked(m_options->useFileMode()); fileMode->setText(m_options->fileMode()); // Directory mode useDirectoryMode->setChecked(m_options->useDirectoryMode()); directoryMode->setText(m_options->directoryMode()); // Remote file system port useFilesystemPort->setChecked(m_options->useFileSystemPort()); filesystemPort->setValue(m_options->fileSystemPort()); // Write access useWriteAccess->setChecked(m_options->useWriteAccess()); switch (m_options->writeAccess()) { case Smb4KMountSettings::EnumWriteAccess::ReadWrite: { writeAccess->setCurrentText(readWriteText); break; } case Smb4KMountSettings::EnumWriteAccess::ReadOnly: { writeAccess->setCurrentText(readOnlyText); break; } default: { break; } } // Security mode useSecurityMode->setChecked(m_options->useSecurityMode()); switch (m_options->securityMode()) { case Smb4KMountSettings::EnumSecurityMode::None: { securityMode->setCurrentText(noneText); break; } case Smb4KMountSettings::EnumSecurityMode::Krb5: { securityMode->setCurrentText(krb5Text); break; } case Smb4KMountSettings::EnumSecurityMode::Krb5i: { securityMode->setCurrentText(krb5iText); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlm: { securityMode->setCurrentText(ntlmText); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmi: { securityMode->setCurrentText(ntlmiText); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmv2: { securityMode->setCurrentText(ntlmv2Text); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmv2i: { securityMode->setCurrentText(ntlmv2iText); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmssp: { securityMode->setCurrentText(ntlmsspText); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmsspi: { securityMode->setCurrentText(ntlmsspiText); break; } default: { break; } } // Remote SMB port useSmbPort->setChecked(m_options->useSmbPort()); smbPort->setValue(m_options->smbPort()); // Kerberos useKerberos->setChecked(m_options->useKerberos()); // MAC address macAddress->setText(m_options->macAddress()); // Send magic package before scan sendPackageBeforeScan->setChecked(m_options->wolSendBeforeNetworkScan()); // Send magic package before mount sendPackageBeforeMount->setChecked(m_options->wolSendBeforeMount()); } else { setDefaultValues(); } // // Enable/disable features // wakeOnLanTab->setEnabled((m_options->type() == Host && Smb4KSettings::enableWakeOnLAN())); slotEnableWOLFeatures(macAddress->text()); slotCifsExtensionsSupport(cifsExtensionsSupport->isChecked()); } #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) // // FreeBSD and NetBSD // void Smb4KCustomOptionsDialog::setupView() { // // Tab widget with settings // QTabWidget *tabWidget = new QTabWidget(this); QVBoxLayout *dialogLayout = qobject_cast(layout()); dialogLayout->addWidget(tabWidget, 0); // // Custom options for mounting // QWidget *mountingTab = new QWidget(tabWidget); QVBoxLayout *mountingTabLayout = new QVBoxLayout(mountingTab); mountingTabLayout->setSpacing(5); // // Common options // QGroupBox *commonBox = new QGroupBox(i18n("Common Options"), mountingTab); QGridLayout *commonBoxLayout = new QGridLayout(commonBox); commonBoxLayout->setSpacing(5); QCheckBox *remountAlways = new QCheckBox(i18n("Always remount this share"), commonBox); remountAlways->setObjectName("RemountAlways"); remountAlways->setEnabled(m_options->type() == Share); connect(remountAlways, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); commonBoxLayout->addWidget(remountAlways, 0, 0, 1, 2, 0); // User Id QCheckBox *useUserId = new QCheckBox(Smb4KMountSettings::self()->useUserIdItem()->label(), commonBox); useUserId->setObjectName("UseUserId"); KComboBox *userId = new KComboBox(commonBox); userId->setObjectName("UserId"); QList allUsers = KUser::allUsers(); for (const KUser &u : allUsers) { userId->addItem(QString("%1 (%2)").arg(u.loginName()).arg(u.userId().nativeId()), QVariant::fromValue(u.groupId().nativeId())); } connect(useUserId, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); connect(userId, SIGNAL(currentIndexChanged(int)), SLOT(slotCheckValues())); commonBoxLayout->addWidget(useUserId, 1, 0, 0); commonBoxLayout->addWidget(userId, 1, 1, 0); // Group Id QCheckBox *useGroupId = new QCheckBox(Smb4KMountSettings::self()->useGroupIdItem()->label(), commonBox); useGroupId->setObjectName("UseGroupId"); KComboBox *groupId = new KComboBox(commonBox); groupId->setObjectName("GroupId"); QList allGroups = KUserGroup::allGroups(); for (const KUserGroup &g : allGroups) { groupId->addItem(QString("%1 (%2)").arg(g.name()).arg(g.groupId().nativeId()), QVariant::fromValue(g.groupId().nativeId())); } connect(useGroupId, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); connect(groupId, SIGNAL(currentIndexChanged(int)), SLOT(slotCheckValues())); commonBoxLayout->addWidget(useGroupId, 2, 0, 0); commonBoxLayout->addWidget(groupId, 2, 1, 0); // File mode QCheckBox *useFileMode = new QCheckBox(Smb4KMountSettings::self()->useFileModeItem()->label(), commonBox); useFileMode->setObjectName("UseFileMode"); KLineEdit *fileMode = new KLineEdit(commonBox); fileMode->setObjectName("FileMode"); fileMode->setClearButtonEnabled(true); fileMode->setAlignment(Qt::AlignRight); connect(useFileMode, SIGNAL(toggled(bool)), this, SLOT(slotCheckValues())); connect(fileMode, SIGNAL(textEdited(QString)), this, SLOT(slotCheckValues())); commonBoxLayout->addWidget(useFileMode, 3, 0, 0); commonBoxLayout->addWidget(fileMode, 3, 1, 0); // Directory mode QCheckBox *useDirectoryMode = new QCheckBox(Smb4KMountSettings::self()->useDirectoryModeItem()->label(), commonBox); useDirectoryMode->setObjectName("UseDirectoryMode"); KLineEdit *directoryMode = new KLineEdit(commonBox); directoryMode->setObjectName("DirectoryMode"); directoryMode->setClearButtonEnabled(true); directoryMode->setAlignment(Qt::AlignRight); connect(useDirectoryMode, SIGNAL(toggled(bool)), this, SLOT(slotCheckValues())); connect(directoryMode, SIGNAL(textEdited(QString)), this, SLOT(slotCheckValues())); commonBoxLayout->addWidget(useDirectoryMode, 4, 0, 0); commonBoxLayout->addWidget(directoryMode, 4, 1, 0); mountingTabLayout->addWidget(commonBox, 0); mountingTabLayout->addStretch(100); tabWidget->addTab(mountingTab, i18n("Mounting")); // // Custom options for Samba // QWidget *sambaTab = new QWidget(tabWidget); QVBoxLayout *sambaTabLayout = new QVBoxLayout(sambaTab); sambaTabLayout->setSpacing(5); // // Common Options // QGroupBox *commonSambaOptionsBox = new QGroupBox(i18n("Common Options"), sambaTab); QGridLayout *commonSambaOptionsBoxLayout = new QGridLayout(commonSambaOptionsBox); commonSambaOptionsBoxLayout->setSpacing(5); // SMB port QCheckBox *useSmbPort = new QCheckBox(Smb4KSettings::self()->useRemoteSmbPortItem()->label(), commonSambaOptionsBox); useSmbPort->setObjectName("UseSmbPort"); QSpinBox *smbPort = new QSpinBox(commonSambaOptionsBox); smbPort->setObjectName("SmbPort"); smbPort->setMinimum(Smb4KSettings::self()->remoteSmbPortItem()->minValue().toInt()); smbPort->setMaximum(Smb4KSettings::self()->remoteSmbPortItem()->maxValue().toInt()); // smbPort->setSliderEnabled(true); connect(useSmbPort, SIGNAL(toggled(bool)), this, SLOT(slotCheckValues())); connect(smbPort, SIGNAL(valueChanged(int)), this, SLOT(slotCheckValues())); commonSambaOptionsBoxLayout->addWidget(useSmbPort, 0, 0, 0); commonSambaOptionsBoxLayout->addWidget(smbPort, 0, 1, 0); sambaTabLayout->addWidget(commonSambaOptionsBox, 0); // // Authentication // QGroupBox *authenticationBox = new QGroupBox(i18n("Authentication"), sambaTab); QVBoxLayout *authenticationBoxLayout = new QVBoxLayout(authenticationBox); authenticationBoxLayout->setSpacing(5); // Kerberos QCheckBox *useKerberos = new QCheckBox(Smb4KSettings::self()->useKerberosItem()->label(), authenticationBox); useKerberos->setObjectName("UseKerberos"); connect(useKerberos, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); authenticationBoxLayout->addWidget(useKerberos, 0); sambaTabLayout->addWidget(authenticationBox, 0); sambaTabLayout->addStretch(100); tabWidget->addTab(sambaTab, i18n("Samba")); // // Custom options for Wake-On-LAN // // NOTE: If you change the texts here, also alter them in the respective // config page. // QWidget *wakeOnLanTab = new QWidget(tabWidget); QVBoxLayout *wakeOnLanTabLayout = new QVBoxLayout(wakeOnLanTab); wakeOnLanTabLayout->setSpacing(5); // // MAC address // QGroupBox *macAddressBox = new QGroupBox(i18n("MAC Address"), wakeOnLanTab); QGridLayout *macAddressBoxLayout = new QGridLayout(macAddressBox); macAddressBoxLayout->setSpacing(5); // MAC address QLabel *macAddressLabel = new QLabel(i18n("MAC Address:"), macAddressBox); KLineEdit *macAddress = new KLineEdit(macAddressBox); macAddress->setObjectName("MACAddress"); macAddress->setClearButtonEnabled(true); macAddress->setInputMask("HH:HH:HH:HH:HH:HH;_"); // MAC address, see QLineEdit doc macAddressLabel->setBuddy(macAddress); connect(macAddress, SIGNAL(textEdited(QString)), SLOT(slotCheckValues())); connect(macAddress, SIGNAL(textEdited(QString)), SLOT(slotEnableWOLFeatures(QString))); macAddressBoxLayout->addWidget(macAddressLabel, 0, 0, 0); macAddressBoxLayout->addWidget(macAddress, 0, 1, 0); wakeOnLanTabLayout->addWidget(macAddressBox, 0); // // Wake-On-LAN Actions // QGroupBox *wakeOnLANActionsBox = new QGroupBox(i18n("Actions"), wakeOnLanTab); QVBoxLayout *wakeOnLANActionsBoxLayout = new QVBoxLayout(wakeOnLANActionsBox); wakeOnLANActionsBoxLayout->setSpacing(5); // Send magic package before network scan QCheckBox *sendPackageBeforeScan = new QCheckBox(i18n("Send magic package before scanning the network neighborhood"), wakeOnLANActionsBox); sendPackageBeforeScan->setObjectName("SendPackageBeforeScan"); connect(sendPackageBeforeScan, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); wakeOnLANActionsBoxLayout->addWidget(sendPackageBeforeScan, 0); // Send magic package before mount QCheckBox *sendPackageBeforeMount = new QCheckBox(i18n("Send magic package before mounting a share"), wakeOnLanTab); sendPackageBeforeMount->setObjectName("SendPackageBeforeMount"); connect(sendPackageBeforeMount, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); wakeOnLANActionsBoxLayout->addWidget(sendPackageBeforeMount, 0); wakeOnLanTabLayout->addWidget(wakeOnLANActionsBox, 0); wakeOnLanTabLayout->addStretch(100); tabWidget->addTab(wakeOnLanTab, i18n("Wake-On-LAN")); // // Load settings // if (m_options->hasOptions()) { if (m_options->type() == Share) { remountAlways->setChecked((m_options->remount() == Smb4KCustomOptions::RemountAlways)); } - else - { - // Do nothing - } // User information useUserId->setChecked(m_options->useUser()); userId->setCurrentText(QString("%1 (%2)").arg(m_options->user().loginName()).arg(m_options->user().userId().nativeId())); // Group information useGroupId->setChecked(m_options->useGroup()); groupId->setCurrentText(QString("%1 (%2)").arg(m_options->group().name()).arg(m_options->group().groupId().nativeId())); // File mode useFileMode->setChecked(m_options->useFileMode()); fileMode->setText(m_options->fileMode()); // Directory mode useDirectoryMode->setChecked(m_options->useDirectoryMode()); directoryMode->setText(m_options->directoryMode()); // Remote SMB port useSmbPort->setChecked(m_options->useSmbPort()); smbPort->setValue(m_options->smbPort()); // Kerberos useKerberos->setChecked(m_options->useKerberos()); // MAC address macAddress->setText(m_options->macAddress()); // Send magic package before scan sendPackageBeforeScan->setChecked(m_options->wolSendBeforeNetworkScan()); // Send magic package before mount sendPackageBeforeMount->setChecked(m_options->wolSendBeforeMount()); } else { setDefaultValues(); } // // Enable/disable features // wakeOnLanTab->setEnabled((m_options->type() == Host && Smb4KSettings::enableWakeOnLAN())); slotEnableWOLFeatures(macAddress->text()); } #else // // Generic (without mount options) // void Smb4KCustomOptionsDialog::setupView() { // // Tab widget with settings // QTabWidget *tabWidget = new QTabWidget(this); QVBoxLayout *dialogLayout = qobject_cast(layout()); dialogLayout->addWidget(tabWidget, 0); // // Custom options for Samba // QWidget *sambaTab = new QWidget(tabWidget); QVBoxLayout *sambaTabLayout = new QVBoxLayout(sambaTab); sambaTabLayout->setSpacing(5); // // Common Options // QGroupBox *commonSambaOptionsBox = new QGroupBox(i18n("Common Options"), sambaTab); QGridLayout *commonSambaOptionsBoxLayout = new QGridLayout(commonSambaOptionsBox); commonSambaOptionsBoxLayout->setSpacing(5); // SMB port QCheckBox *useSmbPort = new QCheckBox(Smb4KSettings::self()->useRemoteSmbPortItem()->label(), commonSambaOptionsBox); useSmbPort->setObjectName("UseSmbPort"); QSpinBox *smbPort = new QSpinBox(commonSambaOptionsBox); smbPort->setObjectName("SmbPort"); smbPort->setMinimum(Smb4KSettings::self()->remoteSmbPortItem()->minValue().toInt()); smbPort->setMaximum(Smb4KSettings::self()->remoteSmbPortItem()->maxValue().toInt()); // smbPort->setSliderEnabled(true); connect(useSmbPort, SIGNAL(toggled(bool)), this, SLOT(slotCheckValues())); connect(smbPort, SIGNAL(valueChanged(int)), this, SLOT(slotCheckValues())); commonSambaOptionsBoxLayout->addWidget(useSmbPort, 0, 0, 0); commonSambaOptionsBoxLayout->addWidget(smbPort, 0, 1, 0); sambaTabLayout->addWidget(commonSambaOptionsBox, 0); // // Authentication // QGroupBox *authenticationBox = new QGroupBox(i18n("Authentication"), sambaTab); QVBoxLayout *authenticationBoxLayout = new QVBoxLayout(authenticationBox); authenticationBoxLayout->setSpacing(5); // Kerberos QCheckBox *useKerberos = new QCheckBox(Smb4KSettings::self()->useKerberosItem()->label(), authenticationBox); useKerberos->setObjectName("UseKerberos"); connect(useKerberos, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); authenticationBoxLayout->addWidget(useKerberos, 0); sambaTabLayout->addWidget(authenticationBox, 0); sambaTabLayout->addStretch(100); tabWidget->addTab(sambaTab, i18n("Samba")); // // Custom options for Wake-On-LAN // // NOTE: If you change the texts here, also alter them in the respective // config page. // QWidget *wakeOnLanTab = new QWidget(tabWidget); QVBoxLayout *wakeOnLanTabLayout = new QVBoxLayout(wakeOnLanTab); wakeOnLanTabLayout->setSpacing(5); // // MAC address // QGroupBox *macAddressBox = new QGroupBox(i18n("MAC Address"), wakeOnLanTab); QGridLayout *macAddressBoxLayout = new QGridLayout(macAddressBox); macAddressBoxLayout->setSpacing(5); // MAC address QLabel *macAddressLabel = new QLabel(i18n("MAC Address:"), macAddressBox); KLineEdit *macAddress = new KLineEdit(macAddressBox); macAddress->setObjectName("MACAddress"); macAddress->setClearButtonEnabled(true); macAddress->setInputMask("HH:HH:HH:HH:HH:HH;_"); // MAC address, see QLineEdit doc macAddressLabel->setBuddy(macAddress); connect(macAddress, SIGNAL(textEdited(QString)), SLOT(slotCheckValues())); connect(macAddress, SIGNAL(textEdited(QString)), SLOT(slotEnableWOLFeatures(QString))); macAddressBoxLayout->addWidget(macAddressLabel, 0, 0, 0); macAddressBoxLayout->addWidget(macAddress, 0, 1, 0); wakeOnLanTabLayout->addWidget(macAddressBox, 0); // // Wake-On-LAN Actions // QGroupBox *wakeOnLANActionsBox = new QGroupBox(i18n("Actions"), wakeOnLanTab); QVBoxLayout *wakeOnLANActionsBoxLayout = new QVBoxLayout(wakeOnLANActionsBox); wakeOnLANActionsBoxLayout->setSpacing(5); // Send magic package before network scan QCheckBox *sendPackageBeforeScan = new QCheckBox(i18n("Send magic package before scanning the network neighborhood"), wakeOnLANActionsBox); sendPackageBeforeScan->setObjectName("SendPackageBeforeScan"); connect(sendPackageBeforeScan, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); wakeOnLANActionsBoxLayout->addWidget(sendPackageBeforeScan, 0); // Send magic package before mount QCheckBox *sendPackageBeforeMount = new QCheckBox(i18n("Send magic package before mounting a share"), wakeOnLanTab); sendPackageBeforeMount->setObjectName("SendPackageBeforeMount"); connect(sendPackageBeforeMount, SIGNAL(toggled(bool)), SLOT(slotCheckValues())); wakeOnLANActionsBoxLayout->addWidget(sendPackageBeforeMount, 0); wakeOnLanTabLayout->addWidget(wakeOnLANActionsBox, 0); wakeOnLanTabLayout->addStretch(100); tabWidget->addTab(wakeOnLanTab, i18n("Wake-On-LAN")); // // Load settings // if (m_options->hasOptions()) { // Remote SMB port useSmbPort->setChecked(m_options->useSmbPort()); smbPort->setValue(m_options->smbPort()); // Kerberos useKerberos->setChecked(m_options->useKerberos()); // MAC address macAddress->setText(m_options->macAddress()); // Send magic package before scan sendPackageBeforeScan->setChecked(m_options->wolSendBeforeNetworkScan()); // Send magic package before mount sendPackageBeforeMount->setChecked(m_options->wolSendBeforeMount()); } else { setDefaultValues(); } // // Enable/disable features // wakeOnLanTab->setEnabled((m_options->type() == Host && Smb4KSettings::enableWakeOnLAN())); slotEnableWOLFeatures(macAddress->text()); } #endif bool Smb4KCustomOptionsDialog::checkDefaultValues() { #if !defined(SMB4K_UNSUPPORTED_PLATFORM) // // Always remount the share // if (m_options->type() == Share) { QCheckBox *remountAlways = findChild("RemountAlways"); if (remountAlways) { if (remountAlways->isChecked()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } } - else - { - // Do nothing - } // // User Id // QCheckBox *useUserId = findChild("UseUserId"); if (useUserId) { if (useUserId->isChecked() != Smb4KMountSettings::useUserId()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } KComboBox *userId = findChild("UserId"); if (userId) { K_UID uid = (K_UID)userId->itemData(userId->currentIndex()).toInt(); if (uid != (K_UID)Smb4KMountSettings::userId().toInt()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // Group Id // QCheckBox *useGroupId = findChild("UseGroupId"); if (useGroupId) { if (useGroupId->isChecked() != Smb4KMountSettings::useGroupId()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } KComboBox *groupId = findChild("GroupId"); if (groupId) { K_GID gid = (K_GID)groupId->itemData(groupId->currentIndex()).toInt(); if (gid != (K_GID)Smb4KMountSettings::groupId().toInt()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // File mode // QCheckBox *useFileMode = findChild("UseFileMode"); if (useFileMode) { if (useFileMode->isChecked() != Smb4KMountSettings::useFileMode()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } KLineEdit *fileMode = findChild("FileMode"); if (fileMode) { if (fileMode->text() != Smb4KMountSettings::fileMode()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // Directory mode // QCheckBox *useDirectoryMode = findChild("UseDirectoryMode"); if (useDirectoryMode) { if (useDirectoryMode->isChecked() != Smb4KMountSettings::useDirectoryMode()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } KLineEdit *directoryMode = findChild("DirectoryMode"); if (directoryMode) { if (directoryMode->text() != Smb4KMountSettings::directoryMode()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } #endif #if defined(Q_OS_LINUX) // // CIFS Unix extensions support // QCheckBox *cifsExtensionsSupport = findChild("CifsExtensionsSupport"); if (cifsExtensionsSupport) { if (cifsExtensionsSupport->isChecked() != Smb4KMountSettings::cifsUnixExtensionsSupport()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // Filesystem port // QCheckBox *useFilesystemPort = findChild("UseFilesystemPort"); if (useFilesystemPort) { if (useFilesystemPort->isChecked() != Smb4KMountSettings::useRemoteFileSystemPort()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } QSpinBox *filesystemPort = findChild("FileSystemPort"); if (filesystemPort) { if (filesystemPort->value() != Smb4KMountSettings::remoteFileSystemPort()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // Write access // QCheckBox *useWriteAccess = findChild("UseWriteAccess"); if (useWriteAccess) { if (useWriteAccess->isChecked() != Smb4KMountSettings::useWriteAccess()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } KComboBox *writeAccess = findChild("WriteAccess"); if (writeAccess) { if (writeAccess->currentText() != Smb4KMountSettings::self()->writeAccessItem()->choices().value(Smb4KMountSettings::self()->writeAccess()).label) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // Security mode // QCheckBox *useSecurityMode = findChild("UseSecurityMode"); if (useSecurityMode) { if (useSecurityMode->isChecked() != Smb4KMountSettings::useSecurityMode()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } KComboBox *securityMode = findChild("SecurityMode"); if (securityMode) { if (securityMode->currentText() != Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::self()->securityMode()).label) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } #endif // // SMB port // QCheckBox *useSmbPort = findChild("UseSmbPort"); if (useSmbPort) { if (useSmbPort->isChecked() != Smb4KSettings::useRemoteSmbPort()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } QSpinBox *smbPort = findChild("SmbPort"); if (smbPort) { if (smbPort->value() != Smb4KSettings::remoteSmbPort()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // Kerberos // QCheckBox *useKerberos = findChild("UseKerberos"); if (useKerberos) { if (useKerberos->isChecked() != Smb4KSettings::useKerberos()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // MAC address & Wake-On-LAN features // if (m_options->type() == Host && Smb4KSettings::enableWakeOnLAN()) { KLineEdit *macAddress = findChild("MACAddress"); if (macAddress) { QRegExp exp("..\\:..\\:..\\:..\\:..\\:.."); if (exp.exactMatch(macAddress->text())) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } QCheckBox *sendPackageBeforeScan = findChild("SendPackageBeforeScan"); if (sendPackageBeforeScan) { if (sendPackageBeforeScan->isChecked()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } QCheckBox *sendPackageBeforeMount = findChild("SendPackageBeforeMount"); if (sendPackageBeforeMount) { if (sendPackageBeforeMount->isChecked()) { return false; } - else - { - // Do nothing - } - } - else - { - // Do nothing } } - else - { - // Do nothing - } return true; } void Smb4KCustomOptionsDialog::setDefaultValues() { #if !defined(SMB4K_UNSUPPORTED_PLATFORM) // // Always remount the share // if (m_options->type() == Share) { QCheckBox *remountAlways = findChild("RemountAlways"); if (remountAlways) { remountAlways->setChecked(false); } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // User Id // QCheckBox *useUserId = findChild("UseUserId"); if (useUserId) { useUserId->setChecked(Smb4KMountSettings::useUserId()); } - else - { - // Do nothing - } KComboBox *userId = findChild("UserId"); if (userId) { KUser user((K_UID)Smb4KMountSettings::userId().toInt()); userId->setCurrentText(QString("%1 (%2)").arg(user.loginName()).arg(user.userId().nativeId())); } - else - { - // Do nothing - } // // Group Id // QCheckBox *useGroupId = findChild("UseGroupId"); if (useGroupId) { useGroupId->setChecked(Smb4KMountSettings::useGroupId()); } - else - { - // Do nothing - } KComboBox *groupId = findChild("GroupId"); if (groupId) { KUserGroup group((K_GID)Smb4KMountSettings::groupId().toInt()); groupId->setCurrentText(QString("%1 (%2)").arg(group.name()).arg(group.groupId().nativeId()));; } - else - { - // Do nothing - } // // File mask // QCheckBox *useFileMode = findChild("UseFileMode"); if (useFileMode) { useFileMode->setChecked(Smb4KMountSettings::useFileMode()); } - else - { - // Do nothing - } KLineEdit *fileMode = findChild("FileMode"); if (fileMode) { fileMode->setText(Smb4KMountSettings::fileMode()); } - else - { - // Do nothing - } // // Directory mode // QCheckBox *useDirectoryMode = findChild("UseDirectoryMode"); if (useDirectoryMode) { useDirectoryMode->setChecked(Smb4KMountSettings::useDirectoryMode()); } - else - { - // Do nothing - } KLineEdit *directoryMode = findChild("DirectoryMode"); if (directoryMode) { directoryMode->setText(Smb4KMountSettings::directoryMode()); } - else - { - // Do nothing - } #endif #if defined(Q_OS_LINUX) // // CIFS Unix extensions support // QCheckBox *cifsExtensionsSupport = findChild("CifsExtensionsSupport"); if (cifsExtensionsSupport) { cifsExtensionsSupport->setChecked(Smb4KMountSettings::cifsUnixExtensionsSupport()); } - else - { - // Do nothing - } // // Filesystem port // QCheckBox *useFilesystemPort = findChild("UseFilesystemPort"); if (useFilesystemPort) { useFilesystemPort->setChecked(Smb4KMountSettings::useRemoteFileSystemPort()); } - else - { - // Do nothing - } QSpinBox *filesystemPort = findChild("FileSystemPort"); if (filesystemPort) { filesystemPort->setValue(Smb4KMountSettings::remoteFileSystemPort()); } - else - { - // Do nothing - } // // Write access // QCheckBox *useWriteAccess = findChild("UseWriteAccess"); if (useWriteAccess) { useWriteAccess->setChecked(Smb4KMountSettings::useWriteAccess()); } - else - { - // Do nothing - } KComboBox *writeAccess = findChild("WriteAccess"); if (writeAccess) { QString readWriteText = Smb4KMountSettings::self()->writeAccessItem()->choices().value(Smb4KMountSettings::EnumWriteAccess::ReadWrite).label; QString readOnlyText = Smb4KMountSettings::self()->writeAccessItem()->choices().value(Smb4KMountSettings::EnumWriteAccess::ReadOnly).label; switch (Smb4KMountSettings::writeAccess()) { case Smb4KMountSettings::EnumWriteAccess::ReadWrite: { writeAccess->setCurrentText(readWriteText); break; } case Smb4KMountSettings::EnumWriteAccess::ReadOnly: { writeAccess->setCurrentText(readOnlyText); break; } default: { break; } } } - else - { - // Do nothing - } // // Security mode // QCheckBox *useSecurityMode = findChild("UseSecurityMode"); if (useSecurityMode) { useSecurityMode->setChecked(Smb4KMountSettings::useSecurityMode()); } - else - { - // Do nothing - } KComboBox *securityMode = findChild("SecurityMode"); if (securityMode) { QString noneText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::None).label; QString krb5Text = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Krb5).label; QString krb5iText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Krb5i).label; QString ntlmText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlm).label; QString ntlmiText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmi).label; QString ntlmv2Text = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmv2).label; QString ntlmv2iText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmv2i).label; QString ntlmsspText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmssp).label; QString ntlmsspiText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmsspi).label; switch (Smb4KMountSettings::securityMode()) { case Smb4KMountSettings::EnumSecurityMode::None: { securityMode->setCurrentText(noneText); break; } case Smb4KMountSettings::EnumSecurityMode::Krb5: { securityMode->setCurrentText(krb5Text); break; } case Smb4KMountSettings::EnumSecurityMode::Krb5i: { securityMode->setCurrentText(krb5iText); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlm: { securityMode->setCurrentText(ntlmText); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmi: { securityMode->setCurrentText(ntlmiText); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmv2: { securityMode->setCurrentText(ntlmv2Text); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmv2i: { securityMode->setCurrentText(ntlmv2iText); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmssp: { securityMode->setCurrentText(ntlmsspText); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmsspi: { securityMode->setCurrentText(ntlmsspiText); break; } default: { break; } } } - else - { - // Do nothing - } #endif // // SMB port // QCheckBox *useSmbPort = findChild("UseSmbPort"); if (useSmbPort) { useSmbPort->setChecked(Smb4KSettings::useRemoteSmbPort()); } - else - { - // Do nothing - } QSpinBox *smbPort = findChild("SmbPort"); if (smbPort) { smbPort->setValue(Smb4KSettings::remoteSmbPort()); } - else - { - // Do nothing - } // // Kerberos // QCheckBox *useKerberos = findChild("UseKerberos"); if (useKerberos) { useKerberos->setChecked(Smb4KSettings::useKerberos()); } - else - { - // Do nothing - } // // MAC address & Wake-On-LAN features // if (m_options->type() == Host) { KLineEdit *macAddress = findChild("MACAddress"); if (macAddress) { macAddress->clear(); macAddress->setInputMask("HH:HH:HH:HH:HH:HH;_"); } - else - { - // Do nothing - } QCheckBox *sendPackageBeforeScan = findChild("SendPackageBeforeScan"); if (sendPackageBeforeScan) { sendPackageBeforeScan->setChecked(false); } - else - { - // Do nothing - } QCheckBox *sendPackageBeforeMount = findChild("SendPackageBeforeMount"); if (sendPackageBeforeMount) { sendPackageBeforeMount->setChecked(false); } - else - { - // Do nothing - } - } - else - { - // Do nothing } } void Smb4KCustomOptionsDialog::saveValues() { #if !defined(SMB4K_UNSUPPORTED_PLATFORM) // // Always remount the share // if (m_options->type() == Share) { QCheckBox *remountAlways = findChild("RemountAlways"); if (remountAlways) { if (remountAlways->isChecked()) { m_options->setRemount(Smb4KCustomOptions::RemountAlways); } else { m_options->setRemount(Smb4KCustomOptions::RemountNever); } } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // User Id // QCheckBox *useUserId = findChild("UseUserId"); if (useUserId) { m_options->setUseUser(useUserId->isChecked()); } - else - { - // Do nothing - } KComboBox *userId = findChild("UserId"); if (userId) { m_options->setUser(KUser(userId->itemData(userId->currentIndex()).toInt())); } - else - { - // Do nothing - } // // Group Id // QCheckBox *useGroupId = findChild("UseGroupId"); if (useGroupId) { m_options->setUseGroup(useGroupId->isChecked()); } - else - { - // Do nothing - } KComboBox *groupId = findChild("GroupId"); if (groupId) { m_options->setGroup(KUserGroup(groupId->itemData(groupId->currentIndex()).toInt())); } - else - { - // Do nothing - } // // File mode // QCheckBox *useFileMode = findChild("UseFileMode"); if (useFileMode) { m_options->setUseFileMode(useFileMode->isChecked()); } - else - { - // Do nothing - } KLineEdit *fileMode = findChild("FileMode"); if (fileMode) { m_options->setFileMode(fileMode->text()); } - else - { - // Do nothing - } // // Directory mode // QCheckBox *useDirectoryMode = findChild("UseDirectoryMode"); if (useDirectoryMode) { m_options->setUseDirectoryMode(useDirectoryMode->isChecked()); } - else - { - // Do nothing - } KLineEdit *directoryMode = findChild("DirectoryMode"); if (directoryMode) { m_options->setDirectoryMode(directoryMode->text()); } - else - { - // Do nothing - } #endif #if defined(Q_OS_LINUX) // // CIFS Unix extensions support // QCheckBox *cifsExtensionsSupport = findChild("CifsExtensionsSupport"); if (cifsExtensionsSupport) { m_options->setCifsUnixExtensionsSupport(cifsExtensionsSupport->isChecked()); } - else - { - // Do nothing - } // // Filesystem port // QCheckBox *useFilesystemPort = findChild("UseFilesystemPort"); if (useFilesystemPort) { m_options->setUseFileSystemPort(useFilesystemPort->isChecked()); } - else - { - // Do nothing - } QSpinBox *filesystemPort = findChild("FileSystemPort"); if (filesystemPort) { m_options->setFileSystemPort(filesystemPort->value()); } - else - { - // Do nothing - } // // Write access // QCheckBox *useWriteAccess = findChild("UseWriteAccess"); if (useWriteAccess) { m_options->setUseWriteAccess(useWriteAccess->isChecked()); } - else - { - // Do nothing - } KComboBox *writeAccess = findChild("WriteAccess"); if (writeAccess) { QString readWriteText = Smb4KMountSettings::self()->writeAccessItem()->choices().value(Smb4KMountSettings::EnumWriteAccess::ReadWrite).label; QString readOnlyText = Smb4KMountSettings::self()->writeAccessItem()->choices().value(Smb4KMountSettings::EnumWriteAccess::ReadOnly).label; if (writeAccess->currentText() == readWriteText) { m_options->setWriteAccess(Smb4KMountSettings::EnumWriteAccess::ReadWrite); } else if (writeAccess->currentText() == readOnlyText) { m_options->setWriteAccess(Smb4KMountSettings::EnumWriteAccess::ReadOnly); } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // Security mode // QCheckBox *useSecurityMode = findChild("UseSecurityMode"); if (useSecurityMode) { m_options->setUseSecurityMode(useSecurityMode->isChecked()); } - else - { - // Do nothing - } KComboBox *securityMode = findChild("SecurityMode"); if (securityMode) { QString noneText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::None).label; QString krb5Text = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Krb5).label; QString krb5iText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Krb5i).label; QString ntlmText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlm).label; QString ntlmiText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmi).label; QString ntlmv2Text = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmv2).label; QString ntlmv2iText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmv2i).label; QString ntlmsspText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmssp).label; QString ntlmsspiText = Smb4KMountSettings::self()->securityModeItem()->choices().value(Smb4KMountSettings::EnumSecurityMode::Ntlmsspi).label; if (securityMode->currentText() == noneText) { m_options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::None); } else if (securityMode->currentText() == krb5Text) { m_options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Krb5); } else if (securityMode->currentText() == krb5iText) { m_options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Krb5i); } else if (securityMode->currentText() == ntlmText) { m_options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Ntlm); } else if (securityMode->currentText() == ntlmiText) { m_options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Ntlmi); } else if (securityMode->currentText() == ntlmv2Text) { m_options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Ntlmv2); } else if (securityMode->currentText() == ntlmv2iText) { m_options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Ntlmv2i); } else if (securityMode->currentText() == ntlmsspText) { m_options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Ntlmssp); } else if (securityMode->currentText() == ntlmsspiText) { m_options->setSecurityMode(Smb4KMountSettings::EnumSecurityMode::Ntlmsspi); } - else - { - // Do nothing - } - } - else - { - // Do nothing } #endif // // SMB port // QCheckBox *useSmbPort = findChild("UseSmbPort"); if (useSmbPort) { m_options->setUseSmbPort(useSmbPort->isChecked()); } - else - { - // Do nothing - } QSpinBox *smbPort = findChild("SmbPort"); if (smbPort) { m_options->setSmbPort(smbPort->value()); } - else - { - // Do nothing - } // Kerberos QCheckBox *useKerberos = findChild("UseKerberos"); if (useKerberos) { m_options->setUseKerberos(useKerberos->isChecked()); } - else - { - // Do nothing - } // MAC address & Wake-On-LAN features if (m_options->type() == Host) { KLineEdit *macAddress = findChild("MACAddress"); if (macAddress) { m_options->setMACAddress(macAddress->text()); } - else - { - // Do nothing - } QCheckBox *sendPackageBeforeScan = findChild("SendPackageBeforeScan"); if (sendPackageBeforeScan) { m_options->setWOLSendBeforeNetworkScan(sendPackageBeforeScan->isChecked()); } - else - { - // Do nothing - } QCheckBox *sendPackageBeforeMount = findChild("SendPackageBeforeMount"); if (sendPackageBeforeMount) { m_options->setWOLSendBeforeMount(sendPackageBeforeMount->isChecked()); } - else - { - // Do nothing - } - } - else - { - // Do nothing } KConfigGroup group(Smb4KSettings::self()->config(), "CustomOptionsDialog"); KWindowConfig::saveWindowSize(windowHandle(), group); } void Smb4KCustomOptionsDialog::slotSetDefaultValues() { setDefaultValues(); } void Smb4KCustomOptionsDialog::slotCheckValues() { QDialogButtonBox *buttonBox = findChild(); if (buttonBox) { for (QAbstractButton *b : buttonBox->buttons()) { if (buttonBox->buttonRole(b) == QDialogButtonBox::ResetRole) { b->setEnabled(!checkDefaultValues()); break; } - else - { - // Do nothing - } } } - else - { - // Do nothing - } } void Smb4KCustomOptionsDialog::slotOKClicked() { saveValues(); accept(); } void Smb4KCustomOptionsDialog::slotEnableWOLFeatures(const QString &mac) { QRegExp exp("..\\:..\\:..\\:..\\:..\\:.."); QCheckBox *sendPackageBeforeScan = findChild("SendPackageBeforeScan"); if (sendPackageBeforeScan) { sendPackageBeforeScan->setEnabled(m_options->type() == Host && exp.exactMatch(mac)); } - else - { - // Do nothing - } QCheckBox *sendPackageBeforeMount = findChild("SendPackageBeforeMount"); if (sendPackageBeforeMount) { sendPackageBeforeMount->setEnabled(m_options->type() == Host && exp.exactMatch(mac)); } - else - { - // Do nothing - } } void Smb4KCustomOptionsDialog::slotCifsExtensionsSupport(bool support) { #if defined(Q_OS_LINUX) // // User id // QCheckBox *useUserId = findChild("UseUserId"); if (useUserId) { useUserId->setEnabled(!support); } - else - { - // Do nothing - } KComboBox *userId = findChild("UserId"); if (userId) { userId->setEnabled(!support); } - else - { - // Do nothing - } // // Group id // QCheckBox *useGroupId = findChild("UseGroupId"); if (useGroupId) { useGroupId->setEnabled(!support); } - else - { - // Do nothing - } KComboBox *groupId = findChild("GroupId"); if (groupId) { groupId->setEnabled(!support); } - else - { - // Do nothing - } // // File mode // QCheckBox *useFileMode = findChild("UseFileMode"); if (useFileMode) { useFileMode->setEnabled(!support); } - else - { - // Do nothing - } KLineEdit *fileMode = findChild("FileMode"); if (fileMode) { fileMode->setEnabled(!support); } - else - { - // Do nothing - } // // Directory mode // QCheckBox *useDirectoryMode = findChild("UseDirectoryMode"); if (useDirectoryMode) { useDirectoryMode->setEnabled(!support); } - else - { - // Do nothing - } KLineEdit *directoryMode = findChild("DirectoryMode"); if (directoryMode) { directoryMode->setEnabled(!support); } - else - { - // Do nothing - } #endif } diff --git a/core/smb4kfile.cpp b/core/smb4kfile.cpp index 656256d..f4a5093 100644 --- a/core/smb4kfile.cpp +++ b/core/smb4kfile.cpp @@ -1,185 +1,186 @@ /*************************************************************************** Smb4K's container class for information about a directory or file. ------------------- begin : Sa Nov 10 2018 - copyright : (C) 2018 by Alexander Reinholdt + copyright : (C) 2018-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kfile.h" #include "smb4kglobal.h" // Qt includes #include #include // KDE includes #include #include using namespace Smb4KGlobal; class Smb4KFilePrivate { public: QString workgroupName; QHostAddress ip; }; Smb4KFile::Smb4KFile(const QUrl& url, Smb4KGlobal::NetworkItem type) : Smb4KBasicNetworkItem(type), d(new Smb4KFilePrivate) { *pUrl = url; if (type == Directory) { *pIcon = KDE::icon("folder"); } else { *pIcon = KDE::icon(KIO::iconNameForUrl(url)); } } Smb4KFile::Smb4KFile(const Smb4KFile &file) : Smb4KBasicNetworkItem(file.type()), d(new Smb4KFilePrivate) { *d = *file.d; } Smb4KFile::~Smb4KFile() { } void Smb4KFile::setWorkgroupName(const QString &name) { d->workgroupName = name; } QString Smb4KFile::workgroupName() const { return d->workgroupName; } QString Smb4KFile::hostName() const { return pUrl->host().toUpper(); } void Smb4KFile::setHostIpAddress(const QHostAddress &address) { if (!address.isNull() && address.protocol() != QAbstractSocket::UnknownNetworkLayerProtocol) { d->ip = address; } - else - { - // Do nothing - } } QString Smb4KFile::hostIpAddress() const { return d->ip.toString(); } bool Smb4KFile::hasHostIpAddress() const { return !d->ip.isNull(); } QString Smb4KFile::shareName() const { return pUrl->path().section('/', 1, 1); } void Smb4KFile::setLogin(const QString &name) { pUrl->setUserName(name); } QString Smb4KFile::login() const { return pUrl->userName(); } void Smb4KFile::setPassword(const QString &pass) { pUrl->setPassword(pass); } QString Smb4KFile::password() const { return pUrl->password(); } bool Smb4KFile::isDirectory() const { return (type() == Directory); } QString Smb4KFile::name() const { QString name; - if (type() == Directory) - { - name = pUrl->path().section(QDir::separator(), -1, -1); - } - else if (type() == File) - { - name = pUrl->fileName(); - } - else + switch (type()) { - // Do nothing + case Directory: + { + name = pUrl->path().section(QDir::separator(), -1, -1); + break; + } + case File: + { + name = pUrl->fileName(); + break; + } + default: + { + break; + } } return name; } bool Smb4KFile::isHidden() const { return name().startsWith('.'); } diff --git a/core/smb4kfile.h b/core/smb4kfile.h index 57217de..b13f2a8 100644 --- a/core/smb4kfile.h +++ b/core/smb4kfile.h @@ -1,164 +1,164 @@ /*************************************************************************** Smb4K's container class for information about a directory or file. ------------------- begin : Sa Nov 10 2018 - copyright : (C) 2018 by Alexander Reinholdt + copyright : (C) 2018-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifndef SMB4KFILE_H #define SMB4KFILE_H // application specific includes #include "smb4kbasicnetworkitem.h" // Qt includes #include #include class Smb4KFilePrivate; class Q_DECL_EXPORT Smb4KFile : public Smb4KBasicNetworkItem { public: /** * Constructor * * @param url The URL of the file or directory * * @param item The type of the item (only Directory and File) */ Smb4KFile(const QUrl &url, Smb4KGlobal::NetworkItem item); /** * Copy constructor * * @param file The other Smb4KFile object */ Smb4KFile(const Smb4KFile &file); /** * Destructor */ ~Smb4KFile(); /** * Sets the workgroup name to @p name. * * @param name The workgroup name */ void setWorkgroupName(const QString &name); /** * Returns the workgroup name. * * @returns the workgroup name. */ QString workgroupName() const; /** * Returns the host's name. * * @returns the name of the host. */ QString hostName() const; /** * Set the host's IP address to @p ip. * * @param ip The IP address of the host */ void setHostIpAddress(const QHostAddress &address); /** * Returns the host's IP address. * * @returns the IP address */ QString hostIpAddress() const; /** * Returns TRUE if the host's IP address is set and FALSE otherwise. * * @returns TRUE if the host's IP address is set and FALSE otherwise. */ bool hasHostIpAddress() const; /** * Returns the share's name. * * @returns the name of the share. */ QString shareName() const; /** * Set the login name for the share where this file or directory is located to @p name. * * @param name The login name */ void setLogin(const QString &name); /** * Return the login name for the share where this file or directory is located. * * @returns the login name */ QString login() const; /** * Set the password for the share where this file or directory is located to @p pass. * * @param pass The password */ void setPassword(const QString &pass); /** * Return the password for the share where this file or directory is located. * * @returns the password */ QString password() const; /** * Returns TRUE if the network item is a directory and FALSE otherwise. * * @return TRUE if this item is a directory */ bool isDirectory() const; /** * Returns the name of the file or directory. * * @returns the name of the file or directory. */ QString name() const; /** * Returns TRUE if the file or directory is hidden and FALSE otherwise. * * @returns TRUE is the file or directory id hidden */ bool isHidden() const; private: const QScopedPointer d; }; #endif diff --git a/core/smb4kglobal.cpp b/core/smb4kglobal.cpp index 6b301d7..c5baf14 100644 --- a/core/smb4kglobal.cpp +++ b/core/smb4kglobal.cpp @@ -1,1213 +1,989 @@ /*************************************************************************** This is the global namespace for Smb4K. ------------------- begin : Sa Apr 2 2005 copyright : (C) 2005-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kglobal.h" #include "smb4kglobal_p.h" #include "smb4knotification.h" #include "smb4ksynchronizer.h" #include "smb4kclient.h" #if !defined(SMB4K_UNSUPPORTED_PLATFORM) #include "smb4kmounter.h" #endif // Qt includes #include #include #include #include // KDE includes #include #include Q_GLOBAL_STATIC(Smb4KGlobalPrivate, p); QMutex mutex(QMutex::Recursive /* needed to avoid dead-locks */); void Smb4KGlobal::initCore(bool modifyCursor, bool initClasses) { if (!p->coreInitialized) { // // Busy cursor // p->modifyCursor = modifyCursor; // // Initialize the necessary core classes // if (initClasses) { Smb4KClient::self()->start(); #if !defined(SMB4K_UNSUPPORTED_PLATFORM) Smb4KMounter::self()->start(); #endif } - else - { - // Do nothing - } p->coreInitialized = true; } - else - { - // Do nothing - } } void Smb4KGlobal::abortCore() { Smb4KClient::self()->abort(); #if !defined(SMB4K_UNSUPPORTED_PLATFORM) Smb4KMounter::self()->abort(); #endif Smb4KSynchronizer::self()->abort(); } bool Smb4KGlobal::coreIsRunning() { return (Smb4KClient::self()->isRunning() || #if !defined(SMB4K_UNSUPPORTED_PLATFORM) Smb4KMounter::self()->isRunning() || #endif Smb4KSynchronizer::self()->isRunning()); } bool Smb4KGlobal::coreIsInitialized() { return p->coreInitialized; } const QList &Smb4KGlobal::workgroupsList() { return p->workgroupsList; } WorkgroupPtr Smb4KGlobal::findWorkgroup(const QString &name) { WorkgroupPtr workgroup; mutex.lock(); for (const WorkgroupPtr &w : p->workgroupsList) { if (QString::compare(w->workgroupName(), name, Qt::CaseInsensitive) == 0) { workgroup = w; break; } - else - { - // Do nothing - } } mutex.unlock(); return workgroup; } bool Smb4KGlobal::addWorkgroup(WorkgroupPtr workgroup) { Q_ASSERT(workgroup); bool added = false; if (workgroup) { mutex.lock(); if (!findWorkgroup(workgroup->workgroupName())) { p->workgroupsList.append(workgroup); added = true; } - else - { - // Do nothing - } mutex.unlock(); } - else - { - // Do nothing - } return added; } bool Smb4KGlobal::updateWorkgroup(WorkgroupPtr workgroup) { Q_ASSERT(workgroup); bool updated = false; if (workgroup) { mutex.lock(); WorkgroupPtr existingWorkgroup = findWorkgroup(workgroup->workgroupName()); if (existingWorkgroup) { existingWorkgroup->update(workgroup.data()); updated = true; } - else - { - // Do nothing - } mutex.unlock(); } - else - { - // Do nothing - } return updated; } bool Smb4KGlobal::removeWorkgroup(WorkgroupPtr workgroup) { Q_ASSERT(workgroup); bool removed = false; if (workgroup) { mutex.lock(); int index = p->workgroupsList.indexOf(workgroup); if (index != -1) { // The workgroup was found. Remove it. p->workgroupsList.takeAt(index).clear(); removed = true; } else { // Try harder to find the workgroup. WorkgroupPtr wg = findWorkgroup(workgroup->workgroupName()); if (wg) { index = p->workgroupsList.indexOf(wg); if (index != -1) { p->workgroupsList.takeAt(index).clear(); removed = true; } - else - { - // Do nothing - } - } - else - { - // Do nothing } workgroup.clear(); } mutex.unlock(); } - else - { - // Do nothing - } return removed; } void Smb4KGlobal::clearWorkgroupsList() { mutex.lock(); while (!p->workgroupsList.isEmpty()) { p->workgroupsList.takeFirst().clear(); } mutex.unlock(); } const QList &Smb4KGlobal::hostsList() { return p->hostsList; } HostPtr Smb4KGlobal::findHost(const QString &name, const QString &workgroup) { HostPtr host; mutex.lock(); for (const HostPtr &h : p->hostsList) { if ((workgroup.isEmpty() || QString::compare(h->workgroupName(), workgroup, Qt::CaseInsensitive) == 0) && QString::compare(h->hostName(), name, Qt::CaseInsensitive) == 0) { host = h; break; } - else - { - // Do nothing - } } mutex.unlock(); return host; } bool Smb4KGlobal::addHost(HostPtr host) { Q_ASSERT(host); bool added = false; if (host) { mutex.lock(); if (!findHost(host->hostName(), host->workgroupName())) { p->hostsList.append(host); added = true; } - else - { - // Do nothing - } mutex.unlock(); } - else - { - // Do nothing - } return added; } bool Smb4KGlobal::updateHost(HostPtr host) { Q_ASSERT(host); bool updated = false; if (host) { mutex.lock(); HostPtr existingHost = findHost(host->hostName(), host->workgroupName()); if (existingHost) { existingHost->update(host.data()); updated = true; } - else - { - // Do nothing - } - + mutex.unlock(); } - else - { - // Do nothing - } return updated; } bool Smb4KGlobal::removeHost(HostPtr host) { Q_ASSERT(host); bool removed = false; if (host) { mutex.lock(); int index = p->hostsList.indexOf(host); if (index != -1) { // The host was found. Remove it. p->hostsList.takeAt(index).clear(); removed = true; } else { // Try harder to find the host. HostPtr h = findHost(host->hostName(), host->workgroupName()); if (h) { index = p->hostsList.indexOf(h); if (index != -1) { p->hostsList.takeAt(index).clear(); removed = true; } - else - { - // Do nothing - } - } - else - { - // Do nothing } host.clear(); } mutex.unlock(); } - else - { - // Do nothing - } return removed; } void Smb4KGlobal::clearHostsList() { mutex.lock(); while (!p->hostsList.isEmpty()) { p->hostsList.takeFirst().clear(); } mutex.unlock(); } QList Smb4KGlobal::workgroupMembers(WorkgroupPtr workgroup) { QList hosts; mutex.lock(); for (const HostPtr &h : p->hostsList) { if (QString::compare(h->workgroupName(), workgroup->workgroupName(), Qt::CaseInsensitive) == 0) { hosts << h; } - else - { - // Do nothing - } } mutex.unlock(); return hosts; } const QList &Smb4KGlobal::sharesList() { return p->sharesList; } SharePtr Smb4KGlobal::findShare(const QUrl& url, const QString& workgroup) { SharePtr share; mutex.lock(); for (const SharePtr &s : p->sharesList) { if (QString::compare(s->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), url.toString(QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0 && (workgroup.isEmpty() || QString::compare(s->workgroupName(), workgroup, Qt::CaseInsensitive) == 0)) { share = s; break; } - else - { - // Do nothing - } } mutex.unlock(); return share; } bool Smb4KGlobal::addShare(SharePtr share) { Q_ASSERT(share); bool added = false; if (share) { mutex.lock(); // // Add the share // if (!findShare(share->url(), share->workgroupName())) { // // Set the share mounted // Only honor shares that are owned by the user // QList mountedShares = findShareByUrl(share->url()); if (!mountedShares.isEmpty()) { for (const SharePtr &s : mountedShares) { if (!s->isForeign()) { share->setMountData(s.data()); break; } else { continue; } } } - else - { - // Do nothing - } // // Add it // p->sharesList.append(share); added = true; } - else - { - // Do nothing - } - } - else - { - // Do nothing } mutex.unlock(); return added; } bool Smb4KGlobal::updateShare(SharePtr share) { Q_ASSERT(share); bool updated = false; if (share) { mutex.lock(); // // Updated the share // SharePtr existingShare = findShare(share->url(), share->workgroupName()); if (existingShare) { // // Set the share mounted // Only honor shares that are owned by the user // QList mountedShares = findShareByUrl(share->url()); if (!mountedShares.isEmpty()) { for (const SharePtr &s : mountedShares) { if (!s->isForeign()) { share->setMountData(s.data()); break; } else { continue; } } } - else - { - // Do nothing - } // // Update it // existingShare->update(share.data()); updated = true; } - else - { - // Do nothing - } - + mutex.unlock(); } - else - { - // Do nothing - } return updated; } bool Smb4KGlobal::removeShare(SharePtr share) { Q_ASSERT(share); bool removed = false; if (share) { mutex.lock(); int index = p->sharesList.indexOf(share); if (index != -1) { // The share was found. Remove it. p->sharesList.takeAt(index).clear(); removed = true; } else { // Try harder to find the share. SharePtr s = findShare(share->url(), share->workgroupName()); if (s) { index = p->sharesList.indexOf(s); if (index != -1) { p->sharesList.takeAt(index).clear(); removed = true; } - else - { - // Do nothing - } - } - else - { - // Do nothing } share.clear(); } mutex.unlock(); } - else - { - // Do nothing - } return removed; } void Smb4KGlobal::clearSharesList() { mutex.lock(); while (!p->sharesList.isEmpty()) { p->sharesList.takeFirst().clear(); } mutex.unlock(); } QList Smb4KGlobal::sharedResources(HostPtr host) { QList shares; mutex.lock(); for (const SharePtr &s : p->sharesList) { if (QString::compare(s->hostName(), host->hostName(), Qt::CaseInsensitive) == 0 && QString::compare(s->workgroupName(), host->workgroupName(), Qt::CaseInsensitive) == 0) { shares += s; } - else - { - // Do nothing - } } mutex.unlock(); return shares; } const QList &Smb4KGlobal::mountedSharesList() { return p->mountedSharesList; } SharePtr Smb4KGlobal::findShareByPath(const QString &path) { SharePtr share; mutex.lock(); if (!path.isEmpty() && !p->mountedSharesList.isEmpty()) { for (const SharePtr &s : p->mountedSharesList) { if (QString::compare(s->path(), path, Qt::CaseInsensitive) == 0 || QString::compare(s->canonicalPath(), path, Qt::CaseInsensitive) == 0) { share = s; break; } - else - { - // Do nothing - } } } - else - { - // Do nothing - } mutex.unlock(); return share; } QList Smb4KGlobal::findShareByUrl(const QUrl &url) { QList shares; mutex.lock(); if (!url.isEmpty() && url.isValid() && !p->mountedSharesList.isEmpty()) { for (const SharePtr &s : p->mountedSharesList) { if (QString::compare(s->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), url.toString(QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0) { shares << s; } - else - { - // Do nothing - } } } - else - { - // Do nothing - } mutex.unlock(); return shares; } QList Smb4KGlobal::findInaccessibleShares() { QList inaccessibleShares; mutex.lock(); for (const SharePtr &s : p->mountedSharesList) { if (s->isInaccessible()) { inaccessibleShares += s; } - else - { - // Do nothing - } } mutex.unlock(); return inaccessibleShares; } bool Smb4KGlobal::addMountedShare(SharePtr share) { Q_ASSERT(share); bool added = false; if (share) { mutex.lock(); // // Copy the mount data to the network share and the search results. // Only honor shares that were mounted by the user. // if (!share->isForeign()) { // Network shares SharePtr networkShare = findShare(share->url(), share->workgroupName()); if (networkShare) { networkShare->setMountData(share.data()); } - else - { - // Do nothing - } - } - else - { - // Do nothing } if (!findShareByPath(share->path())) { // // Check if we have to add a workgroup name and/or IP address // HostPtr networkHost = findHost(share->hostName(), share->workgroupName()); if (networkHost) { // Set the IP address if (!share->hasHostIpAddress() || networkHost->ipAddress() != share->hostIpAddress()) { share->setHostIpAddress(networkHost->ipAddress()); } - else - { - // Do nothing - } // Set the workgroup name if (share->workgroupName().isEmpty()) { share->setWorkgroupName(networkHost->workgroupName()); } - else - { - // Do nothing - } - } - else - { - // Do nothing } p->mountedSharesList.append(share); added = true; p->onlyForeignShares = true; for (const SharePtr &s : p->mountedSharesList) { if (!s->isForeign()) { p->onlyForeignShares = false; break; } - else - { - // Do nothing - } } } - else - { - // Do nothing - } mutex.unlock(); } - else - { - // Do nothing - } return added; } bool Smb4KGlobal::updateMountedShare(SharePtr share) { Q_ASSERT(share); bool updated = false; if (share) { mutex.lock(); // // Copy the mount data to the network share (needed for unmounting from the network browser) // Only honor shares that were mounted by the user. // if (!share->isForeign()) { SharePtr networkShare = findShare(share->url(), share->workgroupName()); if (networkShare) { networkShare->setMountData(share.data()); } - else - { - // Do nothing - } - } - else - { - // Do nothing } SharePtr mountedShare = findShareByPath(share->path()); if (mountedShare) { // // Check if we have to add a workgroup name and/or IP address // HostPtr networkHost = findHost(share->hostName(), share->workgroupName()); if (networkHost) { // Set the IP address if (!share->hasHostIpAddress() || networkHost->ipAddress() != share->hostIpAddress()) { share->setHostIpAddress(networkHost->ipAddress()); } - else - { - // Do nothing - } // Set the workgroup name if (share->workgroupName().isEmpty()) { share->setWorkgroupName(networkHost->workgroupName()); } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // Update share // mountedShare->setMountData(share.data()); updated = true; } - else - { - // Do nothing - } mutex.unlock(); } - else - { - // Do nothing - } return updated; } bool Smb4KGlobal::removeMountedShare(SharePtr share) { Q_ASSERT(share); bool removed = false; if (share) { mutex.lock(); // // Reset the mount data for the network share and the // search result // if (!share->isForeign()) { // Network share SharePtr networkShare = findShare(share->url(), share->workgroupName()); if (networkShare) { networkShare->resetMountData(); } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // Remove the mounted share // int index = p->mountedSharesList.indexOf(share); if (index != -1) { // The share was found. Remove it. p->mountedSharesList.takeAt(index).clear(); removed = true; } else { // Try harder to find the share. SharePtr s = findShareByPath(share->isInaccessible() ? share->path() : share->canonicalPath()); if (s) { index = p->mountedSharesList.indexOf(s); if (index != -1) { p->mountedSharesList.takeAt(index).clear(); removed = true; } - else - { - // Do nothing - } - } - else - { - // Do nothing } share.clear(); } for (const SharePtr &s : p->mountedSharesList) { if (!s->isForeign()) { p->onlyForeignShares = false; break; } - else - { - // Do nothing - } } mutex.unlock(); } - else - { - // Do nothing - } return removed; } bool Smb4KGlobal::onlyForeignMountedShares() { return p->onlyForeignShares; } void Smb4KGlobal::openShare(SharePtr share, OpenWith openWith) { if (!share || share->isInaccessible()) { return; } switch (openWith) { case FileManager: { QUrl url = QUrl::fromLocalFile(share->canonicalPath()); (void) new KRun(url, 0); break; } case Konsole: { QString konsole = QStandardPaths::findExecutable("konsole"); if (konsole.isEmpty()) { Smb4KNotification::commandNotFound("konsole"); } else { KRun::runCommand(konsole+" --workdir "+KShell::quoteArg(share->canonicalPath()), 0); } break; } default: { break; } } } const QMap &Smb4KGlobal::globalSambaOptions() { return p->globalSambaOptions(); } bool Smb4KGlobal::modifyCursor() { return p->modifyCursor; } #if defined(Q_OS_LINUX) QStringList Smb4KGlobal::whitelistedMountArguments() { return p->whitelistedMountArguments; } #endif const QString Smb4KGlobal::findMountExecutable() { QStringList paths; paths << "/bin"; paths << "/sbin"; paths << "/usr/bin"; paths << "/usr/sbin"; paths << "/usr/local/bin"; paths << "/usr/local/sbin"; #if defined(Q_OS_LINUX) return QStandardPaths::findExecutable("mount.cifs", paths); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) return QStandardPaths::findExecutable("mount_smbfs", paths); #else return QString(); #endif } const QString Smb4KGlobal::findUmountExecutable() { QStringList paths; paths << "/bin"; paths << "/sbin"; paths << "/usr/bin"; paths << "/usr/sbin"; paths << "/usr/local/bin"; paths << "/usr/local/sbin"; return QStandardPaths::findExecutable("umount", paths); } const QString Smb4KGlobal::dataLocation() { return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation)+QDir::separator()+"smb4k"; } diff --git a/core/smb4kglobal_p.cpp b/core/smb4kglobal_p.cpp index 4602f44..729e6ae 100644 --- a/core/smb4kglobal_p.cpp +++ b/core/smb4kglobal_p.cpp @@ -1,325 +1,309 @@ /*************************************************************************** These are the private helper classes of the Smb4KGlobal namespace. ------------------- begin : Di Jul 24 2007 copyright : (C) 2007-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kglobal_p.h" #include "smb4knotification.h" #include "smb4ksettings.h" // Qt includes #include #include #include #include #include #include #include #include #include Smb4KGlobalPrivate::Smb4KGlobalPrivate() { onlyForeignShares = false; coreInitialized = false; m_sambaConfigMissing = false; #ifdef Q_OS_LINUX whitelistedMountArguments << "dynperm"; whitelistedMountArguments << "rwpidforward"; whitelistedMountArguments << "hard"; whitelistedMountArguments << "soft"; whitelistedMountArguments << "noacl"; whitelistedMountArguments << "cifsacl"; whitelistedMountArguments << "backupuid"; whitelistedMountArguments << "backupgid"; whitelistedMountArguments << "ignorecase"; whitelistedMountArguments << "nocase"; whitelistedMountArguments << "nobrl"; whitelistedMountArguments << "sfu"; whitelistedMountArguments << "nounix"; whitelistedMountArguments << "nouser_xattr"; whitelistedMountArguments << "fsc"; whitelistedMountArguments << "multiuser"; whitelistedMountArguments << "actimeo"; whitelistedMountArguments << "noposixpaths"; whitelistedMountArguments << "posixpaths"; #endif // // File system watcher for smb.conf file // m_watcher = new QFileSystemWatcher(this); // // Connections // connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), SLOT(slotAboutToQuit())); connect(m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(slotSmbConfModified(QString))); } Smb4KGlobalPrivate::~Smb4KGlobalPrivate() { // Clear the workgroup list. while (!workgroupsList.isEmpty()) { workgroupsList.takeFirst().clear(); } // Clear the host list. while (!hostsList.isEmpty()) { hostsList.takeFirst().clear(); } // Clear the list of mounted shares. while (!mountedSharesList.isEmpty()) { mountedSharesList.takeFirst().clear(); } // Clear the list of shares. while (!sharesList.isEmpty()) { sharesList.takeFirst().clear(); } } const QMap &Smb4KGlobalPrivate::globalSambaOptions(bool read) { if ((!m_sambaConfigMissing && m_sambaOptions.isEmpty()) || read) { // // Clear the options. // m_sambaOptions.clear(); // // Now search the smb.conf file. // // With the introduction of Samba 4, the smb.conf file might also // be named smb4.conf. Thus we need to search for two filenames. // QStringList paths; paths << "/etc"; paths << "/usr/local/etc"; paths << "/usr/pkg/etc"; QStringList files; files << "smb.conf"; files << "smb4.conf"; QString result; for (const QString &path : paths) { QDirIterator it(path, files, QDir::Files, QDirIterator::Subdirectories); while (it.hasNext()) { result = it.next(); } if (!result.isEmpty()) { break; } - else - { - // Do nothing - } } // // Check if we found the file and read it. Otherwise show an error // message to the user. // QStringList contents; if (!result.isEmpty()) { QFile smbConf(result); if (smbConf.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream ts(&smbConf); while (!ts.atEnd()) { contents << ts.readLine(0); } smbConf.close(); } else { Smb4KNotification::openingFileFailed(smbConf); return m_sambaOptions; } // // Add the file to the file system watcher // m_watcher->addPath(result); // // Tell the program that the config file was found // m_sambaConfigMissing = false; } else { if (!m_sambaConfigMissing) { Smb4KNotification::sambaConfigFileMissing(); m_sambaConfigMissing = true; return m_sambaOptions; } - else - { - // Do nothing - } } // // Process the contents of the smb.conf file // if (!contents.isEmpty()) { // // Jump to the [global] section and get the listed parameters // for (int i = contents.indexOf("[global]", 0); i < contents.size(); ++i) { if (i == -1) { // // No [global] section found. Stop. // break; } else if (contents.at(i).trimmed().startsWith('#') || contents.at(i).trimmed().startsWith(';') || contents.at(i).trimmed().isEmpty()) { // // This is either a comment or an empty line. We do not want it. // continue; } else if (contents.at(i).trimmed().startsWith(QLatin1String("include"))) { // // This is an include file. Get its contents and insert it into the // global Samba options map // QFile includeFile(contents.at(i).section('=', 1, 1).trimmed()); if (includeFile.exists()) { if (includeFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream ts(&includeFile); QString buffer; while(!ts.atEnd()) { buffer = ts.readLine(0).trimmed(); if (buffer.startsWith('#') || buffer.startsWith(';')) { // // This is either a comment or an empty line. We do not want it. // continue; } else { // // This is an option. Put it into the global Samba options map // QString key = contents.at(i).section('=', 0, 0).trimmed().toLower(); QString value = contents.at(i).section('=', 1, 1).trimmed().toUpper(); m_sambaOptions.insert(key, value); } } } else { Smb4KNotification::openingFileFailed(includeFile); continue; } } } else if (contents.at(i).trimmed().startsWith('[') && !contents.at(i).contains("[global]", Qt::CaseSensitive)) { // // A new section begins. Stop. // break; } else { // // This is an option. Put it into the global Samba options map // QString key = contents.at(i).section('=', 0, 0).trimmed().toLower(); QString value = contents.at(i).section('=', 1, 1).trimmed().toUpper(); m_sambaOptions.insert(key, value); } } } - else - { - // Do nothing - } - } - else - { - // Do nothing } return m_sambaOptions; } void Smb4KGlobalPrivate::slotAboutToQuit() { Smb4KSettings::self()->save(); } void Smb4KGlobalPrivate::slotSmbConfModified(const QString &/*file*/) { globalSambaOptions(true); } diff --git a/core/smb4khardwareinterface.cpp b/core/smb4khardwareinterface.cpp index 9e1a12c..036219c 100644 --- a/core/smb4khardwareinterface.cpp +++ b/core/smb4khardwareinterface.cpp @@ -1,206 +1,182 @@ /*************************************************************************** Provides an interface to the computer's hardware ------------------- begin : Die Jul 14 2015 - copyright : (C) 2015-2017 by Alexander Reinholdt + copyright : (C) 2015-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4khardwareinterface.h" #include "smb4khardwareinterface_p.h" // Qt includes #include #include // KDE includes #include #include #include #if defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) #include #endif Q_GLOBAL_STATIC(Smb4KHardwareInterfaceStatic, p); Smb4KHardwareInterface::Smb4KHardwareInterface(QObject *parent) : QObject(parent), d(new Smb4KHardwareInterfacePrivate) { d->networkConfigUpdated = false; connect(&d->networkConfigManager, SIGNAL(updateCompleted()), this, SLOT(slotNetworkConfigUpdated())); connect(&d->networkConfigManager, SIGNAL(onlineStateChanged(bool)), this, SIGNAL(onlineStateChanged(bool))); connect(Solid::DeviceNotifier::instance(), SIGNAL(deviceAdded(QString)), this, SLOT(slotDeviceAdded(QString))); connect(Solid::DeviceNotifier::instance(), SIGNAL(deviceRemoved(QString)), this, SLOT(slotDeviceRemoved(QString))); #if defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) startTimer(2000); #endif } Smb4KHardwareInterface::~Smb4KHardwareInterface() { } Smb4KHardwareInterface* Smb4KHardwareInterface::self() { return &p->instance; } void Smb4KHardwareInterface::updateNetworkConfig() { d->networkConfigManager.updateConfigurations(); } bool Smb4KHardwareInterface::networkConfigIsUpdated() const { return d->networkConfigUpdated; } bool Smb4KHardwareInterface::isOnline() const { return d->networkConfigManager.isOnline(); } #if defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) // Using FreeBSD 11 with KF 5.27, Solid is not able to detect mounted shares. // Thus, we check here whether shares have been mounted or unmounted. // This is a hack and should be removed as soon as possible. void Smb4KHardwareInterface::timerEvent(QTimerEvent */*e*/) { KMountPoint::List mountPoints = KMountPoint::currentMountPoints(KMountPoint::BasicInfoNeeded|KMountPoint::NeedMountOptions); QStringList mountPointList, alreadyMounted; for (const QExplicitlySharedDataPointer &mountPoint : mountPoints) { if (QString::compare(mountPoint->mountType(), "smbfs") == 0 || QString::compare(mountPoint->mountType(), "cifs") == 0) { mountPointList.append(mountPoint->mountPoint()); } - else - { - // Do nothing - } } QMutableStringListIterator it(mountPointList); while (it.hasNext()) { QString mp = it.next(); int index = -1; if ((index = d->mountPoints.indexOf(mp)) != -1) { d->mountPoints.removeAt(index); alreadyMounted.append(mp); it.remove(); } - else - { - // Do nothing - } } if (!d->mountPoints.isEmpty()) { emit networkShareRemoved(); } - else - { - // Do nothing - } if (!mountPointList.isEmpty()) { emit networkShareAdded(); } - else - { - // Do nothing - } d->mountPoints.clear(); d->mountPoints.append(alreadyMounted); d->mountPoints.append(mountPointList); } #endif void Smb4KHardwareInterface::slotNetworkConfigUpdated() { d->networkConfigUpdated = true; emit networkConfigUpdated(); } void Smb4KHardwareInterface::slotDeviceAdded(const QString& udi) { Solid::Device device(udi); if (device.isDeviceInterface(Solid::DeviceInterface::NetworkShare)) { d->udis.append(udi); emit networkShareAdded(); } - else - { - // Do nothing - } } void Smb4KHardwareInterface::slotDeviceRemoved(const QString& udi) { Solid::Device device(udi); // For some reason, the device has no valid type at the moment (Frameworks 5.9, // July 2015). Thus, we need the code in the else block for now. if (device.isDeviceInterface(Solid::DeviceInterface::NetworkShare)) { emit networkShareRemoved(); } else { if (d->udis.contains(udi)) { emit networkShareRemoved(); d->udis.removeOne(udi); } - else - { - // Do nothing - } } } diff --git a/core/smb4khardwareinterface.h b/core/smb4khardwareinterface.h index 89fcec2..2a27bc2 100644 --- a/core/smb4khardwareinterface.h +++ b/core/smb4khardwareinterface.h @@ -1,142 +1,142 @@ /*************************************************************************** Provides an interface to the computer's hardware ------------------- begin : Die Jul 14 2015 - copyright : (C) 2015-2017 by Alexander Reinholdt + copyright : (C) 2015-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifndef SMB4KHARDWAREINTERFACE_H #define SMB4KHARDWAREINTERFACE_H // application specific includes #include "smb4kglobal.h" // Qt includes #include #include #include #include class Smb4KHardwareInterfacePrivate; /** * This class provides an interface to the computer's hardware. * @author Alexander Reinholdt * @since 2.0.0 */ class Q_DECL_EXPORT Smb4KHardwareInterface : public QObject { Q_OBJECT friend class Smb4KHardwareInterfacePrivate; public: /** * The constructor */ explicit Smb4KHardwareInterface(QObject *parent = 0); /** * The destructor */ ~Smb4KHardwareInterface(); /** * The static pointer to this class. * @returns a static pointer to this class */ static Smb4KHardwareInterface *self(); /** * This function checks the current network configuration. * You should run this if @see isOnline() and @see networkConfigUpdated() return * both FALSE. */ void updateNetworkConfig(); /** * This function returns TRUE if the network configuration was already updated * and FALSE otherwise. * @returns TRUE if the network configuration was updated and FALSE otherwise. */ bool networkConfigIsUpdated() const; /** * This function returns TRUE if the system is online and FALSE otherwise. * @returns TRUE if the system is online. */ bool isOnline() const; #if defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) protected: /** * Reimplemented from QObject to check for mounts and unmounts on operating * systems that are not fully supported by Solid, yet. */ void timerEvent(QTimerEvent *e); #endif Q_SIGNALS: /** * This signal is emitted when a network share is added to the system */ void networkShareAdded(); /** * This signal is emitted when a network share is removed from the system */ void networkShareRemoved(); /** * This signal is emitted when the network configuration was updated. */ void networkConfigUpdated(); /** * This signal is emitted when the online state changed. */ void onlineStateChanged(bool online); protected Q_SLOTS: /** * This slot is called by the QNetworkConfigurationManager::updateCompleted() * signal and sets d->networkConfigUpdated to TRUE. */ void slotNetworkConfigUpdated(); /** * This slot is called when a device was added to the system. * @param udi the device UDI */ void slotDeviceAdded(const QString &udi); /** * This slot is called when a device was removed from the system. * @param udi the device UDI */ void slotDeviceRemoved(const QString &udi); private: QScopedPointer d; }; #endif diff --git a/core/smb4khomesshareshandler.cpp b/core/smb4khomesshareshandler.cpp index a2d163b..9372f6e 100644 --- a/core/smb4khomesshareshandler.cpp +++ b/core/smb4khomesshareshandler.cpp @@ -1,556 +1,500 @@ /*************************************************************************** This class handles the homes shares ------------------- begin : Do Aug 10 2006 copyright : (C) 2006-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335 USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4khomesshareshandler.h" #include "smb4khomesshareshandler_p.h" #include "smb4kshare.h" #include "smb4ksettings.h" #include "smb4kauthinfo.h" #include "smb4knotification.h" #include "smb4kprofilemanager.h" // Qt includes #include #include #include #include #include #include // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include Q_GLOBAL_STATIC(Smb4KHomesSharesHandlerStatic, p); Smb4KHomesSharesHandler::Smb4KHomesSharesHandler(QObject *parent) : QObject(parent), d(new Smb4KHomesSharesHandlerPrivate) { // First we need the directory. QString path = dataLocation(); QDir dir; if (!dir.exists(path)) { dir.mkpath(path); } - else - { - // Do nothing - } d->homesUsers = readUserNames(false); // Connections connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(slotAboutToQuit())); connect(Smb4KProfileManager::self(), SIGNAL(activeProfileChanged(QString)), this, SLOT(slotActiveProfileChanged(QString))); } Smb4KHomesSharesHandler::~Smb4KHomesSharesHandler() { while (!d->homesUsers.isEmpty()) { delete d->homesUsers.takeFirst(); } } Smb4KHomesSharesHandler *Smb4KHomesSharesHandler::self() { return &p->instance; } bool Smb4KHomesSharesHandler::specifyUser(const SharePtr &share, bool overwrite) { Q_ASSERT(share); bool success = false; // Avoid that the dialog is opened although the homes // user name has already been defined. if (share->isHomesShare() && (share->homeUrl().isEmpty() || overwrite)) { QStringList users = findHomesUsers(share); QPointer dlg = new Smb4KHomesUserDialog(share, QApplication::activeWindow()); dlg->setUserNames(users); if (dlg->exec() == QDialog::Accepted) { QString login = dlg->login(); users = dlg->userNames(); addHomesUsers(share, users); if (!login.isEmpty()) { // If the login names do not match, clear the password. if (!share->login().isEmpty() && QString::compare(share->login(), login) != 0) { share->setPassword(QString()); } - else - { - // Do nothing - } // Set the login name. share->setLogin(login); success = true; } - else - { - // Do nothing - } writeUserNames(d->homesUsers); } - else - { - // Do nothing - } delete dlg; } else { // The user name has already been set. success = true; } return success; } QStringList Smb4KHomesSharesHandler::homesUsers(const SharePtr &share) { Q_ASSERT(share); QStringList users = findHomesUsers(share); return users; } const QList Smb4KHomesSharesHandler::readUserNames(bool allUsers) { QList list; // Locate the XML file. QFile xmlFile(dataLocation()+QDir::separator()+"homes_shares.xml"); if (xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QXmlStreamReader xmlReader(&xmlFile); while (!xmlReader.atEnd()) { xmlReader.readNext(); if (xmlReader.isStartElement()) { if (xmlReader.name() == "homes_shares" && xmlReader.attributes().value("version") != "1.0") { xmlReader.raiseError(i18n("%1 is not a version 1.0 file.", xmlFile.fileName())); break; } else { if (xmlReader.name() == "homes") { QString profile = xmlReader.attributes().value("profile").toString(); // FIXME: Remove the last check in the if statement with Smb4K > 2.0. // It was introduced for migration, because the default profile // (e.g. use of no profiles) was not empty but named "Default"... if (allUsers || QString::compare(profile, Smb4KProfileManager::self()->activeProfile(), Qt::CaseSensitive) == 0 || (!Smb4KProfileManager::self()->useProfiles() && QString::compare(profile, "Default", Qt::CaseSensitive) == 0)) { Smb4KHomesUsers *users = new Smb4KHomesUsers(); users->setProfile(profile); users->setShareName(xmlReader.name().toString()); while (!(xmlReader.isEndElement() && xmlReader.name() == "homes")) { xmlReader.readNext(); if (xmlReader.isStartElement()) { if (xmlReader.name() == "host") { users->setHostName(xmlReader.readElementText()); } else if (xmlReader.name() == "workgroup") { users->setWorkgroupName(xmlReader.readElementText()); } else if (xmlReader.name() == "ip") { users->setHostIP(xmlReader.readElementText()); } else if (xmlReader.name() == "users") { QStringList u; while (!(xmlReader.isEndElement() && xmlReader.name() == "users")) { xmlReader.readNext(); if (xmlReader.isStartElement() && xmlReader.name() == "user") { u << xmlReader.readElementText(); } - else - { - // Do nothing - } } users->setUsers(u); } - else - { - // Do nothing - } continue; } else { continue; } } list << users; } else { continue; } } else { continue; } } } else { continue; } } xmlFile.close(); if (xmlReader.hasError()) { Smb4KNotification::readingFileFailed(xmlFile, xmlReader.errorString()); } - else - { - // Do nothing - } } else { if (xmlFile.exists()) { Smb4KNotification::openingFileFailed(xmlFile); } - else - { - // Do nothing - } } return list; } void Smb4KHomesSharesHandler::writeUserNames(const QList &list, bool listOnly) { QList allUsers; if (!listOnly) { // First read all entries. Then remove all, that belong to // the currently active profile. allUsers = readUserNames(true); QMutableListIterator it(allUsers); while (it.hasNext()) { Smb4KHomesUsers *users = it.next(); if (QString::compare(users->profile(), Smb4KProfileManager::self()->activeProfile()) == 0) { it.remove(); } - else - { - // Do nothing - } } } - else - { - // Do nothing - } - for (int i = 0; i < list.size(); ++i) + for (Smb4KHomesUsers *users : list) { - allUsers << new Smb4KHomesUsers(*list[i]); + allUsers << new Smb4KHomesUsers(*users); } QFile xmlFile(dataLocation()+QDir::separator()+"homes_shares.xml"); if (!allUsers.isEmpty()) { if (xmlFile.open(QIODevice::WriteOnly|QIODevice::Text)) { QXmlStreamWriter xmlWriter(&xmlFile); xmlWriter.setAutoFormatting(true); xmlWriter.writeStartDocument(); xmlWriter.writeStartElement("homes_shares"); xmlWriter.writeAttribute("version", "1.0"); - for (int i = 0; i < allUsers.size(); ++i) + for (Smb4KHomesUsers *users : allUsers) { xmlWriter.writeStartElement("homes"); // FIXME: Remove this block with Smb4K > 2.0 and use the commented line below. // This block was introduced for migration, because the default profile // (i.e. use of no profiles) was not empty but named "Default"... if (!Smb4KProfileManager::self()->useProfiles()) { xmlWriter.writeAttribute("profile", Smb4KSettings::self()->activeProfile()); } else { - xmlWriter.writeAttribute("profile", allUsers.at(i)->profile()); + xmlWriter.writeAttribute("profile", users->profile()); } - // xmlWriter.writeAttribute("profile", allUsers.at(i)->profile); - xmlWriter.writeTextElement("host", allUsers.at(i)->hostName()); - xmlWriter.writeTextElement("workgroup", allUsers.at(i)->workgroupName()); - xmlWriter.writeTextElement("ip", allUsers.at(i)->hostIP()); + // xmlWriter.writeAttribute("profile", users->profile()); + xmlWriter.writeTextElement("host", users->hostName()); + xmlWriter.writeTextElement("workgroup", users->workgroupName()); + xmlWriter.writeTextElement("ip", users->hostIP()); xmlWriter.writeStartElement("users"); - for (int j = 0; j < allUsers.at(i)->users().size(); ++j) + for (const QString &user : users->users()) { - xmlWriter.writeTextElement("user", allUsers.at(i)->users().at(j)); + xmlWriter.writeTextElement("user", user); } xmlWriter.writeEndElement(); xmlWriter.writeEndElement(); } xmlWriter.writeEndDocument(); xmlFile.close(); } else { Smb4KNotification::openingFileFailed(xmlFile); } } else { xmlFile.remove(); } while (!allUsers.isEmpty()) { delete allUsers.takeFirst(); } } const QStringList Smb4KHomesSharesHandler::findHomesUsers(const SharePtr &share) { Q_ASSERT(share); QStringList users; if (!d->homesUsers.isEmpty()) { for (int i = 0; i < d->homesUsers.size(); ++i) { if (QString::compare(share->hostName(), d->homesUsers.at(i)->hostName(), Qt::CaseInsensitive) == 0 && QString::compare(share->shareName(), d->homesUsers.at(i)->shareName(), Qt::CaseInsensitive) == 0 && ((d->homesUsers.at(i)->workgroupName().isEmpty() || share->workgroupName().isEmpty()) || QString::compare(share->workgroupName(), d->homesUsers.at(i)->workgroupName(), Qt::CaseInsensitive) == 0)) { users = d->homesUsers.at(i)->users(); break; } else { continue; } } } return users; } void Smb4KHomesSharesHandler::addHomesUsers(const SharePtr &share, const QStringList &users) { Q_ASSERT(share); bool found = false; if (!d->homesUsers.isEmpty()) { for (int i = 0; i < d->homesUsers.size(); ++i) { if (QString::compare(share->hostName(), d->homesUsers.at(i)->hostName(), Qt::CaseInsensitive) == 0 && QString::compare(share->shareName(), d->homesUsers.at(i)->shareName(), Qt::CaseInsensitive) == 0 && ((d->homesUsers.at(i)->workgroupName().isEmpty() || share->workgroupName().isEmpty()) || QString::compare(share->workgroupName(), d->homesUsers.at(i)->workgroupName(), Qt::CaseInsensitive) == 0)) { d->homesUsers[i]->setUsers(users); found = true; break; } else { continue; } } } - else - { - // Do nothing - } if (!found) { Smb4KHomesUsers *u = new Smb4KHomesUsers(share, users); u->setProfile(Smb4KProfileManager::self()->activeProfile()); d->homesUsers << u; } - else - { - // Do nothing - } } void Smb4KHomesSharesHandler::migrateProfile(const QString& from, const QString& to) { // Read all entries for later conversion. QList allUsers = readUserNames(true); // Replace the old profile name with the new one. for (int i = 0; i < allUsers.size(); ++i) { if (QString::compare(allUsers.at(i)->profile(), from, Qt::CaseSensitive) == 0) { allUsers[i]->setProfile(to); } - else - { - // Do nothing - } } // Write the new list to the file. writeUserNames(allUsers, true); // Profile settings changed, so invoke the slot. slotActiveProfileChanged(Smb4KProfileManager::self()->activeProfile()); // Clear the temporary lists of bookmarks and groups. while (!allUsers.isEmpty()) { delete allUsers.takeFirst(); } } void Smb4KHomesSharesHandler::removeProfile(const QString& name) { // Read all entries for later removal. QList allUsers = readUserNames(true); QMutableListIterator it(allUsers); while (it.hasNext()) { Smb4KHomesUsers *user = it.next(); if (QString::compare(user->profile(), name, Qt::CaseSensitive) == 0) { it.remove(); } - else - { - // Do nothing - } } // Write the new list to the file. writeUserNames(allUsers, true); // Profile settings changed, so invoke the slot. slotActiveProfileChanged(Smb4KProfileManager::self()->activeProfile()); // Clear the temporary list of homes users. while (!allUsers.isEmpty()) { delete allUsers.takeFirst(); } } ///////////////////////////////////////////////////////////////////////////// // SLOT IMPLEMENTATIONS ///////////////////////////////////////////////////////////////////////////// void Smb4KHomesSharesHandler::slotAboutToQuit() { writeUserNames(d->homesUsers); } void Smb4KHomesSharesHandler::slotActiveProfileChanged(const QString& /*activeProfile*/) { // Clear the list of homes users. while (!d->homesUsers.isEmpty()) { delete d->homesUsers.takeFirst(); } // Reload the list of homes users. d->homesUsers = readUserNames(false); } diff --git a/core/smb4khomesshareshandler_p.cpp b/core/smb4khomesshareshandler_p.cpp index a4d0713..f0ff99d 100644 --- a/core/smb4khomesshareshandler_p.cpp +++ b/core/smb4khomesshareshandler_p.cpp @@ -1,321 +1,309 @@ /*************************************************************************** Private helpers for the homes shares handler ------------------- begin : Mo Apr 11 2011 - copyright : (C) 2011-2017 by Alexander Reinholdt + copyright : (C) 2011-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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, 51 Franklin Street, Suite 500, Boston, * * MA 02110-1335 USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4khomesshareshandler_p.h" #include "smb4ksettings.h" #include "smb4kshare.h" // Qt includes #include #include #include #include #include #include #include #include #include #include // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include #include #include Smb4KHomesUsers::Smb4KHomesUsers(const SharePtr &s, const QStringList &u) { m_workgroup_name = s->workgroupName(); m_host_name = s->hostName(); m_share_name = s->shareName(); m_host_ip.setAddress(s->hostIpAddress()); m_users = u; } Smb4KHomesUsers::Smb4KHomesUsers(const Smb4KHomesUsers &u) { m_workgroup_name = u.workgroupName(); m_host_name = u.hostName(); m_share_name = u.shareName(); m_host_ip.setAddress(u.hostIP()); m_users = u.users(); m_profile = u.profile(); } Smb4KHomesUsers::Smb4KHomesUsers() { } Smb4KHomesUsers::~Smb4KHomesUsers() { } QString Smb4KHomesUsers::workgroupName() const { return m_workgroup_name; } void Smb4KHomesUsers::setWorkgroupName(const QString& name) { m_workgroup_name = name; } QString Smb4KHomesUsers::hostName() const { return m_host_name; } void Smb4KHomesUsers::setHostName(const QString& name) { m_host_name = name; } QString Smb4KHomesUsers::shareName() const { return m_share_name; } void Smb4KHomesUsers::setShareName(const QString& name) { m_share_name = name; } QString Smb4KHomesUsers::hostIP() const { return m_host_ip.toString(); } void Smb4KHomesUsers::setHostIP(const QString& ip) { m_host_ip.setAddress(ip); } QStringList Smb4KHomesUsers::users() const { return m_users; } void Smb4KHomesUsers::setUsers(const QStringList& users) { m_users = users; } QString Smb4KHomesUsers::profile() const { return m_profile; } void Smb4KHomesUsers::setProfile(const QString& profile) { m_profile = profile; } Smb4KHomesUserDialog::Smb4KHomesUserDialog(const SharePtr &share, QWidget *parent) : QDialog(parent), m_share(share) { setWindowTitle(i18n("Specify User")); setupView(); setMinimumWidth(sizeHint().width() > 350 ? sizeHint().width() : 350); create(); KConfigGroup group(Smb4KSettings::self()->config(), "HomesUserDialog"); KWindowConfig::restoreWindowSize(windowHandle(), group); resize(windowHandle()->size()); // workaround for QTBUG-40584 m_user_combo->completionObject()->setItems(group.readEntry("HomesUsersCompletion", QStringList())); } Smb4KHomesUserDialog::~Smb4KHomesUserDialog() { } void Smb4KHomesUserDialog::setupView() { QVBoxLayout *layout = new QVBoxLayout(this); layout->setSpacing(5); QWidget *description = new QWidget(this); QHBoxLayout *desc_layout = new QHBoxLayout(description); desc_layout->setSpacing(5); desc_layout->setMargin(0); QLabel *pixmap = new QLabel(description); QPixmap user_pix = KDE::icon("user-identity").pixmap(KIconLoader::SizeHuge); pixmap->setPixmap(user_pix); pixmap->setAlignment(Qt::AlignBottom); QLabel *label = new QLabel(i18n("Please specify a username for share
%1.", m_share->displayString()), description); label->setWordWrap(true); label->setAlignment(Qt::AlignBottom); desc_layout->addWidget(pixmap, 0); desc_layout->addWidget(label, Qt::AlignBottom); QWidget *input = new QWidget(this); QGridLayout *input_layout = new QGridLayout(input); input_layout->setSpacing(5); input_layout->setMargin(0); input_layout->setColumnStretch(0, 0); input_layout->setColumnStretch(1, 1); QLabel *input_label = new QLabel(i18n("User:"), input); m_user_combo = new KComboBox(true, input); m_user_combo->setDuplicatesEnabled(false); m_user_combo->setEditable(true); input_layout->addWidget(input_label, 0, 0, 0); input_layout->addWidget(m_user_combo, 0, 1, 0); QDialogButtonBox *buttonBox = new QDialogButtonBox(Qt::Horizontal, this); m_clear_button = buttonBox->addButton(i18n("Clear List"), QDialogButtonBox::ActionRole); m_clear_button->setIcon(KDE::icon("edit-clear")); m_clear_button->setEnabled(false); m_ok_button = buttonBox->addButton(QDialogButtonBox::Ok); m_ok_button->setEnabled(false); m_cancel_button = buttonBox->addButton(QDialogButtonBox::Cancel); m_ok_button->setShortcut(Qt::CTRL|Qt::Key_Return); m_cancel_button->setShortcut(Qt::Key_Escape); m_ok_button->setDefault(true); layout->addWidget(description, 0); layout->addWidget(input, 0); layout->addWidget(buttonBox, 0); m_user_combo->setFocus(); connect(m_user_combo, SIGNAL(currentTextChanged(QString)), SLOT(slotTextChanged(QString))); connect(m_user_combo->lineEdit(), SIGNAL(editingFinished()), SLOT(slotHomesUserEntered())); connect(m_clear_button, SIGNAL(clicked()), SLOT(slotClearClicked())); connect(m_ok_button, SIGNAL(clicked()), SLOT(slotOkClicked())); connect(m_cancel_button, SIGNAL(clicked()), SLOT(reject())); } void Smb4KHomesUserDialog::setUserNames(const QStringList &users) { if (!users.isEmpty()) { m_user_combo->addItems(users); m_user_combo->setCurrentItem(""); m_clear_button->setEnabled(true); } - else - { - // Do nothing - } } QStringList Smb4KHomesUserDialog::userNames() { QStringList users; for (int i = 0; i < m_user_combo->count(); ++i) { users << m_user_combo->itemText(i); } if (!users.contains(m_user_combo->currentText())) { users << m_user_combo->currentText(); } - else - { - // Do nothing - } return users; } void Smb4KHomesUserDialog::slotTextChanged(const QString &text) { m_ok_button->setEnabled(!text.isEmpty()); } void Smb4KHomesUserDialog::slotClearClicked() { m_user_combo->clearEditText(); m_user_combo->clear(); m_clear_button->setEnabled(false); } void Smb4KHomesUserDialog::slotOkClicked() { KConfigGroup group(Smb4KSettings::self()->config(), "HomesUserDialog"); KWindowConfig::saveWindowSize(windowHandle(), group); group.writeEntry("HomesUsersCompletion", m_user_combo->completionObject()->items()); accept(); } void Smb4KHomesUserDialog::slotHomesUserEntered() { KCompletion *completion = m_user_combo->completionObject(); if (!m_user_combo->currentText().isEmpty()) { completion->addItem(m_user_combo->currentText()); } - else - { - // Do nothing - } } diff --git a/core/smb4khomesshareshandler_p.h b/core/smb4khomesshareshandler_p.h index 42ba1ae..998a94d 100644 --- a/core/smb4khomesshareshandler_p.h +++ b/core/smb4khomesshareshandler_p.h @@ -1,216 +1,216 @@ /*************************************************************************** Private helpers for the homes shares handler ------------------- begin : Mo Apr 11 2011 - copyright : (C) 2011-2017 by Alexander Reinholdt + copyright : (C) 2011-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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, 51 Franklin Street, Suite 500, Boston, * * MA 02110-1335 USA * ***************************************************************************/ #ifndef SMB4KHOMESSHARESHANDLER_P_H #define SMB4KHOMESSHARESHANDLER_P_H // application specific includes #include "smb4khomesshareshandler.h" #include "smb4kglobal.h" // Qt includes #include #include #include #include // KDE includes #include class Smb4KHomesUsers { public: /** * Constructor */ Smb4KHomesUsers(const SharePtr &share, const QStringList &users); /** * Copy constructor */ Smb4KHomesUsers(const Smb4KHomesUsers &users); /** * Empty constructor */ Smb4KHomesUsers(); /** * Destructor */ ~Smb4KHomesUsers(); /** * Workgroup name */ QString workgroupName() const; /** * Set workgroup name */ void setWorkgroupName(const QString &name); /** * Host name */ QString hostName() const; /** * Set host name */ void setHostName(const QString &name); /** * Share name */ QString shareName() const; /** * Set share name */ void setShareName(const QString &name); /** * IP address */ QString hostIP() const; /** * Set IP address */ void setHostIP(const QString &ip); /** * User list */ QStringList users() const; /** * Set user list */ void setUsers(const QStringList &users); /** * Profile */ QString profile() const; /** * Set profile */ void setProfile(const QString &profile); private: QString m_workgroup_name; QString m_host_name; QString m_share_name; QHostAddress m_host_ip; QStringList m_users; QString m_profile; }; class Smb4KHomesUserDialog : public QDialog { Q_OBJECT public: /** * Constructor */ explicit Smb4KHomesUserDialog(const SharePtr &share, QWidget *parent = 0); /** * Destructor */ ~Smb4KHomesUserDialog(); /** * Set the user names */ void setUserNames(const QStringList &users); /** * Get the user names */ QStringList userNames(); /** * Get the user name to use */ QString login() { return m_user_combo->currentText(); } protected Q_SLOTS: /** * Is connected to the textChanged() signal of the combo box * in the "Specify User" dialog. * * @param text The text in the combo box */ void slotTextChanged(const QString &text); /** * This slot is called if the User1 button, i.e. the "Clear" button * in the "Specify User" dialog has been clicked. It removes all * entries from the combo box. */ void slotClearClicked(); /** * This slot is called when the "OK" button is clicked. */ void slotOkClicked(); /** * This slot is used to add the input text to the completion object * of the input combo box. */ void slotHomesUserEntered(); private: void setupView(); QPushButton *m_clear_button; QPushButton *m_ok_button; QPushButton *m_cancel_button; KComboBox *m_user_combo; SharePtr m_share; }; class Smb4KHomesSharesHandlerPrivate { public: QList homesUsers; }; class Smb4KHomesSharesHandlerStatic { public: Smb4KHomesSharesHandler instance; }; #endif diff --git a/core/smb4khost.cpp b/core/smb4khost.cpp index 90d28f0..9e5a9ac 100644 --- a/core/smb4khost.cpp +++ b/core/smb4khost.cpp @@ -1,238 +1,222 @@ /*************************************************************************** Smb4K's container class for information about a host. ------------------- begin : Sa Jan 26 2008 - copyright : (C) 2008-2017 by Alexander Reinholdt + copyright : (C) 2008-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4khost.h" #include "smb4kauthinfo.h" // Qt includes #include #include #include // KDE includes #include class Smb4KHostPrivate { public: QString workgroup; QHostAddress ip; QString comment; bool isMaster; }; Smb4KHost::Smb4KHost(const QString &name) : Smb4KBasicNetworkItem(Host), d(new Smb4KHostPrivate) { d->isMaster = false; *pIcon = KDE::icon("network-server"); setHostName(name); } Smb4KHost::Smb4KHost(const Smb4KHost &h) : Smb4KBasicNetworkItem(Host), d(new Smb4KHostPrivate) { *d = *h.d; if (pIcon->isNull()) { *pIcon = KDE::icon("network-server"); } - else - { - // Do nothing - } } Smb4KHost::Smb4KHost() : Smb4KBasicNetworkItem(Host), d(new Smb4KHostPrivate) { d->isMaster = false; *pIcon = KDE::icon("network-server"); } Smb4KHost::~Smb4KHost() { } void Smb4KHost::setHostName(const QString &name) { pUrl->setHost(name); pUrl->setScheme("smb"); } QString Smb4KHost::hostName() const { return pUrl->host().toUpper(); } void Smb4KHost::setWorkgroupName(const QString &workgroup) { d->workgroup = workgroup.toUpper(); } QString Smb4KHost::workgroupName() const { return d->workgroup; } void Smb4KHost::setIpAddress(const QString &ip) { d->ip.setAddress(ip); } void Smb4KHost::setIpAddress(const QHostAddress& address) { if (!address.isNull() && address.protocol() != QAbstractSocket::UnknownNetworkLayerProtocol) { d->ip = address; } - else - { - // Do nothing - } } QString Smb4KHost::ipAddress() const { return d->ip.toString(); } bool Smb4KHost::hasIpAddress() const { return !d->ip.isNull(); } void Smb4KHost::setComment(const QString &comment) { d->comment = comment; } QString Smb4KHost::comment() const { return d->comment; } void Smb4KHost::setIsMasterBrowser(bool master) { d->isMaster = master; } bool Smb4KHost::isMasterBrowser() const { return d->isMaster; } void Smb4KHost::setLogin(const QString &login) { pUrl->setUserName(login); } QString Smb4KHost::login() const { return pUrl->userName(); } void Smb4KHost::setPassword(const QString &passwd) { pUrl->setPassword(passwd); } QString Smb4KHost::password() const { return pUrl->password(); } void Smb4KHost::setPort(int port) { pUrl->setPort(port); } int Smb4KHost::port() const { return pUrl->port(); } void Smb4KHost::setAuthInfo(Smb4KAuthInfo *authInfo) { pUrl->setUserName(authInfo->userName()); pUrl->setPassword(authInfo->password()); } void Smb4KHost::update(Smb4KHost* host) { if (QString::compare(workgroupName(), host->workgroupName()) == 0 && QString::compare(hostName(), host->hostName()) == 0) { *pUrl = host->url(); setComment(host->comment()); setIsMasterBrowser(host->isMasterBrowser()); // Do not kill the already discovered IP address if (!hasIpAddress() && host->hasIpAddress()) { setIpAddress(host->ipAddress()); } - else - { - // Do nothing - } - } - else - { - // Do nothing } } diff --git a/core/smb4khost.h b/core/smb4khost.h index 5208522..2d8cfff 100644 --- a/core/smb4khost.h +++ b/core/smb4khost.h @@ -1,235 +1,235 @@ /*************************************************************************** Smb4K's container class for information about a host. ------------------- begin : Sa Jan 26 2008 - copyright : (C) 2008-2017 by Alexander Reinholdt + copyright : (C) 2008-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifndef SMB4KHOST_H #define SMB4KHOST_H // application specific includes #include "smb4kbasicnetworkitem.h" // Qt includes #include #include #include // forward declarations class Smb4KAuthInfo; class Smb4KHostPrivate; /** * This class is a container that carries information about a host found in * the network neighborhood. It is part of the core classes of Smb4K. * * @author Alexander Reinholdt */ class Q_DECL_EXPORT Smb4KHost : public Smb4KBasicNetworkItem { friend class Smb4KHostPrivate; public: /** * The default constructor. It takes the name of the host as only argument. * You have to set all other information with the other functions provided * by this class. * * @param name The name of the host */ explicit Smb4KHost(const QString &name); /** * The copy constructor. This constructor takes a Smb4KHost item as argument * and copies its values. * * @param host The Smb4KHost object that is to be copied. */ Smb4KHost(const Smb4KHost &host); /** * The empty constructor. It does not take any argument and you have to set * all information by the other functions provided by this class. */ Smb4KHost(); /** * The destructor. */ ~Smb4KHost(); /** * Set the name of the host. * * @param name The name of the host */ void setHostName(const QString &name); /** * Returns the name of the host. * * @returns the host's name. */ QString hostName() const; /** * Set the workgroup where this host is located. * * @param workgroup The workgroup name */ void setWorkgroupName(const QString &workgroup); /** * Returns the name of the workgroup where this host is located. * * @returns the workgroup name. */ QString workgroupName() const; /** * Set the IP address of this host. @p ip will only be accepted * if it is compatible with either IPv4 or IPv6. * * @param ip The IP address of this host. */ void setIpAddress(const QString &ip); /** * Set the IP address of this host. @p ip will only be accepted * if it is compatible with either IPv4 or IPv6. * * @param ip The IP address of this host. */ void setIpAddress(const QHostAddress &address); /** * Returns the IP address of the host. If the IP address was not * compatible with IPv4 and IPv6 or if no IP address was supplied, * an empty string is returned. * * @returns the host's IP address or an empty string. */ QString ipAddress() const; /** * Returns TRUE if the host's IP address is set and FALSE otherwise. * * @returns TRUE if the host's IP address is known. */ bool hasIpAddress() const; /** * Set the comment that was defined for the host. * * @param comment The comment string */ void setComment(const QString &comment); /** * Returns the comment that was defined or an empty string if there * was no comment. * * @returns the comment or an empty string. */ QString comment() const; /** * Set this host to be a master browser. * * @param master Set this to TRUE if the host is a master * browser. */ void setIsMasterBrowser(bool master); /** * Returns TRUE if the host is a master browser and FALSE otherwise. * * @returns TRUE if the host is a master browser. */ bool isMasterBrowser() const; /** * Set the port for the use in the URL. * * @param port The port */ void setPort(int port); /** * Returns the port that is used in the URL. * * @returns the port. */ int port() const; /** * Set the authentication information for the host. This function will add * the authentication information to the URL of the host. Any previous * user information including the login will be overwritten. * * @param authInfo The authentication information */ void setAuthInfo(Smb4KAuthInfo *authInfo); /** * Set the login name for the host. * * @param login The login name */ void setLogin(const QString &login); /** * Returns the login name. * * @returns the login name. */ QString login() const; /** * Set the password used for authentication. * * @param passwd The password */ void setPassword(const QString &passwd); /** * Returns the password. * * @returns the password. */ QString password() const; /** * Updates the host item if the workgroup and host name of @p host and * of this item is equal. Otherwise it does nothing. * @param host The share object that is used to update * this object */ void update(Smb4KHost *host); private: const QScopedPointer d; }; #endif diff --git a/core/smb4kmounter.cpp b/core/smb4kmounter.cpp index 1fb1d6e..03a3ac5 100644 --- a/core/smb4kmounter.cpp +++ b/core/smb4kmounter.cpp @@ -1,2925 +1,2470 @@ /*************************************************************************** The core class that mounts the shares. ------------------- begin : Die Jun 10 2003 copyright : (C) 2003-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // Application specific includes #include "smb4kmounter.h" #include "smb4kmounter_p.h" #include "smb4kauthinfo.h" #include "smb4kshare.h" #include "smb4ksettings.h" #include "smb4khomesshareshandler.h" #include "smb4kwalletmanager.h" #include "smb4kprocess.h" #include "smb4knotification.h" #include "smb4kbookmarkhandler.h" #include "smb4kcustomoptionsmanager.h" #include "smb4kcustomoptions.h" #include "smb4kbookmark.h" #include "smb4kprofilemanager.h" #include "smb4khardwareinterface.h" #if defined(Q_OS_LINUX) #include "smb4kmountsettings_linux.h" #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) #include "smb4kmountsettings_bsd.h" #endif // Qt includes #include #include #include #include #include #include #include #include #include // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include #include #include #include #include #include #include #include #include using namespace Smb4KGlobal; #define TIMEOUT 50 Q_GLOBAL_STATIC(Smb4KMounterStatic, p); Smb4KMounter::Smb4KMounter(QObject *parent) : KCompositeJob(parent), d(new Smb4KMounterPrivate) { setAutoDelete(false); d->timerId = -1; d->remountTimeout = 0; d->remountAttempts = 0; d->checkTimeout = 0; d->newlyMounted = 0; d->newlyUnmounted = 0; d->dialog = 0; d->firstImportDone = false; d->mountShares = false; d->unmountShares = false; d->activeProfile = Smb4KProfileManager::self()->activeProfile(); d->detectAllShares = Smb4KMountSettings::detectAllShares(); // Connections connect(Smb4KHardwareInterface::self(), SIGNAL(onlineStateChanged(bool)), this, SLOT(slotOnlineStateChanged(bool))); connect(Smb4KHardwareInterface::self(), SIGNAL(networkShareAdded()), this, SLOT(slotTriggerImport())); connect(Smb4KHardwareInterface::self(), SIGNAL(networkShareRemoved()), this, SLOT(slotTriggerImport())); connect(Smb4KProfileManager::self(), SIGNAL(migratedProfile(QString,QString)), this, SLOT(slotProfileMigrated(QString,QString))); connect(Smb4KProfileManager::self(), SIGNAL(aboutToChangeProfile()), this, SLOT(slotAboutToChangeProfile())); connect(Smb4KProfileManager::self(), SIGNAL(activeProfileChanged(QString)), this, SLOT(slotActiveProfileChanged(QString))); connect(Smb4KMountSettings::self(), SIGNAL(configChanged()), this, SLOT(slotConfigChanged())); connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()),this, SLOT(slotAboutToQuit())); } Smb4KMounter::~Smb4KMounter() { while (!d->importedShares.isEmpty()) { d->importedShares.takeFirst().clear(); } while (!d->retries.isEmpty()) { d->retries.takeFirst().clear(); } } Smb4KMounter *Smb4KMounter::self() { return &p->instance; } void Smb4KMounter::abort() { if (!QCoreApplication::closingDown()) { QListIterator it(subjobs()); while (it.hasNext()) { it.next()->kill(KJob::EmitResult); } } - else - { - // Do nothing - } } bool Smb4KMounter::isRunning() { return hasSubjobs(); } void Smb4KMounter::triggerRemounts(bool fill_list) { if (Smb4KMountSettings::remountShares() /* one-time remounts */ || !Smb4KCustomOptionsManager::self()->sharesToRemount().isEmpty() /* permanent remounts */) { if (fill_list) { // // Get the shares that are to be remounted // QList list = Smb4KCustomOptionsManager::self()->sharesToRemount(); if (!list.isEmpty()) { // // Check which shares actually need to be remounted // for (const OptionsPtr &opt : list) { QList mountedShares = findShareByUrl(opt->url()); if (!mountedShares.isEmpty()) { bool mount = true; for (const SharePtr &s : mountedShares) { if (!s->isForeign()) { mount = false; break; } else { continue; } } if (mount) { SharePtr share = SharePtr(new Smb4KShare()); share->setUrl(opt->url()); share->setWorkgroupName(opt->workgroupName()); share->setHostIpAddress(opt->ipAddress()); if (share->url().isValid() && !share->url().isEmpty()) { d->remounts << share; } - else - { - // Do nothing - } - } - else - { - // Do nothing } } else { SharePtr share = SharePtr(new Smb4KShare()); share->setUrl(opt->url()); share->setWorkgroupName(opt->workgroupName()); share->setHostIpAddress(opt->ipAddress()); if (share->url().isValid() && !share->url().isEmpty()) { d->remounts << share; } - else - { - // Do nothing - } } } } - else - { - // Do nothing - } - } - else - { - // Do nothing } if (!d->remounts.isEmpty()) { mountShares(d->remounts); } - else - { - // Do nothing - } d->remountAttempts++; } - else - { - // Do nothing - } } void Smb4KMounter::import(bool checkInaccessible) { // // Immediately return here if we are still processing imported shares // if (!d->importedShares.isEmpty()) { return; } - else - { - // Do nothing - } // // Get the mountpoints that are present on the system // KMountPoint::List mountPoints = KMountPoint::currentMountPoints(KMountPoint::BasicInfoNeeded|KMountPoint::NeedMountOptions); // Now determine all mountpoints that have the SMBFS or the CIFS // filesystem. for (const QExplicitlySharedDataPointer &mountPoint : mountPoints) { if (QString::compare(mountPoint->mountType(), "cifs") == 0 || QString::compare(mountPoint->mountType(), "smbfs") == 0) { // Create new share and set the mountpoint and the filesystem SharePtr share = SharePtr(new Smb4KShare()); share->setUrl(mountPoint->mountedFrom()); share->setPath(mountPoint->mountPoint()); share->setMounted(true); // Get all mount options for (const QString &option : mountPoint->mountOptions()) { if (option.startsWith(QLatin1String("domain=")) || option.startsWith(QLatin1String("workgroup="))) { share->setWorkgroupName(option.section('=', 1, 1).trimmed()); } else if (option.startsWith(QLatin1String("addr="))) { share->setHostIpAddress(option.section('=', 1, 1).trimmed()); } else if (option.startsWith(QLatin1String("username=")) || option.startsWith(QLatin1String("user="))) { share->setLogin(option.section('=', 1, 1).trimmed()); } - else - { - // Do nothing - } } // Work around empty usernames if (share->login().isEmpty()) { share->setLogin("guest"); } - else - { - // Do nothing - } d->importedShares << share; } - else - { - // Do nothing - } } // // Check which shares were unmounted. Remove all obsolete mountpoints, emit // the unmounted() signal on each of the unmounted shares and remove them // from the global list. // NOTE: The unmount() signal is emitted *BEFORE* the share is removed // from the global list! You need to account for that in your application. // QList unmountedShares; bool found = false; for (const SharePtr &mountedShare : mountedSharesList()) { for (const SharePtr &importedShare : d->importedShares) { // Check the mountpoint, since that one is unique. We will only use // Smb4KShare::path(), so that we do not run into trouble if a share // is inaccessible. if (QString::compare(mountedShare->path(), importedShare->path()) == 0) { found = true; break; } - else - { - // Do nothing - } } if (!found) { // Remove the mountpoint if the share is not a foreign one if (!mountedShare->isForeign()) { QDir dir; dir.cd(mountedShare->canonicalPath()); dir.rmdir(dir.canonicalPath()); if (dir.cdUp()) { dir.rmdir(dir.canonicalPath()); } - else - { - // Do nothing - } - } - else - { - // Do nothing } mountedShare->setMounted(false); unmountedShares << mountedShare; } - else - { - // Do nothing - } found = false; } if (!unmountedShares.isEmpty()) { d->newlyUnmounted += unmountedShares.size(); if (!d->mountShares && !d->unmountShares) { if (d->newlyUnmounted == 1) { // Copy the share SharePtr unmountedShare = unmountedShares.first(); // Remove the share from the global list and notify the program and user removeMountedShare(unmountedShares.first()); emit unmounted(unmountedShare); Smb4KNotification::shareUnmounted(unmountedShare); unmountedShare.clear(); } else { for (const SharePtr &share : unmountedShares) { // Copy the share SharePtr unmountedShare = share; // Remove the share from the global list and notify the program removeMountedShare(share); emit unmounted(unmountedShare); unmountedShare.clear(); } // Notify the user Smb4KNotification::sharesUnmounted(d->newlyUnmounted); } d->newlyUnmounted = 0; } else { for (const SharePtr &share : unmountedShares) { // Copy the share SharePtr unmountedShare = share; // Remove the share from the global list and notify the program removeMountedShare(share); emit unmounted(unmountedShare); unmountedShare.clear(); } } emit mountedSharesListChanged(); } else { d->newlyUnmounted = 0; } // // Now stat the imported shares to get information about them. // Do not use Smb4KShare::canonicalPath() here, otherwise we might // get lock-ups with inaccessible shares. // if (Smb4KHardwareInterface::self()->isOnline()) { QMutableListIterator it(d->importedShares); while (it.hasNext()) { SharePtr share = it.next(); SharePtr mountedShare = findShareByPath(share->path()); if (mountedShare) { if (mountedShare->isInaccessible() && !checkInaccessible) { it.remove(); continue; } - else - { - // Do nothing - } - } - else - { - // Do nothing } QUrl url = QUrl::fromLocalFile(share->path()); KIO::StatJob *job = KIO::stat(url, KIO::HideProgressInfo); job->setDetails(0); connect(job, SIGNAL(result(KJob*)), this, SLOT(slotStatResult(KJob*))); // Do not use addSubJob(), because that would confuse isRunning(), etc. job->start(); } - + + // + // Set d->firstImportDone here only for the case that no mounted shares + // could be found. In all other cases d->firstImportDone will be set in + // slotStatResult(). + // if (!d->firstImportDone && d->importedShares.isEmpty()) { d->firstImportDone = true; } - else - { - // Do nothing. d->firstImportDone will be set in slotStatResult(). - } - } - else - { - // Do nothing } } void Smb4KMounter::mountShare(const SharePtr &share) { Q_ASSERT(share); if (share) { // // Check that the URL is valid // if (!share->url().isValid()) { Smb4KNotification::invalidURLPassed(); return; } - else - { - // Do nothing - } // // Check if the share has already been mounted. If it is already present, // do not process it and return. // QUrl url; if (share->isHomesShare()) { if (!Smb4KHomesSharesHandler::self()->specifyUser(share, true)) { return; } - else - { - // Do nothing - } url = share->homeUrl(); } else { url = share->url(); } QList mountedShares = findShareByUrl(url); bool isMounted = false; for (const SharePtr &s : mountedShares) { if (!s->isForeign()) { isMounted = true; break; } - else - { - // Do nothing - } } if (isMounted) { return; } - else - { - // Do nothing - } // // Wake-On-LAN: Wake up the host before mounting // if (Smb4KSettings::enableWakeOnLAN()) { OptionsPtr options = Smb4KCustomOptionsManager::self()->findOptions(KIO::upUrl(share->url())); if (options && options->wolSendBeforeMount()) { emit aboutToStart(WakeUp); QUdpSocket *socket = new QUdpSocket(this); QHostAddress addr; // Use the host's IP address directly from the share object. if (share->hasHostIpAddress()) { addr.setAddress(share->hostIpAddress()); } else { addr.setAddress("255.255.255.255"); } // Construct magic sequence QByteArray sequence; // 6 times 0xFF for (int j = 0; j < 6; ++j) { sequence.append(QChar(0xFF).toLatin1()); } // 16 times the MAC address QStringList parts = options->macAddress().split(':', QString::SkipEmptyParts); for (int j = 0; j < 16; ++j) { for (int k = 0; k < parts.size(); ++k) { sequence.append(QChar(QString("0x%1").arg(parts.at(k)).toInt(0, 16)).toLatin1()); } } socket->writeDatagram(sequence, addr, 9); delete socket; // Wait the defined time int stop = 1000 * Smb4KSettings::wakeOnLANWaitingTime() / 250; int i = 0; while (i++ < stop) { QTest::qWait(250); } emit finished(WakeUp); } - else - { - // Do nothing - } - } - else - { - // Do nothing } - + // // Create the mountpoint // QString mountpoint; mountpoint += Smb4KMountSettings::mountPrefix().path(); mountpoint += QDir::separator(); mountpoint += (Smb4KMountSettings::forceLowerCaseSubdirs() ? share->hostName().toLower() : share->hostName()); mountpoint += QDir::separator(); if (!share->isHomesShare()) { mountpoint += (Smb4KMountSettings::forceLowerCaseSubdirs() ? share->shareName().toLower() : share->shareName()); } else { mountpoint += (Smb4KMountSettings::forceLowerCaseSubdirs() ? share->login().toLower() : share->login()); } // Get the permissions that should be used for creating the // mount prefix and all its subdirectories. // Please note that the actual permissions of the mount points // are determined by the mount utility. QFile::Permissions permissions; QUrl parentDirectory; if (QFile::exists(Smb4KMountSettings::mountPrefix().path())) { parentDirectory = Smb4KMountSettings::mountPrefix(); } else { QUrl u = Smb4KMountSettings::mountPrefix(); parentDirectory = KIO::upUrl(u); } QFile f(parentDirectory.path()); permissions = f.permissions(); QDir dir(mountpoint); if (!dir.mkpath(dir.path())) { share->setPath(""); Smb4KNotification::mkdirFailed(dir); return; } else { QUrl u = QUrl::fromLocalFile(dir.path()); while (!parentDirectory.matches(u, QUrl::StripTrailingSlash)) { QFile(u.path()).setPermissions(permissions); u = KIO::upUrl(u); } } share->setPath(QDir::cleanPath(mountpoint)); // // Get the authentication information // Smb4KWalletManager::self()->readAuthInfo(share); // // Mount arguments // QVariantMap args; if (!fillMountActionArgs(share, args)) { return; } - else - { - // Do nothing - } // // Emit the aboutToStart() signal // emit aboutToStart(MountShare); // // Create the mount action // KAuth::Action mountAction("org.kde.smb4k.mounthelper.mount"); mountAction.setHelperId("org.kde.smb4k.mounthelper"); mountAction.setArguments(args); KAuth::ExecuteJob *job = mountAction.execute(); // // Modify the cursor, if necessary. // if (!hasSubjobs() && modifyCursor()) { QApplication::setOverrideCursor(Qt::BusyCursor); } - else - { - // Do nothing - } // // Add the job // addSubjob(job); // // Start the job and process the returned result. // bool success = job->exec(); if (success) { int errorCode = job->error(); if (errorCode == 0) { // Get the error message QString errorMsg = job->data()["mh_error_message"].toString(); if (!errorMsg.isEmpty()) { #if defined(Q_OS_LINUX) if (errorMsg.contains("mount error 13") || errorMsg.contains("mount error(13)") /* authentication error */) { if (Smb4KWalletManager::self()->showPasswordDialog(share)) { d->retries << share; } - else - { - // Do nothing - } } else if (errorMsg.contains("Unable to find suitable address.")) { // Swallow this } else { Smb4KNotification::mountingFailed(share, errorMsg); } #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) if (errorMsg.contains("Authentication error") || errorMsg.contains("Permission denied")) { if (Smb4KWalletManager::self()->showPasswordDialog(share)) { d->retries << share; } - else - { - // Do nothing - } } else { Smb4KNotification::mountingFailed(share, errorMsg); } #else qWarning() << "Smb4KMounter::slotMountJobFinished(): Error handling not implemented!"; Smb4KNotification::mountingFailed(share.data(), errorMsg); #endif } - else - { - // Do nothing - } } else { Smb4KNotification::actionFailed(errorCode); } } else { // FIXME: Report that the action could not be started - // Do nothing } // // Remove the job from the job list // removeSubjob(job); // // Reset the busy cursor // if (!hasSubjobs() && modifyCursor()) { QApplication::restoreOverrideCursor(); } - else - { - // Do nothing - } - + // // Emit the finished() signal // emit finished(MountShare); } - else - { - // Do nothing - } } void Smb4KMounter::mountShares(const QList &shares) { d->mountShares = true; for (const SharePtr &share : shares) { mountShare(share); } d->mountShares = false; } void Smb4KMounter::unmountShare(const SharePtr &share, bool silent) { Q_ASSERT(share); if (share) { // // Check that the URL is valid. // if (!share->url().isValid()) { Smb4KNotification::invalidURLPassed(); return; } - else - { - // Do nothing - } // // Handle foreign shares according to the settings // if (share->isForeign()) { if (!Smb4KMountSettings::unmountForeignShares()) { if (!silent) { Smb4KNotification::unmountingNotAllowed(share); } - else - { - // Do nothing - } + return; } else { if (!silent) { if (KMessageBox::warningYesNo(QApplication::activeWindow(), i18n("

The share %1 is mounted to
%2 and owned by user %3.

" "

Do you really want to unmount it?

", share->displayString(), share->path(), share->user().loginName()), i18n("Foreign Share")) == KMessageBox::No) { return; } - else - { - // Do nothing - } } else { // Without the confirmation of the user, we are not // unmounting a foreign share! return; } } } - else - { - // Do nothing - } // // Force the unmounting of the share either if the system went offline // or if the user chose to forcibly unmount inaccessible shares (Linux only). // bool force = false; if (Smb4KHardwareInterface::self()->isOnline()) { #if defined(Q_OS_LINUX) if (share->isInaccessible()) { force = Smb4KMountSettings::forceUnmountInaccessible(); } - else - { - // Do nothing - } #endif } else { force = true; } // // Unmount arguments // QVariantMap args; if (!fillUnmountActionArgs(share, force, silent, args)) { return; } - else - { - // Do nothing - } // // Emit the aboutToStart() signal // emit aboutToStart(UnmountShare); // // Create the unmount action // KAuth::Action unmountAction("org.kde.smb4k.mounthelper.unmount"); unmountAction.setHelperId("org.kde.smb4k.mounthelper"); unmountAction.setArguments(args); KAuth::ExecuteJob *job = unmountAction.execute(); // // Modify the cursor, if necessary. // if (!hasSubjobs() && modifyCursor()) { QApplication::setOverrideCursor(Qt::BusyCursor); } - else - { - // Do nothing - } // // Add the job // addSubjob(job); // // Start the job and process the returned result. // bool success = job->exec(); if (success) { int errorCode = job->error(); if (errorCode == 0) { // Get the error message QString errorMsg = job->data()["mh_error_message"].toString(); if (!errorMsg.isEmpty()) { // No error handling needed, just report the error message. Smb4KNotification::unmountingFailed(share, errorMsg); } - else - { - // Do nothing - } } else { Smb4KNotification::actionFailed(errorCode); } } else { // FIXME: Report that the action could not be started - // Do nothing } // // Remove the job from the job list // removeSubjob(job); // // Reset the busy cursor // if (!hasSubjobs() && modifyCursor()) { QApplication::restoreOverrideCursor(); } - else - { - // Do nothing - } // // Emit the finished() signal // emit finished(UnmountShare); } - else - { - // Do nothing - } } void Smb4KMounter::unmountShares(const QList &shares, bool silent) { #if defined(Q_OS_LINUX) // // Under Linux, we have to take an approach that is a bit awkward in this function. // Since the import function is invoked via Smb4KHardwareInterface::networkShareRemoved() // before mountShare() returns, no unmount of multiple shares will ever be reported // when d->unmountShares is set to FALSE *after* the loop ended. To make the reporting // work correctly, we need to set d->unmountShares to FALSE before the last unmount // is started. // d->unmountShares = true; int number = shares.size(); for (const SharePtr &share : shares) { number--; d->unmountShares = (number != 0); unmountShare(share, silent); } #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) // // Since under FreeBSD the emission of Smb4KHardwareInterface::networkShareRemoved() is // triggered by a timer, we can use a nice approach here. // d->unmountShares = true; for (const SharePtr &share : shares) { unmountShare(share, silent); } d->unmountShares = false; #endif } void Smb4KMounter::unmountAllShares(bool silent) { unmountShares(mountedSharesList(), silent); } void Smb4KMounter::openMountDialog() { if (!d->dialog) { SharePtr share = SharePtr(new Smb4KShare()); d->dialog = new Smb4KMountDialog(share, QApplication::activeWindow()); if (d->dialog->exec() == QDialog::Accepted && d->dialog->validUserInput()) { // Pass the share to mountShare(). mountShare(share); // Bookmark the share if the user wants this. if (d->dialog->bookmarkShare()) { Smb4KBookmarkHandler::self()->addBookmark(share); } - else - { - // Do nothing - } - } - else - { - // Do nothing } delete d->dialog; d->dialog = 0; share.clear(); } - else - { - // Do nothing - } } void Smb4KMounter::start() { // // Check the network configurations // Smb4KHardwareInterface::self()->updateNetworkConfig(); // // Connect to Smb4KHardwareInterface to be able to get the response // connect(Smb4KHardwareInterface::self(), SIGNAL(networkConfigUpdated()), this, SLOT(slotStartJobs())); } void Smb4KMounter::saveSharesForRemount() { // // Save the shares for remount // for (const SharePtr &share : mountedSharesList()) { if (!share->isForeign()) { Smb4KCustomOptionsManager::self()->addRemount(share, false); } else { Smb4KCustomOptionsManager::self()->removeRemount(share, false); } } // // Also save each failed remount and remove it from the list // while (!d->remounts.isEmpty()) { SharePtr share = d->remounts.takeFirst(); Smb4KCustomOptionsManager::self()->addRemount(share, false); share.clear(); } } void Smb4KMounter::timerEvent(QTimerEvent *) { // Try to remount those shares that could not be mounted // before. Do this only if there are no subjobs, because we // do not want to get crashes because a share was invalidated // during processing the shares. if ((Smb4KMountSettings::remountShares() || !Smb4KCustomOptionsManager::self()->sharesToRemount().isEmpty()) && Smb4KMountSettings::remountAttempts() > d->remountAttempts) { if (d->firstImportDone && !isRunning()) { if (d->remountAttempts == 0) { triggerRemounts(true); } else if (!d->remounts.isEmpty() && d->remountTimeout >= (60000 * Smb4KMountSettings::remountInterval())) { triggerRemounts(false); d->remountTimeout = -TIMEOUT; } - else - { - // Do nothing - } - } - else - { - // Do nothing } d->remountTimeout += TIMEOUT; } - else - { - // Do nothing - } // Retry mounting those shares that failed. This is also only // done when there are no subjobs. if (!d->retries.isEmpty() && !hasSubjobs()) { mountShares(d->retries); while (!d->retries.isEmpty()) { d->retries.takeFirst().clear(); } } - else - { - // Do nothing - } // // Check the size, accessibility, etc. of the shares // // FIXME: Hopefully we can replace this with a recursive QFileSystemWatcher // approach in the future. However, using the existing QFileSystemWatcher // and a QDirIterator to add all the subdirectories of a share to the watcher // seems to be too resource consuming... // if (d->checkTimeout >= 2500 && !isRunning() && d->importedShares.isEmpty()) { for (const SharePtr &share : mountedSharesList()) { check(share); emit updated(share); } d->checkTimeout = 0; } else { d->checkTimeout += TIMEOUT; } } #if defined(Q_OS_LINUX) // // Linux arguments // bool Smb4KMounter::fillMountActionArgs(const SharePtr &share, QVariantMap& map) { // // Find the mount executable // const QString mount = findMountExecutable(); if (!mount.isEmpty()) { map.insert("mh_command", mount); } else { Smb4KNotification::commandNotFound("mount.cifs"); return false; } // // Global and custom options // QMap globalOptions = globalSambaOptions(); OptionsPtr options = Smb4KCustomOptionsManager::self()->findOptions(share); // // Pass the remote file system port to the URL // if (options) { if (options->useFileSystemPort()) { share->setPort(options->fileSystemPort()); } - else - { - // Do nothing - } } else { if (Smb4KMountSettings::useRemoteFileSystemPort()) { share->setPort(Smb4KMountSettings::remoteFileSystemPort()); } - else - { - // Do nothing - } } // // List of arguments passed via "-o ..." to the mount command // QStringList argumentsList; // // Workgroup or domain // if (!share->workgroupName().trimmed().isEmpty()) { argumentsList << QString("domain=%1").arg(KShell::quoteArg(share->workgroupName())); } - else - { - // Do nothing - } // // Host IP address // if (share->hasHostIpAddress()) { argumentsList << QString("ip=%1").arg(share->hostIpAddress()); } - else - { - // Do nothing - } // // User name (login) // if (!share->login().isEmpty()) { argumentsList << QString("username=%1").arg(share->login()); } else { argumentsList << "guest"; } // // Client's and server's NetBIOS name // // According to the manual page, this is only needed when port 139 // is used. So, we only pass the NetBIOS name in that case. // if (options) { if (options->useFileSystemPort() && options->fileSystemPort() == 139) { // The client's NetBIOS name if (!Smb4KSettings::netBIOSName().isEmpty()) { argumentsList << QString("netbiosname=%1").arg(KShell::quoteArg(Smb4KSettings::netBIOSName())); } else if (!globalOptions["netbios name"].isEmpty()) { argumentsList << QString("netbiosname=%1").arg(KShell::quoteArg(globalOptions["netbios name"])); } - else - { - // Do nothing - } // The server's NetBIOS name argumentsList << QString("servernetbiosname=%1").arg(KShell::quoteArg(share->hostName())); } - else - { - // Do nothing - } } else { if (Smb4KMountSettings::useRemoteFileSystemPort() && Smb4KMountSettings::remoteFileSystemPort() == 139) { // The client's NetBIOS name if (!Smb4KSettings::netBIOSName().isEmpty()) { argumentsList << QString("netbiosname=%1").arg(KShell::quoteArg(Smb4KSettings::netBIOSName())); } else if (!globalOptions["netbios name"].isEmpty()) { argumentsList << QString("netbiosname=%1").arg(KShell::quoteArg(globalOptions["netbios name"])); } - else - { - // Do nothing - } // The server's NetBIOS name argumentsList << QString("servernetbiosname=%1").arg(KShell::quoteArg(share->hostName())); } - else - { - // Do nothing - } } // // CIFS Unix extensions support // // This sets the uid, gid, file_mode and dir_mode arguments, if necessary. // if (options) { if (!options->cifsUnixExtensionsSupport()) { // User id if (options->useUser()) { argumentsList << QString("uid=%1").arg(options->user().userId().nativeId()); } - else - { - // Do nothing - } // Group id if (options->useGroup()) { argumentsList << QString("gid=%1").arg(options->group().groupId().nativeId()); } - else - { - // Do nothing - } // File mode if (options->useFileMode()) { argumentsList << QString("file_mode=%1").arg(options->fileMode()); } - else - { - // Do nothing - } // Directory mode if (options->useDirectoryMode()) { argumentsList << QString("dir_mode=%1").arg(options->directoryMode()); } - else - { - // Do nothing - } - } - else - { - // Do nothing } } else { if (!Smb4KMountSettings::cifsUnixExtensionsSupport()) { // User id if (Smb4KMountSettings::useUserId()) { argumentsList << QString("uid=%1").arg((K_UID)Smb4KMountSettings::userId().toInt()); } - else - { - // Do nothing - } // Group id if (Smb4KMountSettings::useGroupId()) { argumentsList << QString("gid=%1").arg((K_GID)Smb4KMountSettings::groupId().toInt()); } - else - { - // Do nothing - } // File mode if (Smb4KMountSettings::useFileMode()) { argumentsList << QString("file_mode=%1").arg(Smb4KMountSettings::fileMode()); } - else - { - // Do nothing - } // Directory mode if (Smb4KMountSettings::useDirectoryMode()) { argumentsList << QString("dir_mode=%1").arg(Smb4KMountSettings::directoryMode()); } - else - { - // Do nothing - } - } - else - { - // Do nothing } } // // Force user id // // FIXME: The manual page is not clear about this: Is this option only useful when the uid=... // argument is given? If so, this should be moved into the 'User id' code block above. // if (Smb4KMountSettings::forceUID()) { argumentsList << "forceuid"; } - else - { - // Do nothing - } // // Force group id // // FIXME: The manual page is not clear about this: Is this option only useful when the gid=... // argument is given? If so, this should be moved into the 'Group id' code block above. // if (Smb4KMountSettings::forceGID()) { argumentsList << "forcegid"; } - else - { - // Do nothing - } // // Client character set // if (Smb4KMountSettings::useClientCharset()) { switch (Smb4KMountSettings::clientCharset()) { case Smb4KMountSettings::EnumClientCharset::default_charset: { if (!globalOptions["unix charset"].isEmpty()) { argumentsList << QString("iocharset=%1").arg(globalOptions["unix charset"].toLower()); } - else - { - // Do nothing - } + break; } default: { argumentsList << QString("iocharset=%1").arg(Smb4KMountSettings::self()->clientCharsetItem()->choices().value(Smb4KMountSettings::clientCharset()).label); break; } } } - else - { - // Do nothing - } // // File system port // if (options) { if (options->useFileSystemPort()) { argumentsList << QString("port=%1").arg(options->fileSystemPort()); } - else - { - // Do nothing - } } else { if (Smb4KMountSettings::useRemoteFileSystemPort()) { argumentsList << QString("port=%1").arg(Smb4KMountSettings::remoteFileSystemPort()); } - else - { - // Do nothing - } } // // Write access // if (options) { if (options->useWriteAccess()) { switch (options->writeAccess()) { case Smb4KMountSettings::EnumWriteAccess::ReadWrite: { argumentsList << "rw"; break; } case Smb4KMountSettings::EnumWriteAccess::ReadOnly: { argumentsList << "ro"; break; } default: { break; } } } - else - { - // Do nothing - } } else { if (Smb4KMountSettings::useWriteAccess()) { switch (Smb4KMountSettings::writeAccess()) { case Smb4KMountSettings::EnumWriteAccess::ReadWrite: { argumentsList << "rw"; break; } case Smb4KMountSettings::EnumWriteAccess::ReadOnly: { argumentsList << "ro"; break; } default: { break; } } } - else - { - // Do nothing - } } // // Permission checks // if (Smb4KMountSettings::permissionChecks()) { argumentsList << "perm"; } else { argumentsList << "noperm"; } // // Client controls ids // if (Smb4KMountSettings::clientControlsIDs()) { argumentsList << "setuids"; } else { argumentsList << "nosetuids"; } // // Server inode numbers // if (Smb4KMountSettings::serverInodeNumbers()) { argumentsList << "serverino"; } else { argumentsList << "noserverino"; } // // Cache mode // if (Smb4KMountSettings::useCacheMode()) { switch (Smb4KMountSettings::cacheMode()) { case Smb4KMountSettings::EnumCacheMode::None: { argumentsList << "cache=none"; break; } case Smb4KMountSettings::EnumCacheMode::Strict: { argumentsList << "cache=strict"; break; } case Smb4KMountSettings::EnumCacheMode::Loose: { argumentsList << "cache=loose"; break; } default: { break; } } } - else - { - // Do nothing - } // // Translate reserved characters // if (Smb4KMountSettings::translateReservedChars()) { argumentsList << "mapchars"; } else { argumentsList << "nomapchars"; } // // Locking // if (Smb4KMountSettings::noLocking()) { argumentsList << "nolock"; } - else - { - // Do nothing - } // // Security mode // if (options) { if (options->useSecurityMode()) { switch (options->securityMode()) { case Smb4KMountSettings::EnumSecurityMode::None: { argumentsList << "sec=none"; break; } case Smb4KMountSettings::EnumSecurityMode::Krb5: { argumentsList << "sec=krb5"; argumentsList << QString("cruid=%1").arg(KUser(KUser::UseRealUserID).userId().nativeId()); break; } case Smb4KMountSettings::EnumSecurityMode::Krb5i: { argumentsList << "sec=krb5i"; argumentsList << QString("cruid=%1").arg(KUser(KUser::UseRealUserID).userId().nativeId()); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlm: { argumentsList << "sec=ntlm"; break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmi: { argumentsList << "sec=ntlmi"; break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmv2: { argumentsList << "sec=ntlmv2"; break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmv2i: { argumentsList << "sec=ntlmv2i"; break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmssp: { argumentsList << "sec=ntlmssp"; break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmsspi: { argumentsList << "sec=ntlmsspi"; break; } default: { // Smb4KSettings::EnumSecurityMode::Default, break; } } } - else - { - // Do nothing - } } else { if (Smb4KMountSettings::useSecurityMode()) { switch (Smb4KMountSettings::securityMode()) { case Smb4KMountSettings::EnumSecurityMode::None: { argumentsList << "sec=none"; break; } case Smb4KMountSettings::EnumSecurityMode::Krb5: { argumentsList << "sec=krb5"; argumentsList << QString("cruid=%1").arg(KUser(KUser::UseRealUserID).userId().nativeId()); break; } case Smb4KMountSettings::EnumSecurityMode::Krb5i: { argumentsList << "sec=krb5i"; argumentsList << QString("cruid=%1").arg(KUser(KUser::UseRealUserID).userId().nativeId()); break; } case Smb4KMountSettings::EnumSecurityMode::Ntlm: { argumentsList << "sec=ntlm"; break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmi: { argumentsList << "sec=ntlmi"; break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmv2: { argumentsList << "sec=ntlmv2"; break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmv2i: { argumentsList << "sec=ntlmv2i"; break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmssp: { argumentsList << "sec=ntlmssp"; break; } case Smb4KMountSettings::EnumSecurityMode::Ntlmsspi: { argumentsList << "sec=ntlmsspi"; break; } default: { // Smb4KSettings::EnumSecurityMode::Default, break; } } } - else - { - // Do nothing - } } // // SMB protocol version // if (Smb4KMountSettings::useSmbProtocolVersion()) { switch (Smb4KMountSettings::smbProtocolVersion()) { case Smb4KMountSettings::EnumSmbProtocolVersion::OnePointZero: { argumentsList << "vers=1.0"; break; } case Smb4KMountSettings::EnumSmbProtocolVersion::TwoPointZero: { argumentsList << "vers=2.0"; break; } case Smb4KMountSettings::EnumSmbProtocolVersion::TwoPointOne: { argumentsList << "vers=2.1"; break; } case Smb4KMountSettings::EnumSmbProtocolVersion::ThreePointZero: { argumentsList << "vers=3.0"; break; } case Smb4KMountSettings::EnumSmbProtocolVersion::ThreePointOnePointOne: { argumentsList << "vers=3.1.1"; break; } default: { break; } } } - else - { - // Do nothing - } // // Mount options provided by the user // if (!Smb4KMountSettings::customCIFSOptions().isEmpty()) { // SECURITY: Only pass those arguments to mount.cifs that do not pose // a potential security risk and that have not already been defined. // // This is, among others, the proper fix to the security issue reported // by Heiner Markert (aka CVE-2014-2581). QStringList whitelist = whitelistedMountArguments(); QStringList list = Smb4KMountSettings::customCIFSOptions().split(',', QString::SkipEmptyParts); QMutableStringListIterator it(list); while (it.hasNext()) { QString arg = it.next().section("=", 0, 0); if (!whitelist.contains(arg)) { it.remove(); } - else - { - // Do nothing - } argumentsList += list; } } - else - { - // Do nothing - } // // Insert the mount options into the map // QStringList mh_options; mh_options << "-o"; mh_options << argumentsList.join(","); map.insert("mh_options", mh_options); // // Insert the mountpoint into the map // map.insert("mh_mountpoint", share->canonicalPath()); // // Insert information about the share and its URL into the map // if (!share->isHomesShare()) { map.insert("mh_url", share->url()); } else { map.insert("mh_url", share->homeUrl()); map.insert("mh_homes_url", share->url()); } map.insert("mh_workgroup", share->workgroupName()); map.insert("mh_ip", share->hostIpAddress()); // // Location of the Kerberos ticket // // The path to the Kerberos ticket is stored - if it exists - in the // KRB5CCNAME environment variable. By default, the ticket is located // at /tmp/krb5cc_[uid]. So, if the environment variable does not exist, // but the cache file is there, try to use it. // if (QProcessEnvironment::systemEnvironment().contains("KRB5CCNAME")) { map.insert("mh_krb5ticket", QProcessEnvironment::systemEnvironment().value("KRB5CCNAME", "")); } else { QString ticket = QString("/tmp/krb5cc_%1").arg(KUser(KUser::UseRealUserID).userId().nativeId()); if (QFile::exists(ticket)) { map.insert("mh_krb5ticket", "FILE:"+ticket); } - else - { - // Do nothing - } } return true; } #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) // // FreeBSD and NetBSD arguments // bool Smb4KMounter::fillMountActionArgs(const SharePtr &share, QVariantMap& map) { // // Find the mount executable // const QString mount = findMountExecutable(); if (!mount.isEmpty()) { map.insert("mh_command", mount); } else { Smb4KNotification::commandNotFound("mount_smbfs"); return false; } // // Global and custom options // QMap globalOptions = globalSambaOptions(); OptionsPtr options = Smb4KCustomOptionsManager::self()->findOptions(share); // // List of arguments // QStringList argumentsList; // // Workgroup // if (!share->workgroupName().isEmpty()) { argumentsList << "-W"; argumentsList << KShell::quoteArg(share->workgroupName()); } - else - { - // Do nothing - } // // IP address // if (!share->hostIpAddress().isEmpty()) { argumentsList << "-I"; argumentsList << share->hostIpAddress(); } - else - { - // Do nothing - } - + // // User Id // if (options) { if (options->useUser()) { argumentsList << "-u"; argumentsList << QString("%1").arg(options->user().userId().nativeId()); } - else - { - // Do nothing - } } else { if (Smb4KMountSettings::useUserId()) { argumentsList << "-u"; argumentsList << QString("%1").arg((K_UID)Smb4KMountSettings::userId().toInt()); } - else - { - // Do nothing - } } // // Group Id // if (options) { if (options->useGroup()) { argumentsList << "-g"; argumentsList << QString("%1").arg(options->group().groupId().nativeId()); } - else - { - // Do nothing - } } else { if (Smb4KMountSettings::useGroupId()) { argumentsList << "-g"; argumentsList << QString("%1").arg((K_GID)Smb4KMountSettings::groupId().toInt()); } - else - { - // Do nothing - } } if (Smb4KMountSettings::useCharacterSets()) { // Client character set QString clientCharset, serverCharset; switch (Smb4KMountSettings::clientCharset()) { case Smb4KMountSettings::EnumClientCharset::default_charset: { clientCharset = globalOptions["unix charset"].toLower(); // maybe empty break; } default: { clientCharset = Smb4KMountSettings::self()->clientCharsetItem()->choices().value(Smb4KMountSettings::clientCharset()).label; break; } } // Server character set switch (Smb4KMountSettings::serverCodepage()) { case Smb4KMountSettings::EnumServerCodepage::default_codepage: { serverCharset = globalOptions["dos charset"].toLower(); // maybe empty break; } default: { serverCharset = Smb4KMountSettings::self()->serverCodepageItem()->choices().value(Smb4KMountSettings::serverCodepage()).label; break; } } if (!clientCharset.isEmpty() && !serverCharset.isEmpty()) { argumentsList << "-E"; argumentsList << QString("%1:%2").arg(clientCharset, serverCharset); } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // File mode // if (options) { if (options->useFileMode()) { argumentsList << "-f"; argumentsList << options->fileMode(); } - else - { - // Do nothing - } } else { if (Smb4KMountSettings::useFileMode()) { argumentsList << "-f"; argumentsList << Smb4KMountSettings::fileMode(); } - else - { - // Do nothing - } } // // Directory mode // if (options) { if (options->useDirectoryMode()) { argumentsList << "-d"; argumentsList << options->directoryMode(); } - else - { - // Do nothing - } } else { if (Smb4KMountSettings::useDirectoryMode()) { argumentsList << "-d"; argumentsList << Smb4KMountSettings::directoryMode(); } - else - { - // Do nothing - } } // // User name (login) // if (!share->login().isEmpty()) { argumentsList << "-U"; argumentsList << share->login(); } else { argumentsList << "-N"; } // // Insert the mount options into the map // map.insert("mh_options", argumentsList); // // Insert the mountpoint into the map // map.insert("mh_mountpoint", share->canonicalPath()); // // Insert information about the share and its URL into the map // if (!share->isHomesShare()) { map.insert("mh_url", share->url()); } else { map.insert("mh_url", share->homeUrl()); map.insert("mh_homes_url", share->url()); } map.insert("mh_workgroup", share->workgroupName()); map.insert("mh_ip", share->hostIpAddress()); return true; } #else // // Dummy // bool Smb4KMounter::fillMountActionArgs(const SharePtr &, QVariantMap&) { qWarning() << "Smb4KMounter::fillMountActionArgs() is not implemented!"; qWarning() << "Mounting under this operating system is not supported..."; return false; } #endif #if defined(Q_OS_LINUX) // // Linux arguments // bool Smb4KMounter::fillUnmountActionArgs(const SharePtr &share, bool force, bool silent, QVariantMap &map) { // // The umount program // const QString umount = findUmountExecutable(); if (umount.isEmpty() && !silent) { Smb4KNotification::commandNotFound("umount"); return false; } - else - { - // Do nothing - } // // The options // QStringList options; if (force) { options << "-l"; // lazy unmount } - else - { - // Do nothing - } // // Insert data into the map // map.insert("mh_command", umount); map.insert("mh_url", share->url()); if (Smb4KHardwareInterface::self()->isOnline()) { map.insert("mh_mountpoint", share->canonicalPath()); } else { map.insert("mh_mountpoint", share->path()); } map.insert("mh_options", options); return true; } #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) // // FreeBSD and NetBSD arguments // bool Smb4KMounter::fillUnmountActionArgs(const SharePtr &share, bool force, bool silent, QVariantMap &map) { // // The umount program // const QString umount = findUmountExecutable(); if (umount.isEmpty() && !silent) { Smb4KNotification::commandNotFound("umount"); return false; } - else - { - // Do nothing - } // // The options // QStringList options; if (force) { options << "-f"; } - else - { - // Do nothing - } // // Insert data into the map // map.insert("mh_command", umount); map.insert("mh_url", share->url()); if (Smb4KHardwareInterface::self()->isOnline()) { map.insert("mh_mountpoint", share->canonicalPath()); } else { map.insert("mh_mountpoint", share->path()); } map.insert("mh_options", options); return true; } #else // // Dummy // bool Smb4KMounter::fillUnmountActionArgs(const SharePtr &, bool, bool, QVariantMap &) { qWarning() << "Smb4KMounter::fillUnmountActionArgs() is not implemented!"; qWarning() << "Unmounting under this operating system is not supported..."; return false; } #endif void Smb4KMounter::check(const SharePtr &share) { // Get the info about the usage, etc. KDiskFreeSpaceInfo spaceInfo = KDiskFreeSpaceInfo::freeSpaceInfo(share->path()); if (spaceInfo.isValid()) { // Accessibility share->setInaccessible(false); // Size information share->setFreeDiskSpace(spaceInfo.available()); share->setTotalDiskSpace(spaceInfo.size()); share->setUsedDiskSpace(spaceInfo.used()); // Get the owner an group, if possible. QFileInfo fileInfo(share->path()); fileInfo.setCaching(false); if (fileInfo.exists()) { share->setUser(KUser(static_cast(fileInfo.ownerId()))); share->setGroup(KUserGroup(static_cast(fileInfo.groupId()))); share->setInaccessible(!(fileInfo.isDir() && fileInfo.isExecutable())); } else { share->setInaccessible(true); share->setFreeDiskSpace(0); share->setTotalDiskSpace(0); share->setUsedDiskSpace(0); share->setUser(KUser(KUser::UseRealUserID)); share->setGroup(KUserGroup(KUser::UseRealUserID)); } } else { share->setInaccessible(true); share->setFreeDiskSpace(0); share->setTotalDiskSpace(0); share->setUsedDiskSpace(0); share->setUser(KUser(KUser::UseRealUserID)); share->setGroup(KUserGroup(KUser::UseRealUserID)); } } ///////////////////////////////////////////////////////////////////////////// // SLOT IMPLEMENTATIONS ///////////////////////////////////////////////////////////////////////////// void Smb4KMounter::slotStartJobs() { // // Disconnect from Smb4KHardwareInterface. // disconnect(Smb4KHardwareInterface::self(), SIGNAL(networkConfigUpdated()), this, SLOT(slotStartJobs())); // // Start the import of shares // if (Smb4KHardwareInterface::self()->isOnline()) { // // Import the mounted shares // if (!d->firstImportDone) { import(true); } - else - { - // Do nothing - } - + // // Start the timer // if (d->timerId == -1) { d->timerId = startTimer(TIMEOUT); } - else - { - // Do nothing - } - } - else - { - // Do nothing } } void Smb4KMounter::slotAboutToQuit() { // // Abort any actions // abort(); // // Check if the user wants to remount shares and save the // shares for remount if so. // if (Smb4KMountSettings::remountShares()) { saveSharesForRemount(); } - else - { - // Do nothing - } // // Unmount the shares if the user chose to do so. // if (Smb4KMountSettings::unmountSharesOnExit()) { unmountAllShares(true); } - else - { - // Do nothing - } // // Clean up the mount prefix. // KMountPoint::List mountPoints = KMountPoint::currentMountPoints(KMountPoint::BasicInfoNeeded|KMountPoint::NeedMountOptions); QDir dir; dir.cd(Smb4KMountSettings::mountPrefix().path()); QStringList hostDirs = dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot, QDir::NoSort); QStringList mountpoints; for (const QString &hostDir : hostDirs) { dir.cd(hostDir); QStringList shareDirs = dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot, QDir::NoSort); for (const QString &shareDir : shareDirs) { dir.cd(shareDir); mountpoints << dir.absolutePath(); dir.cdUp(); } dir.cdUp(); } // Remove those mountpoints where a share is actually mounted. for (const QExplicitlySharedDataPointer &mountPoint : mountPoints) { mountpoints.removeOne(mountPoint->mountPoint()); } // Remove the empty mountpoints. for (const QString &mp : mountpoints) { dir.cd(mp); dir.rmdir(dir.canonicalPath()); if (dir.cdUp()) { dir.rmdir(dir.canonicalPath()); } - else - { - // Do nothing - } } } void Smb4KMounter::slotOnlineStateChanged(bool online) { if (online) { // Remount shares after the network became available (again) // If the computer awakes from a sleep state, there might still be // an unmount job in the queue. So, wait until all jobs have been // performed before starting to remount the shares. while (isRunning()) { QTest::qWait(TIMEOUT); } triggerRemounts(true); } else { // Abort all running mount jobs abort(); // Mark all mounted shares as inaccessible for (const SharePtr &share : mountedSharesList()) { share->setInaccessible(true); } // Save the shares for automatic remounting saveSharesForRemount(); // Unmount all shares unmountAllShares(true); } } void Smb4KMounter::slotStatResult(KJob *job) { Q_ASSERT(job); // // Stat job // KIO::StatJob *statJob = static_cast(job); // // Get the mountpoint // QString mountpoint = statJob->url().toDisplayString(QUrl::PreferLocalFile); // // Find the imported share // SharePtr importedShare; for (int i = 0; i < d->importedShares.size(); ++i) { if (QString::compare(d->importedShares.at(i)->path(), mountpoint) == 0) { importedShare = d->importedShares.takeAt(i); break; } else { continue; } } // // If the share should have vanished in the meantime, return here. // if (!importedShare) { return; } - else - { - // Do nothing - } // // Add the size, user and group information // if (statJob->error() == 0 /* no error */) { check(importedShare); } else { importedShare->setInaccessible(true); importedShare->setFreeDiskSpace(0); importedShare->setTotalDiskSpace(0); importedShare->setUsedDiskSpace(0); importedShare->setUser(KUser(KUser::UseRealUserID)); importedShare->setGroup(KUserGroup(KUser::UseRealUserID)); } // // Is this a mount done by the user or by someone else? // Make an educated guess... // if ((importedShare->user().userId() == KUser(KUser::UseRealUserID).userId() && importedShare->group().groupId() == KUserGroup(KUser::UseRealUserID).groupId()) || importedShare->path().startsWith(Smb4KMountSettings::mountPrefix().path()) || importedShare->path().startsWith(QDir::homePath()) || importedShare->canonicalPath().startsWith(QDir(Smb4KMountSettings::mountPrefix().path()).canonicalPath()) || importedShare->canonicalPath().startsWith(QDir::home().canonicalPath())) { // Same UID and GID importedShare->setForeign(false); } else { importedShare->setForeign(true); } // // Search for a previously added mounted share and try to update it. If this fails, // add the share to the global list. // if (!importedShare->isForeign() || Smb4KMountSettings::detectAllShares()) { if (updateMountedShare(importedShare)) { SharePtr updatedShare = findShareByPath(importedShare->path()); if (updatedShare) { emit updated(updatedShare); } - else - { - // Do nothing - } importedShare.clear(); } else { if (addMountedShare(importedShare)) { // Remove the share from the list of shares that are to be remounted QMutableListIterator s(d->remounts); while (s.hasNext()) { SharePtr remount = s.next(); if (!importedShare->isForeign() && QString::compare(remount->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), importedShare->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0) { Smb4KCustomOptionsManager::self()->removeRemount(remount); s.remove(); break; } else { continue; } } // Tell the program and the user that the share was mounted. Also, reset the // counter of newly mounted shares, if necessary. d->newlyMounted += 1; emit mounted(importedShare); if (d->importedShares.isEmpty() && !d->mountShares && !d->unmountShares) { if (d->firstImportDone) { if (d->newlyMounted == 1) { Smb4KNotification::shareMounted(importedShare); } else { Smb4KNotification::sharesMounted(d->newlyMounted); } } - else - { - // Do nothing - } d->newlyMounted = 0; } - else - { - // Do nothing - } emit mountedSharesListChanged(); } else { importedShare.clear(); } } } else { importedShare.clear(); } if (!d->firstImportDone && d->importedShares.isEmpty()) { d->firstImportDone = true; } - else - { - // Do nothing - } } void Smb4KMounter::slotAboutToChangeProfile() { // // Save those shares that are to be remounted // if (Smb4KMountSettings::remountShares()) { saveSharesForRemount(); } - else - { - // Do nothing - } } void Smb4KMounter::slotActiveProfileChanged(const QString &newProfile) { if (d->activeProfile != newProfile) { // Stop the timer. killTimer(d->timerId); abort(); // Clear all remounts. while (!d->remounts.isEmpty()) { d->remounts.takeFirst().clear(); } // Clear all retries. while (!d->retries.isEmpty()) { d->retries.takeFirst().clear(); } // Unmount all shares unmountAllShares(true); // Reset some variables. d->remountTimeout = 0; d->remountAttempts = 0; d->firstImportDone = false; d->activeProfile = newProfile; // Restart the timer d->timerId = startTimer(TIMEOUT); } - else - { - // Do nothing - } } void Smb4KMounter::slotProfileMigrated(const QString& from, const QString& to) { if (QString::compare(from, d->activeProfile, Qt::CaseSensitive) == 0) { d->activeProfile = to; } - else - { - // Do nothing - } } void Smb4KMounter::slotTriggerImport() { // Wait until there are no jobs anymore while(isRunning()) { QTest::qWait(TIMEOUT); } // Initialize an import import(true); } void Smb4KMounter::slotConfigChanged() { if (d->detectAllShares != Smb4KMountSettings::detectAllShares()) { slotTriggerImport(); d->detectAllShares = Smb4KMountSettings::detectAllShares(); } - else - { - // Do nothing - } } diff --git a/core/smb4kmounter_p.cpp b/core/smb4kmounter_p.cpp index 06e6d17..e7d1355 100644 --- a/core/smb4kmounter_p.cpp +++ b/core/smb4kmounter_p.cpp @@ -1,302 +1,282 @@ /*************************************************************************** This file contains private helper classes for the Smb4KMounter class. ------------------- begin : Do Jul 19 2007 copyright : (C) 2007-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kmounter_p.h" #include "smb4ksettings.h" #include "smb4knotification.h" #include "smb4khomesshareshandler.h" #include "smb4kglobal.h" #include "smb4kcustomoptions.h" #include "smb4kcustomoptionsmanager.h" // Qt includes #include #include #include #include #include #include // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include #include #include using namespace Smb4KGlobal; Smb4KMountDialog::Smb4KMountDialog(const SharePtr &share, QWidget *parent) : QDialog(parent), m_share(share), m_valid(true) { setWindowTitle(i18n("Mount Share")); setupView(); setMinimumWidth(sizeHint().width() > 350 ? sizeHint().width() : 350); KConfigGroup group(Smb4KSettings::self()->config(), "MountDialog"); KWindowConfig::saveWindowSize(windowHandle(), group); m_share_input->completionObject()->setItems(group.readEntry("ShareNameCompletion", QStringList())); m_ip_input->completionObject()->setItems(group.readEntry("IPAddressCompletion", QStringList())); m_workgroup_input->completionObject()->setItems(group.readEntry("WorkgroupCompletion", QStringList())); } Smb4KMountDialog::~Smb4KMountDialog() { } void Smb4KMountDialog::setupView() { QVBoxLayout *layout = new QVBoxLayout(this); layout->setSpacing(5); QWidget *description = new QWidget(this); QHBoxLayout *desc_layout = new QHBoxLayout(description); desc_layout->setSpacing(5); QLabel *pixmap = new QLabel(description); QPixmap mount_pix = KDE::icon("view-form", QStringList("emblem-mounted")).pixmap(KIconLoader::SizeHuge); pixmap->setPixmap(mount_pix); pixmap->setAlignment(Qt::AlignBottom); QLabel *label = new QLabel(i18n("Enter the location and optionally the IP address and workgroup to mount a share."), description); label->setWordWrap(true); label->setAlignment(Qt::AlignBottom); desc_layout->addWidget(pixmap, 0); desc_layout->addWidget(label, Qt::AlignBottom); QWidget *edit_widget = new QWidget(this); QGridLayout *edit_layout = new QGridLayout(edit_widget); layout->setSpacing(5); QLabel *shareLabel = new QLabel(i18n("Location:"), edit_widget); m_share_input = new KLineEdit(edit_widget); m_share_input->setWhatsThis(i18n("The location of the share is provided by the Uniform Resource Locator (URL). It generally has the following syntax: " "[smb:]//[USER:PASSWORD@]HOST:PORT/SHARE. The username, password and port are optional. You should omit to enter the password here, because it is shown in cleartext.")); // m_share_input->setToolTip(i18n("The URL of the share")); m_share_input->setCompletionMode(KCompletion::CompletionPopupAuto); m_share_input->setClearButtonEnabled(true); m_share_input->setMinimumWidth(200); m_share_input->setFocus(); QLabel *addressLabel = new QLabel(i18n("IP Address:"), edit_widget); m_ip_input = new KLineEdit(edit_widget); m_ip_input->setWhatsThis(i18n("The Internet Protocol (IP) address identifies the " "host in the network and indicates where it is. It has two valid formats, the one " "known as IP version 4 (e.g. 192.168.2.11) and the version 6 format " "(e.g. 2001:0db8:85a3:08d3:1319:8a2e:0370:7334).")); // m_ip_input->setToolTip(i18n("The IP address of the host where the share is located")); m_ip_input->setCompletionMode(KCompletion::CompletionPopupAuto); m_ip_input->setClearButtonEnabled(true); m_ip_input->setMinimumWidth(200); QLabel *workgroupLabel = new QLabel(i18n("Workgroup:"), edit_widget); m_workgroup_input = new KLineEdit(edit_widget); m_workgroup_input->setWhatsThis(i18n("The workgroup or domain identifies the " "peer-to-peer computer network the host is located in.")); // m_workgroup_input->setToolTip(i18n("The workgroup where the host is located")); m_workgroup_input->setCompletionMode(KCompletion::CompletionPopupAuto); m_workgroup_input->setClearButtonEnabled(true); m_workgroup_input->setMinimumWidth(200); edit_layout->addWidget(shareLabel, 0, 0, 0); edit_layout->addWidget(m_share_input, 0, 1, 0); edit_layout->addWidget(addressLabel, 1, 0, 0); edit_layout->addWidget(m_ip_input, 1, 1, 0); edit_layout->addWidget(workgroupLabel, 2, 0, 0); edit_layout->addWidget(m_workgroup_input, 2, 1, 0); m_bookmark = new QCheckBox(i18n("Add this share to the bookmarks"), this); m_bookmark->setWhatsThis(i18n("If you tick this checkbox, the share will be bookmarked " "and you can access it e.g. through the \"Bookmarks\" menu entry in the main window.")); // m_bookmark->setToolTip(i18n("Add this share to the bookmarks")); QDialogButtonBox *buttonBox = new QDialogButtonBox(Qt::Horizontal, this); m_ok_button = buttonBox->addButton(QDialogButtonBox::Ok); m_cancel_button = buttonBox->addButton(QDialogButtonBox::Cancel); m_ok_button->setShortcut(Qt::CTRL|Qt::Key_Return); m_cancel_button->setShortcut(Qt::Key_Escape); layout->addWidget(description, Qt::AlignBottom); layout->addWidget(edit_widget, 0); layout->addWidget(m_bookmark, 0); layout->addWidget(buttonBox, 0); slotChangeInputValue(m_share_input->text()); // Connections connect(m_share_input, SIGNAL(textChanged(QString)) , this, SLOT(slotChangeInputValue(QString))); connect(m_share_input, SIGNAL(editingFinished()), this, SLOT(slotShareNameEntered())); connect(m_ip_input, SIGNAL(editingFinished()), this, SLOT(slotIPEntered())); connect(m_workgroup_input, SIGNAL(editingFinished()), this, SLOT(slotWorkgroupEntered())); connect(m_ok_button, SIGNAL(clicked()), this, SLOT(slotOkClicked())); connect(m_cancel_button, SIGNAL(clicked()), this, SLOT(slotCancelClicked())); } ///////////////////////////////////////////////////////////////////////////// // SLOT IMPLEMENTATIONS ///////////////////////////////////////////////////////////////////////////// void Smb4KMountDialog::slotChangeInputValue(const QString& _test) { m_ok_button->setEnabled(!_test.isEmpty()); } void Smb4KMountDialog::slotOkClicked() { if (!m_share_input->text().trimmed().isEmpty()) { // // Get the URL // QString userInput = m_share_input->text().trimmed(); // // Take care of a Windows-like UNC addresses // if (userInput.startsWith(QLatin1String("\\"))) { userInput.replace("\\", "/"); } - else - { - // Do nothing - } // // Set the URL and adjust the scheme // QUrl smbUrl = QUrl::fromUserInput(userInput); smbUrl.setScheme("smb"); // // Set the URL of the share // if (smbUrl.isValid() && !smbUrl.host().isEmpty() && !smbUrl.path().isEmpty() && !smbUrl.path().endsWith(QLatin1String("/"))) { m_share->setUrl(smbUrl); m_share->setWorkgroupName(m_workgroup_input->text().trimmed()); m_share->setHostIpAddress(m_ip_input->text().trimmed()); } else { Smb4KNotification::invalidURLPassed(); m_valid = false; } } - else - { - // Do nothing - } KConfigGroup group(Smb4KSettings::self()->config(), "MountDialog"); KWindowConfig::saveWindowSize(windowHandle(), group); group.writeEntry("ShareNameCompletion", m_share_input->completionObject()->items()); group.writeEntry("IPAddressCompletion", m_ip_input->completionObject()->items()); group.writeEntry("WorkgroupCompletion", m_workgroup_input->completionObject()->items()); accept(); } void Smb4KMountDialog::slotCancelClicked() { Smb4KMounter::self()->abort(); reject(); } void Smb4KMountDialog::slotShareNameEntered() { KCompletion *completion = m_share_input->completionObject(); QUrl url(m_share_input->userText()); url.setScheme("smb"); if (url.isValid() && !url.isEmpty()) { completion->addItem(m_share_input->userText()); } - else - { - // Do nothing - } } void Smb4KMountDialog::slotIPEntered() { KCompletion *completion = m_ip_input->completionObject(); if (!m_ip_input->userText().isEmpty()) { completion->addItem(m_ip_input->userText()); } - else - { - // Do nothing - } } void Smb4KMountDialog::slotWorkgroupEntered() { KCompletion *completion = m_workgroup_input->completionObject(); if (!m_workgroup_input->userText().isEmpty()) { completion->addItem(m_workgroup_input->userText()); } - else - { - // Do nothing - } } diff --git a/core/smb4knotification.cpp b/core/smb4knotification.cpp index dac7da8..698abea 100644 --- a/core/smb4knotification.cpp +++ b/core/smb4knotification.cpp @@ -1,512 +1,480 @@ /*************************************************************************** This class provides notifications for Smb4K. ------------------- begin : Son Jun 27 2010 copyright : (C) 2010-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4knotification.h" #include "smb4knotification_p.h" #include "smb4ksettings.h" #include "smb4kbookmark.h" #include "smb4kworkgroup.h" #include "smb4khost.h" #include "smb4kshare.h" // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include #include #include #include using namespace KAuth; // // Notifications // void Smb4KNotification::shareMounted(const SharePtr &share) { Q_ASSERT(share); if (share) { QUrl mountpoint = QUrl::fromLocalFile(share->path()); Smb4KNotifier *notification = new Smb4KNotifier("shareMounted"); notification->setText(i18n("

The share %1 has been mounted to %2.

", share->displayString(), share->path())); notification->setPixmap(KIconLoader::global()->loadIcon("folder-network", KIconLoader::NoGroup, 0, KIconLoader::DefaultState, QStringList("emblem-mounted"))); notification->setActions(QStringList(i18n("Open"))); notification->setMountpoint(mountpoint); notification->sendEvent(); } - else - { - // Do nothing - } } void Smb4KNotification::shareUnmounted(const SharePtr &share) { Q_ASSERT(share); if (share) { Smb4KNotifier *notification = new Smb4KNotifier("shareUnmounted"); notification->setText(i18n("

The share %1 has been unmounted from %2.

", share->displayString(), share->path())); notification->setPixmap(KIconLoader::global()->loadIcon("folder-network", KIconLoader::NoGroup, 0, KIconLoader::DefaultState, QStringList("emblem-unmounted"))); notification->sendEvent(); } - else - { - // Do nothing - } } void Smb4KNotification::sharesMounted(int number) { Smb4KNotifier *notification = new Smb4KNotifier("sharesMounted"); notification->setText(i18np("

%1 share has been mounted.

", "

%1 shares have been mounted.

", number)); notification->setPixmap(KIconLoader::global()->loadIcon("folder-network", KIconLoader::NoGroup, 0, KIconLoader::DefaultState, QStringList("emblem-mounted"))); notification->sendEvent(); } void Smb4KNotification::sharesUnmounted(int number) { Smb4KNotifier *notification = new Smb4KNotifier("sharesUnmounted"); notification->setText(i18np("

%1 share has been unmounted.

", "

%1 shares have been unmounted.

", number)); notification->setPixmap(KIconLoader::global()->loadIcon("folder-network", KIconLoader::NoGroup, 0, KIconLoader::DefaultState, QStringList("emblem-unmounted"))); notification->sendEvent(); } // // Warnings // void Smb4KNotification::openingWalletFailed(const QString& name) { Smb4KNotifier *notification = new Smb4KNotifier("openingWalletFailed"); notification->setText(i18n("

Opening the wallet %1 failed.

", name)); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-warning", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } void Smb4KNotification::credentialsNotAccessible() { Smb4KNotifier *notification = new Smb4KNotifier("credentialsNotAccessible"); notification->setText(i18n("

The credentials stored in the wallet could not be accessed. " "There is either no wallet available or it could not be opened.

")); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-warning", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } void Smb4KNotification::mimetypeNotSupported(const QString& mimetype) { Smb4KNotifier *notification = new Smb4KNotifier("mimetypeNotSupported"); notification->setText(i18n("

The mimetype %1 is not supported for printing. " "Please convert the file to PDF or Postscript and try again.

", mimetype)); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-warning", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } void Smb4KNotification::bookmarkExists(Smb4KBookmark* bookmark) { if (bookmark) { Smb4KNotifier *notification = new Smb4KNotifier("bookmarkExists"); notification->setText(i18n("

The bookmark for share %1 already exists and will be skipped.

", bookmark->displayString())); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-warning", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } - else - { - // Do nothing - } } void Smb4KNotification::bookmarkLabelInUse(Smb4KBookmark* bookmark) { if (bookmark) { Smb4KNotifier *notification = new Smb4KNotifier("bookmarkLabelInUse"); notification->setText(i18n("

The label %1 of the bookmark for the share %2 " "is already being used and will automatically be renamed.

", bookmark->label(), bookmark->displayString())); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-warning", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } - else - { - // Do nothing - } } void Smb4KNotification::sambaConfigFileMissing() { Smb4KNotifier *notification = new Smb4KNotifier("sambaConfigFileMissing"); notification->setText(i18n("The configuration file for the Samba suite smb.conf is missing. This is not " "a fatal error, but you should consider creating one.")); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-warning", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } // // Errors // void Smb4KNotification::mountingFailed(const SharePtr &share, const QString& err_msg) { if (share) { QString text; if (!err_msg.isEmpty()) { text = i18n("

Mounting the share %1 failed:

%2

", share->displayString(), err_msg); } else { text = i18n("

Mounting the share %1 failed.

", share->displayString()); } Smb4KNotifier *notification = new Smb4KNotifier("mountingFailed"); notification->setText(text); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } - else - { - // Do nothing - } } void Smb4KNotification::unmountingFailed(const SharePtr &share, const QString& err_msg) { if (share) { QString text; if (!err_msg.isEmpty()) { text = i18n("

Unmounting the share %1 from %2 failed:

%3

", share->displayString(), share->path(), err_msg); } else { text = i18n("

Unmounting the share %1 from %2 failed.

", share->displayString(), share->path()); } Smb4KNotifier *notification = new Smb4KNotifier("unmountingFailed"); notification->setText(text); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } - else - { - // Do nothing - } } void Smb4KNotification::unmountingNotAllowed(const SharePtr &share) { Q_ASSERT(share); if (share) { Smb4KNotifier *notification = new Smb4KNotifier("unmountingNotAllowed"); notification->setText(i18n("

You are not allowed to unmount the share %1 from %2. " "It is owned by the user %3.

", share->displayString(), share->path(), share->user().loginName())); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } - else - { - // Do nothing - } } void Smb4KNotification::synchronizationFailed(const QUrl& src, const QUrl& dest, const QString& err_msg) { QString text; if (!err_msg.isEmpty()) { text = i18n("

Synchronizing %1 with %2 failed:

%3

", dest.path(), src.path(), err_msg); } else { text = i18n("

Synchronizing %1 with %2 failed.

", dest.path(), src.path()); } Smb4KNotifier *notification = new Smb4KNotifier("synchronizationFailed"); notification->setText(text); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } void Smb4KNotification::commandNotFound(const QString& command) { Smb4KNotifier *notification = new Smb4KNotifier("commandNotFound"); notification->setText(i18n("

The command %1 could not be found. Please check your installation.

", command)); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } void Smb4KNotification::cannotBookmarkPrinter(const SharePtr &share) { if (share && share->isPrinter()) { Smb4KNotifier *notification = new Smb4KNotifier("cannotBookmarkPrinter"); notification->setText(i18n("

The share %1 is a printer and cannot be bookmarked.

", share->displayString())); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } - else - { - // Do nothing - } } void Smb4KNotification::fileNotFound(const QString& fileName) { Smb4KNotifier *notification = new Smb4KNotifier("fileNotFound"); notification->setText(i18n("

The file %1 could not be found.

", fileName)); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } void Smb4KNotification::openingFileFailed(const QFile& file) { QString text; if (!file.errorString().isEmpty()) { text = i18n("

Opening the file %1 failed:

%2

", file.fileName(), file.errorString()); } else { text = i18n("

Opening the file %1 failed.

", file.fileName()); } Smb4KNotifier *notification = new Smb4KNotifier("openingFileFailed"); notification->setText(text); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } void Smb4KNotification::readingFileFailed(const QFile& file, const QString& err_msg) { QString text; if (!err_msg.isEmpty()) { text = i18n("

Reading from file %1 failed:

%2

", file.fileName(), err_msg); } else { if (!file.errorString().isEmpty()) { text = i18n("

Reading from file %1 failed:

%2

", file.fileName(), file.errorString()); } else { text = i18n("

Reading from file %1 failed.

", file.fileName()); } } Smb4KNotifier *notification = new Smb4KNotifier("readingFileFailed"); notification->setText(text); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } void Smb4KNotification::mkdirFailed(const QDir& dir) { Smb4KNotifier *notification = new Smb4KNotifier("mkdirFailed"); notification->setText(i18n("

The following directory could not be created:

%1

", dir.absolutePath())); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } void Smb4KNotification::processError(QProcess::ProcessError error) { QString text; switch (error) { case QProcess::FailedToStart: { text = i18n("

The process failed to start (error code: %1).

", error); break; } case QProcess::Crashed: { text = i18n("

The process crashed (error code: %1).

", error); break; } case QProcess::Timedout: { text = i18n("

The process timed out (error code: %1).

", error); break; } case QProcess::WriteError: { text = i18n("

Could not write to the process (error code: %1).

", error); break; } case QProcess::ReadError: { text = i18n("

Could not read from the process (error code: %1).

", error); break; } case QProcess::UnknownError: default: { text = i18n("

The process reported an unknown error.

"); break; } } Smb4KNotifier *notification = new Smb4KNotifier("processError"); notification->setText(text); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } void Smb4KNotification::actionFailed(int err_code) { QString text, err_msg; switch (err_code) { case ActionReply::NoResponderError: { err_msg = "NoResponderError"; break; } case ActionReply::NoSuchActionError: { err_msg = "NoSuchActionError"; break; } case ActionReply::InvalidActionError: { err_msg = "InvalidActionError"; break; } case ActionReply::AuthorizationDeniedError: { err_msg = "AuthorizationDeniedError"; break; } case ActionReply::UserCancelledError: { err_msg = "UserCancelledError"; break; } case ActionReply::HelperBusyError: { err_msg = "HelperBusyError"; break; } case ActionReply::AlreadyStartedError: { err_msg = "AlreadyStartedError"; break; } case ActionReply::DBusError: { err_msg = "DBusError"; break; } case ActionReply::BackendError: { err_msg = "BackendError"; break; } default: { break; } } if (!err_msg.isEmpty()) { text = i18n("

Executing an action with root privileges failed (error code: %1).

", err_msg); } else { text = i18n("

Executing an action with root privileges failed.

"); } Smb4KNotifier *notification = new Smb4KNotifier("actionFailed"); notification->setText(text); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } void Smb4KNotification::invalidURLPassed() { Smb4KNotifier *notification = new Smb4KNotifier("invalidURL"); notification->setText(i18n("

The URL that was passed is invalid.

")); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } void Smb4KNotification::networkCommunicationFailed(const QString& errorMessage) { Smb4KNotifier *notification = new Smb4KNotifier("networkCommunicationFailed"); notification->setText(i18n("

The network communication failed with the following error message:

%1

").arg(errorMessage)); notification->setPixmap(KIconLoader::global()->loadIcon("dialog-error", KIconLoader::NoGroup, 0, KIconLoader::DefaultState)); notification->sendEvent(); } diff --git a/core/smb4kprofilemanager.cpp b/core/smb4kprofilemanager.cpp index 9df377e..e148b98 100644 --- a/core/smb4kprofilemanager.cpp +++ b/core/smb4kprofilemanager.cpp @@ -1,410 +1,345 @@ /*************************************************************************** This class manages the profiles that were defined by the user. ------------------- begin : Mi Aug 06 2014 copyright : (C) 2014-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kprofilemanager.h" #include "smb4kprofilemanager_p.h" #include "smb4ksettings.h" #include "smb4khomesshareshandler.h" #include "smb4kcustomoptionsmanager.h" #include "smb4kbookmarkhandler.h" // Qt includes #include #include #include Q_GLOBAL_STATIC(Smb4KProfileManagerStatic, p); // // NOTE: Do not invoke writeConfig() here, because this will/might // trigger the configChanged() signal which can lead to unwanted // effects. // Smb4KProfileManager::Smb4KProfileManager(QObject* parent) : QObject(parent), d(new Smb4KProfileManagerPrivate) { d->useProfiles = Smb4KSettings::useProfiles(); if (d->useProfiles) { d->profiles = Smb4KSettings::profilesList(); d->activeProfile = !Smb4KSettings::activeProfile().isEmpty() ? Smb4KSettings::activeProfile() : d->profiles.first(); } else { d->profiles.clear(); d->activeProfile.clear(); } - connect(Smb4KSettings::self(), SIGNAL(configChanged()), - this, SLOT(slotConfigChanged())); + connect(Smb4KSettings::self(), SIGNAL(configChanged()), this, SLOT(slotConfigChanged())); } Smb4KProfileManager::~Smb4KProfileManager() { } Smb4KProfileManager* Smb4KProfileManager::self() { return &p->instance; } void Smb4KProfileManager::setActiveProfile(const QString& name) { // // Check if the active profile is going to be changed. If so, // notify the program so that things can be done before the // profile is actually changed. // bool change = false; if (d->useProfiles) { if (name != d->activeProfile) { emit aboutToChangeProfile(); change = true; } - else - { - // Do nothing - } } else { if (!d->activeProfile.isEmpty()) { emit aboutToChangeProfile(); change = true; } - else - { - // Do nothing - } } // // Now change the profile // if (change) { d->activeProfile = d->useProfiles ? name : QString(); Smb4KSettings::setActiveProfile(d->activeProfile); emit activeProfileChanged(d->activeProfile); } - else - { - // Do nothing - } } QString Smb4KProfileManager::activeProfile() const { return d->activeProfile; } QStringList Smb4KProfileManager::profilesList() const { return d->useProfiles ? d->profiles : QStringList(); } bool Smb4KProfileManager::useProfiles() const { return d->useProfiles; } void Smb4KProfileManager::migrateProfile(const QString& from, const QString& to) { QList> list; list << QPair(from, to); migrateProfiles(list); } void Smb4KProfileManager::migrateProfiles(const QList>& list) { if (d->useProfiles || (list.size() == 1 && list.first().second.isEmpty())) { for (int i = 0; i < list.size(); ++i) { QString from = list.at(i).first; QString to = list.at(i).second; if (!to.isEmpty()) { // Migrate one/the default profile to another one. // First exchange the old profile. for (int j = 0; j < d->profiles.size(); ++j) { if (QString::compare(from, d->profiles.at(j), Qt::CaseSensitive) == 0) { d->profiles.replace(j, to); break; } - else - { - // Do nothing - } } // Migrate profiles. Smb4KBookmarkHandler::self()->migrateProfile(from, to); Smb4KCustomOptionsManager::self()->migrateProfile(from, to); Smb4KHomesSharesHandler::self()->migrateProfile(from, to); emit migratedProfile(from, to); // In case the active profile was modified, rename it according // the value passed. if (QString::compare(from, d->activeProfile, Qt::CaseSensitive) == 0) { setActiveProfile(to); } - else - { - // Do nothing - } } else { // Migrate all profiles to the default one. for (int j = 0; j < d->profiles.size(); ++j) { Smb4KBookmarkHandler::self()->migrateProfile(d->profiles.at(j), to); Smb4KCustomOptionsManager::self()->migrateProfile(d->profiles.at(j), to); Smb4KHomesSharesHandler::self()->migrateProfile(d->profiles.at(j), to); emit migratedProfile(d->profiles.at(i), to); } } } Smb4KSettings::setProfilesList(d->profiles); emit profilesListChanged(d->profiles); } - else - { - // Do nothing - } } void Smb4KProfileManager::removeProfile(const QString& name) { QStringList list; list << name; removeProfiles(list); } void Smb4KProfileManager::removeProfiles(const QStringList& list) { if (d->useProfiles) { for (int i = 0; i < list.size(); ++i) { QString name = list.at(i); // First remove the profile from the list. QMutableStringListIterator it(d->profiles); while (it.hasNext()) { QString entry = it.next(); if (QString::compare(name, entry, Qt::CaseSensitive) == 0) { it.remove(); break; } - else - { - // Do nothing - } } if (!d->profiles.isEmpty()) { // Ask the user if he/she wants to migrate the entries // of the removed profile to another one. if (Smb4KSettings::useMigrationAssistant()) { QPointer dlg = new Smb4KProfileMigrationDialog(QStringList(name), d->profiles, QApplication::activeWindow()); if (dlg->exec() == QDialog::Accepted) { migrateProfile(dlg->from(), dlg->to()); } - else - { - // Do nothing - } delete dlg; } - else - { - // Do nothing - } } - else - { - // Do nothing - } // Remove the profile. Smb4KBookmarkHandler::self()->removeProfile(name); Smb4KCustomOptionsManager::self()->removeProfile(name); Smb4KHomesSharesHandler::self()->removeProfile(name); emit removedProfile(name); // Set a new active profile if the user removed the current one. if (QString::compare(name, d->activeProfile, Qt::CaseSensitive) == 0) { setActiveProfile(!d->profiles.isEmpty() ? d->profiles.first() : QString()); } - else - { - // Do nothing - } } Smb4KSettings::setProfilesList(d->profiles); emit profilesListChanged(d->profiles); } - else - { - // Do nothing - } } void Smb4KProfileManager::slotConfigChanged() { bool usageChanged = false; // // Check if the usage of profiles changed // if (d->useProfiles != Smb4KSettings::useProfiles()) { d->useProfiles = Smb4KSettings::useProfiles(); emit profileUsageChanged(d->useProfiles); usageChanged = true; } - else - { - // Do nothing - } // // Updated the list of profiles // if (d->profiles != Smb4KSettings::profilesList()) { d->profiles = Smb4KSettings::profilesList(); emit profilesListChanged(d->profiles); } - else - { - // Do nothing - } // // Migrate profiles. // Profiles are only migrated, if the usage changed and the // user chose to use the migration assistant. // if (usageChanged && Smb4KSettings::useMigrationAssistant()) { QStringList from, to; if (d->useProfiles) { // Since the setting changed, the use of profiles was // switched off before. So, ask the user if he/she wants // to migrate the default profile to any other one. // Therefore, from needs to get one empty entry (default // profile) and to has to be d->profiles. from << QString(); to << d->profiles; } else { // Here it is vice versa: Ask the user if he/she wants to // migrate all profiles to the default profile. Therefore, // set from to d->profiles and to to empty. from << d->profiles; to << QString(); } // Now, launch the migration dialog. QPointer dlg = new Smb4KProfileMigrationDialog(from, to, 0); if (dlg->exec() == QDialog::Accepted) { migrateProfile(dlg->from(), dlg->to()); } - else - { - // Do nothing - } delete dlg; } - else - { - // Do nothing - } // // Set the active profile // if (!Smb4KSettings::activeProfile().isEmpty() && d->profiles.contains(Smb4KSettings::activeProfile())) { setActiveProfile(Smb4KSettings::activeProfile()); } else { setActiveProfile(d->profiles.first()); } } diff --git a/core/smb4kprofilemanager_p.cpp b/core/smb4kprofilemanager_p.cpp index 2a495ab..5d1e771 100644 --- a/core/smb4kprofilemanager_p.cpp +++ b/core/smb4kprofilemanager_p.cpp @@ -1,180 +1,180 @@ /*************************************************************************** Private helper class(es) for the profile manager. ------------------- begin : Mi Aug 12 2014 - copyright : (C) 2014-2017 by Alexander Reinholdt + copyright : (C) 2014-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kprofilemanager_p.h" #include "smb4ksettings.h" // Qt includes #include #include #include #include #include #include #include // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include #include #include Smb4KProfileMigrationDialog::Smb4KProfileMigrationDialog(const QStringList& from, const QStringList& to, QWidget* parent) : QDialog(parent), m_from_list(from), m_to_list(to) { setWindowTitle(i18n("Profile Migration Assistant")); setupView(); setMinimumWidth(sizeHint().width() > 350 ? sizeHint().width() : 350); create(); KConfigGroup group(Smb4KSettings::self()->config(), "ProfileMigrationDialog"); KWindowConfig::restoreWindowSize(windowHandle(), group); resize(windowHandle()->size()); // workaround for QTBUG-40584 } Smb4KProfileMigrationDialog::~Smb4KProfileMigrationDialog() { } void Smb4KProfileMigrationDialog::setupView() { QVBoxLayout *layout = new QVBoxLayout(this); layout->setSpacing(5); // Description QWidget *description = new QWidget(this); QHBoxLayout *desc_layout = new QHBoxLayout(description); desc_layout->setSpacing(5); desc_layout->setMargin(0); QLabel *pixmap = new QLabel(description); QPixmap pix = KDE::icon("format-list-unordered").pixmap(KIconLoader::SizeHuge); pixmap->setPixmap(pix); pixmap->setAlignment(Qt::AlignBottom); QLabel *label = new QLabel(i18n("Migrate all relevant settings of one profile to another.")); label->setWordWrap(true); label->setAlignment(Qt::AlignBottom); desc_layout->addWidget(pixmap, 0); desc_layout->addWidget(label, Qt::AlignBottom); QWidget *editors = new QWidget(this); QGridLayout *editors_layout = new QGridLayout(editors); editors_layout->setSpacing(5); editors_layout->setMargin(0); editors_layout->setColumnStretch(0, 0); editors_layout->setColumnStretch(1, 1); QLabel *from = new QLabel(i18n("Old Profile:"), editors); editors_layout->addWidget(from, 0, 0, 0); m_from_box = new KComboBox(editors); if (m_from_list.size() == 1 && m_from_list.first().isEmpty()) { m_from_box->addItem(i18n("")); } else { if (m_to_list.size() == 1 && m_to_list.first().isEmpty()) { m_from_box->addItem(i18n("")); } else { m_from_box->addItems(m_from_list); } } editors_layout->addWidget(m_from_box, 0, 1, 0); QLabel *to = new QLabel(i18n("New Profile:"), editors); editors_layout->addWidget(to, 1, 0, 0); m_to_box = new KComboBox(editors); if (m_to_list.size() == 1 && m_to_list.first().isEmpty()) { m_to_box->addItem(i18n("")); } else { m_to_box->addItems(m_to_list); m_to_box->setCurrentItem(Smb4KProfileManager::self()->activeProfile()); } editors_layout->addWidget(m_to_box, 1, 1, 0); QDialogButtonBox *buttonBox = new QDialogButtonBox(Qt::Horizontal, this); m_ok_button = buttonBox->addButton(QDialogButtonBox::Ok); m_cancel_button = buttonBox->addButton(QDialogButtonBox::Cancel); m_ok_button->setShortcut(Qt::CTRL|Qt::Key_Return); m_cancel_button->setShortcut(Qt::Key_Escape); m_ok_button->setDefault(true); layout->addWidget(description, 0); layout->addWidget(editors, 0); layout->addWidget(buttonBox, 0); connect(m_ok_button, SIGNAL(clicked()), this, SLOT(slotOkClicked())); connect(m_cancel_button, SIGNAL(clicked()), this, SLOT(reject())); } QString Smb4KProfileMigrationDialog::from() const { return m_from_box->currentText(); } QString Smb4KProfileMigrationDialog::to() const { return m_to_box->currentText(); } void Smb4KProfileMigrationDialog::slotOkClicked() { KConfigGroup group(Smb4KSettings::self()->config(), "ProfileMigrationDialog"); KWindowConfig::saveWindowSize(windowHandle(), group); accept(); } diff --git a/core/smb4kprofilemanager_p.h b/core/smb4kprofilemanager_p.h index 80f75a1..afb5258 100644 --- a/core/smb4kprofilemanager_p.h +++ b/core/smb4kprofilemanager_p.h @@ -1,106 +1,106 @@ /*************************************************************************** Private helper class(es) for the profile manager. ------------------- begin : Mi Aug 12 2014 - copyright : (C) 2014-2017 by Alexander Reinholdt + copyright : (C) 2014-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifndef SMB4KPROFILEMANAGER_P_H #define SMB4KPROFILEMANAGER_P_H // Application specific includes #include "smb4kprofilemanager.h" // Qt includes #include #include #include #include #include // KDE includes #include class Smb4KProfileMigrationDialog : public QDialog { Q_OBJECT public: /** * Constructor */ explicit Smb4KProfileMigrationDialog(const QStringList &from, const QStringList &to, QWidget* parent = 0); /** * Destructor */ virtual ~Smb4KProfileMigrationDialog(); /** * Returns the name of the profile of which the entries * should be migrated. * * @returns the name of the profile. */ QString from() const; /** * Returns the name of the profile where the entries should * be migrated to. * * @returns the name of the new profile. */ QString to() const; protected Q_SLOTS: void slotOkClicked(); private: void setupView(); QPushButton *m_ok_button; QPushButton *m_cancel_button; QStringList m_from_list; QStringList m_to_list; KComboBox *m_from_box; KComboBox *m_to_box; }; class Smb4KProfileManagerPrivate { public: QString activeProfile; QStringList profiles; bool useProfiles; }; class Smb4KProfileManagerStatic { public: Smb4KProfileManager instance; }; #endif diff --git a/core/smb4kshare.cpp b/core/smb4kshare.cpp index c29c9bf..dfa92fa 100644 --- a/core/smb4kshare.cpp +++ b/core/smb4kshare.cpp @@ -1,715 +1,667 @@ /*************************************************************************** Smb4K's container class for information about a share. ------------------- begin : Mo Jan 28 2008 - copyright : (C) 2008-2017 by Alexander Reinholdt + copyright : (C) 2008-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kshare.h" #include "smb4kauthinfo.h" // Qt include #include #include // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include #include #include #include class Smb4KSharePrivate { public: QString workgroup; QString comment; QHostAddress ip; QString path; bool inaccessible; bool foreign; KUser user; KUserGroup group; qulonglong totalSpace; qulonglong freeSpace; qulonglong usedSpace; bool mounted; QString filesystem; Smb4KGlobal::ShareType shareType; }; Smb4KShare::Smb4KShare(const QString &host, const QString &name) : Smb4KBasicNetworkItem(Share), d(new Smb4KSharePrivate) { d->inaccessible = false; d->foreign = false; d->filesystem = QString(); d->user = KUser(KUser::UseRealUserID); d->group = KUserGroup(KUser::UseRealUserID); d->totalSpace = -1; d->freeSpace = -1; d->usedSpace = -1; d->mounted = false; d->shareType = FileShare; setHostName(host); setShareName(name); setShareIcon(); } Smb4KShare::Smb4KShare(const QUrl &url) : Smb4KBasicNetworkItem(Share), d(new Smb4KSharePrivate) { // // Set the private variables // d->inaccessible = false; d->foreign = false; d->filesystem = QString(); d->user = KUser(KUser::UseRealUserID); d->group = KUserGroup(KUser::UseRealUserID); d->totalSpace = -1; d->freeSpace = -1; d->usedSpace = -1; d->mounted = false; d->shareType = FileShare; // // Set the URL // *pUrl = url; // // Set the icon // setShareIcon(); } Smb4KShare::Smb4KShare(const Smb4KShare &s) : Smb4KBasicNetworkItem(Share), d(new Smb4KSharePrivate) { // // Copy the private variables // *d = *s.d; // // Set the icon if necessary // if (pIcon->isNull()) { setShareIcon(); } - else - { - // Do nothing - } } Smb4KShare::Smb4KShare() : Smb4KBasicNetworkItem(Share), d(new Smb4KSharePrivate) { // // Set the private variables // d->inaccessible = false; d->foreign = false; d->filesystem = QString(); d->user = KUser(KUser::UseRealUserID); d->group = KUserGroup(KUser::UseRealUserID); d->totalSpace = -1; d->freeSpace = -1; d->usedSpace = -1; d->mounted = false; d->shareType = FileShare; // // Set the URL // pUrl->setScheme("smb"); // // Set the icon // setShareIcon(); } Smb4KShare::~Smb4KShare() { } void Smb4KShare::setShareName(const QString &name) { if (name.startsWith('/')) { pUrl->setPath(name.trimmed()); } else { pUrl->setPath('/'+name.trimmed()); } pUrl->setScheme("smb"); } QString Smb4KShare::shareName() const { return pUrl->path().remove('/'); } void Smb4KShare::setHostName(const QString &hostName) { pUrl->setHost(hostName.trimmed()); pUrl->setScheme("smb"); } QString Smb4KShare::hostName() const { return pUrl->host().toUpper(); } QUrl Smb4KShare::homeUrl() const { QUrl u; if (isHomesShare() && !pUrl->userName().isEmpty()) { u = *pUrl; u.setPath('/'+pUrl->userName(), QUrl::TolerantMode); } - else - { - // Do nothing - } return u; } QString Smb4KShare::displayString(bool showHomesShare) const { if (showHomesShare && isHomesShare()) { return i18n("%1 on %2", homeUrl().path().remove('/'), hostName()); } - else - { - // Do nothing - } return i18n("%1 on %2", shareName(), hostName()); } void Smb4KShare::setWorkgroupName(const QString &workgroup) { d->workgroup = workgroup; } QString Smb4KShare::workgroupName() const { return d->workgroup; } void Smb4KShare::setShareType(Smb4KGlobal::ShareType type) { d->shareType = type; setShareIcon(); } Smb4KGlobal::ShareType Smb4KShare::shareType() const { return d->shareType; } QString Smb4KShare::shareTypeString() const { QString typeString; switch (d->shareType) { case FileShare: { typeString = i18n("Disk"); break; } case PrinterShare: { typeString = i18n("Printer"); break; } case IpcShare: { typeString = i18n("IPC"); break; } default: { break; } } return typeString; } void Smb4KShare::setComment(const QString &comment) { d->comment = comment; } QString Smb4KShare::comment() const { return d->comment; } void Smb4KShare::setHostIpAddress(const QString &ip) { d->ip.setAddress(ip); } void Smb4KShare::setHostIpAddress(const QHostAddress& address) { if (!address.isNull() && address.protocol() != QAbstractSocket::UnknownNetworkLayerProtocol) { d->ip = address; } - else - { - // Do nothing - } } QString Smb4KShare::hostIpAddress() const { return d->ip.toString(); } bool Smb4KShare::hasHostIpAddress() const { return !d->ip.isNull(); } bool Smb4KShare::isHidden() const { return pUrl->path().endsWith('$'); } bool Smb4KShare::isPrinter() const { return (d->shareType == PrinterShare); } void Smb4KShare::setPath(const QString &mountpoint) { d->path = mountpoint; } QString Smb4KShare::path() const { return d->path; } QString Smb4KShare::canonicalPath() const { return (d->inaccessible ? d->path : QDir(d->path).canonicalPath()); } void Smb4KShare::setInaccessible(bool in) { d->inaccessible = in; setShareIcon(); } bool Smb4KShare::isInaccessible() const { return (d->mounted && d->inaccessible); } void Smb4KShare::setForeign(bool foreign) { d->foreign = foreign; setShareIcon(); } bool Smb4KShare::isForeign() const { return (d->mounted && d->foreign); } QString Smb4KShare::fileSystemString() const { if (!path().isEmpty() && d->filesystem.isEmpty()) { KMountPoint::Ptr mp = KMountPoint::currentMountPoints().findByPath(path()); d->filesystem = mp->mountType().toUpper(); } - else - { - // Do nothing - } return d->filesystem; } void Smb4KShare::setUser(const KUser &user) { d->user = user; } KUser Smb4KShare::user() const { return d->user; } void Smb4KShare::setGroup(const KUserGroup &group) { d->group = group; } KUserGroup Smb4KShare::group() const { return d->group; } void Smb4KShare::setMounted(bool mounted) { if (!isPrinter()) { d->mounted = mounted; setShareIcon(); } - else - { - // Do nothing - } } bool Smb4KShare::isMounted() const { return d->mounted; } void Smb4KShare::setTotalDiskSpace(qulonglong size) { d->totalSpace = size; } qulonglong Smb4KShare::totalDiskSpace() const { return d->totalSpace; } QString Smb4KShare::totalDiskSpaceString() const { return KIO::convertSize(d->totalSpace); } void Smb4KShare::setFreeDiskSpace(qulonglong size) { d->freeSpace = size; } qulonglong Smb4KShare::freeDiskSpace() const { return d->freeSpace; } QString Smb4KShare::freeDiskSpaceString() const { return KIO::convertSize(d->freeSpace); } void Smb4KShare::setUsedDiskSpace(qulonglong size) { d->usedSpace = size; } qulonglong Smb4KShare::usedDiskSpace() const { return d->usedSpace; } QString Smb4KShare::usedDiskSpaceString() const { return KIO::convertSize(d->usedSpace); } qreal Smb4KShare::diskUsage() const { qreal used(usedDiskSpace()); qreal total(totalDiskSpace()); if (total > 0) { return used * 100 / total; } return 0; } QString Smb4KShare::diskUsageString() const { return QString("%1 %").arg(diskUsage(), 0, 'f', 1); } void Smb4KShare::setMountData(Smb4KShare *share) { Q_ASSERT(share); if (QString::compare(url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), share->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0 && QString::compare(workgroupName(), share->workgroupName(), Qt::CaseInsensitive) == 0) { d->path = share->path(); d->inaccessible = share->isInaccessible(); d->foreign = share->isForeign(); d->user = share->user(); d->group = share->group(); d->totalSpace = share->totalDiskSpace(); d->freeSpace = share->freeDiskSpace(); d->usedSpace = share->usedDiskSpace(); d->mounted = share->isMounted(); d->shareType = share->shareType(); setShareIcon(); } - else - { - // Do nothing - } } void Smb4KShare::resetMountData() { d->path.clear(); d->inaccessible = false; d->foreign = false; d->user = KUser(KUser::UseRealUserID); d->group = KUserGroup(KUser::UseRealUserID); d->totalSpace = -1; d->freeSpace = -1; d->usedSpace = -1; d->mounted = false; d->shareType = FileShare; setShareIcon(); } bool Smb4KShare::isHomesShare() const { return pUrl->path().endsWith(QLatin1String("homes")); } void Smb4KShare::setPort(int port) { pUrl->setPort(port); } int Smb4KShare::port() const { return pUrl->port(); } void Smb4KShare::setAuthInfo(Smb4KAuthInfo *authInfo) { // Avoid that the login is overwritten with an empty // string if we have a homes share. if (!isHomesShare() || !authInfo->userName().isEmpty()) { pUrl->setUserName(authInfo->userName()); pUrl->setPassword(authInfo->password()); } - else - { - // Do nothing - } } void Smb4KShare::setLogin(const QString &login) { // Avoid that the login is overwritten with an empty // string if we have a homes share. if (!isHomesShare() || !login.isEmpty()) { pUrl->setUserName(login); } - else - { - // Do nothing - } } QString Smb4KShare::login() const { return pUrl->userName(); } void Smb4KShare::setPassword(const QString &passwd) { // Avoid that the password is overwritten with an empty // string if we have a homes share. if (!isHomesShare() || !passwd.isEmpty()) { pUrl->setPassword(passwd); } - else - { - // Do nothing - } } QString Smb4KShare::password() const { return pUrl->password(); } void Smb4KShare::setShareIcon() { // // We have three base icons: // - remote folder // - locked folder // - printer // if (!isPrinter()) { // Overlays QStringList overlays; if (isMounted()) { overlays << "emblem-mounted"; } else { overlays << ""; } if (isForeign()) { overlays << "task-attention"; } - else - { - // Do nothing - } if (!isInaccessible()) { *pIcon = KDE::icon("folder-network", overlays); } else { *pIcon = KDE::icon("folder-locked", overlays); } } else { *pIcon = KDE::icon("printer"); } } void Smb4KShare::update(Smb4KShare* share) { if (QString::compare(workgroupName(), share->workgroupName(), Qt::CaseInsensitive) == 0 && (QString::compare(url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), share->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0 || QString::compare(homeUrl().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), share->homeUrl().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0)) { *pUrl = share->url(); setMountData(share); setShareType(share->shareType()); setComment(share->comment()); setHostIpAddress(share->hostIpAddress()); } - else - { - // Do nothing - } } diff --git a/core/smb4kshare.h b/core/smb4kshare.h index 76beac2..acb06a7 100644 --- a/core/smb4kshare.h +++ b/core/smb4kshare.h @@ -1,535 +1,535 @@ /*************************************************************************** Smb4K's container class for information about a share. ------------------- begin : Mo Jan 28 2008 - copyright : (C) 2008-2017 by Alexander Reinholdt + copyright : (C) 2008-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifndef SMB4KSHARE_H #define SMB4KSHARE_H // application specific includes #include "smb4kbasicnetworkitem.h" // Qt includes #include #include #include #include #include // KDE includes #include // forward declarations class Smb4KAuthInfo; class Smb4KSharePrivate; class Q_DECL_EXPORT Smb4KShare : public Smb4KBasicNetworkItem { friend class Smb4KSharePrivate; public: /** * This constructor takes the host name @p hostName and the name of the * shared resource @p shareName. All other information has to be set by the * other functions this class provides. * * This constructor will also assemble the UNC from the provided arguments. * * @param hostName The name of the host where the share is * located. * * @param shareName The name of the share. */ Smb4KShare(const QString &hostName, const QString &shareName); /** * This constructor takes the URL @p url as only argument. All other * information has to be set by the other functions this class provides. * * @param url The URL */ explicit Smb4KShare(const QUrl &url); /** * This is the copy constructor. It takes another Smb4KShare item and copies all * its values. * * @param share The Smb4KShare item that is to be copied */ Smb4KShare(const Smb4KShare &share); /** * The empty constructor. You need to set all information by the functions that * are provided with this class. */ Smb4KShare(); /** * The destructor. */ ~Smb4KShare(); /** * Sets the name of the share (*not* the UNC). * * @param name The share name */ void setShareName(const QString &name); /** * Returns the name of the share, e.g. "Music", "Data", etc. * * @returns the name of the share. */ QString shareName() const; /** * Sets the name of the host where the share is located. * * @param hostName The host name */ void setHostName(const QString &hostName); /** * Returns the name of the host where the share is located. * * @returns the host name */ QString hostName() const; /** * In case of a 'homes' share, this function returns the URL of the user's * home repository. * * If the share is not a 'homes' share or no user name for the homes share * has been defined, this function returns an empty string. * * @returns the user's home repository's URL. */ QUrl homeUrl() const; /** * Returns the display string. Prefer this over all other alternatives in your * GUI. * * @param showHomesShare Show the name of the users home share instead of 'homes' * in case this is a homes share. Setting this argument on a * non-homes share does nothing. * * @returns the display string. */ QString displayString(bool showHomeShare = false) const; /** * Set the workgroup where the host is located that offers this share. * * @param workgroup The name of the workgroup */ void setWorkgroupName(const QString &workgroup); /** * Returns the name of the workgroup where the host is located that * offers this share. * * @returns the workgroup name */ QString workgroupName() const; /** * Set the type of the share as reported by the server. * * @param type The type of the string */ void setShareType(Smb4KGlobal::ShareType type); /** * Returns the type of the share as reported by the server. If you are * looking for a translated type string, then use the shareTypeString() * function. * * @returns the type of the share. */ Smb4KGlobal::ShareType shareType() const; /** * Returns the translated type string of the share. You can use this * in the GUI. * * @returns a translated type string. */ QString shareTypeString() const; /** * Sets the comment that was defined for the share. * * @param comment The comment for the share */ void setComment(const QString &comment); /** * Returns the comment that was defined for this share. * * @returns the comment. */ QString comment() const; /** * Set the IP address of the host where the share is located. @p ip will * only be accepted if it is compatible with either IPv4 or IPv6. * * @param ip The host's IP address */ void setHostIpAddress(const QString &ip); /** * Set the IP address of the host where the share is located. @p ip will only be accepted * if it is compatible with either IPv4 or IPv6. * * @param ip The host's IP address */ void setHostIpAddress(const QHostAddress &address); /** * Returns the IP address of the host. If the IP address was not compatible * with IPv4 and IPv6 or if no IP address was supplied, an empty string is * returned. * * @returns the IP address of the host or an empty string. */ QString hostIpAddress() const; /** * Returns TRUE if the host's IP address is set and FALSE otherwise. * * @returns TRUE if the host's IP address is set and FALSE otherwise. */ bool hasHostIpAddress() const; /** * If the share is a hidden one, i.e. it ends with a '$', this function returns * TRUE and FALSE otherwise. * * @returns TRUE if this is a hidden share. */ bool isHidden() const; /** * If the share is a printer this function returns TRUE and otherwise FALSE. * * @returns TRUE if the share is a printer. */ bool isPrinter() const; /** * Sets the path aka mount point of the share as gathered by the mounter. * * @param mountpoint The mount point of the share. */ void setPath(const QString &mountpoint); /** * Returns the path to the mounted share (aka the mount point) as it was gathered * by the mounter. It is a C-type string. * * @returns the path to the mounted share. */ QString path() const; /** * Returns the canonical path to the mounted share. In contrast to the path() * function it will return the absolute path without symlinks. However, should * the share be inaccessible (i.e. the isInaccessible() returns TRUE), only * the "normal" path is returned. * * @returns the canonical path to the mounted share. */ QString canonicalPath() const; /** * Set @p in to TRUE if the share cannot be accessed by the user. This may be * because if strict permissions or because the remote server went offline. By * default it is assumed that the share is accessible. * * @param in Tells if the share is inaccessible or not. */ void setInaccessible(bool in); /** * Returns TRUE if the share is mounted and not accessible by the user. * * @returns TRUE if the share is mounted and inaccessible. */ bool isInaccessible() const; /** * If the share was mounted by another user, @p foreign should be set to TRUE. * By default it is assumed that the share is not foreign but owned by the * user. * * @param foreign TRUE if the share is foreign and FALSE otherwise. */ void setForeign(bool foreign); /** * Returns TRUE if the share is mounted and is owned by another user. * * @returns TRUE if this is a foreign share. */ bool isForeign() const; /** * Returns the file system as string in capital letters. If no file system * was specified, an empty string is returned. * * @returns the file system string or an empty string. */ QString fileSystemString() const; /** * Sets the owner of this share. * @param user The UID of the owner */ void setUser(const KUser &user); /** * Returns the owner of this share or the current user, if * the owner was not set using @see setUser(). * @returns the owner. */ KUser user() const; /** * Set the group that owns this share. * @param group The owning GID */ void setGroup(const KUserGroup &group); /** * Returns the group that owns this share or the current group, if * the group was not set using @see setGroup(). * @returns the group. */ KUserGroup group() const; /** * Sets the value of the total disk space that is available on the share. If * the disk usage could not be determined, @p size has to be set to 0. * * @param total The total disk space that is available on the share */ void setTotalDiskSpace(qulonglong size); /** * Returns the total disk space that is available on the share or 0 if the * total disk space was not set or could not be determined. * * @returns the total disk space or 0. */ qulonglong totalDiskSpace() const; /** * Returns the total disk space in a human readable form with value and unit * (e.g. 10 KiB, 25 MiB, etc.) even if the total disk space was not set or could * not be determined. If the value is a valid one, you have to check by evaluating * the return value of the isInaccessible() function. * * @returns the total disk space in a human readable form. */ QString totalDiskSpaceString() const; /** * Sets the value of the free disk space that is available on the share. If * the free disk space could not be determined, @p size has to be set to 0. * * @param free The free disk space that is available on the share */ void setFreeDiskSpace(qulonglong size); /** * Returns the free disk space that is available on the share or 0 if the * free disk space was not set or could not be determined. * * @returns the free disk space or 0. */ qulonglong freeDiskSpace() const; /** * Returns the free disk space in a human readable form with value and unit * (e.g. 10 KiB, 25 MiB, etc.) even if the free disk space was not set or could * not be determined. If the value is a valid one, you have to check by evaluating * the return value of the isInaccessible() function. * * @returns the free disk space in a human readable form. */ QString freeDiskSpaceString() const; /** * Sets the value of the disk space that is used on the share. If the used * disk space could not be determined, @p size has to be set to 0. * * @param free The free disk space that is available on the share */ void setUsedDiskSpace(qulonglong size); /** * Returns the used disk space that is used on the share or 0 if the * used disk space was not set or could not be determined. * * @returns the used disk space or 0. */ qulonglong usedDiskSpace() const; /** * Returns the used disk space in a human readable form with value and unit * (e.g. 10 KiB, 25 MiB, etc.) even if the used disk space was not set or could * not be determined. If the value is a valid one, you have to check by evaluating * the return value of the isInaccessible() function. * * @returns the used disk space in a human readable form. */ QString usedDiskSpaceString() const; /** * Returns the disk usage in percent. * @returns the disk usage in percent. */ qreal diskUsage() const; /** * Returns the disk usage in a human readable form with value and unit, * for example 3.5 %, 67.0 % etc. If the usage was not set or could not * be determined, this function returns an empty string. * * @returns the disk usage in a human readable form or an empty string. */ QString diskUsageString() const; /** * If this share was mounted, set @p mounted to TRUE. This function will not * work with printer shares. * * @param mounted Should be set to TRUE if the share was mounted. */ void setMounted(bool mounted); /** * This function returns TRUE if the share has been mounted and FALSE * otherwise. * * @returns TRUE if this share was mounted. */ bool isMounted() const; /** * This convenience function sets the mount related data that is copied * from @p share. * * @param share The share object from where the mount related * data should be copied. */ void setMountData(Smb4KShare *share); /** * This convenience function resets the mount related data. */ void resetMountData(); /** * Returns TRUE if the share is or *was* a 'homes' share. That means that * this value is not changed when the share name is changed. * * @returns TRUE if this is or *was* a 'homes' share and FALSE otherwise. */ bool isHomesShare() const; /** * Set the port for the use in the UNC. * * @param port The port */ void setPort(int port); /** * Returns the port that is used in the UNC. * * @returns the port. */ int port() const; /** * Set the authentication information for the share. This function will add * the authentication information to the URL of the share. Any previous * user information including the login will be overwritten. * * @param authInfo The authentication information */ void setAuthInfo(Smb4KAuthInfo *authInfo); /** * Set the login for the share. This function will add the login name * to the URL of the share. * * @param login The login name */ void setLogin(const QString &login); /** * Returns the login. * * @returns the login. */ QString login() const; /** * Set the password used for authentication. * * @param passwd The password */ void setPassword(const QString &passwd); /** * Returns the password. * * @returns the password. */ QString password() const; /** * Updates the share item if the workgroup name and the UNC of @p share and * of this item is equal. Otherwise it does nothing. * @param share The share object that is used to update * this object */ void update(Smb4KShare *share); private: const QScopedPointer d; /** * Set up the shares icon. */ void setShareIcon(); }; #endif diff --git a/core/smb4ksynchronizer.cpp b/core/smb4ksynchronizer.cpp index 45257a3..79285ef 100644 --- a/core/smb4ksynchronizer.cpp +++ b/core/smb4ksynchronizer.cpp @@ -1,174 +1,170 @@ /*************************************************************************** This is the new synchronizer of Smb4K. ------------------- begin : Fr Feb 04 2011 copyright : (C) 2011-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4ksynchronizer.h" #include "smb4ksynchronizer_p.h" #include "smb4knotification.h" #include "smb4kglobal.h" #include "smb4kshare.h" // Qt includes #include #include #include #include #include // KDE includes #include using namespace Smb4KGlobal; Q_GLOBAL_STATIC(Smb4KSynchronizerStatic, p); Smb4KSynchronizer::Smb4KSynchronizer(QObject *parent) : KCompositeJob(parent), d(new Smb4KSynchronizerPrivate) { setAutoDelete(false); connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), SLOT(slotAboutToQuit())); } Smb4KSynchronizer::~Smb4KSynchronizer() { } Smb4KSynchronizer *Smb4KSynchronizer::self() { return &p->instance; } void Smb4KSynchronizer::synchronize(const SharePtr &share) { if (!isRunning(share)) { // Create a new job, add it to the subjobs and register it // with the job tracker. Smb4KSyncJob *job = new Smb4KSyncJob(this); job->setObjectName(QString("SyncJob_%1").arg(share->canonicalPath())); job->setupSynchronization(share, QApplication::activeWindow()); connect(job, SIGNAL(result(KJob*)), SLOT(slotJobFinished(KJob*))); connect(job, SIGNAL(aboutToStart(QString)), SIGNAL(aboutToStart(QString))); connect(job, SIGNAL(finished(QString)), SIGNAL(finished(QString))); addSubjob(job); job->start(); } - else - { - // Do nothing - } } bool Smb4KSynchronizer::isRunning() { return hasSubjobs(); } bool Smb4KSynchronizer::isRunning(const SharePtr &share) { bool running = false; for (int i = 0; i < subjobs().size(); ++i) { if (QString::compare(QString("SyncJob_%1").arg(share->canonicalPath()), subjobs().at(i)->objectName()) == 0) { running = true; break; } else { continue; } } return running; } void Smb4KSynchronizer::abort(const SharePtr &share) { if (share) { for (KJob *job : subjobs()) { if (QString("SyncJob_%1").arg(share->canonicalPath()) == job->objectName()) { job->kill(KJob::EmitResult); break; } } } else { QListIterator it(subjobs()); while (it.hasNext()) { it.next()->kill(KJob::EmitResult); } } } void Smb4KSynchronizer::start() { QTimer::singleShot(0, this, SLOT(slotStartJobs())); } ///////////////////////////////////////////////////////////////////////////// // SLOT IMPLEMENTATIONS ///////////////////////////////////////////////////////////////////////////// void Smb4KSynchronizer::slotStartJobs() { // FIXME: Not implemented yet. I do not see a use case at the moment. } void Smb4KSynchronizer::slotJobFinished(KJob *job) { // Remove the job. removeSubjob(job); } void Smb4KSynchronizer::slotAboutToQuit() { abort(); } diff --git a/core/smb4ksynchronizer_p.cpp b/core/smb4ksynchronizer_p.cpp index 75f84f5..1bfa21e 100644 --- a/core/smb4ksynchronizer_p.cpp +++ b/core/smb4ksynchronizer_p.cpp @@ -1,1069 +1,793 @@ /*************************************************************************** This file contains private helper classes for the Smb4KSynchronizer class. ------------------- begin : Fr Okt 24 2008 - copyright : (C) 2008-2017 by Alexander Reinholdt + copyright : (C) 2008-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4ksynchronizer_p.h" #include "smb4knotification.h" #include "smb4ksettings.h" #include "smb4kglobal.h" #include "smb4kshare.h" // Qt includes #include #include #include #include #include #include #include // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include #include #include #include #include using namespace Smb4KGlobal; Smb4KSyncJob::Smb4KSyncJob(QObject *parent) : KJob(parent), m_started(false), m_share(0), m_parent_widget(0), m_process(0) { setCapabilities(KJob::Killable); m_job_tracker = new KUiServerJobTracker(this); } Smb4KSyncJob::~Smb4KSyncJob() { } void Smb4KSyncJob::start() { m_started = true; QTimer::singleShot(0, this, SLOT(slotStartSynchronization())); } void Smb4KSyncJob::setupSynchronization(const SharePtr &share, QWidget *parent) { Q_ASSERT(share); m_share = share; m_parent_widget = parent; } bool Smb4KSyncJob::doKill() { if (m_process && m_process->state() != KProcess::NotRunning) { m_process->abort(); } - else - { - // Do nothing - } return KJob::doKill(); } void Smb4KSyncJob::slotStartSynchronization() { // // Find the shell command // QString rsync = QStandardPaths::findExecutable("rsync"); if (rsync.isEmpty()) { Smb4KNotification::commandNotFound("rsync"); emitResult(); return; } else { // Go ahead } // // The synchronization dialog // if (m_share) { // Show the user an URL input dialog. QPointer dlg = new Smb4KSynchronizationDialog(m_share, m_parent_widget); if (dlg->exec() == QDialog::Accepted) { // Create the destination directory if it does not already exits. if (!QFile::exists(dlg->destination().path())) { QDir syncDir(dlg->destination().path()); if (!syncDir.mkpath(dlg->destination().path())) { Smb4KNotification::mkdirFailed(syncDir); emitResult(); return; } - else - { - // Do nothing - } - } - else - { - // Do nothing } // Make sure that we have got the trailing slash present. // rsync is very picky regarding it. m_src = dlg->source(); m_dest = dlg->destination(); delete dlg; } else { delete dlg; emitResult(); return; } } else { emitResult(); return; } // // The command // QStringList command; command << rsync; command << "--progress"; // // Basic settings // if (Smb4KSettings::archiveMode()) { command << "--archive"; } else { if (Smb4KSettings::recurseIntoDirectories()) { command << "--recursive"; } - else - { - // Do nothing - } if (Smb4KSettings::preserveSymlinks()) { command << "--links"; } - else - { - // Do nothing - } if (Smb4KSettings::preservePermissions()) { command << "--perms"; } - else - { - // Do nothing - } if (Smb4KSettings::preserveTimes()) { command << "--times"; } - else - { - // Do nothing - } if (Smb4KSettings::preserveGroup()) { command << "--group"; } - else - { - // Do nothing - } if (Smb4KSettings::preserveOwner()) { command << "--owner"; } - else - { - // Do nothing - } if (Smb4KSettings::preserveDevicesAndSpecials()) { // Alias -D command << "--devices"; command << "--specials"; } - else - { - // Do nothing - } } if (Smb4KSettings::relativePathNames()) { command << "--relative"; } - else - { - // Do nothing - } if (Smb4KSettings::noImpliedDirectories()) { command << "--no-implied-dirs"; } - else - { - // Do nothing - } if (Smb4KSettings::transferDirectories()) { command << "--dirs"; } - else - { - // Do nothing - } if (Smb4KSettings::makeBackups()) { command << "--backup"; if (Smb4KSettings::useBackupDirectory()) { command << QString("--backup-dir=%1").arg(Smb4KSettings::backupDirectory().path()); } - else - { - // Do nothing - } if (Smb4KSettings::useBackupSuffix()) { command << QString("--suffix=%1").arg(Smb4KSettings::backupSuffix()); } - else - { - // Do nothing - } - } - else - { - // Do nothing } // // File handling // if (Smb4KSettings::updateTarget()) { command << "--update"; } - else - { - // Do nothing - } if (Smb4KSettings::updateInPlace()) { command << "--inplace"; } - else - { - // Do nothing - } if (Smb4KSettings::efficientSparseFileHandling()) { command << "--sparse"; } - else - { - // Do nothing - } if (Smb4KSettings::copyFilesWhole()) { command << "--whole-file"; } - else - { - // Do nothing - } if (Smb4KSettings::updateExisting()) { command << "--existing"; } - else - { - // Do nothing - } if (Smb4KSettings::ignoreExisting()) { command << "--ignore-existing"; } - else - { - // Do nothing - } if (Smb4KSettings::transformSymlinks()) { command << "--copy-links"; } - else - { - // Do nothing - } if (Smb4KSettings::transformUnsafeSymlinks()) { command << "--copy-unsafe-links"; } - else - { - // Do nothing - } if (Smb4KSettings::ignoreUnsafeSymlinks()) { command << "--safe-links"; } - else - { - // Do nothing - } if (Smb4KSettings::mungeSymlinks()) { command << "--munge-links"; } - else - { - // Do nothing - } if (Smb4KSettings::preserveHardLinks()) { command << "--hard-links"; } - else - { - // Do nothing - } if (Smb4KSettings::copyDirectorySymlinks()) { command << "--copy-dirlinks"; } - else - { - // Do nothing - } if (Smb4KSettings::keepDirectorySymlinks()) { command << "--keep-dirlinks"; } - else - { - // Do nothing - } if (Smb4KSettings::omitDirectoryTimes()) { command << "--omit-dir-times"; } - else - { - // Do nothing - } // // File transfer // if (Smb4KSettings::compressData()) { command << "--compress"; if (Smb4KSettings::useCompressionLevel()) { command << QString("--compress-level=%1").arg(Smb4KSettings::compressionLevel()); } - else - { - // Do nothing - } if (Smb4KSettings::useSkipCompression()) { command << QString("--skip-compress=%1").arg(Smb4KSettings::skipCompression()); } - else - { - // Do nothing - } - } - else - { - // Do nothing } if (Smb4KSettings::self()->useMaximalTransferSize()) { command << QString("--max-size=%1K").arg(Smb4KSettings::self()->maximalTransferSize()); } - else - { - // Do nothing - } if (Smb4KSettings::self()->useMinimalTransferSize()) { command << QString("--min-size=%1K").arg(Smb4KSettings::self()->minimalTransferSize()); } - else - { - // Do nothing - } if (Smb4KSettings::keepPartial()) { command << " --partial"; if (Smb4KSettings::usePartialDirectory()) { command << QString("--partial-dir=%1").arg(Smb4KSettings::partialDirectory().path()); } - else - { - // Do nothing - } - } - else - { - // Do nothing } if (Smb4KSettings::useBandwidthLimit()) { command << QString("--bwlimit=%1K").arg(Smb4KSettings::bandwidthLimit()); } - else - { - // Do nothing - } // // File deletion // if (Smb4KSettings::removeSourceFiles()) { command << "--remove-source-files"; } - else - { - // Do nothing - } if (Smb4KSettings::deleteExtraneous()) { command << "--delete"; } - else - { - // Do nothing - } - + if (Smb4KSettings::deleteBefore()) { command << "--delete-before"; } - else - { - // Do nothing - } if (Smb4KSettings::deleteDuring()) { command << "--delete-during"; } - else - { - // Do nothing - } if (Smb4KSettings::deleteAfter()) { command << "--delete-after"; } - else - { - // Do nothing - } if (Smb4KSettings::deleteExcluded()) { command << "--delete-excluded"; } - else - { - // Do nothing - } if (Smb4KSettings::ignoreErrors()) { command << "--ignore-errors"; } - else - { - // Do nothing - } if (Smb4KSettings::forceDirectoryDeletion()) { command << "--force"; } - else - { - // Do nothing - } if (Smb4KSettings::useMaximumDelete()) { command << QString("--max-delete=%1").arg(Smb4KSettings::maximumDeleteValue()); } - else - { - // Do nothing - } // // Filtering // if (Smb4KSettings::useCVSExclude()) { command << "--cvs-exclude"; } - else - { - // Do nothing - } if (Smb4KSettings::useExcludePattern()) { command << QString("--exclude=%1").arg(Smb4KSettings::excludePattern()); } - else - { - // Do nothing - } if (Smb4KSettings::useExcludeFrom()) { command << QString("--exclude-from=%1").arg(Smb4KSettings::excludeFrom().path()); } - else - { - // Do nothing - } if (Smb4KSettings::useIncludePattern()) { command << QString("--include=%1").arg(Smb4KSettings::includePattern()); } - else - { - // Do nothing - } if (Smb4KSettings::useIncludeFrom()) { command << QString("--include-from=%1").arg(Smb4KSettings::includeFrom().path()); } - else - { - // Do nothing - } if (!Smb4KSettings::customFilteringRules().isEmpty()) { qDebug() << "Do we need to spilt the filtering rules into a list?"; command << Smb4KSettings::customFilteringRules(); } - else - { - // Do nothing - } if (Smb4KSettings::useFFilterRule()) { command << "-F"; } - else - { - // Do nothing - } if (Smb4KSettings::useFFFilterRule()) { command << "-F"; command << "-F"; } - else - { - // Do nothing - } // // Miscellaneous // if (Smb4KSettings::useBlockSize()) { command << QString("--block-size=%1").arg(Smb4KSettings::blockSize()); } - else - { - // Do nothing - } if (Smb4KSettings::useChecksumSeed()) { command << QString("--checksum-seed=%1").arg(Smb4KSettings::checksumSeed()); } - else - { - // Do nothing - } if (Smb4KSettings::useChecksum()) { command << "--checksum"; } - else - { - // Do nothing - } if (Smb4KSettings::oneFileSystem()) { command << "--one-file-system"; } - else - { - // Do nothing - } if (Smb4KSettings::delayUpdates()) { command << "--delay-updates"; } - else - { - // Do nothing - } // Make sure that the trailing slash is present. rsync is very // picky regarding it. QString source = m_src.path() + (!m_src.path().endsWith('/') ? "/" : ""); QString destination = m_dest.path() + (!m_dest.path().endsWith('/') ? "/" : ""); command << source; command << destination; // // The job tracker // m_job_tracker->registerJob(this); connect(this, SIGNAL(result(KJob*)), m_job_tracker, SLOT(unregisterJob(KJob*))); // // The process // m_process = new Smb4KProcess(this); m_process->setOutputChannelMode(KProcess::SeparateChannels); m_process->setProgram(command); connect(m_process, SIGNAL(readyReadStandardOutput()), SLOT(slotReadStandardOutput())); connect(m_process, SIGNAL(readyReadStandardError()), SLOT(slotReadStandardError())); connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)), SLOT(slotProcessFinished(int,QProcess::ExitStatus))); // Start the synchronization process emit aboutToStart(m_dest.path()); // Send description to the GUI emit description(this, i18n("Synchronizing"), qMakePair(i18n("Source"), source), qMakePair(i18n("Destination"), destination)); // Dummy to show 0 % emitPercent(0, 100); m_process->start(); } void Smb4KSyncJob::slotReadStandardOutput() { QStringList stdOut = QString::fromUtf8(m_process->readAllStandardOutput(), -1).split('\n', QString::SkipEmptyParts); for (int i = 0; i < stdOut.size(); ++i) { if (stdOut.at(i)[0].isSpace()) { // Get the overall transfer progress if (stdOut.at(i).contains(" to-check=")) { QString tmp = stdOut.at(i).section(" to-check=", 1, 1).section(')', 0, 0).trimmed(); bool success1 = true; bool success2 = true; qulonglong files = tmp.section('/', 0, 0).trimmed().toLongLong(&success1); qulonglong total = tmp.section('/', 1, 1).trimmed().toLongLong(&success2); if (success1 && success2) { setProcessedAmount(KJob::Files, total - files); setTotalAmount(KJob::Files, total); emitPercent(total - files, total); } - else - { - // Do nothing - } } else if (stdOut.at(i).contains(" to-chk=")) { // Make Smb4K work with rsync >= 3.1. QString tmp = stdOut.at(i).section(" to-chk=", 1, 1).section(')', 0, 0).trimmed(); bool success1 = true; bool success2 = true; qulonglong files = tmp.section('/', 0, 0).trimmed().toLongLong(&success1); qulonglong total = tmp.section('/', 1, 1).trimmed().toLongLong(&success2); if (success1 && success2) { setProcessedAmount(KJob::Files, total - files); setTotalAmount(KJob::Files, total); emitPercent(total - files, total); } - else - { - // Do nothing - } } else if (stdOut.at(i).contains(" ir-chk=")) { // Make Smb4K work with rsync >= 3.1. QString tmp = stdOut.at(i).section(" ir-chk=", 1, 1).section(')', 0, 0).trimmed(); bool success1 = true; bool success2 = true; qulonglong files = tmp.section('/', 0, 0).trimmed().toLongLong(&success1); qulonglong total = tmp.section('/', 1, 1).trimmed().toLongLong(&success2); if (success1 && success2) { setProcessedAmount(KJob::Files, total - files); setTotalAmount(KJob::Files, total); emitPercent(total - files, total); } - else - { - // Do nothing - } - } - else - { - // No overall transfer progress can be determined } // Get transfer rate if (stdOut.at(i).contains("/s ", Qt::CaseSensitive)) { bool success = true; double tmp_speed = stdOut.at(i).section(QRegExp("../s"), 0, 0).section(' ', -1 -1).trimmed().toDouble(&success); if (success) { // MB == 1000000 B and kB == 1000 B per definition! if (stdOut.at(i).contains("MB/s")) { tmp_speed *= 1e6; } else if (stdOut.at(i).contains("kB/s")) { tmp_speed *= 1e3; } - else - { - // Do nothing - } ulong speed = (ulong)tmp_speed; emitSpeed(speed /* B/s */); } - else - { - // Do nothing - } - } - else - { - // No transfer rate available } } else if (!stdOut.at(i).contains("sending incremental file list")) { QString file = stdOut.at(i).trimmed(); QUrl src_url = m_src; src_url.setPath(QDir::cleanPath(src_url.path() + '/' + file)); QUrl dest_url = m_dest; dest_url.setPath(QDir::cleanPath(dest_url.path() + '/' + file)); // Send description to the GUI emit description(this, i18n("Synchronizing"), qMakePair(i18n("Source"), src_url.path()), qMakePair(i18n("Destination"), dest_url.path())); } - else - { - // Do nothing - } } } void Smb4KSyncJob::slotReadStandardError() { QString stdErr = QString::fromUtf8(m_process->readAllStandardError(), -1).trimmed(); // Avoid reporting an error if the process was killed by calling the abort() function. if (!m_process->isAborted() && (stdErr.contains("rsync error:") && !stdErr.contains("(code 23)") /*ignore "some files were not transferred" error*/)) { m_process->abort(); Smb4KNotification::synchronizationFailed(m_src, m_dest, stdErr); } else { // Go ahead } } void Smb4KSyncJob::slotProcessFinished(int, QProcess::ExitStatus status) { // Dummy to show 100 % emitPercent(100, 100); // Handle error. switch (status) { case QProcess::CrashExit: { if (!m_process->isAborted()) { Smb4KNotification::processError(m_process->error()); } - else - { - // Do nothing - } break; } default: { break; } } // Finish job emitResult(); emit finished(m_dest.path()); } Smb4KSynchronizationDialog::Smb4KSynchronizationDialog(const SharePtr &share, QWidget *parent) : QDialog(parent), m_share(share) { setWindowTitle(i18n("Synchronization")); QDialogButtonBox *buttonBox = new QDialogButtonBox(Qt::Horizontal, this); m_swap_button = buttonBox->addButton(i18n("Swap Paths"), QDialogButtonBox::ActionRole); m_swap_button->setToolTip(i18n("Swap source and destination")); m_synchronize_button = buttonBox->addButton(i18n("Synchronize"), QDialogButtonBox::ActionRole); m_synchronize_button->setToolTip(i18n("Synchronize the destination with the source")); m_cancel_button = buttonBox->addButton(QDialogButtonBox::Cancel); m_cancel_button->setShortcut(Qt::Key_Escape); m_synchronize_button->setDefault(true); QGridLayout *layout = new QGridLayout(this); layout->setSpacing(5); QLabel *pixmap = new QLabel(this); QPixmap sync_pix = KDE::icon("folder-sync").pixmap(KIconLoader::SizeHuge); pixmap->setPixmap(sync_pix); pixmap->setAlignment(Qt::AlignBottom); QLabel *description = new QLabel(i18n("Please provide the source and destination " "directory for the synchronization."), this); description->setWordWrap(true); description->setAlignment(Qt::AlignBottom); QUrl src_url = QUrl(QDir::cleanPath(m_share->path())); QUrl dest_url = QUrl(QDir::cleanPath(QString("%1/%2/%3").arg(Smb4KSettings::rsyncPrefix().path()) .arg(m_share->hostName()).arg(m_share->shareName()))); QLabel *source_label = new QLabel(i18n("Source:"), this); m_source = new KUrlRequester(this); m_source->setUrl(src_url); m_source->setMode(KFile::Directory | KFile::LocalOnly); m_source->lineEdit()->setSqueezedTextEnabled(true); m_source->completionObject()->setCompletionMode(KCompletion::CompletionPopupAuto); m_source->completionObject()->setMode(KUrlCompletion::FileCompletion); m_source->setWhatsThis(i18n("This is the source directory. The data that it contains is to be written " "to the destination directory.")); QLabel *destination_label = new QLabel(i18n("Destination:"), this); m_destination = new KUrlRequester(this); m_destination->setUrl(dest_url); m_destination->setMode(KFile::Directory | KFile::LocalOnly); m_destination->lineEdit()->setSqueezedTextEnabled(true); m_destination->completionObject()->setCompletionMode(KCompletion::CompletionPopupAuto); m_destination->completionObject()->setMode(KUrlCompletion::FileCompletion); m_destination->setWhatsThis(i18n("This is the destination directory. It will be updated with the data " "from the source directory.")); layout->addWidget(pixmap, 0, 0, 0); layout->addWidget(description, 0, 1, Qt::AlignBottom); layout->addWidget(source_label, 1, 0, 0); layout->addWidget(m_source, 1, 1, 0); layout->addWidget(destination_label, 2, 0, 0); layout->addWidget(m_destination, 2, 1, 0); layout->addWidget(buttonBox, 3, 0, 1, 2, 0); // Connections connect(m_cancel_button, SIGNAL(clicked()), SLOT(slotCancelClicked())); connect(m_synchronize_button, SIGNAL(clicked()), SLOT(slotSynchronizeClicked())); connect(m_swap_button, SIGNAL(clicked()), SLOT(slotSwapPathsClicked())); setMinimumSize((sizeHint().width() > 350 ? sizeHint().width() : 350), sizeHint().height()); create(); KConfigGroup group(Smb4KSettings::self()->config(), "SynchronizationDialog"); KWindowConfig::restoreWindowSize(windowHandle(), group); resize(windowHandle()->size()); // workaround for QTBUG-40584 } Smb4KSynchronizationDialog::~Smb4KSynchronizationDialog() { } const QUrl Smb4KSynchronizationDialog::source() { return m_source->url(); } const QUrl Smb4KSynchronizationDialog::destination() { return m_destination->url(); } ///////////////////////////////////////////////////////////////////////////// // SLOT IMPLEMENTATIONS ///////////////////////////////////////////////////////////////////////////// void Smb4KSynchronizationDialog::slotCancelClicked() { reject(); } void Smb4KSynchronizationDialog::slotSynchronizeClicked() { KConfigGroup group(Smb4KSettings::self()->config(), "SynchronizationDialog"); KWindowConfig::saveWindowSize(windowHandle(), group); accept(); } void Smb4KSynchronizationDialog::slotSwapPathsClicked() { // Swap URLs. QString sourceURL = m_source->url().path(); QString destinationURL = m_destination->url().path(); m_source->setUrl(QUrl(destinationURL)); m_destination->setUrl(QUrl(sourceURL)); } diff --git a/core/smb4ksynchronizer_p.h b/core/smb4ksynchronizer_p.h index fad376c..a0a3fae 100644 --- a/core/smb4ksynchronizer_p.h +++ b/core/smb4ksynchronizer_p.h @@ -1,208 +1,208 @@ /*************************************************************************** This file contains private helper classes for the Smb4KSynchronizer class. ------------------- begin : Fr Okt 24 2008 - copyright : (C) 2008-2017 by Alexander Reinholdt + copyright : (C) 2008-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifndef SMB4KSYNCHRONIZER_P_H #define SMB4KSYNCHRONIZER_P_H // application specific includes #include "smb4ksynchronizer.h" #include "smb4kprocess.h" #include "smb4kglobal.h" // Qt includes #include #include #include // KDE includes #include #include #include class Smb4KSyncJob : public KJob { Q_OBJECT public: /** * Constructor */ explicit Smb4KSyncJob(QObject *parent = 0); /** * Destructor */ ~Smb4KSyncJob(); /** * Returns TRUE if the job was started and FALSE * otherwise * * @returns TRUE if the job was started */ bool isStarted() { return m_started; } /** * Starts the synchronization */ void start(); /** * Setup the synchronization process. You need to set the share, the parent * widget is optional. * * This function must be called before start() is run. * * @param src The source * * @param dest The destination */ void setupSynchronization(const SharePtr &share, QWidget *parent = 0); /** * Returns the source directory. * * @returns the source directory. */ const QUrl &source() { return m_src; } /** * Returns the destination directory. * * @returns the destination directory. */ const QUrl &destination() { return m_dest; } Q_SIGNALS: /** * This signal is emitted when a job is started. The emitted path * is the one of the destination. * * @param dest The destination's URL */ void aboutToStart(const QString &dest); /** * This signal is emitted when a job has finished. The emitted * URL is the one of the destination. * * @param dest The destination's URL */ void finished(const QString &dest); protected: /** * Reimplemented from KJob. Kills the internal process and * then the job itself. */ bool doKill(); protected Q_SLOTS: void slotStartSynchronization(); void slotReadStandardOutput(); void slotReadStandardError(); void slotProcessFinished(int exitCode, QProcess::ExitStatus status); private: bool m_started; SharePtr m_share; QWidget *m_parent_widget; QUrl m_src; QUrl m_dest; Smb4KProcess *m_process; KUiServerJobTracker *m_job_tracker; }; class Smb4KSynchronizationDialog : public QDialog { Q_OBJECT public: /** * The constructor * * @param share The share item * * @param parent The parent widget */ explicit Smb4KSynchronizationDialog(const SharePtr &share, QWidget *parent = 0); /** * The destructor */ ~Smb4KSynchronizationDialog(); /** * The source URL */ const QUrl source(); /** * The destination URL */ const QUrl destination(); protected Q_SLOTS: void slotCancelClicked(); void slotSynchronizeClicked(); void slotSwapPathsClicked(); private: QPushButton *m_swap_button; QPushButton *m_synchronize_button; QPushButton *m_cancel_button; /** * A pointer to the share object */ SharePtr m_share; /** * The source URL requester */ KUrlRequester *m_source; /** * The destination URL requester */ KUrlRequester *m_destination; }; class Smb4KSynchronizerPrivate { }; class Smb4KSynchronizerStatic { public: Smb4KSynchronizer instance; }; #endif diff --git a/core/smb4kwalletmanager.cpp b/core/smb4kwalletmanager.cpp index 50247f4..41cb0d2 100644 --- a/core/smb4kwalletmanager.cpp +++ b/core/smb4kwalletmanager.cpp @@ -1,885 +1,753 @@ /*************************************************************************** This is the wallet manager of Smb4K. ------------------- begin : Sa Dez 27 2008 copyright : (C) 2008-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kwalletmanager.h" #include "smb4kwalletmanager_p.h" #include "smb4ksettings.h" #include "smb4kauthinfo.h" #include "smb4khomesshareshandler.h" #include "smb4kglobal.h" #include "smb4knotification.h" #include "smb4khost.h" #include "smb4kshare.h" // Qt includes #include #include #include // KDE includes using namespace Smb4KGlobal; Q_GLOBAL_STATIC(Smb4KWalletManagerStatic, p); Smb4KWalletManager::Smb4KWalletManager(QObject *parent) : QObject(parent), d(new Smb4KWalletManagerPrivate) { d->wallet = 0; } Smb4KWalletManager::~Smb4KWalletManager() { } Smb4KWalletManager *Smb4KWalletManager::self() { return &p->instance; } void Smb4KWalletManager::init() { if (useWalletSystem()) { // // Get a pointer to the wallet, if we do not have one yet // if (!d->wallet) { // // Open the wallet synchronously. // d->wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(), QApplication::activeWindow() ? QApplication::activeWindow()->winId() : 0); // // Check if the walled was opened successfully and set the // right folder, if it was // if (d->wallet) { if (d->wallet->isOpen()) { if (!d->wallet->hasFolder("Smb4K")) { d->wallet->createFolder("Smb4K"); d->wallet->setFolder("Smb4K"); } else { d->wallet->setFolder("Smb4K"); } } else { Smb4KNotification::credentialsNotAccessible(); } } else { delete d->wallet; d->wallet = 0; Smb4KNotification::openingWalletFailed(KWallet::Wallet::NetworkWallet()); } } - else - { - // Do nothing - } } else { if (d->wallet) { // // Close the wallet, if Smb4K is the only application that // is using it. Thus, use force=false, otherwise it will definitely // be closed. // d->wallet->closeWallet(KWallet::Wallet::NetworkWallet(), false); // // Delete the wallet and set it to 0. // delete d->wallet; d->wallet = 0; } - else - { - // Do nothing - } } emit initialized(); } void Smb4KWalletManager::readAuthInfo(const NetworkItemPtr &networkItem) { // // Only do something, if the networkItem is not null // if (networkItem) { // // Initialize the wallet manager. // init(); // // Proceed if the wallet is open // if (walletIsOpen()) { // // Get the list of entries // QStringList entryList = d->wallet->entryList(); // // Create the map to store the authentication information // QMap authInfoMap; // // Now loop through the stored credentials and make a case insensitive comparison // with the URL of the network item. // for (const QString &entry : entryList) { if (networkItem->type() == Host) { if (QString::compare(entry, networkItem->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0 || QString::compare(entry, networkItem->url().toString(QUrl::RemoveScheme|QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0) { d->wallet->readMap(entry, authInfoMap); break; } - else - { - // Do nothing - } } else if (networkItem->type() == Share) { // // Cast the network item. We need some share specific info // SharePtr share = networkItem.staticCast(); if (share) { // // Process normal and 'homes' shares differently // if (!share->isHomesShare()) { // // Prefer the credentials for the share. Use the ones for the // host as fallback. // if (QString::compare(entry, share->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0 || QString::compare(entry, share->url().toString(QUrl::RemoveScheme|QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0) { d->wallet->readMap(entry, authInfoMap); break; } else if (QString::compare(entry, share->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort|QUrl::RemovePath), Qt::CaseInsensitive) == 0 || QString::compare(entry, share->url().toString(QUrl::RemoveScheme|QUrl::RemoveUserInfo|QUrl::RemovePort|QUrl::RemovePath), Qt::CaseInsensitive) == 0) { d->wallet->readMap(entry, authInfoMap); } - else - { - // Do nothing - } } else { // // Prefer the credentials for the share. Use the ones for the // host as fallback. // if (QString::compare(entry, share->homeUrl().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0 || QString::compare(entry, share->homeUrl().toString(QUrl::RemoveScheme|QUrl::RemoveUserInfo|QUrl::RemovePort), Qt::CaseInsensitive) == 0) { d->wallet->readMap(entry, authInfoMap); break; } else if (QString::compare(entry, share->homeUrl().toString(QUrl::RemoveUserInfo|QUrl::RemovePort|QUrl::RemovePath), Qt::CaseInsensitive) == 0 || QString::compare(entry, share->homeUrl().toString(QUrl::RemoveScheme|QUrl::RemoveUserInfo|QUrl::RemovePort|QUrl::RemovePath), Qt::CaseInsensitive) == 0) { d->wallet->readMap(entry, authInfoMap); } - else - { - // Do nothing - } } } - else - { - // Do nothing - } - } - else - { - // Do nothing } } // // Set the authentication information // if (!authInfoMap.isEmpty()) { switch (networkItem->type()) { case Host: { HostPtr host = networkItem.staticCast(); if (QString::compare(host->workgroupName(), authInfoMap.value("Workgroup"), Qt::CaseInsensitive) == 0) { host->setLogin(authInfoMap.value("Login")); host->setPassword(authInfoMap.value("Password")); } - else - { - // Do nothing - } break; } case Share: { SharePtr share = networkItem.staticCast(); if (QString::compare(share->workgroupName(), authInfoMap.value("Workgroup"), Qt::CaseInsensitive) == 0) { share->setLogin(authInfoMap.value("Login")); share->setPassword(authInfoMap.value("Password")); } - else - { - // Do nothing - } break; } default: { break; } } } else { // // In case the map is empty, set the default login, if it is to be used // if (Smb4KSettings::useDefaultLogin()) { d->wallet->readMap("DEFAULT_LOGIN", authInfoMap); switch (networkItem->type()) { case Host: { HostPtr host = networkItem.staticCast(); host->setLogin(authInfoMap.value("Login")); host->setPassword(authInfoMap.value("Password")); break; } case Share: { SharePtr share = networkItem.staticCast(); share->setLogin(authInfoMap.value("Login")); share->setPassword(authInfoMap.value("Password")); break; } default: { break; } } } - else - { - // Do nothing - } } } - else - { - // Do nothing - } - } - else - { - // Do nothing } } void Smb4KWalletManager::readDefaultAuthInfo(Smb4KAuthInfo *authInfo) { if (authInfo) { // // Initialize the wallet manager. // init(); if (walletIsOpen()) { // // Read the default authentication information from the // wallet. // QMap authInfoMap; d->wallet->readMap("DEFAULT_LOGIN", authInfoMap); if (!authInfoMap.isEmpty()) { authInfo->setUserName(authInfoMap.value("Login")); authInfo->setPassword(authInfoMap.value("Password")); } - else - { - // Do nothing - } - } - else - { - // Do nothing } } - else - { - // Do nothing - } } void Smb4KWalletManager::writeAuthInfo(const NetworkItemPtr &networkItem) { if (networkItem) { // // Initialize the wallet manager. // init(); if (walletIsOpen()) { // // Handle the network item according to its type // switch (networkItem->type()) { case Host: { // // Cast the network item // HostPtr host = networkItem.staticCast(); if (host) { // // Write the authentication information to the wallet, if it // is not empty. // if (!host->login().isEmpty() /* allow empty passwords */ && !host->hostName().isEmpty()) { // // Create the map that carries the authentication information // QMap authInfoMap; // // Insert login and password // authInfoMap.insert("Login", host->login()); authInfoMap.insert("Password", host->password()); // // Enter the workgroup, if it exists // if (!host->workgroupName().isEmpty()) { authInfoMap.insert("Workgroup", host->workgroupName()); } - else - { - // Do nothing - } // // Enter the IP address, if is exists // if (host->hasIpAddress()) { authInfoMap.insert("IP Address", host->ipAddress()); } - else - { - // Do nothing - } // // Write the entry to the wallet // d->wallet->writeMap(host->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), authInfoMap); d->wallet->sync(); } - else - { - // Do nothing - } } - else - { - // Do nothing - } break; } case Share: { // // Cast the network item // SharePtr share = networkItem.staticCast(); if (share) { // // Write the authentication information to the wallet, if it // is not empty. // if (!share->login().isEmpty() /* allow empty passwords */ && !share->hostName().isEmpty()) { // // Create the map that carries the authentication information // QMap authInfoMap; // // Insert login and password // authInfoMap.insert("Login", share->login()); authInfoMap.insert("Password", share->password()); // // Enter the workgroup, if it exists // if (!share->workgroupName().isEmpty()) { authInfoMap.insert("Workgroup", share->workgroupName()); } - else - { - // Do nothing - } // // Enter the IP address, if is exists // if (share->hasHostIpAddress()) { authInfoMap.insert("IP Address", share->hostIpAddress()); } - else - { - // Do nothing - } // // Write the entry to the wallet // if (!share->isHomesShare()) { d->wallet->writeMap(share->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), authInfoMap); } else { d->wallet->writeMap(share->homeUrl().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), authInfoMap); } } - else - { - // Do nothing - } - } - else - { - // Do nothing } break; } default: { break; } } } - else - { - // Do nothing - } - } - else - { - // Do nothing } } void Smb4KWalletManager::writeDefaultAuthInfo(Smb4KAuthInfo *authInfo) { if (authInfo) { // // Initialize the wallet manager. // init(); if (walletIsOpen()) { // // Write the default authentication information to the // wallet. // if (!authInfo->userName().isEmpty() /* allow empty passwords */) { QMap authInfoMap; authInfoMap.insert("Login", authInfo->userName()); authInfoMap.insert("Password", authInfo->password()); d->wallet->writeMap("DEFAULT_LOGIN", authInfoMap); d->wallet->sync(); } - else - { - // Do nothing - } - } - else - { - // Do nothing } } - else - { - // Do nothing - } } bool Smb4KWalletManager::showPasswordDialog(const NetworkItemPtr &networkItem) { // // Define the return value here // bool success = false; // // Check that the network item is not null // if (networkItem) { // // Initialize the wallet manager. // init(); // // Get the known logins (for homes shares) and read the authentication // information. // QMap knownLogins; switch(networkItem->type()) { case Share: { // // Cast the network item // SharePtr share = networkItem.staticCast(); // // If the share is a 'homes' share, read the known logins // for that share. // if (share && share->isHomesShare()) { // // Get the known logins // QStringList users = Smb4KHomesSharesHandler::self()->homesUsers(share); // // Read the authentication information for all known logins // for (const QString &user : users) { // // Create a temp share // SharePtr tempShare = share; // // Set the login // tempShare->setLogin(user); // // Read the authentication information // readAuthInfo(tempShare); // // Save the authentication data in the map // knownLogins.insert(tempShare->login(), tempShare->password()); // // Clear the temp share // tempShare.clear(); } } - else - { - // Do nothing - } break; } default: { readAuthInfo(networkItem); break; } } // // Set up the password dialog and show it // QPointer dlg = new Smb4KPasswordDialog(networkItem, knownLogins, QApplication::activeWindow()); if (dlg->exec() == Smb4KPasswordDialog::Accepted) { // Write the authentication information. writeAuthInfo(networkItem); success = true; } - else - { - // Do nothing - } delete dlg; } - else - { - // Do nothing - } return success; } bool Smb4KWalletManager::useWalletSystem() const { return (KWallet::Wallet::isEnabled() && Smb4KSettings::useWallet()); } QList Smb4KWalletManager::walletEntries() { // // Initialize the wallet manager. // init(); // // Define the return value // QList entries; // // Only read from the wallet if it is open // if (walletIsOpen()) { // // Get all entries from the wallet // QStringList entryList = d->wallet->entryList(); // // Process the entries // for (const QString &entry : entryList) { // // Create a auth info object // Smb4KAuthInfo *authInfo = new Smb4KAuthInfo(); // // Read the authentication information from the wallet // QMap authInfoMap; d->wallet->readMap(entry, authInfoMap); // // Process the entry // if (entry == "DEFAULT_LOGIN") { // // Default login // authInfo->setUserName(authInfoMap.value("Login")); authInfo->setPassword(authInfoMap.value("Password")); } else { // // Entry for a specific URL // authInfo->setUrl(entry); authInfo->setIpAddress(authInfoMap.value("IP Address")); authInfo->setWorkgroupName(authInfoMap.value("Workgroup")); authInfo->setUserName(authInfoMap.value("Login")); authInfo->setPassword(authInfoMap.value("Password")); } entries << authInfo; } } - else - { - // Do nothing - } return entries; } void Smb4KWalletManager::writeWalletEntries(const QList &entries) { // // Initialize the wallet manager. // init(); // // Write the list if the wallet is open // if (walletIsOpen()) { // // First clear the wallet // QStringList entryList = d->wallet->entryList(); for (const QString &entry : entryList) { d->wallet->removeEntry(entry); } // // Now write the new entries to the wallet // for (Smb4KAuthInfo *authInfo : entries) { QMap authInfoMap; if (authInfo->type() == UnknownNetworkItem) { // // Default login // authInfoMap.insert("Login", authInfo->userName()); authInfoMap.insert("Password", authInfo->password()); // // Write the default authentication information to the wallet // d->wallet->writeMap("DEFAULT_LOGIN", authInfoMap); } else { // // Authentication information for a specific URL // authInfoMap.insert("IP Address", authInfo->ipAddress()); authInfoMap.insert("Workgroup", authInfo->workgroupName()); authInfoMap.insert("Login", authInfo->userName()); authInfoMap.insert("Password", authInfo->password()); // // Write the authentication information to the wallet // d->wallet->writeMap(authInfo->url().toString(QUrl::RemoveUserInfo|QUrl::RemovePort), authInfoMap); } // // Sync the entries to disk // d->wallet->sync(); } } - else - { - // Do nothing - } } bool Smb4KWalletManager::walletIsOpen() const { return (d->wallet ? (useWalletSystem() && d->wallet->isOpen()) : false); } diff --git a/core/smb4kwalletmanager_p.cpp b/core/smb4kwalletmanager_p.cpp index 4b22b03..b83f805 100644 --- a/core/smb4kwalletmanager_p.cpp +++ b/core/smb4kwalletmanager_p.cpp @@ -1,153 +1,141 @@ /*************************************************************************** Private helper classes for the wallet manager of Smb4K. ------------------- begin : Mo Dez 31 2012 copyright : (C) 2012-2019 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ // application specific includes #include "smb4kwalletmanager_p.h" #include "smb4khost.h" #include "smb4kshare.h" #include "smb4khomesshareshandler.h" #include "smb4kglobal.h" // Qt includes #include // KDE includes #define TRANSLATION_DOMAIN "smb4k-core" #include using namespace Smb4KGlobal; Smb4KPasswordDialog::Smb4KPasswordDialog(const NetworkItemPtr &networkItem, const QMap &knownLogins, QWidget* parent) : KPasswordDialog(parent, KPasswordDialog::ShowUsernameLine) { m_item = networkItem; switch (m_item->type()) { case Host: { HostPtr host = m_item.staticCast(); if (host) { setUsername(host->login()); setPassword(host->password()); setPrompt(i18n("Please enter a username and a password for the host %1.", host->hostName())); } - else - { - // Do nothing - } + break; } case Share: { SharePtr share = m_item.staticCast(); if (share) { // Enter authentication information into the dialog if (!knownLogins.isEmpty()) { setKnownLogins(knownLogins); } else { setUsername(share->login()); setPassword(share->password()); } if (!share->isHomesShare()) { setPrompt(i18n("Please enter a username and a password for the share %1.", share->displayString())); } else { setPrompt(i18n("Please enter a username and a password for the share %1 on %2.", share->displayString(true))); } } - else - { - // Do nothing - } + break; } default: { break; } } connect(this, SIGNAL(gotUsernameAndPassword(QString,QString,bool)), SLOT(slotGotUsernameAndPassword(QString,QString,bool))); } Smb4KPasswordDialog::~Smb4KPasswordDialog() { } void Smb4KPasswordDialog::slotGotUsernameAndPassword(const QString &user, const QString &pass, bool /*keep*/) { switch (m_item->type()) { case Host: { HostPtr host = m_item.staticCast(); if (host) { host->setLogin(user); host->setPassword(pass); } - else - { - // Do nothing - } + break; } case Share: { SharePtr share = m_item.staticCast(); if (share) { share->setLogin(user); share->setPassword(pass); } - else - { - // Do nothing - } + break; } default: { break; } } } diff --git a/core/smb4kworkgroup.cpp b/core/smb4kworkgroup.cpp index 8a6ed6d..1e9faea 100644 --- a/core/smb4kworkgroup.cpp +++ b/core/smb4kworkgroup.cpp @@ -1,178 +1,170 @@ /*************************************************************************** Smb4K's container class for information about a workgroup. ------------------- begin : Sa Jan 26 2008 copyright : (C) 2008-2017 by Alexander Reinholdt email : alexander.reinholdt@kdemail.net ***************************************************************************/ /*************************************************************************** * 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 Street, Suite 500, Boston,* * MA 02110-1335, USA * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif // application specific includes #include "smb4kworkgroup.h" #include "smb4kglobal.h" // Qt includes #include #include // KDE includes #include using namespace Smb4KGlobal; class Smb4KWorkgroupPrivate { public: QUrl masterURL; QHostAddress masterIP; }; Smb4KWorkgroup::Smb4KWorkgroup(const QString &name) : Smb4KBasicNetworkItem(Workgroup), d(new Smb4KWorkgroupPrivate) { // // Set the URL of the workgroup // pUrl->setScheme("smb"); pUrl->setHost(name); // // Set the icon // *pIcon = KDE::icon("network-workgroup"); } Smb4KWorkgroup::Smb4KWorkgroup(const Smb4KWorkgroup &w) : Smb4KBasicNetworkItem(Workgroup), d(new Smb4KWorkgroupPrivate) { // Copy the private variables // *d = *w.d; // // Set the icon if necessary // if (pIcon->isNull()) { *pIcon = KDE::icon("network-workgroup"); } - else - { - // Do nothing - } } Smb4KWorkgroup::Smb4KWorkgroup() : Smb4KBasicNetworkItem(Workgroup), d(new Smb4KWorkgroupPrivate) { // // Set the URL // pUrl->setScheme("smb"); // // Set the icon // *pIcon = KDE::icon("network-workgroup"); } Smb4KWorkgroup::~Smb4KWorkgroup() { } void Smb4KWorkgroup::setWorkgroupName(const QString &name) { pUrl->setHost(name); pUrl->setScheme("smb"); } QString Smb4KWorkgroup::workgroupName() const { return pUrl->host().toUpper(); } void Smb4KWorkgroup::setMasterBrowserName(const QString &name) { d->masterURL.setHost(name); d->masterURL.setScheme("smb"); } QString Smb4KWorkgroup::masterBrowserName() const { return d->masterURL.host().toUpper(); } void Smb4KWorkgroup::setMasterBrowserIpAddress(const QString &ip) { d->masterIP.setAddress(ip); } void Smb4KWorkgroup::setMasterBrowserIpAddress(const QHostAddress& address) { if (!address.isNull() && address.protocol() != QAbstractSocket::UnknownNetworkLayerProtocol) { d->masterIP = address; } - else - { - // Do nothing - } } QString Smb4KWorkgroup::masterBrowserIpAddress() const { return d->masterIP.toString(); } bool Smb4KWorkgroup::hasMasterBrowserIpAddress() const { return !d->masterIP.isNull(); } void Smb4KWorkgroup::update(Smb4KWorkgroup* workgroup) { if (QString::compare(workgroupName(), workgroup->workgroupName()) == 0) { setMasterBrowserName(workgroup->masterBrowserName()); setMasterBrowserIpAddress(workgroup->masterBrowserIpAddress()); } - else - { - // Do nothing - } + + + + }