Newer
Older
Filipe Marques
committed
* This file is part of the mhwd - Manjaro Hardware Detection project
*
* mhwd - Manjaro Hardware Detection
* Roland Singer <roland@manjaro.org>
* Łukasz Matysiak <december0123@gmail.com>
* Copyright (C) 2007 Free Software Foundation, Inc.
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
bool Mhwd::performTransaction(std::shared_ptr<Config> config, MHWD::TRANSACTIONTYPE transactionType)
Transaction transaction (data_, config, transactionType,
if (MHWD::TRANSACTIONTYPE::INSTALL == transactionType)
{
// Print conflicts
if (!transaction.conflictedConfigs_.empty())
{
std::string conflicts;
for (auto&& conflictedConfig : transaction.conflictedConfigs_)
{
conflicts += " " + conflictedConfig->name_;
}
printer_.printError("config '" + config->name_ + "' conflicts with config(s):" +
conflicts);
for (auto&& dependencyConfig : transaction.dependencyConfigs_)
{
dependencies += " " + dependencyConfig->name_;
}
printer_.printStatus("Dependencies to install:" + dependencies +
"\nProceed with installation? [Y/n]");
std::string input;
std::getline(std::cin, input);
return proceedWithInstallation(input);
else if (MHWD::TRANSACTIONTYPE::REMOVE == transactionType)
{
// Print requirements
if (!transaction.configsRequirements_.empty())
{
std::string requirements;
for (auto&& requirement : transaction.configsRequirements_)
{
requirements += " " + requirement->name_;
}
printer_.printError("config '" + config->name_ + "' is required by config(s):" +
requirements);
MHWD::STATUS status = performTransaction(transaction);
switch (status)
{
case MHWD::STATUS::SUCCESS:
break;
case MHWD::STATUS::ERROR_CONFLICTS:
printer_.printError("config '" + config->name_ +
"' conflicts with installed config(s)!");
break;
case MHWD::STATUS::ERROR_REQUIREMENTS:
printer_.printError("config '" + config->name_ +
"' is required by installed config(s)!");
break;
case MHWD::STATUS::ERROR_NOT_INSTALLED:
printer_.printError("config '" + config->name_ + "' is not installed!");
break;
case MHWD::STATUS::ERROR_ALREADY_INSTALLED:
printer_.printWarning("a version of config '" + config->name_ +
"' is already installed!\nUse -f/--force to force installation...");
break;
case MHWD::STATUS::ERROR_NO_MATCH_LOCAL_CONFIG:
printer_.printError("passed config does not match with installed config!");
break;
case MHWD::STATUS::ERROR_SCRIPT_FAILED:
printer_.printError("script failed!");
break;
case MHWD::STATUS::ERROR_SET_DATABASE:
printer_.printError("failed to set database!");
break;
return (MHWD::STATUS::SUCCESS == status);
bool Mhwd::proceedWithInstallation(const std::string& input) const
if ((input.length() == 1) && (('y' == input[0]) || ('Y' == input[0])))
{
return true;
}
{
return true;
}
else
{
return false;
}
}
dec
committed
std::vector<std::string> Mhwd::checkEnvironment() const
dec
committed
std::vector<std::string> missingDirs;
if (!dirExists(MHWD_USB_CONFIG_DIR))
dec
committed
missingDirs.emplace_back(MHWD_USB_CONFIG_DIR);
if (!dirExists(MHWD_PCI_CONFIG_DIR))
dec
committed
missingDirs.emplace_back(MHWD_PCI_CONFIG_DIR);
if (!dirExists(MHWD_USB_DATABASE_DIR))
dec
committed
missingDirs.emplace_back(MHWD_USB_DATABASE_DIR);
if (!dirExists(MHWD_PCI_DATABASE_DIR))
dec
committed
missingDirs.emplace_back(MHWD_PCI_DATABASE_DIR);
dec
committed
return missingDirs;
std::shared_ptr<Config> Mhwd::getInstalledConfig(const std::string& configName,
std::vector<std::shared_ptr<Config>>* installedConfigs;
{
installedConfigs = &data_.installedUSBConfigs;
}
else
{
installedConfigs = &data_.installedPCIConfigs;
}
auto installedConfig = std::find_if(installedConfigs->begin(), installedConfigs->end(),
[configName](const std::shared_ptr<Config>& config) {
return configName == config->name_;
});
if (installedConfig != installedConfigs->end())
std::shared_ptr<Config> Mhwd::getDatabaseConfig(const std::string& configName,
const std::string& configType)
{
allConfigs = &data_.allUSBConfigs;
}
else
{
allConfigs = &data_.allPCIConfigs;
}
auto config = std::find_if(allConfigs->begin(), allConfigs->end(),
[configName](const std::shared_ptr<Config>& config) {
return config->name_ == configName;
});
if (config != allConfigs->end())
std::shared_ptr<Config> Mhwd::getAvailableConfig(const std::string& configName,
const std::string& configType)
{
devices = &data_.USBDevices;
}
else
{
devices = &data_.PCIDevices;
}
for (auto&& device = devices->begin(); device != devices->end();
auto& availableConfigs = (*device)->availableConfigs_;
auto availableConfig = std::find_if(availableConfigs.begin(), availableConfigs.end(),
[configName](const std::shared_ptr<Config>& config){
return config->name_ == configName;
});
if (availableConfig != availableConfigs.end())
MHWD::STATUS Mhwd::performTransaction(const Transaction& transaction)
if ((MHWD::TRANSACTIONTYPE::INSTALL == transaction.type_) &&
!transaction.conflictedConfigs_.empty())
else if ((MHWD::TRANSACTIONTYPE::REMOVE == transaction.type_)
&& !transaction.configsRequirements_.empty())
{
return MHWD::STATUS::ERROR_REQUIREMENTS;
}
std::shared_ptr<Config> installedConfig{getInstalledConfig(transaction.config_->name_,
transaction.config_->type_)};
if ((MHWD::TRANSACTIONTYPE::REMOVE == transaction.type_)
|| (installedConfig != nullptr && transaction.isAllowedToReinstall()))
if (nullptr == installedConfig)
printer_.printMessage(MHWD::MESSAGETYPE::REMOVE_START, installedConfig->name_);
if (MHWD::STATUS::SUCCESS != (status = uninstallConfig(installedConfig.get())))
printer_.printMessage(MHWD::MESSAGETYPE::REMOVE_END, installedConfig->name_);
if (MHWD::TRANSACTIONTYPE::INSTALL == transaction.type_)
{
// Check if already installed but not allowed to reinstall
if ((nullptr != installedConfig) && !transaction.isAllowedToReinstall())
for (auto&& dependencyConfig = transaction.dependencyConfigs_.end() - 1;
dependencyConfig != transaction.dependencyConfigs_.begin() - 1;
--dependencyConfig)
{
printer_.printMessage(MHWD::MESSAGETYPE::INSTALLDEPENDENCY_START,
(*dependencyConfig)->name_);
if (MHWD::STATUS::SUCCESS != (status = installConfig((*dependencyConfig))))
{
return status;
}
else
{
printer_.printMessage(MHWD::MESSAGETYPE::INSTALLDEPENDENCY_END,
(*dependencyConfig)->name_);
}
}
printer_.printMessage(MHWD::MESSAGETYPE::INSTALL_START, transaction.config_->name_);
if (MHWD::STATUS::SUCCESS != (status = installConfig(transaction.config_)))
{
return status;
}
else
{
printer_.printMessage(MHWD::MESSAGETYPE::INSTALL_END,
transaction.config_->name_);
bool Mhwd::copyDirectory(const std::string& source, const std::string& destination)
if (0 != lstat(destination.c_str(), &filestatus))
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
{
if (!createDir(destination))
{
return false;
}
}
else if (S_ISREG(filestatus.st_mode))
{
return false;
}
else if (S_ISDIR(filestatus.st_mode))
{
if (!removeDirectory(destination))
{
return false;
}
if (!createDir(destination))
{
return false;
}
}
struct dirent *dir;
DIR *d = opendir(source.c_str());
if (!d)
{
return false;
}
while ((dir = readdir(d)) != nullptr)
december0123
committed
std::string filename {dir->d_name};
if (("." == filename) || (".." == filename) || ("" == filename))
std::string sourcePath {source + "/" + filename};
std::string destinationPath {destination + "/" + filename};
if (S_ISREG(filestatus.st_mode))
{
{
success = false;
}
}
else if (S_ISDIR(filestatus.st_mode))
{
{
success = false;
}
}
bool Mhwd::copyFile(const std::string& source, const std::string destination, const mode_t mode)
std::ifstream src(source, std::ios::binary);
std::ofstream dst(destination, std::ios::binary);
dst << src.rdbuf();
mode_t process_mask = umask(0);
chmod(destination.c_str(), mode);
umask(process_mask);
return true;
bool Mhwd::removeDirectory(const std::string& directory)
DIR *d = opendir(directory.c_str());
if (!d)
{
return false;
}
else
{
bool success = true;
struct dirent *dir;
while ((dir = readdir(d)) != nullptr)
{
if (("." == filename) || (".." == filename) || ("" == filename))
std::string filepath {directory + "/" + filename};
struct stat filestatus;
lstat(filepath.c_str(), &filestatus);
if (S_ISREG(filestatus.st_mode))
{
if (0 != unlink(filepath.c_str()))
{
success = false;
}
}
else if (S_ISDIR(filestatus.st_mode))
{
if (!removeDirectory(filepath))
{
success = false;
}
}
}
}
closedir(d);
if (0 != rmdir(directory.c_str()))
{
success = false;
}
return success;
}
dec
committed
bool Mhwd::dirExists(const std::string& path) const
if (0 != stat(path.c_str(), &filestatus))
bool Mhwd::createDir(const std::string& path, const mode_t mode)
mode_t process_mask = umask(0);
int ret = mkdir(path.c_str(), mode);
umask(process_mask);
MHWD::STATUS Mhwd::installConfig(std::shared_ptr<Config> config)
{
databaseDir = MHWD_USB_DATABASE_DIR;
}
else
{
databaseDir = MHWD_PCI_DATABASE_DIR;
}
if (!runScript(config, MHWD::TRANSACTIONTYPE::INSTALL))
{
return MHWD::STATUS::ERROR_SCRIPT_FAILED;
}
if (!copyDirectory(config->basePath_, databaseDir + "/" + config->name_))
{
return MHWD::STATUS::ERROR_SET_DATABASE;
}
// Installed config vectors have to be updated manual with updateInstalledConfigData(Data*)
return MHWD::STATUS::SUCCESS;
}
MHWD::STATUS Mhwd::uninstallConfig(Config *config)
{
std::shared_ptr<Config> installedConfig{getInstalledConfig(config->name_, config->type_)};
if (nullptr == installedConfig)
{
return MHWD::STATUS::ERROR_NOT_INSTALLED;
}
else if (installedConfig->basePath_ != config->basePath_)
{
return MHWD::STATUS::ERROR_NO_MATCH_LOCAL_CONFIG;
}
// TODO: Should we check for local requirements here?
// Run script
if (!runScript(installedConfig, MHWD::TRANSACTIONTYPE::REMOVE))
{
return MHWD::STATUS::ERROR_SCRIPT_FAILED;
}
if (!removeDirectory(installedConfig->basePath_))
{
return MHWD::STATUS::ERROR_SET_DATABASE;
}
// Installed config vectors have to be updated manual with updateInstalledConfigData(Data*)
return MHWD::STATUS::SUCCESS;
}
bool Mhwd::runScript(std::shared_ptr<Config> config, MHWD::TRANSACTIONTYPE operationType)
std::string cmd = "exec " + std::string(MHWD_SCRIPT_PATH);
if (MHWD::TRANSACTIONTYPE::REMOVE == operationType)
{
cmd += " --remove";
}
else
{
cmd += " --install";
}
if (data_.environment.syncPackageManagerDatabase)
{
cmd += " --sync";
}
cmd += " --cachedir \"" + data_.environment.PMCachePath + "\"";
cmd += " --pmconfig \"" + data_.environment.PMConfigPath + "\"";
cmd += " --pmroot \"" + data_.environment.PMRootPath + "\"";
cmd += " --config \"" + config->configPath_ + "\"";
// Set all config devices as argument
std::vector<std::shared_ptr<Device>> foundDevices;
std::vector<std::shared_ptr<Device>> devices;
data_.getAllDevicesOfConfig(config, foundDevices);
for (auto&& foundDevice = foundDevices.begin();
foundDevice != foundDevices.end(); ++foundDevice)
{
bool found = false;
// Check if already in list
for (auto&& dev = devices.begin(); dev != devices.end(); ++dev)
if ((*foundDevice)->sysfsBusID_ == (*dev)->sysfsBusID_
&& (*foundDevice)->sysfsID_ == (*dev)->sysfsID_)
{
found = true;
break;
}
}
if (!found)
{
devices.push_back(std::shared_ptr<Device>{*foundDevice});
for (auto&& dev = devices.begin(); dev != devices.end(); ++dev)
{
std::vector<Vita::string> split = Vita::string(busID).replace(".", ":").explode(":");
if (size >= 3)
{
// Convert to int to remove leading 0
busID = Vita::string::toStr<int>(std::stoi(split[size - 3], nullptr, 16));
busID += ":" + Vita::string::toStr<int>(std::stoi(split[size - 2], nullptr, 16));
busID += ":" + Vita::string::toStr<int>(std::stoi(split[size - 1], nullptr, 16));
cmd += " --device \"" + (*dev)->classID_ + "|" + (*dev)->vendorID_ + "|" + (*dev)->deviceID_
+ "|" + busID + "\"";
}
cmd += " 2>&1";
FILE *in;
if (!(in = popen(cmd.c_str(), "r")))
{
return false;
}
else
{
char buff[512];
while (fgets(buff, sizeof(buff), in) != nullptr)
{
printer_.printMessage(MHWD::MESSAGETYPE::CONSOLE_OUTPUT, buff);
}
int stat = pclose(in);
if (WEXITSTATUS(stat) != 0)
{
return false;
}
else
{
// Only one database sync is required
if (MHWD::TRANSACTIONTYPE::INSTALL == operationType)
{
data_.environment.syncPackageManagerDatabase = false;
}
return true;
}
}
void Mhwd::setVersionMhwd(std::string versionOfSoftware, std::string yearCopyright)
Filipe Marques
committed
{
version_ = versionOfSoftware;
year_ = yearCopyright;
Filipe Marques
committed
}
void Mhwd::tryToParseCmdLineOptions(int argc, char* argv[], bool& autoConfigureNonFreeDriver,
std::string& operationType, std::string& autoConfigureClassID)
{
if (argc <= 1)
{
arguments_.LIST_AVAILABLE = true;
}
for (int nArg = 1; nArg < argc; ++nArg)
{
const std::string option{ argv[nArg] };
if (("-h" == option) || ("--help" == option))
{
printer_.printHelp();
}
Filipe Marques
committed
else if (("-v" == option) || ("--version" == option))
{
printer_.printVersion(version_, year_);
}
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
else if (("-f" == option) || ("--force" == option))
{
arguments_.FORCE = true;
}
else if (("-d" == option) || ("--detail" == option))
{
arguments_.DETAIL = true;
}
else if (("-la" == option) || ("--listall" == option))
{
arguments_.LIST_ALL = true;
}
else if (("-li" == option) || ("--listinstalled" == option))
{
arguments_.LIST_INSTALLED = true;
}
else if (("-l" == option) || ("--list" == option))
{
arguments_.LIST_AVAILABLE = true;
}
else if (("-lh" == option) || ("--listhardware" == option))
{
arguments_.LIST_HARDWARE = true;
}
else if ("--pci" == option)
{
arguments_.SHOW_PCI = true;
}
else if ("--usb" == option)
{
arguments_.SHOW_USB = true;
}
else if (("-a" == option) || ("--auto" == option))
{
if ((nArg + 3) >= argc)
{
throw std::runtime_error{"invalid use of option: -a/--auto\n"};
}
else
{
const std::string deviceType{ argv[nArg + 1] };
const std::string driverType{ argv[nArg + 2] };
const std::string classID{ argv[nArg + 3] };
if ((("pci" != deviceType) && ("usb" != deviceType))
|| (("free" != driverType) && ("nonfree" != driverType)))
{
throw std::runtime_error{"invalid use of option: -a/--auto\n"};
}
else
{
operationType = Vita::string{ deviceType }.toUpper();
autoConfigureNonFreeDriver = ("nonfree" == driverType);
autoConfigureClassID = Vita::string(classID).toLower().trim();
arguments_.AUTOCONFIGURE = true;
nArg += 3;
}
}
}
else if (("-ic" == option) || ("--installcustom" == option))
{
if ((nArg + 1) >= argc)
{
throw std::runtime_error{"invalid use of option: -ic/--installcustom\n"};
}
else
{
const std::string deviceType{ argv[++nArg] };
if (("pci" != deviceType) && ("usb" != deviceType))
{
throw std::runtime_error{"invalid use of option: -ic/--installcustom\n"};
}
else
{
operationType = Vita::string{ deviceType }.toUpper();
arguments_.CUSTOM_INSTALL = true;
}
}
}
else if (("-i" == option) || ("--install" == option))
{
if ((nArg + 1) >= argc)
{
throw std::runtime_error{"invalid use of option: -i/--install\n"};
}
else
{
const std::string deviceType{ argv[++nArg] };
if (("pci" != deviceType) && ("usb" != deviceType))
{
throw std::runtime_error{"invalid use of option: -i/--install\n"};
}
else
{
operationType = Vita::string{ deviceType }.toUpper();
arguments_.INSTALL = true;
}
}
}
else if (("-r" == option) || ("--remove" == option))
{
if ((nArg + 1) >= argc)
{
throw std::runtime_error{"invalid use of option: -r/--remove\n"};
}
else
{
const std::string deviceType{ argv[++nArg] };
if (("pci" != deviceType) && ("usb" != deviceType))
{
throw std::runtime_error{"invalid use of option: -r/--remove\n"};
}
else
{
operationType = Vita::string{ deviceType }.toUpper();
arguments_.REMOVE = true;
}
}
}
else if ("--pmcachedir" == option)
{
if (nArg + 1 >= argc)
{
throw std::runtime_error{"invalid use of option: --pmcachedir\n"};
}
else
{
data_.environment.PMCachePath = Vita::string(argv[++nArg]).trim("\"").trim();
}
}
else if ("--pmconfig" == option)
{
if (nArg + 1 >= argc)
{
throw std::runtime_error{"invalid use of option: --pmconfig\n"};
}
else
{
data_.environment.PMConfigPath = Vita::string(argv[++nArg]).trim("\"").trim();
}
}
else if ("--pmroot" == option)
{
if (nArg + 1 >= argc)
{
throw std::runtime_error{"invalid use of option: --pmroot\n"};
}
else
{
data_.environment.PMRootPath = Vita::string(argv[++nArg]).trim("\"").trim();
}
}
else if (arguments_.INSTALL || arguments_.REMOVE)
{
bool found = false;
std::string name;
if (arguments_.CUSTOM_INSTALL)
{
name = std::string{ argv[nArg] };
}
else
{
name = Vita::string(argv[nArg]).toLower();
}
for (const auto& config : configs_)
{
if (config == name)
{
found = true;
break;
}
}
if (!found)
{
configs_.push_back(name);
}
}
else
{
throw std::runtime_error{"invalid option: " + std::string(argv[nArg]) + "\n"};
}
}
if (!arguments_.SHOW_PCI && !arguments_.SHOW_USB)
{
arguments_.SHOW_USB = true;
arguments_.SHOW_PCI = true;
}
}
bool Mhwd::optionsDontInterfereWithEachOther() const
{
if (arguments_.INSTALL && arguments_.REMOVE)
{
printer_.printError("install and remove options can only be used separately!\n");
printer_.printHelp();
return false;
}
else if ((arguments_.INSTALL || arguments_.REMOVE) && arguments_.AUTOCONFIGURE)
{
printer_.printError("auto option can't be combined with install and remove options!\n");
printer_.printHelp();
return false;
}
else if ((arguments_.REMOVE || arguments_.INSTALL) && configs_.empty())
{
printer_.printError("nothing to do?!\n");
printer_.printHelp();
return false;
}
return true;
}
dec
committed
std::vector<std::string> missingDirs { checkEnvironment() };
if (!missingDirs.empty())
{
printer_.printError("Following directories do not exist:");
for (const auto& dir : missingDirs)
{
printer_.printStatus(dir);
}
return 1;
}
bool autoConfigureNonFreeDriver = false;
tryToParseCmdLineOptions(argc, argv, autoConfigureNonFreeDriver, operationType,
autoConfigureClassID);
catch(const std::runtime_error& e)
printer_.printError(e.what());
printer_.printHelp();
return 1;
if (!optionsDontInterfereWithEachOther())
for (auto&& invalidConfig : data_.invalidConfigs)
{
printer_.printWarning("config '" + invalidConfig->configPath_ + "' is invalid!");
}
// > Perform operations:
// List all configs
if (arguments_.LIST_ALL && arguments_.SHOW_PCI)
if (!data_.allPCIConfigs.empty())
{
printer_.listConfigs(data_.allPCIConfigs, "All PCI configs:");
}
else
{
printer_.printWarning("No PCI configs found!");
}
if (arguments_.LIST_ALL && arguments_.SHOW_USB)
if (!data_.allUSBConfigs.empty())
{
printer_.listConfigs(data_.allUSBConfigs, "All USB configs:");
}
else
{
printer_.printWarning("No USB configs found!");
}
if (arguments_.LIST_INSTALLED && arguments_.SHOW_PCI)
{
printer_.printInstalledConfigs("PCI", data_.installedPCIConfigs);
}
else