id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,538,699
string_list_edit.cpp
altlinux_admc/src/admc/attribute_edits/string_list_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/string_list_edit.h" #include "adldap.h" #include "attribute_dialogs/list_attribute_dialog.h" #include "utils.h" #include <QPushButton> StringListEdit::StringListEdit(QPushButton *button_arg, const QString &attribute_arg, QObject *parent) : AttributeEdit(parent) { button = button_arg; attribute = attribute_arg; connect( button, &QPushButton::clicked, this, &StringListEdit::on_button); } void StringListEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); values = object.get_values(attribute); } bool StringListEdit::apply(AdInterface &ad, const QString &dn) const { const bool success = ad.attribute_replace_values(dn, attribute, values); return success; } void StringListEdit::on_button() { const bool read_only = false; auto dialog = new ListAttributeDialog(values, attribute, read_only, button); dialog->setWindowTitle(tr("Edit values")); dialog->open(); connect( dialog, &QDialog::accepted, this, [this, dialog]() { values = dialog->get_value_list(); emit edited(); }); }
1,928
C++
.cpp
53
32.54717
102
0.71766
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,700
account_option_multi_edit.cpp
altlinux_admc/src/admc/attribute_edits/account_option_multi_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/account_option_multi_edit.h" #include "adldap.h" #include "attribute_edits/account_option_edit.h" #include "globals.h" #include <QCheckBox> AccountOptionMultiEdit::AccountOptionMultiEdit(const QHash<AccountOption, QCheckBox *> &check_map_arg, QObject *parent) : AttributeEdit(parent) { check_map = check_map_arg; account_option_setup_conflicts(check_map); } // NOTE: this is slightly inefficient because every account // option bit is changed with one request, when the whole // bitmask can be changed at the same time. BUT, do need to // do this if want to get separate status messages for each // bit. bool AccountOptionMultiEdit::apply(AdInterface &ad, const QString &target) const { const QList<AccountOption> option_change_list = [&]() { QList<AccountOption> out; const AdObject object = ad.search_object(target); for (const AccountOption &option : check_map.keys()) { QCheckBox *check = check_map[option]; const bool current_option_state = object.get_account_option(option, g_adconfig); const bool new_option_state = check->isChecked(); const bool option_changed = (new_option_state != current_option_state); if (option_changed) { out.append(option); } } return out; }(); bool total_success = true; for (const AccountOption &option : option_change_list) { QCheckBox *check = check_map[option]; const bool option_is_set = check->isChecked(); const bool success = ad.user_set_account_option(target, option, option_is_set); if (!success) { total_success = false; } } return total_success; } void AccountOptionMultiEdit::set_enabled(const bool enabled) { for (QCheckBox *check : check_map.values()) { check->setEnabled(enabled); } }
2,679
C++
.cpp
65
36.184615
119
0.698999
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,701
manager_widget.cpp
altlinux_admc/src/admc/attribute_edits/manager_widget.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/manager_widget.h" #include "attribute_edits/ui_manager_widget.h" #include "adldap.h" #include "globals.h" #include "properties_widgets/properties_dialog.h" #include "select_dialogs/select_object_dialog.h" #include "utils.h" ManagerWidget::ManagerWidget(QWidget *parent) : QWidget(parent) { ui = new Ui::ManagerWidget(); ui->setupUi(this); ui->manager_display->setReadOnly(true); connect( ui->change_button, &QPushButton::clicked, this, &ManagerWidget::on_change); connect( ui->properties_button, &QPushButton::clicked, this, &ManagerWidget::on_properties); connect( ui->clear_button, &QPushButton::clicked, this, &ManagerWidget::on_clear); } ManagerWidget::~ManagerWidget() { delete ui; } void ManagerWidget::set_attribute(const QString &attribute) { manager_attribute = attribute; } void ManagerWidget::load(const AdObject &object) { const QString manager = object.get_string(manager_attribute); load_value(manager); } bool ManagerWidget::apply(AdInterface &ad, const QString &dn) const { const bool success = ad.attribute_replace_string(dn, manager_attribute, current_value); return success; } QString ManagerWidget::get_manager() const { return current_value; } void ManagerWidget::reset() { ui->manager_display->setText(QString()); } void ManagerWidget::on_change() { auto dialog = new SelectObjectDialog({CLASS_USER, CLASS_CONTACT}, SelectObjectDialogMultiSelection_No, ui->manager_display); dialog->setWindowTitle(tr("Change Manager")); connect( dialog, &SelectObjectDialog::accepted, this, [this, dialog]() { const QList<QString> selected = dialog->get_selected(); load_value(selected[0]); emit edited(); }); dialog->open(); } void ManagerWidget::on_properties() { AdInterface ad; if (ad_failed(ad, this)) { return; } PropertiesDialog::open_for_target(ad, current_value); } void ManagerWidget::on_clear() { load_value(QString()); emit edited(); } void ManagerWidget::load_value(const QString &value) { current_value = value; const QString name = dn_get_name(current_value); ui->manager_display->setText(name); const bool have_manager = !current_value.isEmpty(); ui->properties_button->setEnabled(have_manager); ui->clear_button->setEnabled(have_manager); }
3,233
C++
.cpp
93
30.677419
128
0.713323
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,702
manager_edit.cpp
altlinux_admc/src/admc/attribute_edits/manager_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/manager_edit.h" #include "adldap.h" #include "attribute_edits/manager_widget.h" #include "globals.h" #include "utils.h" ManagerEdit::ManagerEdit(ManagerWidget *widget_arg, const QString &manager_attribute_arg, QObject *parent) : AttributeEdit(parent) { manager_attribute = manager_attribute_arg; widget = widget_arg; widget->set_attribute(manager_attribute_arg); connect( widget, &ManagerWidget::edited, this, &AttributeEdit::edited); } void ManagerEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); widget->load(object); } bool ManagerEdit::apply(AdInterface &ad, const QString &dn) const { return widget->apply(ad, dn); } void ManagerEdit::set_enabled(const bool enabled) { widget->setEnabled(enabled); } QString ManagerEdit::get_manager() const { return widget->get_manager(); }
1,663
C++
.cpp
46
33.413043
106
0.745488
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,703
country_edit.cpp
altlinux_admc/src/admc/attribute_edits/country_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/country_edit.h" #include "adldap.h" #include "attribute_edits/country_combo.h" #include "globals.h" #include "utils.h" #include <QComboBox> CountryEdit::CountryEdit(QComboBox *combo_arg, QObject *parent) : AttributeEdit(parent) { combo = combo_arg; country_combo_init(combo); connect( combo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AttributeEdit::edited); } void CountryEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); country_combo_load(combo, object); } bool CountryEdit::apply(AdInterface &ad, const QString &dn) const { return country_combo_apply(combo, ad, dn); } void CountryEdit::set_enabled(const bool enabled) { combo->setEnabled(enabled); }
1,546
C++
.cpp
43
33.27907
72
0.744809
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,704
delegation_edit.cpp
altlinux_admc/src/admc/attribute_edits/delegation_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/delegation_edit.h" #include "adldap.h" #include "globals.h" #include "utils.h" #include <QRadioButton> DelegationEdit::DelegationEdit(QRadioButton *off_button_arg, QRadioButton *on_button_arg, QObject *parent) : AttributeEdit(parent) { off_button = off_button_arg; on_button = on_button_arg; connect( off_button, &QAbstractButton::clicked, this, &AttributeEdit::edited); connect( on_button, &QAbstractButton::clicked, this, &AttributeEdit::edited); } void DelegationEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); const bool is_on = object.get_account_option(AccountOption_TrustedForDelegation, g_adconfig); if (is_on) { on_button->setChecked(true); } else { off_button->setChecked(true); } } bool DelegationEdit::apply(AdInterface &ad, const QString &dn) const { const bool is_on = [&]() { if (on_button->isChecked()) { return true; } else if (off_button->isChecked()) { return false; } return false; }(); const bool success = ad.user_set_account_option(dn, AccountOption_TrustedForDelegation, is_on); return success; }
2,011
C++
.cpp
56
31.589286
106
0.702007
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,705
dn_edit.cpp
altlinux_admc/src/admc/attribute_edits/dn_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2021 BaseALT Ltd. * Copyright (C) 2020-2021 Dmitry Degtyarev * * 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 "attribute_edits/dn_edit.h" #include "adldap.h" #include "utils.h" #include <QLineEdit> DNEdit::DNEdit(QLineEdit *edit_arg, QObject *parent) : AttributeEdit(parent) { edit = edit_arg; limit_edit(edit, ATTRIBUTE_DN); connect( edit, &QLineEdit::textChanged, this, &AttributeEdit::edited); } void DNEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); const QString dn = object.get_dn(); const QString dn_as_canonical = dn_canonical(dn); edit->setText(dn_as_canonical); }
1,322
C++
.cpp
37
32.810811
72
0.731191
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,706
country_combo.cpp
altlinux_admc/src/admc/attribute_edits/country_combo.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/country_combo.h" #include "adldap.h" #include "globals.h" #include "settings.h" #include "status.h" #include "utils.h" #include <QComboBox> #include <QDebug> #include <QFile> #include <QHash> #include <algorithm> #define COUNTRY_CODE_NONE 0 bool loaded_country_data = false; QHash<QString, int> string_to_code; QHash<int, QString> country_strings; QHash<int, QString> country_strings_ru; QHash<int, QString> country_abbreviations; QHash<QString, int> abbreviation_to_code; enum CountryColumn { CountryColumn_Country, CountryColumn_CountryRu, CountryColumn_Abbreviation, CountryColumn_Code, CountryColumn_COUNT, }; void country_combo_load_data() { if (loaded_country_data) { qDebug() << "ERROR: Attempted to load country data more than once"; return; } QFile file(":/admc/countries.csv"); if (!file.open(QIODevice::ReadOnly)) { qDebug() << "ERROR: Failed to load countries file!\n"; return; } else { // Load countries csv into maps. Map country code to // country string and country abbreviation // Skip header file.readLine(); while (!file.atEnd()) { const QByteArray line_array = file.readLine(); const QString line = QString(line_array); // Split line by comma's, taking into // account that some comma's are inside // quoted parts and ignoring those. // // NOTE: there's definitely a better way to // do this const QList<QString> line_split = [&]() -> QList<QString> { if (line.contains('\"')) { QList<QString> split_by_quotes = line.split('\"'); split_by_quotes.removeAll(""); if (split_by_quotes.size() == 2) { QList<QString> split_rest = split_by_quotes[1].split(','); split_rest.removeAll(""); QList<QString> out; out.append(split_by_quotes[0]); out.append(split_rest); return out; } else { return QList<QString>(); } } else { return line.split(','); } }(); if (line_split.size() != CountryColumn_COUNT) { qDebug() << "country.csv contains malformed line: " << line; continue; } const QString country_string = line_split[CountryColumn_Country]; const QString country_string_ru = line_split[CountryColumn_CountryRu]; const QString abbreviation = line_split[CountryColumn_Abbreviation]; const QString code_string = line_split[CountryColumn_Code]; const int code = code_string.toInt(); country_strings[code] = country_string; country_strings_ru[code] = country_string_ru; country_abbreviations[code] = abbreviation; abbreviation_to_code[abbreviation] = code; string_to_code[country_string] = code; } file.close(); } loaded_country_data = true; } void country_combo_init(QComboBox *combo) { const QHash<int, QString> name_map = [&]() { const bool locale_is_ru = [&]() { const QLocale locale = settings_get_variant(SETTING_locale).toLocale(); const bool out = (locale.language() == QLocale::Russian); return out; }(); if (locale_is_ru) { return country_strings_ru; } else { return country_strings; } }(); // Generate order of countries that will be used to // fill the combo. // // NOTE: modify order of countries in the combo to // put a particular country at the top of the list. // If this program ever happens to be used outside // of that particular country, there is a feature // flag "SETTING_feature_current_locale_first". const QList<QString> country_list = [&]() { const QString country_russia = [&]() { const QLocale top_locale = [&]() { const bool current_locale_first = settings_get_variant(SETTING_feature_current_locale_first).toBool(); if (current_locale_first) { const QLocale current_locale = settings_get_variant(SETTING_locale).toLocale(); return current_locale; } else { const QLocale russia_locale = QLocale(QLocale::Russian, QLocale::Russia); return russia_locale; } }(); const QString locale_name = top_locale.name(); const QList<QString> locale_name_split = locale_name.split("_"); if (locale_name_split.size() == 2) { const QString abbreviation = locale_name_split[1]; const int code = abbreviation_to_code[abbreviation]; const QString country_name = name_map[code]; return country_name; } else { return QString(); } }(); QList<QString> out = name_map.values(); std::sort(out.begin(), out.end()); out.removeAll(country_russia); out.prepend(country_russia); return out; }(); // Add "None" at the start combo->addItem(QCoreApplication::translate("country_widget", "None"), COUNTRY_CODE_NONE); for (const QString &country : country_list) { const int code = name_map.key(country); combo->addItem(country, code); } } void country_combo_load(QComboBox *combo, const AdObject &object) { const int country_code = [object]() { if (object.contains(ATTRIBUTE_COUNTRY_CODE)) { return object.get_int(ATTRIBUTE_COUNTRY_CODE); } else { return COUNTRY_CODE_NONE; } }(); const int index = combo->findData(QVariant(country_code)); if (index != -1) { combo->setCurrentIndex(index); } } bool country_combo_apply(const QComboBox *combo, AdInterface &ad, const QString &dn) { const int code = combo->currentData().toInt(); // NOTE: this handles the COUNTRY_CODE_NONE case by // using empty strings for it's values const QString code_string = QString::number(code); const QString country_string = country_strings.value(code, QString()); const QString abbreviation = country_abbreviations.value(code, QString()); bool success = true; success = success && ad.attribute_replace_string(dn, ATTRIBUTE_COUNTRY_CODE, code_string); success = success && ad.attribute_replace_string(dn, ATTRIBUTE_COUNTRY_ABBREVIATION, abbreviation); success = success && ad.attribute_replace_string(dn, ATTRIBUTE_COUNTRY, country_string); return success; }
7,711
C++
.cpp
187
32.251337
118
0.609277
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,707
group_type_edit.cpp
altlinux_admc/src/admc/attribute_edits/group_type_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/group_type_edit.h" #include "adldap.h" #include "utils.h" #include <QComboBox> GroupTypeEdit::GroupTypeEdit(QComboBox *combo_arg, QObject *parent) : AttributeEdit(parent) { combo = combo_arg; for (int i = 0; i < GroupType_COUNT; i++) { const GroupType type = (GroupType) i; const QString type_string = group_type_string(type); combo->addItem(type_string, (int) type); } connect( combo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AttributeEdit::edited); } void GroupTypeEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); const GroupType type = object.get_group_type(); combo->setCurrentIndex((int) type); const bool is_critical_system_object = object.get_bool(ATTRIBUTE_IS_CRITICAL_SYSTEM_OBJECT); if (is_critical_system_object) { combo->setDisabled(true); } } bool GroupTypeEdit::apply(AdInterface &ad, const QString &dn) const { const GroupType new_value = (GroupType) combo->currentData().toInt(); const bool success = ad.group_set_type(dn, new_value); return success; }
1,923
C++
.cpp
49
35.55102
96
0.719892
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,708
expiry_widget.cpp
altlinux_admc/src/admc/attribute_edits/expiry_widget.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/expiry_widget.h" #include "attribute_edits/ui_expiry_widget.h" #include "adldap.h" #include "globals.h" #include <QButtonGroup> const QTime END_OF_DAY(23, 59); ExpiryWidget::ExpiryWidget(QWidget *parent) : QWidget(parent) { ui = new Ui::ExpiryWidget(); ui->setupUi(this); auto button_group = new QButtonGroup(this); button_group->addButton(ui->never_check); button_group->addButton(ui->end_of_check); connect( ui->never_check, &QRadioButton::toggled, this, &ExpiryWidget::on_never_check); connect( ui->end_of_check, &QRadioButton::toggled, this, &ExpiryWidget::on_end_of_check); connect( ui->date_edit, &QDateEdit::dateChanged, this, &ExpiryWidget::edited); } ExpiryWidget::~ExpiryWidget() { delete ui; } void ExpiryWidget::load(const AdObject &object) { const bool never = [object]() { const QString expiry_string = object.get_string(ATTRIBUTE_ACCOUNT_EXPIRES); return large_integer_datetime_is_never(expiry_string); }(); if (never) { ui->never_check->setChecked(true); ui->end_of_check->setChecked(false); ui->date_edit->setEnabled(false); } else { ui->never_check->setChecked(false); ui->end_of_check->setChecked(true); ui->date_edit->setEnabled(true); } const QDate date = [=]() { if (never) { // Default to current date when expiry is never return QDate::currentDate(); } else { const QDateTime datetime = object.get_datetime(ATTRIBUTE_ACCOUNT_EXPIRES, g_adconfig); return datetime.date(); } }(); ui->date_edit->setDate(date); } bool ExpiryWidget::apply(AdInterface &ad, const QString &dn) const { const bool never = ui->never_check->isChecked(); if (never) { return ad.attribute_replace_string(dn, ATTRIBUTE_ACCOUNT_EXPIRES, AD_LARGE_INTEGER_DATETIME_NEVER_2); } else { const QDateTime datetime = QDateTime(ui->date_edit->date(), END_OF_DAY, Qt::UTC); return ad.attribute_replace_datetime(dn, ATTRIBUTE_ACCOUNT_EXPIRES, datetime); } } void ExpiryWidget::on_never_check() { if (ui->never_check->isChecked()) { ui->date_edit->setEnabled(false); emit edited(); } } void ExpiryWidget::on_end_of_check() { if (ui->end_of_check->isChecked()) { ui->date_edit->setEnabled(true); emit edited(); } }
3,257
C++
.cpp
91
30.626374
109
0.672178
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,709
account_option_edit.cpp
altlinux_admc/src/admc/attribute_edits/account_option_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/account_option_edit.h" #include "adldap.h" #include "globals.h" #include "utils.h" #include <QCheckBox> #include <QFormLayout> #include <QGroupBox> #include <QMap> AccountOptionEdit::AccountOptionEdit(QCheckBox *check_arg, const AccountOption option_arg, QObject *parent) : AttributeEdit(parent) { option = option_arg; check = check_arg; connect( check, &QCheckBox::stateChanged, this, &AttributeEdit::edited); } void AccountOptionEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); const bool option_is_set = object.get_account_option(option, g_adconfig); check->setChecked(option_is_set); } bool AccountOptionEdit::apply(AdInterface &ad, const QString &dn) const { const bool new_value = check->isChecked(); const bool success = ad.user_set_account_option(dn, option, new_value); return success; } // PasswordExpired conflicts with (DontExpirePassword and // CantChangePassword) When PasswordExpired is set, the // other two can't be set When any of the other two are set, // PasswordExpired can't be set Implement this by connecting // to state changes of all options and resetting to previous // state if state transition is invalid void account_option_setup_conflicts(const QHash<AccountOption, QCheckBox *> &check_map) { auto setup_conflict = [&](const AccountOption subject_option, const AccountOption blocker_option) { if (!check_map.contains(subject_option) || !check_map.contains(blocker_option)) { return; } QCheckBox *subject = check_map[subject_option]; QCheckBox *blocker = check_map[blocker_option]; QObject::connect( subject, &QCheckBox::clicked, blocker, [subject, blocker, subject_option, blocker_option]() { const bool conflict = (subject->isChecked() && blocker->isChecked()); if (conflict) { subject->setChecked(false); const QString subject_name = account_option_string(subject_option); const QString blocker_name = account_option_string(blocker_option); const QString error = QString(QObject::tr("Can't set \"%1\" when \"%2\" is set.")).arg(subject_name, blocker_name); message_box_warning(blocker, QObject::tr("Error"), error); } }); }; const QList<AccountOption> other_two_options = { AccountOption_DontExpirePassword, AccountOption_CantChangePassword, }; for (auto other_option : other_two_options) { setup_conflict(AccountOption_PasswordExpired, other_option); setup_conflict(other_option, AccountOption_PasswordExpired); } }
3,542
C++
.cpp
81
37.925926
135
0.695879
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,710
laps_expiry_edit.cpp
altlinux_admc/src/admc/attribute_edits/laps_expiry_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/laps_expiry_edit.h" #include "adldap.h" #include "globals.h" #include "utils.h" #include <QDateTimeEdit> #include <QPushButton> LAPSExpiryEdit::LAPSExpiryEdit(QDateTimeEdit *edit_arg, QPushButton *reset_expiry_button, QObject *parent) : AttributeEdit(parent) { edit = edit_arg; connect( edit, &QDateTimeEdit::dateTimeChanged, this, &AttributeEdit::edited); connect( reset_expiry_button, &QPushButton::clicked, this, &LAPSExpiryEdit::reset_expiry); } void LAPSExpiryEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); const QDateTime datetime = object.get_datetime(ATTRIBUTE_LAPS_EXPIRATION, g_adconfig); const QDateTime datetime_local = datetime.toLocalTime(); edit->setDateTime(datetime_local); } bool LAPSExpiryEdit::apply(AdInterface &ad, const QString &dn) const { const QDateTime datetime_local = edit->dateTime(); const QDateTime datetime = datetime_local.toUTC(); const bool success = ad.attribute_replace_datetime(dn, ATTRIBUTE_LAPS_EXPIRATION, datetime); return success; } void LAPSExpiryEdit::reset_expiry() { const QDateTime current_datetime_local = QDateTime::currentDateTime(); edit->setDateTime(current_datetime_local); emit edited(); }
2,070
C++
.cpp
52
36.519231
106
0.748628
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,711
logon_computers_edit.cpp
altlinux_admc/src/admc/attribute_edits/logon_computers_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/logon_computers_edit.h" #include "attribute_edits/logon_computers_dialog.h" #include "adldap.h" #include "utils.h" #include <QPushButton> LogonComputersEdit::LogonComputersEdit(QPushButton *button_arg, QObject *parent) : AttributeEdit(parent) { button = button_arg; connect( button, &QPushButton::clicked, this, &LogonComputersEdit::open_dialog); } void LogonComputersEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); current_value = object.get_value(ATTRIBUTE_USER_WORKSTATIONS); } bool LogonComputersEdit::apply(AdInterface &ad, const QString &dn) const { const bool success = ad.attribute_replace_string(dn, ATTRIBUTE_USER_WORKSTATIONS, current_value); return success; } void LogonComputersEdit::open_dialog() { auto dialog = new LogonComputersDialog(current_value, button); dialog->open(); connect( dialog, &QDialog::accepted, this, [this, dialog]() { current_value = dialog->get(); emit edited(); }); }
1,849
C++
.cpp
50
33.2
101
0.727324
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,712
general_name_edit.cpp
altlinux_admc/src/admc/attribute_edits/general_name_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/general_name_edit.h" #include "adldap.h" #include "utils.h" #include <QLabel> GeneralNameEdit::GeneralNameEdit(QLabel *label_arg, QObject *parent) : AttributeEdit(parent) { label = label_arg; } void GeneralNameEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); const QString label_text = [&]() { const QString name_attribute = [&]() { const bool is_gpc = object.is_class(CLASS_GP_CONTAINER); if (is_gpc) { return ATTRIBUTE_DISPLAY_NAME; } else { return ATTRIBUTE_NAME; } }(); const QString name = object.get_string(name_attribute); return name; }(); label->setText(label_text); }
1,541
C++
.cpp
43
31.116279
72
0.686156
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,713
logon_computers_dialog.cpp
altlinux_admc/src/admc/attribute_edits/logon_computers_dialog.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/logon_computers_dialog.h" #include "attribute_edits/ui_logon_computers_dialog.h" #include "adldap.h" #include "settings.h" #include "utils.h" #include <QPushButton> LogonComputersDialog::LogonComputersDialog(const QString &value, QWidget *parent) : QDialog(parent) { ui = new Ui::LogonComputersDialog(); ui->setupUi(this); setAttribute(Qt::WA_DeleteOnClose); if (!value.isEmpty()) { const QList<QString> value_list = value.split(","); for (const QString &subvalue : value_list) { ui->list->addItem(subvalue); } } enable_widget_on_selection(ui->remove_button, ui->list); settings_setup_dialog_geometry(SETTING_logon_computers_dialog_geometry, this); connect( ui->add_button, &QPushButton::clicked, this, &LogonComputersDialog::on_add_button); connect( ui->remove_button, &QPushButton::clicked, this, &LogonComputersDialog::on_remove_button); } LogonComputersDialog::~LogonComputersDialog() { delete ui; } QString LogonComputersDialog::get() const { const QList<QString> value_list = [&]() { QList<QString> out; for (int i = 0; i < ui->list->count(); i++) { QListWidgetItem *item = ui->list->item(i); const QString value = item->text(); out.append(value); } return out; }(); const QString value_string = value_list.join(","); return value_string; } void LogonComputersDialog::on_add_button() { const QString value = ui->edit->text(); if (value.isEmpty()) { return; } ui->list->addItem(value); ui->edit->clear(); } void LogonComputersDialog::on_remove_button() { const QList<QListWidgetItem *> selected = ui->list->selectedItems(); for (const QListWidgetItem *item : selected) { ui->list->takeItem(ui->list->row(item)); delete item; } }
2,704
C++
.cpp
76
30.789474
82
0.681888
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,714
string_other_edit.cpp
altlinux_admc/src/admc/attribute_edits/string_other_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/string_other_edit.h" #include "adldap.h" #include "attribute_dialogs/list_attribute_dialog.h" #include "attribute_edits/string_edit.h" #include "globals.h" #include <QLineEdit> #include <QPushButton> StringOtherEdit::StringOtherEdit(QLineEdit *line_edit_arg, QPushButton *other_button_arg, const QString &main_attribute, const QString &other_attribute_arg, QObject *parent) : AttributeEdit(parent) , other_attribute(other_attribute_arg) { main_edit = new StringEdit(line_edit_arg, main_attribute, parent); line_edit = line_edit_arg; other_button = other_button_arg; connect( main_edit, &AttributeEdit::edited, this, &AttributeEdit::edited); connect( other_button, &QPushButton::clicked, this, &StringOtherEdit::on_other_button); } void StringOtherEdit::load(AdInterface &ad, const AdObject &object) { main_edit->load(ad, object); other_values = object.get_values(other_attribute); } void StringOtherEdit::set_read_only(const bool read_only_arg) { read_only = read_only_arg; line_edit->setReadOnly(read_only); } bool StringOtherEdit::apply(AdInterface &ad, const QString &dn) const { const bool main_succcess = main_edit->apply(ad, dn); const bool other_success = ad.attribute_replace_values(dn, other_attribute, other_values); return (main_succcess && other_success); } void StringOtherEdit::on_other_button() { auto dialog = new ListAttributeDialog(other_values, other_attribute, read_only, other_button); dialog->setWindowTitle(tr("Edit other values")); dialog->open(); connect( dialog, &QDialog::accepted, this, [this, dialog]() { other_values = dialog->get_value_list(); emit edited(); }); }
2,563
C++
.cpp
64
36.15625
173
0.724235
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,715
protect_deletion_edit.cpp
altlinux_admc/src/admc/attribute_edits/protect_deletion_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/protect_deletion_edit.h" #include "adldap.h" #include "globals.h" #include "utils.h" #include <QCheckBox> // Object is protected from deletion if it denies // permissions for "delete" and "delete subtree" for // "WORLD"(everyone) trustee ProtectDeletionEdit::ProtectDeletionEdit(QCheckBox *check_arg, QObject *parent) : AttributeEdit(parent) { check = check_arg; connect( check, &QCheckBox::stateChanged, this, &AttributeEdit::edited); } void ProtectDeletionEdit::set_enabled(const bool enabled) { check->setChecked(enabled); } void ProtectDeletionEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); const bool enabled = ad_security_get_protected_against_deletion(object); check->setChecked(enabled); } bool ProtectDeletionEdit::apply(AdInterface &ad, const QString &dn) const { const bool enabled = check->isChecked(); const bool apply_success = ad_security_set_protected_against_deletion(ad, dn, enabled); return apply_success; }
1,814
C++
.cpp
47
35.851064
91
0.752707
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,716
expiry_edit.cpp
altlinux_admc/src/admc/attribute_edits/expiry_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/expiry_edit.h" #include "adldap.h" #include "attribute_edits/expiry_widget.h" #include "globals.h" #include "utils.h" ExpiryEdit::ExpiryEdit(ExpiryWidget *edit_widget_arg, QObject *parent) : AttributeEdit(parent) { edit_widget = edit_widget_arg; connect( edit_widget, &ExpiryWidget::edited, this, &AttributeEdit::edited); } void ExpiryEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); edit_widget->load(object); } bool ExpiryEdit::apply(AdInterface &ad, const QString &dn) const { return edit_widget->apply(ad, dn); } void ExpiryEdit::set_enabled(const bool enabled) { edit_widget->setEnabled(enabled); }
1,473
C++
.cpp
41
33.317073
72
0.74368
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,717
attribute_edit.cpp
altlinux_admc/src/admc/attribute_edits/attribute_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/attribute_edit.h" #include "utils.h" bool AttributeEdit::verify(AdInterface &ad, const QString &dn) const { UNUSED_ARG(ad); UNUSED_ARG(dn); return true; } bool AttributeEdit::verify(const QList<AttributeEdit *> &edit_list, AdInterface &ad, const QString &dn) { for (auto edit : edit_list) { const bool verify_success = edit->verify(ad, dn); if (!verify_success) { return false; } } return true; } bool AttributeEdit::apply(const QList<AttributeEdit *> &edit_list, AdInterface &ad, const QString &dn) { bool success = true; for (auto edit : edit_list) { const bool apply_success = edit->apply(ad, dn); if (!apply_success) { success = false; } } return success; } void AttributeEdit::load(const QList<AttributeEdit *> &edit_list, AdInterface &ad, const AdObject &object) { for (auto edit : edit_list) { edit->load(ad, object); } } void AttributeEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); UNUSED_ARG(object); } bool AttributeEdit::apply(AdInterface &ad, const QString &dn) const { UNUSED_ARG(ad); UNUSED_ARG(dn); return true; } void AttributeEdit::set_enabled(const bool enabled) { UNUSED_ARG(enabled); }
2,097
C++
.cpp
62
29.822581
108
0.696384
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,718
upn_edit.cpp
altlinux_admc/src/admc/attribute_edits/upn_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/upn_edit.h" #include "adldap.h" #include "attribute_edits/upn_suffix_combo.h" #include "globals.h" #include "utils.h" #include <QComboBox> #include <QLineEdit> UpnEdit::UpnEdit(QLineEdit *prefix_edit_arg, QComboBox *upn_suffix_combo_arg, QObject *parent) : AttributeEdit(parent) { prefix_edit = prefix_edit_arg; upn_suffix_combo = upn_suffix_combo_arg; connect( prefix_edit, &QLineEdit::textChanged, this, &AttributeEdit::edited); connect( upn_suffix_combo, &QComboBox::currentTextChanged, this, &UpnEdit::on_suffix_combo_changed); } void UpnEdit::init_suffixes(AdInterface &ad) { upn_suffix_combo_init(upn_suffix_combo, ad); on_suffix_combo_changed(); } void UpnEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); upn_suffix_combo_load(upn_suffix_combo, object); const QString prefix = object.get_upn_prefix(); prefix_edit->setText(prefix); } bool UpnEdit::verify(AdInterface &ad, const QString &dn) const { const QString new_value = get_new_value(); const QString new_prefix = prefix_edit->text(); const bool contains_bad_chars = [&]() { const bool some_bad_chars = string_contains_bad_chars(new_prefix, UPN_BAD_CHARS); const bool starts_with_space = new_prefix.startsWith(" "); const bool ends_with_space = new_prefix.endsWith(" "); const bool out = (some_bad_chars || starts_with_space || ends_with_space); return out; }(); if (contains_bad_chars) { const QString text = tr("Input field for User Principal Name contains one or more of the following illegal characters: # , + \" \\ < > (leading space) (trailing space)"); message_box_warning(prefix_edit, tr("Error"), text); return false; } // Check that new upn is unique // NOTE: filter has to also check that it's not the same object because of attribute edit weirdness. If user edits logon name, then retypes original, then applies, the edit will apply because it was modified by the user, even if the value didn't change. Without "not_object_itself", this check would determine that object's logon name conflicts with itself. const QString base = g_adconfig->domain_dn(); const SearchScope scope = SearchScope_All; const QString filter = [=]() { const QString not_object_itself = filter_CONDITION(Condition_NotEquals, ATTRIBUTE_DN, dn); const QString same_upn = filter_CONDITION(Condition_Equals, ATTRIBUTE_USER_PRINCIPAL_NAME, new_value); return filter_AND({same_upn, not_object_itself}); }(); const QList<QString> attributes = QList<QString>(); const QHash<QString, AdObject> results = ad.search(base, scope, filter, attributes); const bool upn_not_unique = (results.size() > 0); if (upn_not_unique) { const QString text = tr("The specified user logon name already exists."); message_box_warning(prefix_edit, tr("Error"), text); return false; } return true; } bool UpnEdit::apply(AdInterface &ad, const QString &dn) const { const QString new_value = get_new_value(); const bool success = ad.attribute_replace_string(dn, ATTRIBUTE_USER_PRINCIPAL_NAME, new_value); return success; } QString UpnEdit::get_new_value() const { const QString prefix = prefix_edit->text().trimmed(); const QString suffix = upn_suffix_combo->currentText(); return QString("%1@%2").arg(prefix, suffix); } void UpnEdit::on_suffix_combo_changed() { const int prefix_range_upper = [&]() { const int total_range_upper = g_adconfig->get_attribute_range_upper(ATTRIBUTE_USER_PRINCIPAL_NAME); const int at_length = QString("@").length(); const int suffix_length = upn_suffix_combo->currentText().length(); const int out = total_range_upper - at_length - suffix_length; return out; }(); prefix_edit->setMaxLength(prefix_range_upper); emit edited(); }
4,760
C++
.cpp
102
41.911765
361
0.702528
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,719
string_large_edit.cpp
altlinux_admc/src/admc/attribute_edits/string_large_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/string_large_edit.h" #include "adldap.h" #include "globals.h" #include "utils.h" #include <QPlainTextEdit> StringLargeEdit::StringLargeEdit(QPlainTextEdit *edit_arg, const QString &attribute_arg, QObject *parent) : AttributeEdit(parent) { attribute = attribute_arg; edit = edit_arg; ignore_on_text_changed = false; connect( edit, &QPlainTextEdit::textChanged, this, &AttributeEdit::edited); connect( edit, &QPlainTextEdit::textChanged, this, &StringLargeEdit::on_text_changed); } void StringLargeEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); const QString value = object.get_string(attribute); edit->setPlainText(value); } bool StringLargeEdit::apply(AdInterface &ad, const QString &dn) const { const QString new_value = edit->toPlainText(); const bool success = ad.attribute_replace_string(dn, attribute, new_value); return success; } // NOTE: this is a custom length limit mechanism // because QPlainText doesn't have it built-in void StringLargeEdit::on_text_changed() { ignore_on_text_changed = true; { const int range_upper = g_adconfig->get_attribute_range_upper(attribute); const QString value = edit->toPlainText(); if (value.length() > range_upper) { const QString shortened_value = value.left(range_upper); edit->setPlainText(shortened_value); } } ignore_on_text_changed = false; }
2,277
C++
.cpp
60
33.966667
105
0.721416
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,720
gpoptions_edit.cpp
altlinux_admc/src/admc/attribute_edits/gpoptions_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/gpoptions_edit.h" #include "adldap.h" #include "utils.h" #include <QCheckBox> GpoptionsEdit::GpoptionsEdit(QCheckBox *check_arg, QObject *parent) : AttributeEdit(parent) { check = check_arg; connect( check, &QCheckBox::stateChanged, this, &AttributeEdit::edited); } void GpoptionsEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); const QString value = object.get_string(ATTRIBUTE_GPOPTIONS); const bool checked = (value == GPOPTIONS_BLOCK_INHERITANCE); check->setChecked(checked); } bool GpoptionsEdit::apply(AdInterface &ad, const QString &dn) const { const QString new_value = [this]() { const bool checked = check->isChecked(); if (checked) { return GPOPTIONS_BLOCK_INHERITANCE; } else { return GPOPTIONS_INHERIT; } }(); const bool success = ad.attribute_replace_string(dn, ATTRIBUTE_GPOPTIONS, new_value); emit gp_options_changed(check->isChecked()); return success; }
1,819
C++
.cpp
49
33.183673
89
0.717045
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,721
logon_hours_edit.cpp
altlinux_admc/src/admc/attribute_edits/logon_hours_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/logon_hours_edit.h" #include "adldap.h" #include "attribute_edits/logon_hours_dialog.h" #include "utils.h" #include <QPushButton> LogonHoursEdit::LogonHoursEdit(QPushButton *button_arg, QObject *parent) : AttributeEdit(parent) { button = button_arg; connect( button, &QPushButton::clicked, this, &LogonHoursEdit::open_dialog); } void LogonHoursEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); current_value = object.get_value(ATTRIBUTE_LOGON_HOURS); } bool LogonHoursEdit::apply(AdInterface &ad, const QString &dn) const { const bool success = ad.attribute_replace_value(dn, ATTRIBUTE_LOGON_HOURS, current_value); return success; } void LogonHoursEdit::open_dialog() { auto dialog = new LogonHoursDialog(current_value, button); dialog->open(); connect( dialog, &QDialog::accepted, this, [this, dialog]() { const QByteArray new_value = dialog->get(); const bool value_changed = (new_value != current_value); if (value_changed) { current_value = dialog->get(); emit edited(); } }); }
1,980
C++
.cpp
54
32.055556
94
0.698902
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,722
upn_suffix_combo.cpp
altlinux_admc/src/admc/attribute_edits/upn_suffix_combo.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/upn_suffix_combo.h" #include "adldap.h" #include "globals.h" #include <QComboBox> void upn_suffix_combo_init(QComboBox *combo, AdInterface &ad) { const QList<QString> suffixes = [&]() { QList<QString> out; const QString partitions_dn = g_adconfig->partitions_dn(); const AdObject partitions_object = ad.search_object(partitions_dn); out = partitions_object.get_strings(ATTRIBUTE_UPN_SUFFIXES); const QString domain = g_adconfig->domain(); const QString domain_suffix = domain.toLower(); if (!out.contains(domain_suffix)) { out.append(domain_suffix); } return out; }(); for (const QString &suffix : suffixes) { combo->addItem(suffix); } combo->setCurrentIndex(0); } void upn_suffix_combo_load(QComboBox *combo, const AdObject &object) { const QString suffix = object.get_upn_suffix(); // Select current suffix in suffix combo. Add current // suffix to combo if it's not there already. const int suffix_index = combo->findText(suffix); if (suffix_index != -1) { combo->setCurrentIndex(suffix_index); } else { combo->addItem(suffix); const int added_index = combo->findText(suffix); combo->setCurrentIndex(added_index); } }
2,106
C++
.cpp
54
34.240741
75
0.695929
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,723
sam_name_edit.cpp
altlinux_admc/src/admc/attribute_edits/sam_name_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/sam_name_edit.h" #include "adldap.h" #include "globals.h" #include "utils.h" #include <QLineEdit> #include <QRegularExpression> SamNameEdit::SamNameEdit(QLineEdit *edit_arg, QLineEdit *domain_edit, QObject *parent) : AttributeEdit(parent) { edit = edit_arg; edit->setMaxLength(SAM_NAME_MAX_LENGTH); const QString domain_text = []() { const QString domain = g_adconfig->domain(); const QString domain_name = domain.split(".")[0]; const QString out = domain_name + "\\"; return out; }(); domain_edit->setText(domain_text); connect( edit, &QLineEdit::textChanged, this, &AttributeEdit::edited); } void SamNameEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); const QString value = object.get_string(ATTRIBUTE_SAM_ACCOUNT_NAME); edit->setText(value); } bool SamNameEdit::verify(AdInterface &ad, const QString &dn) const { UNUSED_ARG(ad); UNUSED_ARG(dn); const bool out = sam_name_edit_verify(edit); return out; } // NOTE: requirements are from here // https://social.technet.microsoft.com/wiki/contents/articles/11216.active-directory-requirements-for-creating-objects.aspx#Note_Regarding_the_quot_quot_Character_in_sAMAccountName bool sam_name_edit_verify(QLineEdit *edit) { const QString new_value = edit->text().trimmed(); const bool contains_bad_chars = string_contains_bad_chars(new_value, SAM_NAME_BAD_CHARS); const bool ends_with_dot = new_value.endsWith("."); const bool value_is_valid = (!contains_bad_chars && !ends_with_dot); if (!value_is_valid) { const QString error_text = QString(QCoreApplication::translate("SamNameEdit", "Input field for Logon name (pre-Windows 2000) contains one or more of the following illegal characters: @ \" [ ] : ; | = + * ? < > / \\ ,")); message_box_warning(edit, QCoreApplication::translate("SamNameEdit", "Error"), error_text); return false; } return true; } bool SamNameEdit::apply(AdInterface &ad, const QString &dn) const { const QString new_value = edit->text().trimmed(); const bool success = ad.attribute_replace_string(dn, ATTRIBUTE_SAM_ACCOUNT_NAME, new_value); return success; } void SamNameEdit::set_enabled(const bool enabled) { edit->setEnabled(enabled); }
3,122
C++
.cpp
73
38.890411
228
0.715041
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,724
password_edit.cpp
altlinux_admc/src/admc/attribute_edits/password_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/password_edit.h" #include "adldap.h" #include "globals.h" #include "settings.h" #include "utils.h" #include <QCheckBox> #include <QLineEdit> #include <QTextCodec> PasswordEdit::PasswordEdit(QLineEdit *edit_arg, QLineEdit *confirm_edit_arg, QCheckBox *show_password_check, QObject *parent) : AttributeEdit(parent) { edit = edit_arg; confirm_edit = confirm_edit_arg; limit_edit(edit, ATTRIBUTE_PASSWORD); limit_edit(confirm_edit, ATTRIBUTE_PASSWORD); connect( edit, &QLineEdit::textChanged, this, &AttributeEdit::edited); connect( show_password_check, &QCheckBox::toggled, this, &PasswordEdit::on_show_password_check); const bool show_password_is_ON = settings_get_variant(SETTING_show_password).toBool(); show_password_check->setChecked(show_password_is_ON); } void PasswordEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); UNUSED_ARG(object); edit->clear(); confirm_edit->clear(); } bool PasswordEdit::verify(AdInterface &ad, const QString &) const { UNUSED_ARG(ad); const QString pass = edit->text(); const QString confirm_pass = confirm_edit->text(); if (pass.isEmpty()) { const QString error_text = QString(tr("Password cannot be empty.")); message_box_warning(edit, tr("Error"), error_text); return false; } if (pass != confirm_pass) { const QString error_text = QString(tr("Passwords don't match!")); message_box_warning(edit, tr("Error"), error_text); return false; } const auto codec = QTextCodec::codecForName("UTF-16LE"); const bool can_encode = codec->canEncode(pass); if (!can_encode) { const QString error_text = QString(tr("Password contains invalid characters")); message_box_warning(edit, tr("Error"), error_text); return false; } return true; } bool PasswordEdit::apply(AdInterface &ad, const QString &dn) const { const QString new_value = edit->text(); const bool success = ad.user_set_pass(dn, new_value); return success; } QLineEdit *PasswordEdit::get_edit() const { return edit; } QLineEdit *PasswordEdit::get_confirm_edit() const { return confirm_edit; } void PasswordEdit::on_show_password_check(bool checked) { const QLineEdit::EchoMode echo_mode = [&]() { if (checked) { return QLineEdit::Normal; } else { return QLineEdit::Password; } }(); edit->setEchoMode(echo_mode); confirm_edit->setEchoMode(echo_mode); settings_set_variant(SETTING_show_password, checked); }
3,423
C++
.cpp
94
31.882979
125
0.696639
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,725
datetime_edit.cpp
altlinux_admc/src/admc/attribute_edits/datetime_edit.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "attribute_edits/datetime_edit.h" #include "adldap.h" #include "globals.h" #include "utils.h" #include <QDateTimeEdit> DateTimeEdit::DateTimeEdit(QDateTimeEdit *edit_arg, const QString &attribute_arg, QObject *parent) : AttributeEdit(parent) { edit = edit_arg; attribute = attribute_arg; attribute = attribute_arg; edit->setDisplayFormat(DATETIME_DISPLAY_FORMAT); connect( edit, &QDateTimeEdit::dateTimeChanged, this, &AttributeEdit::edited); } void DateTimeEdit::load(AdInterface &ad, const AdObject &object) { UNUSED_ARG(ad); const QDateTime datetime = object.get_datetime(attribute, g_adconfig); const QDateTime datetime_local = datetime.toLocalTime(); edit->setDateTime(datetime_local); } bool DateTimeEdit::apply(AdInterface &ad, const QString &dn) const { const QDateTime datetime_local = edit->dateTime(); const QDateTime datetime = datetime_local.toUTC(); const bool success = ad.attribute_replace_datetime(dn, attribute, datetime); return success; }
1,822
C++
.cpp
46
36.478261
98
0.748866
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,726
rename_other_dialog.cpp
altlinux_admc/src/admc/rename_dialogs/rename_other_dialog.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "rename_other_dialog.h" #include "ui_rename_other_dialog.h" #include "rename_object_helper.h" #include "settings.h" RenameOtherDialog::RenameOtherDialog(AdInterface &ad, const QString &target_arg, QWidget *parent) : RenameObjectDialog(parent) { ui = new Ui::RenameOtherDialog(); ui->setupUi(this); const QList<QLineEdit *> required_list = { ui->name_edit, }; helper = new RenameObjectHelper(ad, target_arg, ui->name_edit, {}, this, required_list, ui->button_box); settings_setup_dialog_geometry(SETTING_rename_other_dialog_geometry, this); } void RenameOtherDialog::accept() { const bool accepted = helper->accept(); if (accepted) { QDialog::accept(); } } QString RenameOtherDialog::get_new_dn() const { return helper->get_new_dn(); } RenameOtherDialog::~RenameOtherDialog() { delete ui; }
1,643
C++
.cpp
45
33.555556
108
0.731738
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,727
rename_policy_dialog.cpp
altlinux_admc/src/admc/rename_dialogs/rename_policy_dialog.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "rename_policy_dialog.h" #include "ui_rename_policy_dialog.h" #include "adldap.h" #include "globals.h" #include "rename_object_helper.h" #include "settings.h" #include "status.h" #include "utils.h" RenamePolicyDialog::RenamePolicyDialog(AdInterface &ad, const QString &target_dn_arg, QWidget *parent) : QDialog(parent) { ui = new Ui::RenamePolicyDialog(); ui->setupUi(this); setAttribute(Qt::WA_DeleteOnClose); target_dn = target_dn_arg; target_name = [&]() { const AdObject object = ad.search_object(target_dn); return object.get_string(ATTRIBUTE_DISPLAY_NAME); }(); ui->name_edit->setText(target_name); limit_edit(ui->name_edit, ATTRIBUTE_DISPLAY_NAME); connect(ui->name_edit, &QLineEdit::textChanged, this, &RenamePolicyDialog::on_edited); on_edited(); settings_setup_dialog_geometry(SETTING_rename_policy_dialog_geometry, this); } RenamePolicyDialog::~RenamePolicyDialog() { delete ui; } void RenamePolicyDialog::accept() { AdInterface ad; if (ad_failed(ad, this)) { return; } const QString new_name = ui->name_edit->text().trimmed(); const bool apply_success = ad.attribute_replace_string(target_dn, ATTRIBUTE_DISPLAY_NAME, new_name); if (apply_success) { RenameObjectHelper::success_msg(target_name); } else { RenameObjectHelper::fail_msg(target_name); } g_status->display_ad_messages(ad, this); if (apply_success) { QDialog::accept(); } } void RenamePolicyDialog::on_edited() { QRegExp reg_exp_spaces("^\\s*$"); if (ui->name_edit->text().isEmpty() || ui->name_edit->text().contains(reg_exp_spaces)) { ui->button_box->button(QDialogButtonBox::Ok)->setEnabled(false); } else { ui->button_box->button(QDialogButtonBox::Ok)->setEnabled(true); } }
2,622
C++
.cpp
71
33.014085
104
0.705209
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,728
rename_group_dialog.cpp
altlinux_admc/src/admc/rename_dialogs/rename_group_dialog.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "rename_group_dialog.h" #include "ui_rename_group_dialog.h" #include "ad_defines.h" #include "attribute_edits/sam_name_edit.h" #include "rename_object_helper.h" #include "settings.h" #include "utils.h" RenameGroupDialog::RenameGroupDialog(AdInterface &ad, const QString &target_arg, QWidget *parent) : RenameObjectDialog(parent) { ui = new Ui::RenameGroupDialog(); ui->setupUi(this); auto sam_name_edit = new SamNameEdit(ui->sam_name_edit, ui->sam_name_domain_edit, this); const QList<AttributeEdit *> edit_list = { sam_name_edit, }; QList<QLineEdit *> requred_list = { ui->name_edit, ui->sam_name_edit, }; helper = new RenameObjectHelper(ad, target_arg, ui->name_edit, edit_list, this, requred_list, ui->button_box); setup_lineedit_autofill(ui->name_edit, ui->sam_name_edit); settings_setup_dialog_geometry(SETTING_rename_group_dialog_geometry, this); } void RenameGroupDialog::accept() { const bool accepted = helper->accept(); if (accepted) { QDialog::accept(); } } QString RenameGroupDialog::get_new_dn() const { return helper->get_new_dn(); } RenameGroupDialog::~RenameGroupDialog() { delete ui; }
1,990
C++
.cpp
54
33.592593
114
0.722453
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,729
rename_user_dialog.cpp
altlinux_admc/src/admc/rename_dialogs/rename_user_dialog.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "rename_user_dialog.h" #include "ui_rename_user_dialog.h" #include "adldap.h" #include "attribute_edits/sam_name_edit.h" #include "attribute_edits/string_edit.h" #include "attribute_edits/upn_edit.h" #include "rename_object_helper.h" #include "settings.h" #include "utils.h" RenameUserDialog::RenameUserDialog(AdInterface &ad, const QString &target_arg, QWidget *parent) : RenameObjectDialog(parent) { ui = new Ui::RenameUserDialog(); ui->setupUi(this); auto first_name_edit = new StringEdit(ui->first_name_edit, ATTRIBUTE_FIRST_NAME, this); auto last_name_edit = new StringEdit(ui->last_name_edit, ATTRIBUTE_LAST_NAME, this); auto display_name_edit = new StringEdit(ui->full_name_edit, ATTRIBUTE_DISPLAY_NAME, this); auto upn_edit = new UpnEdit(ui->upn_prefix_edit, ui->upn_suffix_edit, this); upn_edit->init_suffixes(ad); auto sam_name_edit = new SamNameEdit(ui->sam_name_edit, ui->sam_name_domain_edit, this); const QList<AttributeEdit *> edit_list = { first_name_edit, last_name_edit, display_name_edit, upn_edit, sam_name_edit, }; const QList<QLineEdit *> required_list = { ui->name_edit, ui->upn_prefix_edit, ui->sam_name_edit, }; helper = new RenameObjectHelper(ad, target_arg, ui->name_edit, edit_list, this, required_list, ui->button_box); setup_lineedit_autofill(ui->upn_prefix_edit, ui->sam_name_edit); settings_setup_dialog_geometry(SETTING_rename_user_dialog_geometry, this); } void RenameUserDialog::accept() { const bool accepted = helper->accept(); if (accepted) { QDialog::accept(); } } QString RenameUserDialog::get_new_dn() const { return helper->get_new_dn(); } RenameUserDialog::~RenameUserDialog() { delete ui; }
2,585
C++
.cpp
66
35.363636
115
0.714457
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,730
policy_results_widget.cpp
altlinux_admc/src/admc/results_widgets/policy_results_widget.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "policy_results_widget.h" #include "ui_policy_results_widget.h" #include "adldap.h" #include "console_impls/item_type.h" #include "console_impls/policy_impl.h" #include "console_widget/console_widget.h" #include "console_widget/results_view.h" #include "globals.h" #include "settings.h" #include "status.h" #include "utils.h" #include "icon_manager/icon_manager.h" #include <QAction> #include <QHeaderView> #include <QMenu> #include <QModelIndex> #include <QStandardItemModel> #include <QTreeView> #include <QVBoxLayout> enum PolicyResultsColumn { PolicyResultsColumn_Name, PolicyResultsColumn_Enforced, PolicyResultsColumn_Disabled, PolicyResultsColumn_Path, PolicyResultsColumn_COUNT, }; enum PolicyResultsRole { PolicyResultsRole_DN = Qt::UserRole, PolicyResultsRole_GplinkString = Qt::UserRole + 1, PolicyResultsRole_COUNT, }; const QSet<PolicyResultsColumn> option_columns = { PolicyResultsColumn_Disabled, PolicyResultsColumn_Enforced, }; const QHash<PolicyResultsColumn, GplinkOption> column_to_option = { {PolicyResultsColumn_Disabled, GplinkOption_Disabled}, {PolicyResultsColumn_Enforced, GplinkOption_Enforced}, }; PolicyResultsWidget::PolicyResultsWidget(QWidget *parent) : QWidget(parent) { ui = new Ui::PolicyResultsWidget(); ui->setupUi(this); auto delete_link_action = new QAction(tr("Delete link"), this); context_menu = new QMenu(this); context_menu->addAction(delete_link_action); model = new QStandardItemModel(0, PolicyResultsColumn_COUNT, this); set_horizontal_header_labels_from_map(model, { {PolicyResultsColumn_Name, tr("Location")}, {PolicyResultsColumn_Enforced, tr("Enforced")}, {PolicyResultsColumn_Disabled, tr("Disabled")}, {PolicyResultsColumn_Path, tr("Path")}, }); ui->view->set_model(model); ui->view->detail_view()->header()->resizeSection(0, 300); ui->view->detail_view()->header()->resizeSection(1, 100); ui->view->detail_view()->header()->resizeSection(2, 100); ui->view->detail_view()->header()->resizeSection(3, 500); const QVariant state = settings_get_variant(SETTING_policy_results_state); ui->view->restore_state(state, { PolicyResultsColumn_Name, PolicyResultsColumn_Enforced, PolicyResultsColumn_Disabled, PolicyResultsColumn_Path, }); connect( model, &QStandardItemModel::itemChanged, this, &PolicyResultsWidget::on_item_changed); connect( ui->view, &ResultsView::context_menu, this, &PolicyResultsWidget::open_context_menu); connect( delete_link_action, &QAction::triggered, this, &PolicyResultsWidget::delete_link); } PolicyResultsWidget::~PolicyResultsWidget() { const QVariant state = ui->view->save_state(); settings_set_variant(SETTING_policy_results_state, state); delete ui; } void PolicyResultsWidget::update(const QModelIndex &index) { const ItemType type = (ItemType) console_item_get_type(index); if (type != ItemType_Policy) { return; } const QString new_gpo = index.data(PolicyRole_DN).toString(); update(new_gpo); } void PolicyResultsWidget::update(const QString &new_gpo) { gpo = new_gpo; AdInterface ad; if (ad_failed(ad, this)) { return; } model->removeRows(0, model->rowCount()); const QString base = g_adconfig->domain_dn(); const SearchScope scope = SearchScope_All; const QList<QString> attributes = {ATTRIBUTE_NAME, ATTRIBUTE_GPLINK, ATTRIBUTE_OBJECT_CATEGORY}; const QString filter = filter_CONDITION(Condition_Contains, ATTRIBUTE_GPLINK, gpo); const QHash<QString, AdObject> results = ad.search(base, scope, filter, attributes); for (const AdObject &object : results.values()) { const QList<QStandardItem *> row = make_item_row(PolicyResultsColumn_COUNT); const QString dn = object.get_dn(); const QString name = dn_get_name(dn); row[PolicyResultsColumn_Name]->setText(name); row[PolicyResultsColumn_Path]->setText(dn_get_parent_canonical(dn)); const QString gplink_string = object.get_string(ATTRIBUTE_GPLINK); const Gplink gplink = Gplink(gplink_string); const Qt::CheckState enforced_checkstate = [&]() { const bool is_enforced = gplink.get_option(gpo, GplinkOption_Enforced); if (is_enforced) { return Qt::Checked; } else { return Qt::Unchecked; } }(); row[PolicyResultsColumn_Enforced]->setCheckable(true); row[PolicyResultsColumn_Enforced]->setCheckState(enforced_checkstate); for (const auto column : option_columns) { QStandardItem *item = row[column]; item->setCheckable(true); const Qt::CheckState checkstate = [=]() { const GplinkOption option = column_to_option[column]; const bool option_is_set = gplink.get_option(gpo, option); if (option_is_set) { return Qt::Checked; } else { return Qt::Unchecked; } }(); item->setCheckState(checkstate); } row[0]->setData(dn, PolicyResultsRole_DN); row[0]->setData(gplink_string, PolicyResultsRole_GplinkString); const QIcon icon = g_icon_manager->get_object_icon(object); row[0]->setIcon(icon); model->appendRow(row); } } ResultsView *PolicyResultsWidget::get_view() const { return ui->view; } QString PolicyResultsWidget::get_current_gpo() const { return gpo; } void PolicyResultsWidget::on_item_changed(QStandardItem *item) { const PolicyResultsColumn column = (PolicyResultsColumn) item->column(); if (!option_columns.contains(column)) { return; } const QModelIndex this_index = item->index(); const QModelIndex index = this_index.siblingAtColumn(0); const QString ou_dn = index.data(PolicyResultsRole_DN).toString(); const GplinkOption option = column_to_option[column]; const bool is_checked = (item->checkState() == Qt::Checked); const QString gplink_string = index.data(PolicyResultsRole_GplinkString).toString(); Gplink gplink = Gplink(gplink_string); gplink.set_option(gpo, option, is_checked); const QString updated_gplink_string = gplink.to_string(); const bool gplink_didnt_change = gplink.equals(gplink_string); if (gplink_didnt_change) { return; } AdInterface ad; if (ad_failed(ad, this)) { return; } show_busy_indicator(); const bool success = ad.attribute_replace_string(ou_dn, ATTRIBUTE_GPLINK, updated_gplink_string); if (success) { model->setData(index, updated_gplink_string, PolicyResultsRole_GplinkString); emit ou_gplink_changed(ou_dn, gplink, gpo, option); } else { const Qt::CheckState undo_check_state = [&]() { if (item->checkState() == Qt::Checked) { return Qt::Unchecked; } else { return Qt::Checked; } }(); item->setCheckState(undo_check_state); } g_status->display_ad_messages(ad, this); hide_busy_indicator(); } void PolicyResultsWidget::open_context_menu(const QPoint &pos) { const QModelIndex index = ui->view->current_view()->indexAt(pos); if (!index.isValid()) { return; } const QPoint global_pos = ui->view->current_view()->mapToGlobal(pos); context_menu->popup(global_pos); } void PolicyResultsWidget::delete_link() { AdInterface ad; if (ad_failed(ad, this)) { return; } show_busy_indicator(); const QList<QModelIndex> selected = ui->view->get_selected_indexes(); QList<QPersistentModelIndex> removed_indexes; for (const QModelIndex &index : selected) { const QString dn = index.data(PolicyResultsRole_DN).toString(); const QString gplink_string = index.data(PolicyResultsRole_GplinkString).toString(); Gplink gplink = Gplink(gplink_string); gplink.remove(gpo); const QString updated_gplink_string = gplink.to_string(); const bool gplink_didnt_change = gplink.equals(gplink_string); if (gplink_didnt_change) { continue; } const bool success = ad.attribute_replace_string(dn, ATTRIBUTE_GPLINK, updated_gplink_string); if (success) { removed_indexes.append(QPersistentModelIndex(index)); emit ou_gplink_changed(dn, gplink, gpo); } } for (const QPersistentModelIndex &index : removed_indexes) { model->removeRow(index.row()); } g_status->display_ad_messages(ad, this); hide_busy_indicator(); }
9,646
C++
.cpp
244
33.090164
102
0.676124
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,731
policy_ou_results_widget.cpp
altlinux_admc/src/admc/results_widgets/policy_ou_results_widget/policy_ou_results_widget.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "policy_ou_results_widget.h" #include "ui_policy_ou_results_widget.h" #include "console_widget/console_widget.h" #include "linked_policies_widget.h" #include "inherited_policies_widget.h" #include <QModelIndex> PolicyOUResultsWidget::PolicyOUResultsWidget(ConsoleWidget *console_arg) : QWidget(console_arg), console(console_arg) { ui = new Ui::PolicyOUResultsWidget(); ui->setupUi(this); links_widget = new LinkedPoliciesWidget(console_arg); ui->tab_widget->addTab(links_widget, tr("Linked policies")); inheritance_widget = new InheritedPoliciesWidget(console_arg); ui->tab_widget->addTab(inheritance_widget, tr("Inherited policies")); connect(links_widget, &LinkedPoliciesWidget::gplink_changed, this, &PolicyOUResultsWidget::update_inheritance_widget); } PolicyOUResultsWidget::~PolicyOUResultsWidget() { delete ui; } void PolicyOUResultsWidget::update(const QModelIndex &index) { update_inheritance_widget(index); update_links_widget(index); } void PolicyOUResultsWidget::update_inheritance_widget(const QModelIndex &index) { inheritance_widget->update(index); } void PolicyOUResultsWidget::update_links_widget(const QModelIndex &index) { links_widget->update(index); }
2,027
C++
.cpp
49
38.55102
81
0.766141
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,732
inherited_policies_widget.cpp
altlinux_admc/src/admc/results_widgets/policy_ou_results_widget/inherited_policies_widget.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2023 BaseALT Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 "inherited_policies_widget.h" #include "ui_inherited_policies_widget.h" #include "utils.h" #include "settings.h" #include "console_impls/policy_ou_impl.h" #include "console_impls/policy_impl.h" #include "console_widget/console_widget.h" #include "console_impls/item_type.h" #include "gplink.h" #include "icon_manager/icon_manager.h" #include "globals.h" #include <QStandardItemModel> #include <QStringList> InheritedPoliciesWidget::InheritedPoliciesWidget(ConsoleWidget *console_arg, QWidget *parent) : QWidget(parent), ui(new Ui::InheritedPoliciesWidget), console(console_arg) { ui->setupUi(this); model = new QStandardItemModel(0, InheritedPoliciesColumns_COUNT, this); set_horizontal_header_labels_from_map(model, { {InheritedPoliciesColumns_Prority, tr("Priority")}, {InheritedPoliciesColumns_Name, tr("Name")}, {InheritedPoliciesColumns_Location, tr("Location")}, {InheritedPoliciesColumns_Status, tr("Status")}, }); ui->view->set_model(model); const QVariant state = settings_get_variant(SETTING_inheritance_widget_state); ui->view->restore_state(state, { InheritedPoliciesColumns_Prority, InheritedPoliciesColumns_Name, InheritedPoliciesColumns_Location, InheritedPoliciesColumns_Status }); ui->view->set_drag_drop_enabled(false); } InheritedPoliciesWidget::~InheritedPoliciesWidget() { const QVariant state = ui->view->save_state(); settings_set_variant(SETTING_inheritance_widget_state, state); delete ui; } void InheritedPoliciesWidget::update(const QModelIndex &index) { model->removeRows(0, model->rowCount()); selected_scope_index = index; add_enabled_policy_items(index); remove_link_duplicates(); set_priority_to_items(); model->sort(InheritedPoliciesColumns_Prority); } void InheritedPoliciesWidget::hide_not_enforced_inherited_links(bool hide) { const Gplink gplink = Gplink(selected_scope_index. data(PolicyOURole_Gplink_String). toString()); const QStringList gplink_strings = gplink.get_gpo_list(); for (int row = 0; row < model->rowCount(); ++row) { if (!gplink_strings.contains(model->item(row)->data(RowRole_DN).toString()) && !model->item(row)->data(RowRole_IsEnforced).toBool()) { ui->view->set_row_hidden(row, hide); } } } void InheritedPoliciesWidget::add_enabled_policy_items(const QModelIndex &index, bool inheritance_blocked) { if (index.data(ConsoleRole_Type) != ItemType_PolicyOU) return; QString gplink_string = index.data(PolicyOURole_Gplink_String).toString(); const Gplink gplink = Gplink(gplink_string); const QStringList enforced_links = gplink.enforced_gpo_dn_list(); const QStringList disabled_links = gplink.disabled_gpo_dn_list(); int row_number = 0; for (QString gpo_dn : gplink.get_gpo_list()) { if (disabled_links.contains(gpo_dn)) { continue; } bool policy_is_enforced = enforced_links.contains(gpo_dn); QList<QStandardItem *> row; if (policy_is_enforced) { row = make_item_row(InheritedPoliciesColumns_COUNT); load_item(row, index, gpo_dn, policy_is_enforced); model->insertRow(row_number, row); ++row_number; } else if (index == selected_scope_index || !inheritance_blocked) { row = make_item_row(InheritedPoliciesColumns_COUNT); load_item(row, index, gpo_dn, policy_is_enforced); model->appendRow(row); } } bool inheritance_is_blocked = index.data(PolicyOURole_Inheritance_Block).toBool() || inheritance_blocked; add_enabled_policy_items(index.parent(), inheritance_is_blocked); } void InheritedPoliciesWidget::remove_link_duplicates() { QStringList dn_list; for (int row = 0; row < model->rowCount(); ++row) { // The same dn is set to each item in the row const QString dn = model->index(row, 0).data(RowRole_DN).toString(); if (dn_list.contains(dn)) { model->removeRow(row); --row; continue; } dn_list << dn; } } void InheritedPoliciesWidget::set_priority_to_items() { for(int row = 0; row < model->rowCount(); ++row) { model->item(row, InheritedPoliciesColumns_Prority)-> setData(row + 1, Qt::DisplayRole); } } void InheritedPoliciesWidget::load_item(const QList<QStandardItem *> row, const QModelIndex &ou_index, const QString &policy_dn, bool is_enforced) { QModelIndex enforced_policy_index = console->search_item(ou_index, PolicyRole_DN, policy_dn, {ItemType_Policy}); const QString dn = enforced_policy_index.data(PolicyRole_DN).toString(); set_data_for_row(row, dn, RowRole_DN); set_data_for_row(row, is_enforced, RowRole_IsEnforced); row[InheritedPoliciesColumns_Name]->setText(enforced_policy_index.data(Qt::DisplayRole).toString()); row[InheritedPoliciesColumns_Location]->setText(ou_index.data(Qt::DisplayRole).toString()); row[InheritedPoliciesColumns_Status]->setText(enforced_policy_index.data(PolicyRole_GPO_Status).toString()); if (is_enforced) row[0]->setIcon(g_icon_manager->get_icon_for_type(ItemIconType_Policy_Enforced)); else row[0]->setIcon(g_icon_manager->get_icon_for_type(ItemIconType_Policy_Link)); }
6,367
C++
.cpp
148
36.168919
146
0.675484
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,733
linked_policies_widget.cpp
altlinux_admc/src/admc/results_widgets/policy_ou_results_widget/linked_policies_widget.cpp
#include "adldap.h" #include "linked_policies_widget.h" #include "ui_linked_policies_widget.h" #include "console_impls/item_type.h" #include "console_impls/policy_impl.h" #include "console_impls/policy_ou_impl.h" #include "console_impls/policy_root_impl.h" #include "console_widget/console_widget.h" #include "console_widget/results_view.h" #include "globals.h" #include "settings.h" #include "status.h" #include "utils.h" #include "icon_manager/icon_manager.h" #include "drag_drop_links_model.h" #include <QAction> #include <QHeaderView> #include <QMenu> #include <QMessageBox> #include <QModelIndex> #include <QStandardItemModel> #include <QTreeView> LinkedPoliciesWidget::LinkedPoliciesWidget(ConsoleWidget *console_arg, QWidget *parent) : QWidget(parent), ui(new Ui::LinkedPoliciesWidget), console(console_arg) { ui->setupUi(this); if (!console) { return; } auto remove_link_action = new QAction(tr("Remove link"), this); auto move_up_action = new QAction(tr("Move up"), this); auto move_down_action = new QAction(tr("Move down"), this); context_menu = new QMenu(this); context_menu->addAction(remove_link_action); context_menu->addAction(move_up_action); context_menu->addAction(move_down_action); model = new DragDropLinksModel(gplink, 0, LinkedPoliciesColumn_COUNT, this); set_horizontal_header_labels_from_map(model, { {LinkedPoliciesColumn_Order, tr("Order")}, {LinkedPoliciesColumn_Name, tr("Name")}, {LinkedPoliciesColumn_Enforced, tr("Enforced")}, {LinkedPoliciesColumn_Disabled, tr("Disabled")}, }); ui->view->set_model(model); QHeaderView *detail_view_header = ui->view->detail_view()->header(); detail_view_header->resizeSection(0, 50); detail_view_header->resizeSection(1, 300); detail_view_header->resizeSection(2, 100); detail_view_header->resizeSection(3, 100); detail_view_header->resizeSection(4, 500); ui->view->set_drag_drop_internal(); ui->view->current_view()->setDragDropOverwriteMode(false); ui->view->current_view()->setSelectionBehavior(QAbstractItemView::SelectRows); ui->view->current_view()->setSelectionMode(QAbstractItemView::ExtendedSelection); const QVariant state = settings_get_variant(SETTING_policy_ou_results_state); ui->view->restore_state(state, { LinkedPoliciesColumn_Order, LinkedPoliciesColumn_Name, LinkedPoliciesColumn_Enforced, LinkedPoliciesColumn_Disabled, }); connect( model, &QStandardItemModel::itemChanged, this, &LinkedPoliciesWidget::on_item_changed); connect( ui->view, &ResultsView::context_menu, this, &LinkedPoliciesWidget::open_context_menu); connect( remove_link_action, &QAction::triggered, this, &LinkedPoliciesWidget::remove_link); connect( move_up_action, &QAction::triggered, this, &LinkedPoliciesWidget::move_up); connect( move_down_action, &QAction::triggered, this, &LinkedPoliciesWidget::move_down); connect(model, &DragDropLinksModel::link_orders_changed, [this](const Gplink &gplink_arg) { AdInterface ad; if (ad_failed(ad, this)) { model->arrange_orders_from_gplink(gplink); return; } bool success = ad.attribute_replace_string(ou_dn, ATTRIBUTE_GPLINK, gplink_arg.to_string()); if (!success) { model->arrange_orders_from_gplink(gplink); return; } gplink = gplink_arg; const QModelIndex scope_tree_ou_index = console->get_current_scope_item(); update_ou_item_gplink_data(gplink.to_string(), scope_tree_ou_index, console); g_status->add_message(tr("Organizational unit ") + scope_tree_ou_index.data().toString() + tr("'s link orders have been succesfuly changed."), StatusType_Success); emit gplink_changed(scope_tree_ou_index); }); } LinkedPoliciesWidget::~LinkedPoliciesWidget() { const QVariant state = ui->view->save_state(); settings_set_variant(SETTING_policy_ou_results_state, state); delete ui; } void LinkedPoliciesWidget::update(const QModelIndex &ou_index) { const ItemType type = (ItemType) console_item_get_type(ou_index); if (type != ItemType_PolicyOU) { return; } ou_dn = ou_index.data(PolicyOURole_DN).toString(); AdInterface ad; if (ad_failed(ad, this)) { return; } gplink = [&]() { const AdObject object = ad.search_object(ou_dn); const QString gplink_string = object.get_string(ATTRIBUTE_GPLINK); const Gplink out = Gplink(gplink_string); return out; }(); update_link_items(); emit gplink_changed(ou_index); } void LinkedPoliciesWidget::on_item_changed(QStandardItem *item) { const LinkedPoliciesColumn column = (LinkedPoliciesColumn) item->column(); if (!option_columns.contains(column)) { return; } show_busy_indicator(); AdInterface ad; if (ad_failed(ad, this)) { return; } const QModelIndex this_index = item->index(); const QString gpo_dn = this_index.data(LinkedPoliciesRole_DN).toString(); const GplinkOption option = column_to_option[column]; const bool is_checked = (item->checkState() == Qt::Checked); Gplink gplink_modified = gplink; gplink_modified.set_option(gpo_dn, option, is_checked); const QString gplink_string = gplink_modified.to_string(); bool success = ad.attribute_replace_string(ou_dn, ATTRIBUTE_GPLINK, gplink_string); if (!success) { hide_busy_indicator(); g_status->display_ad_messages(ad, this); return; } g_status->display_ad_messages(ad, this); update_policy_link_icons(this_index, is_checked, option); gplink.set_option(gpo_dn, option, is_checked); const QModelIndex scope_tree_ou_index = console->get_current_scope_item(); update_ou_item_gplink_data(gplink_string, scope_tree_ou_index, console); emit gplink_changed(scope_tree_ou_index); hide_busy_indicator(); } void LinkedPoliciesWidget::open_context_menu(const QPoint &pos) { const QModelIndex index = ui->view->current_view()->indexAt(pos); if (!index.isValid()) { return; } const QPoint global_pos = ui->view->current_view()->mapToGlobal(pos); context_menu->popup(global_pos); } void LinkedPoliciesWidget::remove_link() { // NOTE: save gpo dn list before they are removed in // modify_gplink() const QList<QString> gpo_dn_list = [&]() { QList<QString> out; const QList<QModelIndex> selected = ui->view->get_selected_indexes(); for (const QModelIndex &index : selected) { const QString gpo_dn = index.data(LinkedPoliciesRole_DN).toString(); out.append(gpo_dn); } return out; }(); auto modify_function = [](Gplink &gplink_arg, const QString &gpo) { gplink_arg.remove(gpo); }; modify_gplink(modify_function); // Also remove gpo from OU in console const QModelIndex policy_root = get_policy_tree_root(console); if (policy_root.isValid()) { const QModelIndex ou_index = console->search_item(policy_root, PolicyOURole_DN, ou_dn, {ItemType_PolicyOU}); if (ou_index.isValid()) { for (const QString &gpo_dn : gpo_dn_list) { const QModelIndex gpo_index = console->search_item(ou_index, PolicyRole_DN, gpo_dn, {ItemType_Policy}); if (gpo_index.isValid()) { console->delete_item(gpo_index); } } } } } void LinkedPoliciesWidget::move_up() { auto modify_function = [](Gplink &gplink_arg, const QString &gpo) { gplink_arg.move_up(gpo); }; modify_gplink(modify_function); } void LinkedPoliciesWidget::move_down() { auto modify_function = [](Gplink &gplink_arg, const QString &gpo) { gplink_arg.move_down(gpo); }; modify_gplink(modify_function); } void LinkedPoliciesWidget::update_link_items() { model->removeRows(0, model->rowCount()); AdInterface ad; if (ad_failed(ad, ui->view)) { return; } const QList<AdObject> gpo_obj_list = gpo_object_list(ad); for (const AdObject &gpo_object : gpo_obj_list) { const QList<QStandardItem *> row = make_item_row(LinkedPoliciesColumn_COUNT); load_item_row(gpo_object, row); model->appendRow(row); } model->sort(LinkedPoliciesColumn_Order); } // Takes as argument function that modifies the gplink. // Modify function accepts gplink as argument and gpo dn // used in the operation. void LinkedPoliciesWidget::modify_gplink(void (*modify_function)(Gplink &, const QString &)) { AdInterface ad; if (ad_failed(ad, this)) { return; } show_busy_indicator(); const QList<QModelIndex> selected = ui->view->get_selected_indexes(); for (const QModelIndex &index : selected) { const QString gpo_dn = index.data(LinkedPoliciesRole_DN).toString(); modify_function(gplink, gpo_dn); } const QString gplink_string = gplink.to_string(); ad.attribute_replace_string(ou_dn, ATTRIBUTE_GPLINK, gplink_string); g_status->display_ad_messages(ad, this); update_link_items(); const QModelIndex scope_tree_ou_index = console->get_current_scope_item(); update_ou_item_gplink_data(gplink_string, scope_tree_ou_index, console); emit gplink_changed(scope_tree_ou_index); hide_busy_indicator(); } void LinkedPoliciesWidget::update_policy_link_icons(const QModelIndex &changed_item_index, bool is_checked, GplinkOption option) { bool is_disabled, is_enforced; if (option == GplinkOption_Disabled) { is_disabled = is_checked; is_enforced = model->itemFromIndex(changed_item_index.siblingAtColumn(LinkedPoliciesColumn_Enforced))-> checkState() == Qt::Checked; } else if (option == GplinkOption_Enforced) { is_enforced = is_checked; is_disabled = model->itemFromIndex(changed_item_index.siblingAtColumn(LinkedPoliciesColumn_Disabled))-> checkState() == Qt::Checked; } set_policy_link_icon(model->itemFromIndex(changed_item_index.siblingAtColumn(0)), is_enforced, is_disabled); const QString gpo_dn = changed_item_index.data(LinkedPoliciesRole_DN).toString(); QModelIndex target_policy_index = get_ou_child_policy_index(console, console->get_current_scope_item(), gpo_dn); if (target_policy_index.isValid()) { set_policy_link_icon(console->get_item(target_policy_index), is_enforced, is_disabled); } } QList<AdObject> LinkedPoliciesWidget::gpo_object_list(AdInterface &ad) { const QList<QString> gpo_dn_list = gplink.get_gpo_list(); if (gpo_dn_list.isEmpty()) { return QList<AdObject>(); } const QString base = g_adconfig->policies_dn(); const SearchScope scope = SearchScope_Children; const QString filter = filter_dn_list(gpo_dn_list); const QList<QString> attributes = QList<QString>(); const QHash<QString, AdObject> search_results = ad.search(base, scope, filter, attributes); const QList<AdObject> gpo_objects = search_results.values(); return gpo_objects; } void LinkedPoliciesWidget::load_item_row(const AdObject &gpo_object, QList<QStandardItem*> row) { const QList<QString> gpo_dn_list = gplink.get_gpo_list(); // NOTE: Gplink may contain invalid gpo's, in which // case there's no real object for the policy, but // we still show the broken object to the user so he // is aware of it. const bool gpo_is_valid = !gpo_object.is_empty(); const QString gpo_dn = gpo_object.get_dn(); const QString name = gpo_is_valid ? gpo_object.get_string(ATTRIBUTE_DISPLAY_NAME) : tr("Not found"); const int index = gpo_dn_list.indexOf(gpo_object.get_dn()) + 1; row[LinkedPoliciesColumn_Order]->setData(index, Qt::DisplayRole); row[LinkedPoliciesColumn_Name]->setText(name); set_data_for_row(row, gpo_dn, LinkedPoliciesRole_DN); for (const auto column : option_columns) { QStandardItem *item = row[column]; item->setCheckable(true); const Qt::CheckState checkstate = [=]() { const GplinkOption option = column_to_option[column]; const bool option_is_set = gplink.get_option(gpo_dn, option); if (option_is_set) { return Qt::Checked; } else { return Qt::Unchecked; } }(); item->setCheckState(checkstate); } set_policy_link_icon(row[0], gplink.get_option(gpo_dn, GplinkOption_Enforced), gplink.get_option(gpo_dn, GplinkOption_Disabled)); if (!gpo_is_valid) { row[LinkedPoliciesColumn_Name]->setIcon(g_icon_manager->get_object_icon("block-indicator")); for (QStandardItem *item : row) { item->setToolTip(tr("The GPO for this link could not be found. It maybe have been recently created and is being replicated or it could have been deleted.")); } } }
13,243
C++
.cpp
312
35.875
169
0.671908
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,734
drag_drop_links_model.cpp
altlinux_admc/src/admc/results_widgets/policy_ou_results_widget/drag_drop_links_model.cpp
#include "drag_drop_links_model.h" #include "utils.h" #include "globals.h" #include "icon_manager/icon_manager.h" #include "ad_interface.h" #include "console_impls/policy_impl.h" #include <QMimeData> #include <QDataStream> #include <QMessageBox> #include <QDebug> DragDropLinksModel::DragDropLinksModel(const Gplink &gplink, int rows, int columns, QObject *parent) : QStandardItemModel{rows, columns, parent}, gplink_ref{gplink} { } QMimeData *DragDropLinksModel::mimeData(const QModelIndexList &indexes) const { QMimeData *mime_data = new QMimeData; QByteArray encoded_data; QDataStream stream(&encoded_data, QIODevice::WriteOnly); int row = -1; for (const QModelIndex &index : indexes) { if (row != index.row()) { row = index.row(); // Data for items to be inserted after drop is taken from gplink object. But gplink doesn't // contain visible name, thus visible name is also added to mime data const QString dn_name_data_string = index.data(LinkedPoliciesRole_DN).toString() + ':' + index.siblingAtColumn(LinkedPoliciesColumn_Name).data().toString(); stream << dn_name_data_string; } } mime_data->setData(links_model_mime_type, encoded_data); return mime_data; } Qt::DropActions DragDropLinksModel::supportedDropActions() const { return Qt::MoveAction; } bool DragDropLinksModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { if (!canDropMimeData(data, action, row, column, parent)) { return false; } int insert_row; if (row != -1) { insert_row = row; } else if (parent.isValid()) { insert_row = parent.row(); } else { insert_row = rowCount(); } QByteArray encoded_data = data->data(links_model_mime_type); QDataStream stream(&encoded_data, QIODevice::ReadOnly); QStringList dn_name_strings; while (!stream.atEnd()) { QString dn_name; stream >> dn_name; dn_name_strings << dn_name; } const int max_order = gplink_ref.get_max_order(); int target_order; if (insert_row == rowCount()) { target_order = max_order; } else { target_order = index(insert_row, LinkedPoliciesColumn_Order).data().toInt(); } Gplink gplink_modified = gplink_ref; for (const QString &dn_name : dn_name_strings) { const QString dn = dn_name.split(':').first(); const QString display_name = dn_name.split(':').last(); int current_order = gplink_ref.get_gpo_order(dn); QList<QStandardItem *> item_row = make_item_row(LinkedPoliciesColumn_COUNT); load_row(item_row, current_order, dn, display_name); insertRow(insert_row, item_row); gplink_modified.move(current_order, target_order); if (insert_row < rowCount()) { insert_row++; } if (target_order < max_order) { target_order++; } } arrange_orders_from_gplink(gplink_modified); emit link_orders_changed(gplink_modified); return true; } bool DragDropLinksModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const { Q_UNUSED(action); Q_UNUSED(row); Q_UNUSED(column); Q_UNUSED(parent) if (!data->hasFormat(links_model_mime_type)) { return false; } return true; } void DragDropLinksModel::arrange_orders_from_gplink(const Gplink &gplink) { for (int row = 0; row < rowCount(); ++row) { QStandardItem *link_item = item(row, LinkedPoliciesColumn_Order); const QString gpo_dn = link_item->data(LinkedPoliciesRole_DN).toString(); const int previous_order = link_item->data(Qt::DisplayRole).toInt(); const int actual_order = gplink.get_gpo_order(gpo_dn); if (previous_order != actual_order) { link_item->setData(actual_order, Qt::DisplayRole); } } } void DragDropLinksModel::update_sort_column(LinkedPoliciesColumn column) { sort_column = column; } void DragDropLinksModel::load_row(QList<QStandardItem *> &item_row, int order, const QString &dn, const QString &display_name) { Qt::CheckState is_enforced = gplink_ref.get_option(dn, GplinkOption_Enforced) ? Qt::Checked : Qt::Unchecked; Qt::CheckState is_disabled = gplink_ref.get_option(dn, GplinkOption_Disabled) ? Qt::Checked : Qt::Unchecked; set_policy_link_icon(item_row[0], is_enforced == Qt::Checked, is_disabled == Qt::Checked); item_row[LinkedPoliciesColumn_Order]->setData(order, Qt::DisplayRole); item_row[LinkedPoliciesColumn_Name]->setText(display_name); item_row[LinkedPoliciesColumn_Enforced]->setCheckable(true); item_row[LinkedPoliciesColumn_Enforced]->setCheckState(is_enforced); item_row[LinkedPoliciesColumn_Disabled]->setCheckable(true); item_row[LinkedPoliciesColumn_Disabled]->setCheckState(is_disabled); set_data_for_row(item_row, dn, LinkedPoliciesRole_DN); }
5,049
C++
.cpp
120
36.275
142
0.683534
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,735
pso_results_widget.cpp
altlinux_admc/src/admc/results_widgets/pso_results_widget/pso_results_widget.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2024 BaseALT Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 "pso_results_widget.h" #include "ui_pso_results_widget.h" #include "ad_interface.h" #include "utils.h" #include "console_impls/object_impl.h" #include <QModelIndex> // #include <QDebug> PSOResultsWidget::PSOResultsWidget(QWidget *parent) : QWidget(parent), ui(new Ui::PSOResultsWidget) { ui->setupUi(this); connect(ui->apply_button, &QPushButton::clicked, this, &PSOResultsWidget::on_apply); connect(ui->cancel_button, &QPushButton::clicked, this, &PSOResultsWidget::on_cancel); connect(ui->edit_button, &QPushButton::clicked, this, &PSOResultsWidget::on_edit); } PSOResultsWidget::~PSOResultsWidget() { delete ui; } void PSOResultsWidget::update(const QModelIndex &index) { AdInterface ad; if (ad_failed(ad, this)) { return; } AdObject pso = ad.search_object(index.data(ObjectRole_DN).toString()); update(pso); } void PSOResultsWidget::update(const AdObject &pso) { saved_pso_object = pso; ui->pso_edit_widget->update(pso); ui->edit_button->setDisabled(false); ui->cancel_button->setDisabled(true); ui->apply_button->setDisabled(true); ui->pso_edit_widget->set_read_only(true); } void PSOResultsWidget::on_apply() { if (changed_setting_attrs().isEmpty()) { set_editable(false); return; } AdInterface ad; if (ad_failed(ad, this)) { on_cancel(); return; } const QString &pso_dn = saved_pso_object.get_dn(); QStringList changed_attrs = changed_setting_attrs(); auto settings_values = ui->pso_edit_widget->pso_settings_values(); for (const QString &attribute : changed_attrs) { ad.attribute_replace_values(pso_dn, attribute, settings_values[attribute]); } saved_pso_object = ad.search_object(pso_dn); set_editable(false); } void PSOResultsWidget::on_edit() { set_editable(true); } void PSOResultsWidget::on_cancel() { ui->pso_edit_widget->update(saved_pso_object); set_editable(false); } QStringList PSOResultsWidget::changed_setting_attrs() { QStringList attrs; auto new_values = ui->pso_edit_widget->pso_settings_values(); for (const QString &attribute : new_values.keys()) { if (saved_pso_object.get_values(attribute) != new_values[attribute]) { attrs.append(attribute); } } return attrs; } void PSOResultsWidget::set_editable(bool is_editable) { ui->pso_edit_widget->set_read_only(!is_editable); ui->edit_button->setDisabled(is_editable); ui->cancel_button->setDisabled(!is_editable); ui->apply_button->setDisabled(!is_editable); }
3,335
C++
.cpp
94
31.5
90
0.706083
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,736
pso_edit_widget.cpp
altlinux_admc/src/admc/results_widgets/pso_results_widget/pso_edit_widget.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2024 BaseALT Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 "pso_edit_widget.h" #include "ui_pso_edit_widget.h" #include "ad_interface.h" #include "ad_object.h" #include "ad_utils.h" #include "select_dialogs/select_object_dialog.h" #include "icon_manager/icon_manager.h" #include "status.h" #include "globals.h" #include <chrono> #include <QDebug> PSOEditWidget::PSOEditWidget(QWidget *parent) : QWidget(parent), ui(new Ui::PSOEditWidget) { ui->setupUi(this); connect(ui->applied_list_widget, &QListWidget::itemSelectionChanged, this, [this]() { ui->remove_button->setDisabled(ui->applied_list_widget->count() == 0); }); connect(ui->add_button, &QPushButton::clicked, this, &PSOEditWidget::on_add); connect(ui->remove_button, &QPushButton::clicked, this, &PSOEditWidget::on_remove); update_defaults(); default_setting_values = pso_settings_values(); } PSOEditWidget::~PSOEditWidget() { delete ui; } void PSOEditWidget::update(const AdObject &passwd_settings_obj) { ui->name_edit->setText(passwd_settings_obj.get_string(ATTRIBUTE_CN)); ui->name_edit->setReadOnly(true); ui->precedence_spinbox->setValue(passwd_settings_obj.get_int(ATTRIBUTE_MS_DS_PASSWORD_SETTINGS_PRECEDENCE)); ui->min_passwd_len_spinbox->setValue(passwd_settings_obj.get_int(ATTRIBUTE_MS_DS_MIN_PASSWORD_LENGTH)); ui->history_length_spinbox->setValue(passwd_settings_obj.get_int(ATTRIBUTE_MS_DS_PASSWORD_HISTORY_LENGTH)); ui->logon_attempts_spinbox->setValue(passwd_settings_obj.get_int(ATTRIBUTE_MS_DS_LOCKOUT_THRESHOLD)); ui->lockout_duration_spinbox->setValue(spinbox_timespan_units(passwd_settings_obj, ATTRIBUTE_MS_DS_LOCKOUT_DURATION)); ui->reset_lockout_spinbox->setValue(spinbox_timespan_units(passwd_settings_obj, ATTRIBUTE_MS_DS_LOCKOUT_OBSERVATION_WINDOW)); ui->min_age_spinbox->setValue(spinbox_timespan_units(passwd_settings_obj, ATTRIBUTE_MS_DS_MIN_PASSWORD_AGE)); ui->max_age_spinbox->setValue(spinbox_timespan_units(passwd_settings_obj, ATTRIBUTE_MS_DS_MAX_PASSWORD_AGE)); ui->complexity_req_checkbox->setChecked(passwd_settings_obj.get_bool(ATTRIBUTE_MS_DS_PASSWORD_COMPLEXITY_ENABLED)); ui->store_passwd_checkbox->setChecked(passwd_settings_obj.get_bool(ATTRIBUTE_MS_DS_PASSWORD_REVERSIBLE_ENCRYPTION_ENABLED)); ui->applied_list_widget->clear(); dn_applied_list = passwd_settings_obj.get_strings(ATTRIBUTE_PSO_APPLIES_TO); if (dn_applied_list.isEmpty()) { ui->remove_button->setDisabled(true); return; } AdInterface ad; if (!ad.is_connected()) { return; } for (const QString &dn : dn_applied_list) { AdObject applied_object = ad.search_object(dn, {ATTRIBUTE_OBJECT_CATEGORY}); if (applied_object.is_empty()) { continue; } QListWidgetItem *item = new QListWidgetItem(g_icon_manager->get_object_icon(applied_object), dn_get_name(dn), ui->applied_list_widget); item->setData(AppliedItemRole_DN, dn); } } QHash<QString, QList<QByteArray>> PSOEditWidget::pso_settings_values() { using namespace std::chrono; QHash<QString, QList<QByteArray>> settings; settings[ATTRIBUTE_CN] = {ui->name_edit->text().trimmed().toUtf8()}; settings[ATTRIBUTE_MS_DS_PASSWORD_SETTINGS_PRECEDENCE] = {QByteArray::number(ui->precedence_spinbox->value())}; settings[ATTRIBUTE_MS_DS_MIN_PASSWORD_LENGTH] = {QByteArray::number(ui->min_passwd_len_spinbox->value())}; settings[ATTRIBUTE_MS_DS_PASSWORD_HISTORY_LENGTH] = {QByteArray::number(ui->history_length_spinbox->value())}; settings[ATTRIBUTE_MS_DS_LOCKOUT_THRESHOLD] = {QByteArray::number(ui->logon_attempts_spinbox->value())}; settings[ATTRIBUTE_MS_DS_LOCKOUT_DURATION] = { QByteArray::number(-duration_cast<milliseconds>( minutes(ui->lockout_duration_spinbox->value())).count() * MILLIS_TO_100_NANOS) }; settings[ATTRIBUTE_MS_DS_LOCKOUT_OBSERVATION_WINDOW] = { QByteArray::number(-duration_cast<milliseconds>( minutes(ui->reset_lockout_spinbox->value())).count() * MILLIS_TO_100_NANOS) }; settings[ATTRIBUTE_MS_DS_MIN_PASSWORD_AGE] = { QByteArray::number(-duration_cast<milliseconds>( hours(24 * ui->min_age_spinbox->value())).count() * MILLIS_TO_100_NANOS) }; settings[ATTRIBUTE_MS_DS_MAX_PASSWORD_AGE] = { QByteArray::number(-duration_cast<milliseconds>( hours(24 * ui->max_age_spinbox->value())).count() * MILLIS_TO_100_NANOS) }; settings[ATTRIBUTE_MS_DS_PASSWORD_COMPLEXITY_ENABLED] = { QString(ui->complexity_req_checkbox->isChecked() ? LDAP_BOOL_TRUE : LDAP_BOOL_FALSE).toUtf8() }; settings[ATTRIBUTE_MS_DS_PASSWORD_REVERSIBLE_ENCRYPTION_ENABLED] = { QString(ui->store_passwd_checkbox->isChecked() ? LDAP_BOOL_TRUE : LDAP_BOOL_FALSE).toUtf8() }; for (const QString &dn : dn_applied_list) { settings[ATTRIBUTE_PSO_APPLIES_TO].append(dn.toUtf8()); } return settings; } QHash<QString, QList<QString> > PSOEditWidget::pso_settings_string_values() { QHash<QString, QList<QString>> string_value_settings; QHash<QString, QList<QByteArray>> byte_value_settings = pso_settings_values(); for (const QString &attr : byte_value_settings.keys()) { QList<QString> string_values; for (const QByteArray &value : byte_value_settings[attr]) { string_values.append(value); } string_value_settings[attr] = string_values; } return string_value_settings; } QStringList PSOEditWidget::applied_dn_list() const { return dn_applied_list; } QLineEdit *PSOEditWidget::name_line_edit() { return ui->name_edit; } bool PSOEditWidget::settings_are_default() { auto current_values = pso_settings_values(); const QStringList excluded_attrs = { ATTRIBUTE_CN, ATTRIBUTE_MS_DS_PASSWORD_SETTINGS_PRECEDENCE, ATTRIBUTE_APPLIES_TO }; for (const QString &attr : default_setting_values.keys()) { if (excluded_attrs.contains(attr)) { continue; } if (default_setting_values[attr] != current_values[attr]) { return false; } } return true; } void PSOEditWidget::update_defaults() { // TODO: Get defaults from Default Domain Policy. ui->min_passwd_len_spinbox->setValue(7); ui->history_length_spinbox->setValue(24); ui->logon_attempts_spinbox->setValue(0); ui->lockout_duration_spinbox->setValue(30); ui->reset_lockout_spinbox->setValue(30); ui->min_age_spinbox->setValue(1); ui->max_age_spinbox->setValue(42); ui->complexity_req_checkbox->setChecked(true); ui->store_passwd_checkbox->setChecked(false); ui->applied_list_widget->clear(); } void PSOEditWidget::on_add() { auto dialog = new SelectObjectDialog({CLASS_USER, CLASS_GROUP}, SelectObjectDialogMultiSelection_Yes, this); dialog->setWindowTitle(tr("Add applied users/group")); dialog->open(); connect(dialog, &SelectObjectDialog::accepted, this, [this, dialog]() { for (auto selected_data : dialog->get_selected_advanced()) { QListWidgetItem *item = new QListWidgetItem(g_icon_manager->get_object_icon(dn_get_name(selected_data.category)), dn_get_name(selected_data.dn), ui->applied_list_widget); item->setData(AppliedItemRole_DN, selected_data.dn); dn_applied_list.append(selected_data.dn); } }); } void PSOEditWidget::on_remove() { for (auto item : ui->applied_list_widget->selectedItems()) { dn_applied_list.removeAll(item->data(AppliedItemRole_DN).toString()); delete item; } } void PSOEditWidget::set_read_only(bool read_only) { QList<QSpinBox*> spinbox_children = findChildren<QSpinBox*>(QString(), Qt::FindChildrenRecursively); for (auto spinbox : spinbox_children) { spinbox->setReadOnly(read_only); } QList<QCheckBox*> checkbox_children = findChildren<QCheckBox*>(QString(), Qt::FindChildrenRecursively); for (auto checkbox : checkbox_children) { checkbox->setDisabled(read_only); } ui->add_button->setDisabled(read_only); // Only true because no items are selected after list widget enabling ui->remove_button->setDisabled(true); ui->applied_list_widget->setDisabled(read_only); } int PSOEditWidget::spinbox_timespan_units(const AdObject &obj, const QString &attribute) { using namespace std::chrono; qint64 hundred_nanos = -obj.get_value(attribute).toLongLong(); milliseconds msecs(hundred_nanos / MILLIS_TO_100_NANOS); if (attribute == ATTRIBUTE_MS_DS_LOCKOUT_OBSERVATION_WINDOW || attribute == ATTRIBUTE_MS_DS_LOCKOUT_DURATION) { int mins = duration_cast<minutes>(msecs).count(); return mins; } if (attribute == ATTRIBUTE_MS_DS_MIN_PASSWORD_AGE || attribute == ATTRIBUTE_MS_DS_MAX_PASSWORD_AGE) { int days = duration_cast<hours>(msecs).count() / 24; return days; } return 0; }
9,911
C++
.cpp
212
40.415094
129
0.688161
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,737
domain_info_results_widget.cpp
altlinux_admc/src/admc/results_widgets/domain_info_results_widget/domain_info_results_widget.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2023 BaseALT Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 "domain_info_results_widget.h" #include "ui_domain_info_results_widget.h" #include "console_widget/console_widget.h" #include "ad_interface.h" #include "settings.h" #include "ad_defines.h" #include "console_impls/object_impl.h" #include "console_impls/item_type.h" #include "globals.h" #include "ad_config.h" #include "status.h" #include "fsmo/fsmo_utils.h" #include "icon_manager/icon_manager.h" #include "utils.h" #include <QStandardItemModel> #include <QPushButton> DomainInfoResultsWidget::DomainInfoResultsWidget(ConsoleWidget *console_arg) : QWidget(console_arg), ui(new Ui::DomainInfoResultsWidget), console(console_arg) { ui->setupUi(this); model = new QStandardItemModel(this); ui->tree->setModel(model); ui->tree->setHeaderHidden(true); connect(console, &ConsoleWidget::fsmo_master_changed, this, &DomainInfoResultsWidget::update_fsmo_roles); update(); } DomainInfoResultsWidget::~DomainInfoResultsWidget() { delete ui; } void DomainInfoResultsWidget::update() { update_defaults(); DomainInfo_SearchResults results = search_results(); populate_widgets(results); } void DomainInfoResultsWidget::update_fsmo_roles(const QString &new_master_dn, const QString &fsmo_role_string) { QList<QStandardItem*> fsmo_role_item_list = model->findItems(fsmo_role_string, Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive)); if (fsmo_role_item_list.isEmpty()) { return; } const QModelIndex start_index = model->index(0, 0, QModelIndex()); QModelIndexList new_master_index_list = model->match(start_index, DomainInfoTreeItemRole_DN, new_master_dn, 1, Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive)); if (new_master_index_list.isEmpty()) { return; } QStandardItem *fsmo_role_item = fsmo_role_item_list[0]; QModelIndex new_master_index = new_master_index_list[0]; QModelIndex roles_container_index = model->match(new_master_index, DomainInfoTreeItemRole_ItemType, DomainInfoTreeItemType_FSMO_Container, 1, Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive))[0]; model->itemFromIndex(roles_container_index)->appendRow( fsmo_role_item->parent()->takeRow(fsmo_role_item->row())); } void DomainInfoResultsWidget::update_defaults() { model->clear(); const QList<QLabel*> labels { ui->sites_count_value, ui->dc_count_value, ui->domain_functionality_value, ui->forest_functionality_value, ui->domain_schema_value, ui->dc_version_value }; for (auto label : labels) { set_label_failed(label, false); } } QList<QStandardItem *> DomainInfoResultsWidget::get_tree_items(AdInterface &ad) { const QString sites_container_dn = "CN=Sites,CN=Configuration," + g_adconfig->domain_dn(); const QString filter = filter_CONDITION(Condition_Equals, ATTRIBUTE_OBJECT_CLASS, CLASS_SITE); const QHash<QString, AdObject> site_objects = ad.search(sites_container_dn, SearchScope_Children, filter, {ATTRIBUTE_DN, ATTRIBUTE_NAME/*, ATTRIBUTE_GPLINK*/}); QList<QStandardItem *> site_items; if (site_objects.isEmpty()) { g_status->add_message("Failed to find domain sites.", StatusType_Error); return site_items; } for (const AdObject &site_object : site_objects.values()) { QStandardItem *site_item = add_tree_item(site_object.get_string(ATTRIBUTE_NAME), g_icon_manager->get_icon_for_type(ItemIconType_Site_Clean), DomainInfoTreeItemType_Site, nullptr); site_item->setData(site_object.get_dn(), DomainInfoTreeItemRole_DN); add_host_items(site_item, site_object, ad); site_items.append(site_item); } return site_items; } DomainInfo_SearchResults DomainInfoResultsWidget::search_results() { DomainInfo_SearchResults results; AdInterface ad; if (!ad.is_connected()) { return results; } results.tree_items = get_tree_items(ad); const QStringList root_dse_attributes = { ATTRIBUTE_DOMAIN_FUNCTIONALITY_LEVEL, ATTRIBUTE_FOREST_FUNCTIONALITY_LEVEL, ATTRIBUTE_SCHEMA_NAMING_CONTEXT, ATTRIBUTE_DNS_HOST_NAME, ATTRIBUTE_SERVER_NAME }; const AdObject rootDSE = ad.search_object("", root_dse_attributes); const QString server_name = rootDSE.get_string(ATTRIBUTE_SERVER_NAME); const AdObject server_object = ad.search_object(server_name, {ATTRIBUTE_SERVER_REFERENCE}); const AdObject host = ad.search_object(server_object.get_string(ATTRIBUTE_SERVER_REFERENCE), {ATTRIBUTE_OS, ATTRIBUTE_OS_VERSION}); const QString dc_version = host.get_string(ATTRIBUTE_OS).isEmpty() ? QString() : host.get_string(ATTRIBUTE_OS) + QString(" (%1)").arg(host.get_string(ATTRIBUTE_OS_VERSION)); results.domain_controller_version = dc_version; const int forest_level = rootDSE.get_int(ATTRIBUTE_FOREST_FUNCTIONALITY_LEVEL); const QString forest_level_string = QString::number(forest_level) + " " + functionality_level_to_string(forest_level); results.forest_functional_level = forest_level_string; const int domain_level = rootDSE.get_int(ATTRIBUTE_DOMAIN_FUNCTIONALITY_LEVEL); const QString domain_level_string = QString::number(domain_level) + " " + functionality_level_to_string(domain_level); results.domain_functional_level = domain_level_string; const QString schema_dn = rootDSE.get_string(ATTRIBUTE_SCHEMA_NAMING_CONTEXT); const AdObject schema_object = ad.search_object(schema_dn, {ATTRIBUTE_OBJECT_VERSION}); const int domain_schema_version = schema_object.get_int(ATTRIBUTE_OBJECT_VERSION); const QString domain_schema_version_string = QString::number(domain_schema_version) + " " + schema_version_to_string(domain_schema_version); results.domain_schema_version = domain_schema_version_string; return results; } void DomainInfoResultsWidget::populate_widgets(DomainInfo_SearchResults results) { for (auto item : results.tree_items) { model->appendRow(item); } model->sort(0); ui->tree->expandToDepth(1); // Set dc and sites count to label text // Search is performed in the tree to avoid excessive ldap queries const QHash<int, QLabel*> type_label_hash { {DomainInfoTreeItemType_Site, ui->sites_count_value}, {DomainInfoTreeItemType_Host, ui->dc_count_value} }; for (int type : type_label_hash.keys()) { const QModelIndex start_index = model->index(0, 0, QModelIndex()); int count = model->match(start_index, DomainInfoTreeItemRole_ItemType, type, -1, Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive)).count(); if (!count) { set_label_failed(type_label_hash[type], true); } type_label_hash[type]->setText(QString::number(count)); } // Populate labels. Widgets are keys because levels can match const QHash<QLabel*, QString> label_results_hash { {ui->domain_functionality_value, results.domain_functional_level}, {ui->forest_functionality_value, results.forest_functional_level}, {ui->domain_schema_value, results.domain_schema_version}, {ui->dc_version_value, results.domain_controller_version} }; for (QLabel *label : label_results_hash.keys()) { if (label_results_hash[label].isEmpty()) { set_label_failed(label, true); } else { label->setText(label_results_hash[label]); } } } void DomainInfoResultsWidget::add_host_items(QStandardItem *site_item, const AdObject &site_object, AdInterface &ad) { const QString servers_container_dn = "CN=Servers," + site_object.get_dn(); const QString filter = filter_CONDITION(Condition_Equals, ATTRIBUTE_OBJECT_CLASS, CLASS_SERVER); const QHash<QString, AdObject> host_objects = ad.search(servers_container_dn, SearchScope_Children, filter, {ATTRIBUTE_DN, ATTRIBUTE_NAME, ATTRIBUTE_DNS_HOST_NAME}); QHash<QString, QStringList> host_fsmo_map; for (int role = 0; role < FSMORole_COUNT; ++role) { const QString host = current_master_for_role(ad, FSMORole(role)); host_fsmo_map[host].append(string_fsmo_role(FSMORole(role))); } QString host; for (const AdObject &host_object : host_objects.values()) { QStandardItem *host_item = add_tree_item(host_object.get_string(ATTRIBUTE_DNS_HOST_NAME), g_icon_manager->get_icon_for_type(ItemIconType_Domain_Clean), DomainInfoTreeItemType_Host, site_item); host_item->setData(host_object.get_dn(), DomainInfoTreeItemRole_DN); host = host_object.get_string(ATTRIBUTE_DNS_HOST_NAME); QStandardItem *fsmo_roles_container_item = add_tree_item(tr("FSMO roles"), g_icon_manager->get_object_icon(ADMC_CATEGORY_FSMO_ROLE_CONTAINER), DomainInfoTreeItemType_FSMO_Container, host_item); if (host_fsmo_map.keys().contains(host_item->text())) { for (const QString &fsmo_role : host_fsmo_map[host_item->text()]) { add_tree_item(fsmo_role, g_icon_manager->get_object_icon(ADMC_CATEGORY_FSMO_ROLE), DomainInfoTreeItemType_FSMO_Role,fsmo_roles_container_item); } } } } void DomainInfoResultsWidget::set_label_failed(QLabel *label, bool failed) { if (failed) { label->setStyleSheet("color: red"); label->setText(tr("Undefined")); } else { label->setStyleSheet(""); label->setText(""); } } QStandardItem* DomainInfoResultsWidget::add_tree_item(const QString &text, const QIcon &icon, DomainInfoTreeItemType type, QStandardItem *parent_item) { QStandardItem *item = new QStandardItem(icon, text); item->setEditable(false); item->setData(type, DomainInfoTreeItemRole_ItemType); if (parent_item) { parent_item->appendRow(item); } return item; } QString DomainInfoResultsWidget::schema_version_to_string(int version) { switch (version) { case DomainSchemaVersion_WindowsServer2008R2: return "(Windows Server 2008R2)"; case DomainSchemaVersion_WindowsServer2012: return "(Windows Server 2012)"; case DomainSchemaVersion_WindowsServer2012R2: return "(Windows Server 2012R2)"; case DomainSchemaVersion_WindowsServer2016: return "(Windows Server 2016)"; case DomainSchemaVersion_WindowsServer2019: return "(Windows Server 2019/2022)"; default: return QString(); } } QString DomainInfoResultsWidget::functionality_level_to_string(int level) { switch (level) { case 2: return "(Windows Server 2003)"; case 3: return "(Windows Server 2008)"; case 4: return schema_version_to_string(DomainSchemaVersion_WindowsServer2008R2); case 5: return schema_version_to_string(DomainSchemaVersion_WindowsServer2012); case 6: return schema_version_to_string(DomainSchemaVersion_WindowsServer2012R2); case 7: return schema_version_to_string(DomainSchemaVersion_WindowsServer2016); default: return QString(); } }
12,366
C++
.cpp
253
40.960474
159
0.677719
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,738
fsmo_utils.cpp
altlinux_admc/src/admc/fsmo/fsmo_utils.cpp
#include "fsmo_utils.h" #include "ad_config.h" #include "globals.h" #include "adldap.h" #include "utils.h" #include "settings.h" #include "console_widget/console_widget.h" #include "status.h" #include <QString> #include <QModelIndex> bool gpo_edit_without_PDC_disabled = true; QString dn_from_role(FSMORole role) { const QString domain_dn = g_adconfig->domain_dn(); switch (role) { case FSMORole_DomainDNS: return QString("CN=Infrastructure,DC=DomainDnsZones,%1").arg(domain_dn); case FSMORole_ForestDNS: return QString("CN=Infrastructure,DC=ForestDnsZones,%1").arg(domain_dn); case FSMORole_PDCEmulation: return domain_dn; case FSMORole_Schema: return g_adconfig->schema_dn(); case FSMORole_DomainNaming: return g_adconfig->partitions_dn(); case FSMORole_Infrastructure: return QString("CN=Infrastructure,%1").arg(domain_dn); case FSMORole_RidAllocation: return QString("CN=RID Manager$,CN=System,%1").arg(domain_dn); case FSMORole_COUNT: break; }; return QString(); } QString current_master_for_role_dn(AdInterface &ad, QString role_dn) { const AdObject role_object = ad.search_object(role_dn); const QString master_settings_dn = role_object.get_string(ATTRIBUTE_FSMO_ROLE_OWNER); const QString master_dn = dn_get_parent(master_settings_dn); const AdObject master_object = ad.search_object(master_dn); const QString current_master = master_object.get_string(ATTRIBUTE_DNS_HOST_NAME); return current_master; } bool current_dc_is_master_for_role(AdInterface &ad, FSMORole role) { QString role_dn = dn_from_role(role); QString current_master = current_master_for_role_dn(ad, role_dn); QString current_dc = current_dc_dns_host_name(ad); return current_master == current_dc; } void connect_host_with_role(AdInterface &ad, FSMORole role) { QString current_master = current_master_for_role(ad, role); settings_set_variant(SETTING_host, current_master); AdInterface::set_dc(current_master); ad.update_dc(); } void connect_to_PDC_emulator(AdInterface &ad, ConsoleWidget *console) { connect_host_with_role(ad, FSMORole_PDCEmulation); console->refresh_scope(console->domain_info_index()); g_status->add_message(QObject::tr("PDC-Emulator is connected"), StatusType_Success); } QString current_master_for_role(AdInterface &ad, FSMORole role) { QString role_dn = dn_from_role(role); return current_master_for_role_dn(ad, role_dn); } QString string_fsmo_role(FSMORole role) { switch (role) { case FSMORole_DomainDNS: return "Domain DNS"; case FSMORole_ForestDNS: return "Forest DNS"; case FSMORole_PDCEmulation: return "PDC Emulator"; case FSMORole_Schema: return "Schema master"; case FSMORole_DomainNaming: return "Domain naming master"; case FSMORole_Infrastructure: return "Infrastructure master"; case FSMORole_RidAllocation: return "RID master"; case FSMORole_COUNT: break; }; return QString(); } QString fsmo_string_from_dn(const QString &fsmo_role_dn) { for (int role = 0; role < FSMORole_COUNT; ++role) { if (dn_from_role(FSMORole(role)) == fsmo_role_dn) { return string_fsmo_role(FSMORole(role)); } } return QString(); }
3,306
C++
.cpp
83
35.361446
105
0.716246
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,739
fsmo_dialog.cpp
altlinux_admc/src/admc/fsmo/fsmo_dialog.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "fsmo/fsmo_dialog.h" #include "ui_fsmo_dialog.h" #include "adldap.h" #include "fsmo/fsmo_tab.h" #include "fsmo/fsmo_utils.h" #include "globals.h" #include "settings.h" #include <QMessageBox> FSMODialog::FSMODialog(AdInterface &ad, QWidget *parent) : QDialog(parent) { ui = new Ui::FSMODialog(); ui->setupUi(this); setAttribute(Qt::WA_DeleteOnClose); for (int role_i = 0; role_i < FSMORole_COUNT; role_i++) { const FSMORole role = (FSMORole) role_i; const QString title = [&]() { switch (role) { case FSMORole_DomainDNS: return tr("Domain DNS"); case FSMORole_ForestDNS: return tr("Forest DNS"); case FSMORole_PDCEmulation: return tr("PDC Emulation"); case FSMORole_Schema: return tr("Schema"); case FSMORole_DomainNaming: return tr("Domain Naming"); case FSMORole_Infrastructure: return tr("Infrastructure"); case FSMORole_RidAllocation: return tr("Rid Allocation"); case FSMORole_COUNT: break; }; return QString(); }(); const QString role_dn = dn_from_role(role); auto tab = new FSMOTab(title, role_dn); ui->tab_widget->add_tab(tab, title); tab->load(ad); connect(tab, &FSMOTab::master_changed, this, &FSMODialog::master_changed); } ui->warning_widget->setVisible(false); ui->gpo_edit_PDC_check->setChecked(gpo_edit_without_PDC_disabled); connect(ui->gpo_edit_PDC_check, &QCheckBox::toggled, this, &FSMODialog::gpo_edit_PDC_check_toggled); settings_setup_dialog_geometry(SETTING_fsmo_dialog_geometry, this); } FSMODialog::~FSMODialog() { delete ui; } void FSMODialog::gpo_edit_PDC_check_toggled(bool is_checked) { gpo_edit_without_PDC_disabled = is_checked; if (!is_checked) ui->warning_widget->setVisible(true); else ui->warning_widget->setVisible(false); }
2,755
C++
.cpp
69
34.144928
104
0.673783
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,740
fsmo_tab.cpp
altlinux_admc/src/admc/fsmo/fsmo_tab.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "fsmo_tab.h" #include "ui_fsmo_tab.h" #include "adldap.h" #include "globals.h" #include "status.h" #include "utils.h" #include "fsmo/fsmo_utils.h" FSMOTab::FSMOTab(const QString &title, const QString &role_dn_arg) { ui = new Ui::FSMOTab(); ui->setupUi(this); ui->title_label->setText(title); role_dn = role_dn_arg; connect( ui->change_button, &QPushButton::clicked, this, &FSMOTab::change_master); } FSMOTab::~FSMOTab() { delete ui; } void FSMOTab::load(AdInterface &ad) { const QString current_master = current_master_for_role_dn(ad, role_dn); const QString new_master = current_dc_dns_host_name(ad); ui->current_edit->setText(current_master); ui->new_edit->setText(new_master); } void FSMOTab::change_master() { AdInterface ad; if (ad_failed(ad, this)) { return; } const QString current_master = ui->current_edit->text(); const QString new_master = ui->new_edit->text(); if (current_master == new_master) { message_box_warning(this, tr("Error"), tr("This machine is already a master for this role. Switch to a different machine in Connection Options to change master.")); return; } const AdObject rootDSE = ad.search_object(""); const QString new_master_service = rootDSE.get_string(ATTRIBUTE_DS_SERVICE_NAME); const bool success = ad.attribute_replace_string(role_dn, ATTRIBUTE_FSMO_ROLE_OWNER, new_master_service); g_status->display_ad_messages(ad, this); if (success) { load(ad); const QString new_master_dn = rootDSE.get_string(ATTRIBUTE_SERVER_NAME); emit master_changed(new_master_dn, fsmo_string_from_dn(role_dn)); } }
2,485
C++
.cpp
65
34.276923
172
0.703997
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,741
console_drag_model.cpp
altlinux_admc/src/admc/console_widget/console_drag_model.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "console_widget/console_drag_model.h" #include "console_widget/console_widget.h" #include "console_widget/console_widget_p.h" #include <QMimeData> #define MIME_TYPE_CONSOLE "MIME_TYPE_CONSOLE" QModelIndex prev_parent = QModelIndex(); bool drag_start = false; ConsoleDragModel::ConsoleDragModel(ConsoleWidget *console_arg) : QStandardItemModel(console_arg) { console = console_arg; } QMimeData *ConsoleDragModel::mimeData(const QModelIndexList &indexes) const { const QList<QPersistentModelIndex> main_indexes = [&]() { QList<QPersistentModelIndex> out; for (const QModelIndex &index : indexes) { if (index.column() == 0) { out.append(QPersistentModelIndex(index)); } } return out; }(); console->d->start_drag(main_indexes); auto data = new QMimeData(); // NOTE: even though we don't store any data in // mimedata, set empty data with our type so that we can // reject any mimedata not created in console drag model // by checking if mimedata has our mime type. data->setData(MIME_TYPE_CONSOLE, QByteArray()); drag_start = true; return data; } bool ConsoleDragModel::canDropMimeData(const QMimeData *data, Qt::DropAction, int, int, const QModelIndex &parent) const { if (!data->hasFormat(MIME_TYPE_CONSOLE)) { return false; } // NOTE: this is a bandaid for a Qt bug. The bug causes // canDropMimeData() to stop being called for a given // view if canDropMimeData() returns false for the first // call when drag is entering the view. This results in // the drop indicator being stuck in "can't drop" state // until dragging leaves the view. The bandaid fix is to // always return true from canDropMimeData() when parent // index changes (when hovering over new object). Also // return true for invalid index for cases where drag is // hovered over empty space. Also return true for the // first canDrop() call when drag just started. // https://bugreports.qt.io/browse/QTBUG-76418 if (prev_parent != parent || parent == QModelIndex() || drag_start) { prev_parent = parent; drag_start = false; return true; } // NOTE: using index at 0th column because that column // has the item roles const QModelIndex target = parent.siblingAtColumn(0); const bool can_drop = console->d->can_drop(target); return can_drop; } bool ConsoleDragModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int, int, const QModelIndex &parent) { UNUSED_ARG(action); if (!data->hasFormat(MIME_TYPE_CONSOLE)) { return false; } // NOTE: using index at 0th column because that column // has the item roles const QModelIndex target = parent.siblingAtColumn(0); console->d->drop(target); return true; }
3,664
C++
.cpp
88
37.011364
122
0.706843
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,742
console_impl.cpp
altlinux_admc/src/admc/console_widget/console_impl.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "console_widget/console_impl.h" #include "console_widget/console_widget.h" #include "console_widget/results_view.h" #include <QSet> #include <QVariant> ConsoleImpl::ConsoleImpl(ConsoleWidget *console_arg) : QObject(console_arg) { console = console_arg; results_widget = nullptr; results_view = nullptr; } void ConsoleImpl::fetch(const QModelIndex &index) { UNUSED_ARG(index); } bool ConsoleImpl::can_drop(const QList<QPersistentModelIndex> &dropped_list, const QSet<int> &dropped_type_list, const QPersistentModelIndex &target, const int target_type) { UNUSED_ARG(dropped_list); UNUSED_ARG(dropped_type_list); UNUSED_ARG(target); UNUSED_ARG(target_type); return false; } void ConsoleImpl::drop(const QList<QPersistentModelIndex> &dropped_list, const QSet<int> &dropped_type_list, const QPersistentModelIndex &target, const int target_type) { UNUSED_ARG(dropped_list); UNUSED_ARG(dropped_type_list); UNUSED_ARG(target); UNUSED_ARG(target_type); } QString ConsoleImpl::get_description(const QModelIndex &index) const { UNUSED_ARG(index); return QString(); } void ConsoleImpl::activate(const QModelIndex &index) { UNUSED_ARG(index); } void ConsoleImpl::selected_as_scope(const QModelIndex &index) { UNUSED_ARG(index); } QList<QAction *> ConsoleImpl::get_all_custom_actions() const { return {}; } QSet<QAction *> ConsoleImpl::get_custom_actions(const QModelIndex &index, const bool single_selection) const { UNUSED_ARG(index); UNUSED_ARG(single_selection); return {}; } QSet<QAction *> ConsoleImpl::get_disabled_custom_actions(const QModelIndex &index, const bool single_selection) const { UNUSED_ARG(index); UNUSED_ARG(single_selection); return {}; } QSet<StandardAction> ConsoleImpl::get_standard_actions(const QModelIndex &index, const bool single_selection) const { UNUSED_ARG(index); UNUSED_ARG(single_selection); return {}; } QSet<StandardAction> ConsoleImpl::get_disabled_standard_actions(const QModelIndex &index, const bool single_selection) const { UNUSED_ARG(index); UNUSED_ARG(single_selection); return {}; } void ConsoleImpl::copy(const QList<QModelIndex> &index_list) { UNUSED_ARG(index_list); } void ConsoleImpl::cut(const QList<QModelIndex> &index_list) { UNUSED_ARG(index_list); } void ConsoleImpl::rename(const QList<QModelIndex> &index_list) { UNUSED_ARG(index_list); } void ConsoleImpl::delete_action(const QList<QModelIndex> &index_list) { UNUSED_ARG(index_list); } void ConsoleImpl::paste(const QList<QModelIndex> &index_list) { UNUSED_ARG(index_list); } void ConsoleImpl::print(const QList<QModelIndex> &index_list) { UNUSED_ARG(index_list); } void ConsoleImpl::refresh(const QList<QModelIndex> &index_list) { UNUSED_ARG(index_list); } void ConsoleImpl::properties(const QList<QModelIndex> &index_list) { UNUSED_ARG(index_list); } QList<QString> ConsoleImpl::column_labels() const { return QList<QString>(); } QList<int> ConsoleImpl::default_columns() const { return QList<int>(); } void ConsoleImpl::update_results_widget(const QModelIndex &index) const { UNUSED_ARG(index); } QVariant ConsoleImpl::save_state() const { if (view() != nullptr) { return view()->save_state(); } else { return QVariant(); } } void ConsoleImpl::restore_state(const QVariant &state) { if (view() != nullptr) { view()->restore_state(state, default_columns()); } } QWidget *ConsoleImpl::widget() const { if (results_widget != nullptr) { return results_widget; } else if (results_view != nullptr) { return results_view; } else { return nullptr; } } ResultsView *ConsoleImpl::view() const { return results_view; } void ConsoleImpl::set_results_view(ResultsView *results_view_arg) { results_view = results_view_arg; } void ConsoleImpl::set_results_widget(QWidget *results_widget_arg) { results_widget = results_widget_arg; }
4,798
C++
.cpp
143
30.34965
174
0.73381
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,743
scope_proxy_model.cpp
altlinux_admc/src/admc/console_widget/scope_proxy_model.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "console_widget/scope_proxy_model.h" #include "console_widget/console_widget_p.h" // This tricks the view into thinking that an item in tree // has children while the item is unfetched. This causes the // expander to be shown while the item is unfetched. After // the item is fetched, normal behavior is restored. bool ScopeProxyModel::hasChildren(const QModelIndex &parent) const { const bool was_fetched = parent.data(ConsoleRole_WasFetched).toBool(); const bool unfetched = !was_fetched; if (unfetched) { return true; } else { return QSortFilterProxyModel::hasChildren(parent); } } bool ScopeProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { const QModelIndex source_index = sourceModel()->index(source_row, 0, source_parent); const bool is_scope = source_index.data(ConsoleRole_IsScope).toBool(); return is_scope; } bool ScopeProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { const int left_sort_index = left.data(ConsoleRole_SortIndex).toInt(); const int right_sort_index = right.data(ConsoleRole_SortIndex).toInt(); if (left_sort_index != right_sort_index) { const bool out = (left_sort_index < right_sort_index); return out; } const bool out = QSortFilterProxyModel::lessThan(left, right); return out; }
2,161
C++
.cpp
49
40.693878
96
0.742381
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,744
customize_columns_dialog.cpp
altlinux_admc/src/admc/console_widget/customize_columns_dialog.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "console_widget/customize_columns_dialog.h" #include "console_widget/customize_columns_dialog_p.h" #include <QCheckBox> #include <QDialog> #include <QDialogButtonBox> #include <QHeaderView> #include <QPushButton> #include <QScrollArea> #include <QTreeView> #include <QVBoxLayout> CustomizeColumnsDialogPrivate::CustomizeColumnsDialogPrivate(CustomizeColumnsDialog *q) : QObject(q) { } CustomizeColumnsDialog::CustomizeColumnsDialog(QTreeView *view_arg, const QList<int> &default_columns_arg, QWidget *parent) : QDialog(parent) { d = new CustomizeColumnsDialogPrivate(this); setAttribute(Qt::WA_DeleteOnClose); setWindowTitle(tr("Customize Columns")); d->view = view_arg; d->default_columns = default_columns_arg; QHeaderView *header = d->view->header(); QAbstractItemModel *model = d->view->model(); auto checkboxes_widget = new QWidget(); auto checkboxes_layout = new QVBoxLayout(); checkboxes_widget->setLayout(checkboxes_layout); for (int i = 0; i < header->count(); i++) { const QString column_name = model->headerData(i, Qt::Horizontal).toString(); auto checkbox = new QCheckBox(column_name); const bool currently_hidden = header->isSectionHidden(i); checkbox->setChecked(!currently_hidden); d->checkbox_list.append(checkbox); } for (int i = 0; i < header->count(); i++) { auto checkbox = d->checkbox_list[i]; checkboxes_layout->addWidget(checkbox); } auto scroll_area = new QScrollArea(); scroll_area->setWidget(checkboxes_widget); auto button_box = new QDialogButtonBox(); auto ok_button = button_box->addButton(QDialogButtonBox::Ok); auto cancel_button = button_box->addButton(QDialogButtonBox::Cancel); auto restore_defaults_button = button_box->addButton(QDialogButtonBox::RestoreDefaults); auto dialog_layout = new QVBoxLayout(); setLayout(dialog_layout); dialog_layout->addWidget(scroll_area); dialog_layout->addWidget(button_box); connect( ok_button, &QPushButton::clicked, this, &CustomizeColumnsDialog::accept); connect( cancel_button, &QPushButton::clicked, this, &QDialog::reject); connect( restore_defaults_button, &QPushButton::clicked, d, &CustomizeColumnsDialogPrivate::restore_defaults); } void CustomizeColumnsDialog::accept() { QHeaderView *header = d->view->header(); for (int i = 0; i < d->checkbox_list.size(); i++) { QCheckBox *checkbox = d->checkbox_list[i]; const bool hidden = !checkbox->isChecked(); header->setSectionHidden(i, hidden); } QDialog::accept(); } void CustomizeColumnsDialogPrivate::restore_defaults() { for (int i = 0; i < checkbox_list.size(); i++) { QCheckBox *checkbox = checkbox_list[i]; const bool hidden = !default_columns.contains(i); checkbox->setChecked(!hidden); } }
3,713
C++
.cpp
91
36.230769
123
0.711864
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,745
console_widget.cpp
altlinux_admc/src/admc/console_widget/console_widget.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "console_widget/console_widget.h" #include "console_widget/console_widget_p.h" #include "console_widget/console_drag_model.h" #include "console_widget/console_impl.h" #include "console_widget/customize_columns_dialog.h" #include "console_widget/results_view.h" #include "console_widget/scope_proxy_model.h" #include "console_impls/item_type.h" #include <QAction> #include <QApplication> #include <QDebug> #include <QHeaderView> #include <QLabel> #include <QMenu> #include <QSplitter> #include <QStack> #include <QStackedWidget> #include <QToolBar> #include <QTreeView> #include <QVBoxLayout> #include <algorithm> #define SPLITTER_STATE "SPLITTER_STATE" const QString CONSOLE_TREE_STATE = "CONSOLE_TREE_STATE"; const QString DESCRIPTION_BAR_STATE = "DESCRIPTION_BAR_STATE"; const QList<StandardAction> standard_action_list = { StandardAction_Copy, StandardAction_Cut, StandardAction_Rename, StandardAction_Delete, StandardAction_Paste, StandardAction_Print, StandardAction_Refresh, StandardAction_Properties, }; QString results_state_name(const int type); class ScopeView : public QTreeView { public: using QTreeView::QTreeView; void resizeEvent(QResizeEvent *event) override { QTreeView::resizeEvent(event); QSize areaSize = viewport()->size(); const int view_width = areaSize.width(); const int content_width = sizeHintForColumn(0); header()->setDefaultSectionSize(std::max(view_width, content_width)); } }; ConsoleWidget::ConsoleWidget(QWidget *parent) : QWidget(parent) { d = new ConsoleWidgetPrivate(this); d->scope_view = new ScopeView(this); d->scope_view->setHeaderHidden(true); d->scope_view->setExpandsOnDoubleClick(true); d->scope_view->setEditTriggers(QAbstractItemView::NoEditTriggers); d->scope_view->setContextMenuPolicy(Qt::CustomContextMenu); d->scope_view->setDragDropMode(QAbstractItemView::DragDrop); // NOTE: this makes it so that you can't drag drop between rows (even though name/description don't say anything about that) d->scope_view->setDragDropOverwriteMode(true); // NOTE: this is a hacky solution to the problem of // scope view cutting off long items and not turning on // scrollbar so that full item can be viewed. // "stretchLastSection" setting is turned off - this // fixes item being stretched to fit the view and now // items can be their full length. // // BUT, without "stretchLastSection", selecting items // looks wrong because selection rectangle doesn't // stretch to the whole view and also depends on the // width of the widest item that is currently visible. // To fix this visual problem, we change resize mode to // interactive and override scope view's resizeEvent. In // resizeEvent() we resize section to width of scope // view or to content width, depending on which one is // greater at the moment. d->scope_view->header()->setStretchLastSection(false); d->scope_view->header()->setSectionResizeMode(QHeaderView::Interactive); d->scope_view->setRootIsDecorated(false); d->model = new ConsoleDragModel(this); // NOTE: using a proxy model for scope to be able to do // case insensitive sorting d->scope_proxy_model = new ScopeProxyModel(this); d->scope_proxy_model->setSourceModel(d->model); d->scope_proxy_model->setSortCaseSensitivity(Qt::CaseInsensitive); d->scope_view->setModel(d->scope_proxy_model); d->focused_view = d->scope_view; d->description_bar = new QWidget(); d->description_bar_left = new QLabel(); d->description_bar_right = new QLabel(); d->description_bar_left->setStyleSheet("font-weight: bold"); d->description_bar_right->setAlignment(Qt::AlignRight); d->results_stacked_widget = new QStackedWidget(); d->standard_action_map[StandardAction_Copy] = new QAction(tr("Copy"), this); d->standard_action_map[StandardAction_Cut] = new QAction(tr("Cut"), this); d->standard_action_map[StandardAction_Rename] = new QAction(tr("Rename"), this); d->standard_action_map[StandardAction_Delete] = new QAction(tr("Delete"), this); d->standard_action_map[StandardAction_Paste] = new QAction(tr("Paste"), this); d->standard_action_map[StandardAction_Print] = new QAction(tr("Print"), this); d->standard_action_map[StandardAction_Refresh] = new QAction(tr("Refresh"), this); d->standard_action_map[StandardAction_Properties] = new QAction(tr("Properties"), this); // NOTE: need to add a dummy view until a real view is // added when a scope item is selected. If this is not // done and stacked widget is left empty, it's sizing is // set to minimum which causes an incorrect ratio in the // scope/results splitter auto dummy_view = new QTreeView(); d->results_stacked_widget->addWidget(dummy_view); auto description_layout = new QHBoxLayout(); description_layout->setContentsMargins(0, 0, 0, 0); description_layout->setSpacing(0); d->description_bar->setLayout(description_layout); description_layout->addWidget(d->description_bar_left); description_layout->addSpacing(10); description_layout->addStretch(); description_layout->addWidget(d->description_bar_right); description_layout->addSpacing(10); auto results_wrapper = new QWidget(); auto results_layout = new QVBoxLayout(); results_wrapper->setLayout(results_layout); results_layout->setContentsMargins(0, 0, 0, 0); results_layout->setSpacing(0); results_layout->addWidget(d->description_bar); results_layout->addWidget(d->results_stacked_widget); d->splitter = new QSplitter(Qt::Horizontal); d->splitter->addWidget(d->scope_view); d->splitter->addWidget(results_wrapper); d->splitter->setStretchFactor(0, 1); d->splitter->setStretchFactor(1, 2); auto layout = new QVBoxLayout(); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); setLayout(layout); layout->addWidget(d->splitter); d->default_results_widget = new QWidget(); d->results_stacked_widget->addWidget(d->default_results_widget); // NOTE: default impl uses base class which will do // nothing d->default_impl = new ConsoleImpl(this); connect( d->scope_view, &QTreeView::expanded, d, &ConsoleWidgetPrivate::on_scope_expanded); connect( d->scope_view->selectionModel(), &QItemSelectionModel::currentChanged, d, &ConsoleWidgetPrivate::on_current_scope_item_changed); connect( d->scope_view->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ConsoleWidget::selection_changed); connect( d->model, &QStandardItemModel::rowsAboutToBeRemoved, d, &ConsoleWidgetPrivate::on_scope_items_about_to_be_removed); // Update description bar when results count changes connect( d->model, &QAbstractItemModel::rowsInserted, d, &ConsoleWidgetPrivate::update_description); connect( d->model, &QAbstractItemModel::rowsRemoved, d, &ConsoleWidgetPrivate::update_description); for (const StandardAction &action_enum : standard_action_list) { QAction *action = d->standard_action_map[action_enum]; connect( action, &QAction::triggered, this, [this, action_enum]() { d->on_standard_action(action_enum); }); } connect( d->scope_view, &QWidget::customContextMenuRequested, d, &ConsoleWidgetPrivate::on_scope_context_menu); connect( qApp, &QApplication::focusChanged, d, &ConsoleWidgetPrivate::on_focus_changed); d->domain_info_index = add_scope_item(ItemType_DomainInfo, QModelIndex())[0]->index(); d->scope_view->expand(d->domain_info_index); connect(d->scope_view, &QTreeView::collapsed, [this](const QModelIndex &index_proxy) { const QModelIndex index = d->scope_proxy_model->mapToSource(index_proxy); if (index == d->domain_info_index) { d->scope_view->expand(index_proxy); } }); } void ConsoleWidget::register_impl(const int type, ConsoleImpl *impl) { d->impl_map[type] = impl; QWidget *results_widget = impl->widget(); if (results_widget != nullptr) { d->results_stacked_widget->addWidget(results_widget); } ResultsView *results_view = impl->view(); if (results_view != nullptr) { results_view->set_model(d->model); results_view->set_parent(get_current_scope_item()); connect( results_view, &ResultsView::activated, d, &ConsoleWidgetPrivate::on_results_activated); connect( results_view, &ResultsView::context_menu, d, &ConsoleWidgetPrivate::on_results_context_menu); connect( results_view, &ResultsView::selection_changed, this, &ConsoleWidget::selection_changed); } } QList<QStandardItem *> ConsoleWidget::add_scope_item(const int type, const QModelIndex &parent) { const QList<QStandardItem *> row = add_results_item(type, parent); row[0]->setData(false, ConsoleRole_WasFetched); row[0]->setData(true, ConsoleRole_IsScope); d->scope_proxy_model->sort(0, Qt::AscendingOrder); return row; } QList<QStandardItem *> ConsoleWidget::add_results_item(const int type, const QModelIndex &parent) { QStandardItem *parent_item = [&]() { if (parent.isValid()) { return d->model->itemFromIndex(parent); } else { return d->model->invisibleRootItem(); } }(); // Make item row const QList<QStandardItem *> row = [&]() { QList<QStandardItem *> out; const int column_count = [&]() { if (parent_item == d->model->invisibleRootItem()) { return 1; } else { ConsoleImpl *parent_impl = d->get_impl(parent); return parent_impl->column_labels().size(); } }(); for (int i = 0; i < column_count; i++) { const auto item = new QStandardItem(); out.append(item); } return out; }(); row[0]->setData(false, ConsoleRole_IsScope); row[0]->setData(type, ConsoleRole_Type); parent_item->appendRow(row); return row; } void ConsoleWidget::delete_item(const QModelIndex &index) { if (!index.isValid()) { return; } // NOTE: select parent of index, if index is currently // selected. Qt crashes otherwise, not sure why. const QModelIndex current_scope = get_current_scope_item(); if (current_scope == index) { set_current_scope(index.parent()); } d->model->removeRows(index.row(), 1, index.parent()); } void ConsoleWidget::set_current_scope(const QModelIndex &index) { const QModelIndex index_proxy = d->scope_proxy_model->mapFromSource(index); d->scope_view->selectionModel()->setCurrentIndex(index_proxy, QItemSelectionModel::Current | QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); } void ConsoleWidget::refresh_scope(const QModelIndex &index) { if (!index.isValid()) { return; } ConsoleImpl *impl = d->get_impl(index); impl->refresh({index}); } QList<QModelIndex> ConsoleWidget::get_selected_items(const int type) const { QList<QModelIndex> out; const QList<QModelIndex> all_selected = d->get_all_selected_items(); for (const QModelIndex &index : all_selected) { const int this_type = console_item_get_type(index); if (this_type == type) { out.append(index); } } return out; } QModelIndex ConsoleWidget::get_selected_item(const int type) const { const QList<QModelIndex> index_list = get_selected_items(type); if (!index_list.isEmpty()) { return index_list[0]; } else { return QModelIndex(); } } QList<QModelIndex> ConsoleWidget::search_items(const QModelIndex &parent, int role, const QVariant &value, const QList<int> &type_list) const { const QList<QModelIndex> all_matches = [&]() { QList<QModelIndex> out; // NOTE: start index may be invalid if parent has no // children const QModelIndex start_index = d->model->index(0, 0, parent); if (start_index.isValid()) { const QList<QModelIndex> descendant_matches = d->model->match(start_index, role, value, -1, Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive)); out.append(descendant_matches); } const QVariant parent_value = parent.data(role); const bool parent_is_match = (parent_value.isValid() && parent_value == value); if (parent_is_match) { out.append(parent); } return out; }(); const QList<QModelIndex> filtered_matches = [&]() { if (type_list.isEmpty()) { return all_matches; } QList<QModelIndex> out; for (const QModelIndex &index : all_matches) { const QVariant type_variant = index.data(ConsoleRole_Type); if (type_variant.isValid()) { const int this_type = type_variant.toInt(); if (type_list.contains(this_type)) { out.append(index); } } } return out; }(); return filtered_matches; } // TODO: remove duplication between two search_items() // f-ns and deal with the weirdness around whether // search iteration includes parent or not. Once this // is done it may be possible to simplify // get_x_tree_root() f-ns. QList<QModelIndex> ConsoleWidget::search_items(const QModelIndex &parent, const QList<int> &type_list) const { QList<QModelIndex> out; for (const int type : type_list) { const int role = ConsoleRole_Type; const int value = type; // NOTE: start index may be invalid if parent has no // children const QModelIndex start_index = d->model->index(0, 0, parent); if (start_index.isValid()) { const QList<QModelIndex> descendant_matches = d->model->match(start_index, role, value, -1, Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive)); out.append(descendant_matches); } const QVariant parent_value = parent.data(role); const bool parent_is_match = (parent_value.isValid() && parent_value == value); if (parent_is_match) { out.append(parent); } } return out; } QModelIndex ConsoleWidget::search_item(const QModelIndex &parent, int role, const QVariant &value, const QList<int> &type_list) const { const QList<QModelIndex> index_list = search_items(parent, role, value, type_list); if (!index_list.isEmpty()) { const QModelIndex out = index_list[0]; return out; } else { return QModelIndex(); } } QModelIndex ConsoleWidget::search_item(const QModelIndex &parent, const QList<int> &type) const { const QList<QModelIndex> index_list = search_items(parent, type); if (!index_list.isEmpty()) { const QModelIndex out = index_list[0]; return out; } else { return QModelIndex(); } } QModelIndex ConsoleWidget::get_current_scope_item() const { const QModelIndex index = d->scope_view->selectionModel()->currentIndex(); if (index.isValid()) { const QModelIndex source_index = d->scope_proxy_model->mapToSource(index); return source_index; } else { return QModelIndex(); } } int ConsoleWidget::get_child_count(const QModelIndex &index) const { const int out = d->model->rowCount(index); return out; } QStandardItem *ConsoleWidget::get_item(const QModelIndex &index) const { return d->model->itemFromIndex(index); } QList<QStandardItem *> ConsoleWidget::get_row(const QModelIndex &index) const { QList<QStandardItem *> row; for (int col = 0; col < d->model->columnCount(index.parent()); col++) { const QModelIndex sibling = index.siblingAtColumn(col); QStandardItem *item = d->model->itemFromIndex(sibling); row.append(item); } return row; } QVariant ConsoleWidget::save_state() const { QHash<QString, QVariant> state; const QByteArray splitter_state = d->splitter->saveState(); state[SPLITTER_STATE] = QVariant(splitter_state); state[CONSOLE_TREE_STATE] = d->actions.toggle_console_tree->isChecked(); state[DESCRIPTION_BAR_STATE] = d->actions.toggle_description_bar->isChecked(); for (const int type : d->impl_map.keys()) { const ConsoleImpl *impl = d->impl_map[type]; const QString results_name = results_state_name(type); const QVariant results_state = impl->save_state(); state[results_name] = results_state; } return QVariant(state); } void ConsoleWidget::restore_state(const QVariant &state_variant) { const QHash<QString, QVariant> state = state_variant.toHash(); const QByteArray splitter_state = state.value(SPLITTER_STATE, QVariant()).toByteArray(); d->splitter->restoreState(splitter_state); const bool toggle_console_tree_value = state.value(CONSOLE_TREE_STATE, true).toBool(); d->actions.toggle_console_tree->setChecked(toggle_console_tree_value); d->on_toggle_console_tree(); const bool toggle_description_bar_value = state.value(DESCRIPTION_BAR_STATE, true).toBool(); d->actions.toggle_description_bar->setChecked(toggle_description_bar_value); d->on_toggle_description_bar(); for (const int type : d->impl_map.keys()) { ConsoleImpl *impl = d->impl_map[type]; // NOTE: need to call this before restoring results // state because otherwise results view header can // have incorrect sections which breaks state // restoration d->model->setHorizontalHeaderLabels(impl->column_labels()); const QString results_name = results_state_name(type); const QVariant results_state = state.value(results_name, QVariant()); impl->restore_state(results_state); } // Restore displayed of currently selected view // type setting QAction *current_view_type_action = [&]() -> QAction * { ConsoleImpl *current_impl = d->get_current_scope_impl(); ResultsView *current_results_view = current_impl->view(); if (!current_results_view) { return nullptr; } const ResultsViewType current_results_view_type = current_results_view->current_view_type(); switch (current_results_view_type) { case ResultsViewType_Icons: return d->actions.view_icons; case ResultsViewType_List: return d->actions.view_list; case ResultsViewType_Detail: return d->actions.view_detail; } return nullptr; }(); if (current_view_type_action != nullptr) { current_view_type_action->setChecked(true); } } void ConsoleWidget::set_scope_view_visible(const bool visible) { d->scope_view->setVisible(visible); } void ConsoleWidget::delete_children(const QModelIndex &parent) { d->model->removeRows(0, d->model->rowCount(parent), parent); } // Show/hide actions based on what's selected and emit the // signal void ConsoleWidget::setup_menubar_action_menu(QMenu *menu) { d->add_actions(menu); connect( menu, &QMenu::aboutToShow, d, &ConsoleWidgetPrivate::update_actions); } void ConsoleWidget::set_item_sort_index(const QModelIndex &index, const int sort_index) { d->model->setData(index, sort_index, ConsoleRole_SortIndex); } void ConsoleWidget::update_current_item_results_widget() { d->get_current_scope_impl()->update_results_widget(get_current_scope_item()); } QWidget *ConsoleWidget::get_result_widget_for_index(const QModelIndex &index) { ConsoleImpl *current_item_impl = d->get_impl(index); QWidget *result_widget; if (current_item_impl) result_widget = current_item_impl->widget(); return result_widget; } void ConsoleWidget::clear_scope_tree() { delete_children(d->domain_info_index); } void ConsoleWidget::expand_item(const QModelIndex &index) { if (!index.isValid()) { return; } const QModelIndex index_proxy = d->scope_proxy_model->mapFromSource(index); d->scope_view->expand(index_proxy); } QPersistentModelIndex ConsoleWidget::domain_info_index() { return d->domain_info_index; } void ConsoleWidget::resizeEvent(QResizeEvent *event) { d->update_description(); QWidget::resizeEvent(event); } void ConsoleWidgetPrivate::add_actions(QMenu *menu) { // Add custom actions const QList<QAction *> custom_action_list = get_custom_action_list(); for (QAction *action : custom_action_list) { menu->addAction(action); } menu->addSeparator(); // Add standard actions menu->addAction(standard_action_map[StandardAction_Copy]); menu->addAction(standard_action_map[StandardAction_Cut]); menu->addAction(standard_action_map[StandardAction_Rename]); menu->addAction(standard_action_map[StandardAction_Delete]); menu->addAction(standard_action_map[StandardAction_Paste]); menu->addAction(standard_action_map[StandardAction_Print]); menu->addAction(standard_action_map[StandardAction_Refresh]); menu->addSeparator(); menu->addAction(standard_action_map[StandardAction_Properties]); } // Returns whether any action is visible bool ConsoleWidgetPrivate::update_actions() { const QList<QModelIndex> selected_list = get_all_selected_items(); if (!selected_list.isEmpty() && !selected_list[0].isValid()) { return false; } const bool single_selection = (selected_list.size() == 1); // // Collect information about action state from impl's // const QSet<QAction *> visible_custom_action_set = [&]() { QSet<QAction *> out; for (int i = 0; i < selected_list.size(); i++) { const QModelIndex index = selected_list[i]; ConsoleImpl *impl = get_impl(index); QSet<QAction *> for_this_index = impl->get_custom_actions(index, single_selection); if (i == 0) { // NOTE: for first index, add the whole set // instead of intersecting, otherwise total set // would just stay empty out = for_this_index; } else { out.intersect(for_this_index); } } return out; }(); const QSet<QAction *> disabled_custom_action_set = [&]() { QSet<QAction *> out; for (int i = 0; i < selected_list.size(); i++) { const QModelIndex index = selected_list[i]; ConsoleImpl *impl = get_impl(index); QSet<QAction *> for_this_index = impl->get_disabled_custom_actions(index, single_selection); if (i == 0) { // NOTE: for first index, add the whole set // instead of intersecting, otherwise total set // would just stay empty out = for_this_index; } else { out.intersect(for_this_index); } } return out; }(); const QSet<StandardAction> visible_standard_actions = [&]() { QSet<StandardAction> out; for (int i = 0; i < selected_list.size(); i++) { const QModelIndex index = selected_list[i]; ConsoleImpl *impl = get_impl(index); QSet<StandardAction> for_this_index = impl->get_standard_actions(index, single_selection); if (i == 0) { // NOTE: for first index, add the whole set // instead of intersecting, otherwise total set // would just stay empty out = for_this_index; } else { out.intersect(for_this_index); } } return out; }(); const QSet<StandardAction> disabled_standard_actions = [&]() { QSet<StandardAction> out; for (int i = 0; i < selected_list.size(); i++) { const QModelIndex index = selected_list[i]; ConsoleImpl *impl = get_impl(index); QSet<StandardAction> for_this_index = impl->get_disabled_standard_actions(index, single_selection); if (i == 0) { // NOTE: for first index, add the whole set // instead of intersecting, otherwise total set // would just stay empty out = for_this_index; } else { out.intersect(for_this_index); } } return out; }(); // // Apply action state // const QList<QAction *> custom_action_list = get_custom_action_list(); // Show/hide custom actions for (QAction *action : custom_action_list) { const bool visible = visible_custom_action_set.contains(action); action->setVisible(visible); } // Enable/disable custom actions for (QAction *action : custom_action_list) { const bool disabled = disabled_custom_action_set.contains(action); action->setDisabled(disabled); } // Show/hide standard actions for (const StandardAction &action_enum : standard_action_list) { const bool visible = visible_standard_actions.contains(action_enum); QAction *action = standard_action_map[action_enum]; action->setVisible(visible); } // Enable/disable standard actions for (const StandardAction &action_enum : standard_action_list) { const bool disabled = disabled_standard_actions.contains(action_enum); QAction *action = standard_action_map[action_enum]; action->setDisabled(disabled); } const bool any_action_is_visible = (!visible_standard_actions.isEmpty() || !visible_custom_action_set.isEmpty()); return any_action_is_visible; } void ConsoleWidget::set_actions(const ConsoleWidgetActions &actions_arg) { d->actions = actions_arg; // Setup exclusivity for view type actions auto view_type_group = new QActionGroup(this); view_type_group->addAction(d->actions.view_icons); view_type_group->addAction(d->actions.view_list); view_type_group->addAction(d->actions.view_detail); connect( d->actions.navigate_up, &QAction::triggered, d, &ConsoleWidgetPrivate::on_navigate_up); connect( d->actions.navigate_back, &QAction::triggered, d, &ConsoleWidgetPrivate::on_navigate_back); connect( d->actions.navigate_forward, &QAction::triggered, d, &ConsoleWidgetPrivate::on_navigate_forward); connect( d->actions.refresh, &QAction::triggered, d, &ConsoleWidgetPrivate::on_refresh); connect( d->actions.customize_columns, &QAction::triggered, d, &ConsoleWidgetPrivate::on_customize_columns); connect( d->actions.view_icons, &QAction::triggered, d, &ConsoleWidgetPrivate::on_view_icons); connect( d->actions.view_list, &QAction::triggered, d, &ConsoleWidgetPrivate::on_view_list); connect( d->actions.view_detail, &QAction::triggered, d, &ConsoleWidgetPrivate::on_view_detail); connect( d->actions.toggle_console_tree, &QAction::triggered, d, &ConsoleWidgetPrivate::on_toggle_console_tree); connect( d->actions.toggle_description_bar, &QAction::triggered, d, &ConsoleWidgetPrivate::on_toggle_description_bar); d->update_navigation_actions(); d->update_view_actions(); } ConsoleWidgetPrivate::ConsoleWidgetPrivate(ConsoleWidget *q_arg) : QObject(q_arg) { q = q_arg; } // NOTE: as long as this is called where appropriate (on every target change), it is not necessary to do any condition checks in navigation f-ns since the actions that call them will be disabled if they can't be done void ConsoleWidgetPrivate::update_navigation_actions() { const bool can_navigate_up = [this]() { const QModelIndex current = q->get_current_scope_item(); const QModelIndex current_parent = current.parent(); return (current.isValid() && current_parent.isValid()); }(); actions.navigate_up->setEnabled(can_navigate_up); actions.navigate_back->setEnabled(!targets_past.isEmpty()); actions.navigate_forward->setEnabled(!targets_future.isEmpty()); } void ConsoleWidgetPrivate::update_view_actions() { ConsoleImpl *impl = get_current_scope_impl(); const bool results_view_exists = (impl->view() != nullptr); actions.view_icons->setVisible(results_view_exists); actions.view_list->setVisible(results_view_exists); actions.view_detail->setVisible(results_view_exists); actions.customize_columns->setVisible(results_view_exists); } void ConsoleWidgetPrivate::start_drag(const QList<QPersistentModelIndex> &dropped_list_arg) { dropped_list = dropped_list_arg; dropped_type_list = [&]() { QSet<int> out; for (const QPersistentModelIndex &index : dropped_list) { const int type = index.data(ConsoleRole_Type).toInt(); out.insert(type); } return out; }(); } bool ConsoleWidgetPrivate::can_drop(const QModelIndex &target) { const int target_type = target.data(ConsoleRole_Type).toInt(); ConsoleImpl *impl = get_impl(target); const bool ok = impl->can_drop(dropped_list, dropped_type_list, target, target_type); return ok; } void ConsoleWidgetPrivate::drop(const QModelIndex &target) { const int target_type = target.data(ConsoleRole_Type).toInt(); ConsoleImpl *impl = get_impl(target); impl->drop(dropped_list, dropped_type_list, target, target_type); } void ConsoleWidgetPrivate::set_results_to_type(const ResultsViewType type) { ConsoleImpl *impl = get_current_scope_impl(); if (impl->view() != nullptr) { impl->view()->set_view_type(type); // NOTE: changing results type causes a // selection change because selection is there // is a separate selection for each type of // results view emit q->selection_changed(); } } void ConsoleWidgetPrivate::fetch_scope(const QModelIndex &index) { const bool was_fetched = index.data(ConsoleRole_WasFetched).toBool(); if (!was_fetched) { model->setData(index, true, ConsoleRole_WasFetched); ConsoleImpl *impl = get_impl(index); impl->fetch(index); } } ConsoleImpl *ConsoleWidgetPrivate::get_current_scope_impl() const { const QModelIndex current_scope = q->get_current_scope_item(); ConsoleImpl *impl = get_impl(current_scope); return impl; } ConsoleImpl *ConsoleWidgetPrivate::get_impl(const QModelIndex &index) const { const int type = index.data(ConsoleRole_Type).toInt(); ConsoleImpl *impl = impl_map.value(type, default_impl); return impl; } void ConsoleWidgetPrivate::update_description() { const QModelIndex current_scope = q->get_current_scope_item(); const QString scope_name = current_scope.data().toString(); const QString elided_name = description_bar_left->fontMetrics().elidedText(scope_name, Qt::ElideRight, description_bar->width()/2); ConsoleImpl *impl = get_impl(current_scope); const QString description = impl->get_description(current_scope); description_bar_left->setText(elided_name); description_bar_left->setToolTip(scope_name); description_bar_right->setText(description); } QList<QModelIndex> ConsoleWidgetPrivate::get_all_selected_items() const { ConsoleImpl *current_impl = get_current_scope_impl(); ResultsView *results_view = current_impl->view(); const bool focused_scope = (focused_view == scope_view); const bool focused_results = (results_view != nullptr && focused_view == results_view->current_view()); const QList<QModelIndex> scope_selected = [&]() { QList<QModelIndex> out; const QList<QModelIndex> selected_proxy = scope_view->selectionModel()->selectedRows(); for (const QModelIndex &index : selected_proxy) { const QModelIndex source_index = scope_proxy_model->mapToSource(index); out.append(source_index); } return out; }(); if (focused_scope) { return scope_selected; } else if (focused_results) { const QList<QModelIndex> results_selected = results_view->get_selected_indexes(); // NOTE: this is necessary for the "context // menu targets current scope if clicked on // empty space in results view" feature. if (!results_selected.isEmpty()) { return results_selected; } else { return scope_selected; } } else { return QList<QModelIndex>(); } } // Get all custom actions from impl's, in order QList<QAction *> ConsoleWidgetPrivate::get_custom_action_list() const { QList<QAction *> out; for (const int type : impl_map.keys()) { ConsoleImpl *impl = impl_map[type]; QList<QAction *> for_this_type = impl->get_all_custom_actions(); for (QAction *action : for_this_type) { if (!out.contains(action)) { out.append(action); } } } return out; } void ConsoleWidgetPrivate::on_current_scope_item_changed(const QModelIndex &current_proxy, const QModelIndex &previous_proxy) { // NOTE: technically this slot should never be called // with invalid current index if (!current_proxy.isValid()) { return; } const QModelIndex current = scope_proxy_model->mapToSource(current_proxy); const QModelIndex previous = scope_proxy_model->mapToSource(previous_proxy); // Move current to past, if current changed and is valid if (previous.isValid() && (previous != current)) { targets_past.append(QPersistentModelIndex(previous)); } // When a new current is selected, a new future begins targets_future.clear(); ConsoleImpl *impl = get_current_scope_impl(); impl->selected_as_scope(current); // Switch to new parent for results view's model if view // exists const bool results_view_exists = (impl->view() != nullptr); if (results_view_exists) { model->setHorizontalHeaderLabels(impl->column_labels()); // NOTE: setting horizontal labes may make columns // visible again in scope view, so re-hide them for (int i = 1; i < 100; i++) { scope_view->hideColumn(i); } // NOTE: need to add a dummy row if new current item // has no children because otherwise view header // will be hidden. Dummy row is removed later. const bool need_dummy = (model->rowCount(current) == 0); if (need_dummy) { q->add_results_item(0, current); } impl->view()->set_parent(current); if (need_dummy) { model->removeRow(0, current); } const ResultsViewType results_type = impl->view()->current_view_type(); switch (results_type) { case ResultsViewType_Icons: { actions.view_icons->setChecked(true); break; } case ResultsViewType_List: { actions.view_list->setChecked(true); break; } case ResultsViewType_Detail: { actions.view_detail->setChecked(true); break; } } } // Switch to this item's results widget QWidget *results_widget = impl->widget(); if (results_widget != nullptr) { results_stacked_widget->setCurrentWidget(results_widget); } else { results_stacked_widget->setCurrentWidget(default_results_widget); } update_navigation_actions(); update_view_actions(); fetch_scope(current); update_description(); } void ConsoleWidgetPrivate::on_scope_items_about_to_be_removed(const QModelIndex &parent, int first, int last) { const QList<QModelIndex> removed_scope_items = [=]() { QList<QModelIndex> out; QStack<QStandardItem *> stack; for (int r = first; r <= last; r++) { const QModelIndex removed_index = model->index(r, 0, parent); auto removed_item = model->itemFromIndex(removed_index); stack.push(removed_item); } while (!stack.isEmpty()) { auto item = stack.pop(); out.append(item->index()); // Iterate through children for (int r = 0; r < item->rowCount(); r++) { auto child = item->child(r, 0); stack.push(child); } } return out; }(); // Remove removed items from navigation history for (const QModelIndex index : removed_scope_items) { targets_past.removeAll(index); targets_future.removeAll(index); } // Update navigation since an item in history could've been removed update_navigation_actions(); } void ConsoleWidgetPrivate::on_focus_changed(QWidget *old, QWidget *now) { UNUSED_ARG(old); QAbstractItemView *new_focused_view = qobject_cast<QAbstractItemView *>(now); if (new_focused_view != nullptr) { ConsoleImpl *current_impl = get_current_scope_impl(); QAbstractItemView *results_view = [=]() -> QAbstractItemView * { ResultsView *view = current_impl->view(); if (view != nullptr) { return view->current_view(); } else { return nullptr; } }(); if (new_focused_view == scope_view || new_focused_view == results_view) { focused_view = new_focused_view; emit q->selection_changed(); } } } void ConsoleWidgetPrivate::on_refresh() { const QModelIndex current_scope = q->get_current_scope_item(); q->refresh_scope(current_scope); } void ConsoleWidgetPrivate::on_customize_columns() { ConsoleImpl *current_impl = get_current_scope_impl(); ResultsView *results_view = current_impl->view(); if (results_view != nullptr) { auto dialog = new CustomizeColumnsDialog(results_view->detail_view(), current_impl->default_columns(), q); dialog->open(); } } // Set target to parent of current target void ConsoleWidgetPrivate::on_navigate_up() { const QPersistentModelIndex old_current = q->get_current_scope_item(); if (!old_current.isValid()) { return; } const QModelIndex new_current = old_current.parent(); // NOTE: parent of target can be invalid, if current is // head item in which case we've reached top of tree and // can't go up higher const bool can_go_up = (new_current.isValid()); if (can_go_up) { q->set_current_scope(new_current); } } // NOTE: for "back" and "forward" navigation, setCurrentIndex() triggers "current changed" slot which by default erases future history, so manually restore correct navigation state afterwards void ConsoleWidgetPrivate::on_navigate_back() { const QPersistentModelIndex old_current = q->get_current_scope_item(); if (!old_current.isValid()) { return; } // NOTE: saving and restoring past and future // before/after setCurrentIndex() because on_current() // slot modifies them with the assumption that current // changed due to user input. auto saved_past = targets_past; auto saved_future = targets_future; const QPersistentModelIndex new_current = targets_past.last(); q->set_current_scope(new_current); targets_past = saved_past; targets_future = saved_future; targets_past.removeLast(); targets_future.prepend(old_current); update_navigation_actions(); } void ConsoleWidgetPrivate::on_navigate_forward() { const QPersistentModelIndex old_current = q->get_current_scope_item(); if (!old_current.isValid()) { return; } // NOTE: saving and restoring past and future // before/after setCurrentIndex() because on_current() // slot modifies them with the assumption that current // changed due to user input. auto saved_past = targets_past; auto saved_future = targets_future; const QPersistentModelIndex new_current = targets_future.first(); q->set_current_scope(new_current); targets_past = saved_past; targets_future = saved_future; targets_past.append(old_current); targets_future.removeFirst(); update_navigation_actions(); } void ConsoleWidgetPrivate::on_view_icons() { set_results_to_type(ResultsViewType_Icons); } void ConsoleWidgetPrivate::on_view_list() { set_results_to_type(ResultsViewType_List); } void ConsoleWidgetPrivate::on_view_detail() { set_results_to_type(ResultsViewType_Detail); } void ConsoleWidgetPrivate::on_toggle_console_tree() { const bool visible = actions.toggle_console_tree->isChecked(); scope_view->setVisible(visible); } void ConsoleWidgetPrivate::on_toggle_description_bar() { const bool visible = actions.toggle_description_bar->isChecked(); description_bar->setVisible(visible); } void ConsoleWidgetPrivate::on_standard_action(const StandardAction action_enum) { const QSet<int> type_set = [&]() { QSet<int> out; const QList<QModelIndex> selected_list = get_all_selected_items(); for (const QModelIndex &index : selected_list) { const int type = index.data(ConsoleRole_Type).toInt(); out.insert(type); } return out; }(); // Call impl's action f-n for all present types for (const int type : type_set) { // Filter selected list so that it only contains indexes of this type const QList<QModelIndex> selected_of_type = q->get_selected_items(type); ConsoleImpl *impl = impl_map[type]; switch (action_enum) { case StandardAction_Copy: { impl->copy(selected_of_type); break; } case StandardAction_Cut: { impl->cut(selected_of_type); break; } case StandardAction_Rename: { impl->rename(selected_of_type); break; } case StandardAction_Delete: { impl->delete_action(selected_of_type); break; } case StandardAction_Paste: { impl->paste(selected_of_type); break; } case StandardAction_Print: { impl->print(selected_of_type); break; } case StandardAction_Refresh: { impl->refresh(selected_of_type); break; } case StandardAction_Properties: { impl->properties(selected_of_type); break; } } } } void ConsoleWidgetPrivate::on_results_context_menu(const QPoint &pos) { const QAbstractItemView *results_view = [&]() { ConsoleImpl *current_impl = get_current_scope_impl(); ResultsView *results = current_impl->view(); QAbstractItemView *out = results->current_view(); return out; }(); // NOTE: have to manually clear selection when // clicking on empty space in view because by // default Qt doesn't do it. This is necessary for // the "context menu targets current scope if // clicked on empty space in results view" feature const QModelIndex index = results_view->indexAt(pos); const bool clicked_empty_space = !index.isValid(); if (clicked_empty_space) { results_view->selectionModel()->clear(); } const QPoint global_pos = results_view->mapToGlobal(pos); open_context_menu(global_pos); } void ConsoleWidgetPrivate::on_scope_context_menu(const QPoint &pos) { const QModelIndex index = scope_view->indexAt(pos); if (!index.isValid()) { return; } const QPoint global_pos = focused_view->mapToGlobal(pos); open_context_menu(global_pos); } void ConsoleWidgetPrivate::open_context_menu(const QPoint &global_pos) { auto menu = new QMenu(q); menu->setAttribute(Qt::WA_DeleteOnClose); add_actions(menu); const bool need_to_open = update_actions(); if (need_to_open) { menu->popup(global_pos); } else { delete menu; } } void ConsoleWidgetPrivate::on_scope_expanded(const QModelIndex &index_proxy) { const QModelIndex index = scope_proxy_model->mapToSource(index_proxy); fetch_scope(index); } void ConsoleWidgetPrivate::on_results_activated(const QModelIndex &index) { const QModelIndex main_index = index.siblingAtColumn(0); const bool is_scope = main_index.data(ConsoleRole_IsScope).toBool(); if (is_scope) { q->set_current_scope(main_index); } else { ConsoleImpl *impl = get_impl(main_index); impl->activate(main_index); } } int console_item_get_type(const QModelIndex &index) { const int type = index.data(ConsoleRole_Type).toInt(); return type; } bool console_item_get_was_fetched(const QModelIndex &index) { const int was_fetched = index.data(ConsoleRole_WasFetched).toBool(); return was_fetched; } QString results_state_name(const int type) { return QString("RESULTS_STATE_%1").arg(type); }
46,308
C++
.cpp
1,107
34.828365
216
0.661047
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,746
results_view.cpp
altlinux_admc/src/admc/console_widget/results_view.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "console_widget/results_view.h" #include <QHeaderView> #include <QListView> #include <QSortFilterProxyModel> #include <QStackedWidget> #include <QTreeView> #include <QVBoxLayout> ResultsView::ResultsView(QWidget *parent) : QWidget(parent) { // Setup child views m_detail_view = new QTreeView(); m_detail_view->setSortingEnabled(true); m_detail_view->header()->setDefaultSectionSize(200); m_detail_view->setRootIsDecorated(false); auto list_view = new QListView(); list_view->setViewMode(QListView::ListMode); auto icons_view = new QListView(); icons_view->setViewMode(QListView::IconMode); icons_view->setGridSize(QSize(100, 100)); icons_view->setIconSize(QSize(64, 64)); // Put child views into map views[ResultsViewType_Icons] = icons_view; views[ResultsViewType_List] = list_view; views[ResultsViewType_Detail] = m_detail_view; proxy_model = new QSortFilterProxyModel(this); proxy_model->setSortCaseSensitivity(Qt::CaseInsensitive); // Perform common setup on child views for (auto view : views.values()) { view->setEditTriggers(QAbstractItemView::NoEditTriggers); view->setContextMenuPolicy(Qt::CustomContextMenu); view->setSelectionMode(QAbstractItemView::ExtendedSelection); view->setDragDropOverwriteMode(true); // NOTE: a proxy is model is inserted between // results views and results models for more // efficient sorting. If results views and models // are connected directly, deletion of results // models becomes extremely slow. view->setModel(proxy_model); connect( view->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ResultsView::selection_changed); } set_drag_drop_enabled(true); stacked_widget = new QStackedWidget(); for (auto view : views.values()) { stacked_widget->addWidget(view); } auto layout = new QVBoxLayout(); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); setLayout(layout); layout->addWidget(stacked_widget); for (auto view : views.values()) { connect( view, &QTreeView::activated, this, &ResultsView::on_item_activated); connect( view, &QWidget::customContextMenuRequested, this, &ResultsView::context_menu); } set_view_type(ResultsViewType_Detail); } void ResultsView::set_model(QAbstractItemModel *model) { proxy_model->setSourceModel(model); } void ResultsView::set_parent(const QModelIndex &source_index) { const QModelIndex proxy_index = proxy_model->mapFromSource(source_index); for (auto view : views.values()) { view->setRootIndex(proxy_index); } } void ResultsView::set_view_type(const ResultsViewType type) { QAbstractItemView *view = views[type]; // NOTE: current view must be changed before // setCurrentWidget(), because that causes a focus // change m_current_view_type = type; stacked_widget->setCurrentWidget(view); // Clear selection since view type changed for (auto the_view : views.values()) { the_view->clearSelection(); } } QAbstractItemView *ResultsView::current_view() const { return views[m_current_view_type]; } ResultsViewType ResultsView::current_view_type() const { return m_current_view_type; } QTreeView *ResultsView::detail_view() const { return m_detail_view; } QList<QModelIndex> ResultsView::get_selected_indexes() const { const QList<QModelIndex> proxy_indexes = [this]() { QItemSelectionModel *selection_model = current_view()->selectionModel(); if (current_view_type() == ResultsViewType_Detail) { return selection_model->selectedRows(); } else { return selection_model->selectedIndexes(); } }(); // NOTE: need to map from proxy to source indexes if // focused view is results QList<QModelIndex> source_indexes; for (const QModelIndex &index : proxy_indexes) { const QModelIndex source_index = proxy_model->mapToSource(index); source_indexes.append(source_index); } return source_indexes; } QVariant ResultsView::save_state() const { QHash<QString, QVariant> state; state["header"] = detail_view()->header()->saveState(); state["view_type"] = m_current_view_type; return QVariant(state); } void ResultsView::restore_state(const QVariant &state_variant, const QList<int> &default_columns) { QHeaderView *header = detail_view()->header(); if (state_variant.isValid()) { const QHash<QString, QVariant> state = state_variant.toHash(); const QByteArray header_state = state["header"].toByteArray(); header->restoreState(header_state); const ResultsViewType view_type = (ResultsViewType) state["view_type"].toInt(); set_view_type(view_type); } else { // Set default state in absence of saved state for (int i = 0; i < header->count(); i++) { const bool hidden = !default_columns.contains(i); header->setSectionHidden(i, hidden); } // NOTE: it is important to set default sort // state here by modifying header of detail // view, NOT the detail view itself. If we // modify detail view only, then by default // header will be in unsorted state, that state // will get saved and overwrite sorted state // the next time the app is run. Also, setting // sort state for header is enough, because it // propagates to detail view itself and // icons/list views, because they share // model/proxy header->setSortIndicator(0, Qt::AscendingOrder); } } void ResultsView::on_item_activated(const QModelIndex &proxy_index) { const QModelIndex &source_index = proxy_model->mapToSource(proxy_index); emit activated(source_index); } void ResultsView::set_drag_drop_enabled(const bool enabled) { const QAbstractItemView::DragDropMode mode = [&]() { if (enabled) { return QAbstractItemView::DragDrop; } else { return QAbstractItemView::NoDragDrop; } }(); for (auto view : views.values()) { view->setDragDropMode(mode); } } void ResultsView::set_drag_drop_internal() { for (auto view : views.values()) { view->setDragDropMode(QAbstractItemView::InternalMove); } } void ResultsView::set_row_hidden(int row, bool hidden) { m_detail_view->setRowHidden(row, QModelIndex(), hidden); }
7,396
C++
.cpp
188
33.696809
99
0.688625
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,747
ad_utils.cpp
altlinux_admc/src/adldap/ad_utils.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "ad_utils.h" #include "ad_config.h" #include "ad_display.h" #include "samba/dom_sid.h" #include <krb5.h> #include <ldap.h> #include <QByteArray> #include <QCoreApplication> #include <QDateTime> #include <QDebug> #include <QLocale> #include <QString> #include <QTranslator> #define GENERALIZED_TIME_FORMAT_STRING "yyyyMMddhhmmss.zZ" #define UTC_TIME_FORMAT_STRING "yyMMddhhmmss.zZ" const QDateTime ntfs_epoch = QDateTime(QDate(1601, 1, 1), QTime(), Qt::UTC); QString escape_name_for_dn(const QString &unescaped); bool large_integer_datetime_is_never(const QString &value) { const bool is_never = (value == AD_LARGE_INTEGER_DATETIME_NEVER_1 || value == AD_LARGE_INTEGER_DATETIME_NEVER_2); return is_never; } QString datetime_qdatetime_to_string(const QString &attribute, const QDateTime &datetime, const AdConfig *adconfig) { if (adconfig == nullptr) { return QString(); } const AttributeType type = adconfig->get_attribute_type(attribute); switch (type) { case AttributeType_LargeInteger: { const qint64 millis = ntfs_epoch.msecsTo(datetime); const qint64 hundred_nanos = millis * MILLIS_TO_100_NANOS; return QString::number(hundred_nanos); break; } case AttributeType_UTCTime: { return datetime.toString(UTC_TIME_FORMAT_STRING); break; } case AttributeType_GeneralizedTime: { return datetime.toString(GENERALIZED_TIME_FORMAT_STRING); break; } default: return ""; } return ""; } QDateTime datetime_string_to_qdatetime(const QString &attribute, const QString &raw_value, const AdConfig *adconfig) { if (adconfig == nullptr) { return QDateTime(); } const AttributeType type = adconfig->get_attribute_type(attribute); QDateTime datetime = [=]() { switch (type) { case AttributeType_LargeInteger: { const LargeIntegerSubtype subtype = adconfig->get_attribute_large_integer_subtype(attribute); if (subtype == LargeIntegerSubtype_Datetime) { QDateTime out = ntfs_epoch; const qint64 hundred_nanos = raw_value.toLongLong(); const qint64 millis = hundred_nanos / MILLIS_TO_100_NANOS; out = out.addMSecs(millis); return out; } else { break; } } case AttributeType_GeneralizedTime: { return QDateTime::fromString(raw_value, GENERALIZED_TIME_FORMAT_STRING); } case AttributeType_UTCTime: { return QDateTime::fromString(raw_value, UTC_TIME_FORMAT_STRING); } default: break; } return QDateTime(); }(); // NOTE: change timespec without changing the datetime. // All datetimes are UTC by default. Calling // setTimeSpec() would alter the datetime so we don't // use that. const QDateTime utc_datetime = QDateTime(datetime.date(), datetime.time(), Qt::UTC); return utc_datetime; } QString account_option_string(const AccountOption &option) { switch (option) { case AccountOption_Disabled: return QCoreApplication::translate("ad_utils", "Account disabled"); case AccountOption_CantChangePassword: return QCoreApplication::translate("ad_utils", "User cannot change password"); case AccountOption_AllowReversibleEncryption: return QCoreApplication::translate("ad_utils", "Store password using reversible encryption"); case AccountOption_PasswordExpired: return QCoreApplication::translate("ad_utils", "User must change password on next logon"); case AccountOption_DontExpirePassword: return QCoreApplication::translate("ad_utils", "Don't expire password"); case AccountOption_UseDesKey: return QCoreApplication::translate("ad_utils", "Use Kerberos DES encryption types for this account"); case AccountOption_SmartcardRequired: return QCoreApplication::translate("ad_utils", "Smartcard is required for interactive logon"); case AccountOption_CantDelegate: return QCoreApplication::translate("ad_utils", "Account is sensitive and cannot be delegated"); case AccountOption_DontRequirePreauth: return QCoreApplication::translate("ad_utils", "Don't require Kerberos preauthentication"); case AccountOption_TrustedForDelegation: return QCoreApplication::translate("ad_utils", "Trusted for delegation"); case AccountOption_COUNT: return QString("AccountOption_COUNT"); } return ""; } int account_option_bit(const AccountOption &option) { switch (option) { case AccountOption_Disabled: return UAC_ACCOUNTDISABLE; case AccountOption_AllowReversibleEncryption: return UAC_ENCRYPTED_TEXT_PASSWORD_ALLOWED; case AccountOption_DontExpirePassword: return UAC_DONT_EXPIRE_PASSWORD; case AccountOption_UseDesKey: return UAC_USE_DES_KEY_ONLY; case AccountOption_SmartcardRequired: return UAC_SMARTCARD_REQUIRED; case AccountOption_DontRequirePreauth: return UAC_DONT_REQUIRE_PREAUTH; case AccountOption_CantDelegate: return UAC_NOT_DELEGATED; case AccountOption_TrustedForDelegation: return UAC_TRUSTED_FOR_DELEGATION; // NOTE: not all account options can be directly // mapped to bits case AccountOption_CantChangePassword: return 0; case AccountOption_PasswordExpired: return 0; case AccountOption_COUNT: return 0; } return 0; } int group_scope_bit(GroupScope scope) { switch (scope) { case GroupScope_Global: return 0x00000002; case GroupScope_DomainLocal: return 0x00000004; case GroupScope_Universal: return 0x00000008; case GroupScope_COUNT: return 0; } return 0; } QString group_scope_string(GroupScope scope) { switch (scope) { case GroupScope_Global: return QCoreApplication::translate("ad_utils", "Global"); case GroupScope_DomainLocal: return QCoreApplication::translate("ad_utils", "Domain Local"); case GroupScope_Universal: return QCoreApplication::translate("ad_utils", "Universal"); case GroupScope_COUNT: return "COUNT"; } return ""; } QString group_type_string(GroupType type) { switch (type) { case GroupType_Security: return QCoreApplication::translate("ad_utils", "Security"); case GroupType_Distribution: return QCoreApplication::translate("ad_utils", "Distribution"); case GroupType_COUNT: return "COUNT"; } return ""; } // NOTE: need a special translation for Russian where type // adjectives get suffixes. QString group_type_string_adjective(GroupType type) { switch (type) { case GroupType_Security: return QCoreApplication::translate("ad_utils", "Security Group"); case GroupType_Distribution: return QCoreApplication::translate("ad_utils", "Distribution Group"); case GroupType_COUNT: return "COUNT"; } return ""; } QString extract_rid_from_sid(const QByteArray &sid, AdConfig *adconfig) { const QString sid_string = attribute_display_value(ATTRIBUTE_OBJECT_SID, sid, adconfig); const int cut_index = sid_string.lastIndexOf("-") + 1; const QString rid = sid_string.mid(cut_index); return rid; } bool ad_string_to_bool(const QString &string) { return (string == LDAP_BOOL_TRUE); } // "CN=foo,CN=bar,DC=domain,DC=com" // => // "CN=foo" QString dn_get_rdn(const QString &dn) { const QStringList exploded_dn = dn.split(','); const QString rdn = exploded_dn[0]; return rdn; } // "CN=foo,CN=bar,DC=domain,DC=com" // => // "foo" QString dn_get_name(const QString &dn) { int equals_i = dn.indexOf('=') + 1; int comma_i = dn.indexOf(','); int segment_length = comma_i - equals_i; QString name = dn.mid(equals_i, segment_length); // Unescape name name.replace("\\?", "?"); return name; } QString dn_get_parent(const QString &dn) { const int comma_i = dn.indexOf(','); const QString parent_dn = dn.mid(comma_i + 1); return parent_dn; } QString dn_get_parent_canonical(const QString &dn) { const QString parent_dn = dn_get_parent(dn); return dn_canonical(parent_dn); } QString dn_rename(const QString &dn, const QString &new_name) { const QStringList exploded_dn = dn.split(','); const QString new_rdn = [=]() { const QString old_rdn = exploded_dn[0]; const int prefix_index = old_rdn.indexOf('=') + 1; const QString prefix = old_rdn.left(prefix_index); const QString new_name_escaped = escape_name_for_dn(new_name); return (prefix + new_name_escaped); }(); QStringList new_exploded_dn(exploded_dn); new_exploded_dn.replace(0, new_rdn); const QString new_dn = new_exploded_dn.join(','); return new_dn; } QString dn_move(const QString &dn, const QString &new_parent_dn) { const QString rdn = dn_get_rdn(dn); const QString new_dn = QString("%1,%2").arg(rdn, new_parent_dn); return new_dn; } // "CN=foo,CN=bar,DC=domain,DC=com" // => // "domain.com/bar/foo" QString dn_canonical(const QString &dn) { char *canonical_cstr = ldap_dn2ad_canonical(cstr(dn)); const QString canonical = QString(canonical_cstr); ldap_memfree(canonical_cstr); return canonical; } QString dn_from_name_and_parent(const QString &name, const QString &parent, const QString &object_class) { const QString suffix = [object_class]() { if (object_class == CLASS_OU) { return "OU"; } else { return "CN"; } }(); const QString name_escaped = escape_name_for_dn(name); const QString dn = QString("%1=%2,%3").arg(suffix, name_escaped, parent); return dn; } QString get_default_domain_from_krb5() { krb5_error_code result; krb5_context context; krb5_ccache default_cache; krb5_principal default_principal; result = krb5_init_context(&context); if (result) { qDebug() << "Failed to init krb5 context"; return QString(); } result = krb5_cc_default(context, &default_cache); if (result) { qDebug() << "Failed to get default krb5 ccache"; krb5_free_context(context); return QString(); } result = krb5_cc_get_principal(context, default_cache, &default_principal); if (result) { qDebug() << "Failed to get default krb5 principal"; krb5_cc_close(context, default_cache); krb5_free_context(context); return QString(); } const QString out = QString::fromLocal8Bit(default_principal->realm.data, default_principal->realm.length); krb5_free_principal(context, default_principal); krb5_cc_close(context, default_cache); krb5_free_context(context); return out; } int bitmask_set(const int input_mask, const int mask_to_set, const bool is_set) { if (is_set) { return input_mask | mask_to_set; } else { return input_mask & ~mask_to_set; } } bool bitmask_is_set(const int input_mask, const int mask_to_read) { return ((input_mask & mask_to_read) == mask_to_read); } const char *cstr(const QString &qstr) { static QList<QByteArray> buffer; const QByteArray bytes = qstr.toUtf8(); buffer.append(bytes); // Limit buffer to 100 strings if (buffer.size() > 100) { buffer.removeAt(0); } // NOTE: return data of bytes in buffer NOT the temp local bytes return buffer.last().constData(); } bool load_adldap_translation(QTranslator &translator, const QLocale &locale) { return translator.load(locale, "adldap", "_", ":/adldap"); } QByteArray guid_string_to_bytes(const QString &guid_string) { if (guid_string.isEmpty()) { return QByteArray(); } const QList<QByteArray> segment_list = [&]() { QList<QByteArray> out; const QList<QString> string_segment_list = guid_string.split('-'); for (const QString &string_segment : string_segment_list) { const QByteArray segment = QByteArray::fromHex(string_segment.toLatin1()); out.append(segment); } std::reverse(out[0].begin(), out[0].end()); std::reverse(out[1].begin(), out[1].end()); std::reverse(out[2].begin(), out[2].end()); return out; }(); const QByteArray guid_bytes = [&]() { QByteArray out; for (const QByteArray &segment : segment_list) { out.append(segment); } return out; }(); return guid_bytes; } QByteArray sid_string_to_bytes(const QString &sid_string) { dom_sid sid; string_to_sid(&sid, cstr(sid_string)); const QByteArray sid_bytes = QByteArray((char *) &sid, sizeof(dom_sid)); return sid_bytes; } QString attribute_type_display_string(const AttributeType type) { switch (type) { case AttributeType_Boolean: return QCoreApplication::translate("ad_utils.cpp", "Boolean"); case AttributeType_Enumeration: return QCoreApplication::translate("ad_utils.cpp", "Enumeration"); case AttributeType_Integer: return QCoreApplication::translate("ad_utils.cpp", "Integer"); case AttributeType_LargeInteger: return QCoreApplication::translate("ad_utils.cpp", "Large Integer"); case AttributeType_StringCase: return QCoreApplication::translate("ad_utils.cpp", "String Case"); case AttributeType_IA5: return QCoreApplication::translate("ad_utils.cpp", "IA5"); case AttributeType_NTSecDesc: return QCoreApplication::translate("ad_utils.cpp", "NT Security Descriptor"); case AttributeType_Numeric: return QCoreApplication::translate("ad_utils.cpp", "Numeric"); case AttributeType_ObjectIdentifier: return QCoreApplication::translate("ad_utils.cpp", "Object Identifier"); case AttributeType_Octet: return QCoreApplication::translate("ad_utils.cpp", "Octet"); case AttributeType_ReplicaLink: return QCoreApplication::translate("ad_utils.cpp", "Replica Link"); case AttributeType_Printable: return QCoreApplication::translate("ad_utils.cpp", "Printable"); case AttributeType_Sid: return QCoreApplication::translate("ad_utils.cpp", "SID"); case AttributeType_Teletex: return QCoreApplication::translate("ad_utils.cpp", "Teletex"); case AttributeType_Unicode: return QCoreApplication::translate("ad_utils.cpp", "Unicode String"); case AttributeType_UTCTime: return QCoreApplication::translate("ad_utils.cpp", "UTC Time"); case AttributeType_GeneralizedTime: return QCoreApplication::translate("ad_utils.cpp", "Generalized Time"); case AttributeType_DNString: return QCoreApplication::translate("ad_utils.cpp", "DN String"); case AttributeType_DNBinary: return QCoreApplication::translate("ad_utils.cpp", "DN Binary"); case AttributeType_DSDN: return QCoreApplication::translate("ad_utils.cpp", "Distinguished Name"); } return QString(); } QString int_to_hex_string(const int n) { return QString("0x%1").arg(n, 8, 16, QLatin1Char('0')); } QString escape_name_for_dn(const QString &unescaped) { QString out = unescaped; out.replace("?", "\\?"); return out; } QHash<int, QString> attribute_value_bit_string_map(const QString &attribute) { QHash<int, QString> bit_string_map; if (attribute == ATTRIBUTE_GROUP_TYPE) { bit_string_map = { {GROUP_TYPE_BIT_SYSTEM, "SYSTEM_GROUP"}, {GROUP_TYPE_BIT_SECURITY, "SECURITY_ENABLED"}, {group_scope_bit(GroupScope_Global), "ACCOUNT_GROUP"}, {group_scope_bit(GroupScope_DomainLocal), "RESOURCE_GROUP"}, {group_scope_bit(GroupScope_Universal), "UNIVERSAL_GROUP"}, }; } else if (attribute == ATTRIBUTE_SYSTEM_FLAGS) { bit_string_map = { {SystemFlagsBit_DomainCannotMove, "DOMAIN_DISALLOW_MOVE"}, {SystemFlagsBit_DomainCannotRename, "DOMAIN_DISALLOW_RENAME"}, {SystemFlagsBit_CannotDelete, "DISALLOW_DELETE"} }; } return bit_string_map; }
17,019
C++
.cpp
393
36.875318
147
0.68008
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,748
ad_interface.cpp
altlinux_admc/src/adldap/ad_interface.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "ad_interface.h" #include "ad_interface_p.h" #include "ad_config.h" #include "ad_display.h" #include "ad_object.h" #include "ad_security.h" #include "ad_utils.h" #include "gplink.h" #include "samba/dom_sid.h" #include "samba/gp_manage.h" #include "samba/libsmb_xattr.h" #include "samba/ndr_security.h" #include "samba/security_descriptor.h" #include "ad_filter.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <dirent.h> #include <krb5.h> #include <lber.h> #include <ldap.h> #include <libsmbclient.h> #include <resolv.h> #include <sasl/sasl.h> #include <sys/stat.h> #include <sys/types.h> #include <uuid/uuid.h> #include <QDebug> #include <QTextCodec> // NOTE: LDAP library char* inputs are non-const in the API // but are const for practical purposes so we use forced // casts (const char *) -> (char *) #ifdef __GNUC__ #define UNUSED(x) x __attribute__((unused)) #else #define UNUSED(x) x #endif #define UNUSED_ARG(x) (void) (x) #define MAX_DN_LENGTH 1024 #define MAX_PASSWORD_LENGTH 255 typedef struct sasl_defaults_gssapi { char *mech; char *realm; char *authcid; char *passwd; char *authzid; } sasl_defaults_gssapi; enum AceMaskFormat { AceMaskFormat_Hexadecimal, AceMaskFormat_Decimal, }; QList<QString> query_server_for_hosts(const char *dname); int sasl_interact_gssapi(LDAP *ld, unsigned flags, void *indefaults, void *in); QString get_gpt_sd_string(const AdObject &gpc_object, const AceMaskFormat format); int create_sd_control(bool get_sacl, int is_critical, LDAPControl **ctrlp, bool set_dacl = false); AdConfig *AdInterfacePrivate::adconfig = nullptr; bool AdInterfacePrivate::s_log_searches = false; QString AdInterfacePrivate::s_dc = QString(); bool AdInterfacePrivate::s_domain_is_default = true; QString AdInterfacePrivate::s_custom_domain = QString(); void *AdInterfacePrivate::s_sasl_nocanon = LDAP_OPT_ON; int AdInterfacePrivate::s_port = 0; CertStrategy AdInterfacePrivate::s_cert_strat = CertStrategy_Never; SMBCCTX *AdInterfacePrivate::smbc = NULL; QMutex AdInterfacePrivate::mutex; void get_auth_data_fn(const char *pServer, const char *pShare, char *pWorkgroup, int maxLenWorkgroup, char *pUsername, int maxLenUsername, char *pPassword, int maxLenPassword) { UNUSED_ARG(pServer); UNUSED_ARG(pShare); UNUSED_ARG(pWorkgroup); UNUSED_ARG(maxLenWorkgroup); UNUSED_ARG(pUsername); UNUSED_ARG(maxLenUsername); UNUSED_ARG(pPassword); UNUSED_ARG(maxLenPassword); } AdInterface::AdInterface() { d = new AdInterfacePrivate(this); d->is_connected = false; d->ld = NULL; const QString connect_error_context = tr("Failed to connect."); if (AdInterfacePrivate::s_domain_is_default) d->domain = get_default_domain_from_krb5(); else d->domain = AdInterfacePrivate::s_custom_domain; if (d->domain.isEmpty()) { d->error_message(connect_error_context, tr("Failed to get a domain. Check that you have initialized kerberos credentials (kinit).")); return; } // // Connect via LDAP // d->dc = [&]() { const QList<QString> dc_list = get_domain_hosts(d->domain, QString()); if (dc_list.isEmpty()) { d->error_message_plain(tr("Failed to find domain controllers. Make sure your computer is in the domain and that domain controllers are operational.")); return QString(); } if (!AdInterfacePrivate::s_dc.isEmpty()) { if (dc_list.contains(AdInterfacePrivate::s_dc)) { return AdInterfacePrivate::s_dc; } else { return dc_list[0]; } } else { return dc_list[0]; } }(); if (AdInterfacePrivate::s_dc.isEmpty()) { AdInterfacePrivate::s_dc = d->dc; } if (!ldap_init()) { return; } // Initialize SMB context // NOTE: initialize only once, because otherwise // wouldn't be able to have multiple active // AdInterface's instances at the same time if (AdInterfacePrivate::smbc == NULL) { smbc_init(get_auth_data_fn, 0); AdInterfacePrivate::smbc = smbc_new_context(); smbc_setOptionUseKerberos(AdInterfacePrivate::smbc, true); smbc_setOptionFallbackAfterKerberos(AdInterfacePrivate::smbc, true); if (!smbc_init_context(AdInterfacePrivate::smbc)) { d->error_message(connect_error_context, tr("Failed to initialize SMB context.")); return; } smbc_set_context(AdInterfacePrivate::smbc); } d->is_connected = true; } AdInterface::~AdInterface() { ldap_free(); delete d; } void AdInterface::set_config(AdConfig *config_arg) { AdInterfacePrivate::adconfig = config_arg; } void AdInterface::set_log_searches(const bool enabled) { AdInterfacePrivate::s_log_searches = enabled; } void AdInterface::set_dc(const QString &dc) { AdInterfacePrivate::s_dc = dc; } void AdInterface::set_sasl_nocanon(const bool is_on) { AdInterfacePrivate::s_sasl_nocanon = [&]() { if (is_on) { return LDAP_OPT_ON; } else { return LDAP_OPT_OFF; } }(); } void AdInterface::set_port(const int port) { AdInterfacePrivate::s_port = port; } void AdInterface::set_cert_strategy(const CertStrategy strategy) { AdInterfacePrivate::s_cert_strat = strategy; } void AdInterface::set_domain_is_default(const bool is_default) { AdInterfacePrivate::s_domain_is_default = is_default; } void AdInterface::set_custom_domain(const QString &domain) { AdInterfacePrivate::s_custom_domain = domain; } AdInterfacePrivate::AdInterfacePrivate(AdInterface *q_arg) { mutex.lock(); q = q_arg; mutex.unlock(); } bool AdInterface::is_connected() const { return d->is_connected; } QList<AdMessage> AdInterface::messages() const { return d->messages; } bool AdInterface::any_error_messages() const { for (const auto &message : d->messages) { if (message.type() == AdMessageType_Error) { return true; } } return false; } void AdInterface::clear_messages() { d->messages.clear(); } AdConfig *AdInterface::adconfig() const { return d->adconfig; } QString AdInterface::client_user() const { return d->client_user; } // Helper f-n for search() // NOTE: cookie is starts as NULL. Then after each while // loop, it is set to the value returned by // ldap_search_ext_s(). At the end cookie is set back to // NULL. bool AdInterfacePrivate::search_paged_internal(const char *base, const int scope, const char *filter, char **attributes, QHash<QString, AdObject> *results, AdCookie *cookie, const bool get_sacl) { int result; LDAPMessage *res = NULL; LDAPControl *page_control = NULL; LDAPControl *sd_control = NULL; LDAPControl **returned_controls = NULL; struct berval *prev_cookie = cookie->cookie; struct berval *new_cookie = NULL; auto cleanup = [&]() { ldap_msgfree(res); ldap_control_free(page_control); ldap_control_free(sd_control); ldap_controls_free(returned_controls); ber_bvfree(prev_cookie); ber_bvfree(new_cookie); }; const int is_critical = 1; result = create_sd_control(get_sacl, is_critical, &sd_control); if (result != LDAP_SUCCESS) { qDebug() << "Failed to create sd control: " << ldap_err2string(result); cleanup(); return false; } // Create page control const ber_int_t page_size = 100; result = ldap_create_page_control(ld, page_size, prev_cookie, is_critical, &page_control); if (result != LDAP_SUCCESS) { qDebug() << "Failed to create page control: " << ldap_err2string(result); cleanup(); return false; } LDAPControl *server_controls[3] = {page_control, sd_control, NULL}; // Perform search const int attrsonly = 0; result = ldap_search_ext_s(ld, base, scope, filter, attributes, attrsonly, server_controls, NULL, NULL, LDAP_NO_LIMIT, &res); if ((result != LDAP_SUCCESS) && (result != LDAP_PARTIAL_RESULTS)) { // NOTE: it's not really an error for an object to // not exist. For example, sometimes it's needed to // check whether an object exists. Not sure how to // distinguish this error type from others if (result != LDAP_NO_SUCH_OBJECT) { qDebug() << "Error in paged ldap_search_ext_s: " << ldap_err2string(result); } cleanup(); return false; } // Collect results for this search for (LDAPMessage *entry = ldap_first_entry(ld, res); entry != NULL; entry = ldap_next_entry(ld, entry)) { char *dn_cstr = ldap_get_dn(ld, entry); const QString dn(dn_cstr); ldap_memfree(dn_cstr); QHash<QString, QList<QByteArray>> object_attributes; BerElement *berptr; for (char *attr = ldap_first_attribute(ld, entry, &berptr); attr != NULL; attr = ldap_next_attribute(ld, entry, berptr)) { struct berval **values_ldap = ldap_get_values_len(ld, entry, attr); const QList<QByteArray> values_bytes = [=]() { QList<QByteArray> out; if (values_ldap != NULL) { const int values_count = ldap_count_values_len(values_ldap); for (int i = 0; i < values_count; i++) { struct berval value_berval = *values_ldap[i]; const QByteArray value_bytes(value_berval.bv_val, value_berval.bv_len); out.append(value_bytes); } } return out; }(); const QString attribute(attr); object_attributes[attribute] = values_bytes; ldap_value_free_len(values_ldap); ldap_memfree(attr); } ber_free(berptr, 0); AdObject object; object.load(dn, object_attributes); results->insert(dn, object); } // Parse the results to retrieve returned controls int errcodep; result = ldap_parse_result(ld, res, &errcodep, NULL, NULL, NULL, &returned_controls, false); if (result != LDAP_SUCCESS) { qDebug() << "Failed to parse result: " << ldap_err2string(result); cleanup(); return false; } // Get page response control // // NOTE: not sure if absence of page response control is // an error. Decided to not treat it as error because // searching the rootDSE doesn't return this control. LDAPControl *pageresponse_control = ldap_control_find(LDAP_CONTROL_PAGEDRESULTS, returned_controls, NULL); if (pageresponse_control != NULL) { // Parse page response control to determine whether // there are more pages ber_int_t total_count; new_cookie = (struct berval *) malloc(sizeof(struct berval)); result = ldap_parse_pageresponse_control(ld, pageresponse_control, &total_count, new_cookie); if (result != LDAP_SUCCESS) { qDebug() << "Failed to parse pageresponse control: " << ldap_err2string(result); cleanup(); return false; } // Switch to new cookie if there are more pages // NOTE: there are more pages if the cookie isn't // empty const bool more_pages = (new_cookie->bv_len > 0); if (more_pages) { cookie->cookie = ber_bvdup(new_cookie); } else { cookie->cookie = NULL; } } else { cookie->cookie = NULL; } cleanup(); return true; } QHash<QString, AdObject> AdInterface::search(const QString &base, const SearchScope scope, const QString &filter, const QList<QString> &attributes, const bool get_sacl) { AdCookie cookie; QHash<QString, AdObject> results; while (true) { const bool success = search_paged(base, scope, filter, attributes, &results, &cookie, get_sacl); if (!success) { break; } if (!cookie.more_pages()) { break; } } return results; } bool AdInterface::search_paged(const QString &base, const SearchScope scope, const QString &filter, const QList<QString> &attributes, QHash<QString, AdObject> *results, AdCookie *cookie, const bool get_sacl) { // NOTE: only log once per cycle of search pages, // to avoid duplicate messages const bool is_first_page = results->isEmpty(); const bool need_to_log = (AdInterfacePrivate::s_log_searches && is_first_page); if (need_to_log) { const QString attributes_string = "{" + attributes.join(",") + "}"; const QString scope_string = [&scope]() -> QString { switch (scope) { case SearchScope_Object: return "object"; case SearchScope_Children: return "children"; case SearchScope_Descendants: return "descendants"; case SearchScope_All: return "all"; default: break; } return QString(); }(); d->success_message(QString(tr("Search:\n\tfilter = \"%1\"\n\tattributes = %2\n\tscope = \"%3\"\n\tbase = \"%4\"")).arg(filter, attributes_string, scope_string, base)); } const char *base_cstr = cstr(base); const int scope_int = [&]() { switch (scope) { case SearchScope_Object: return LDAP_SCOPE_BASE; case SearchScope_Children: return LDAP_SCOPE_ONELEVEL; case SearchScope_All: return LDAP_SCOPE_SUBTREE; case SearchScope_Descendants: return LDAP_SCOPE_CHILDREN; } return 0; }(); const char *filter_cstr = [&]() { if (filter.isEmpty()) { // NOTE: need to pass NULL instead of empty // string to denote "no filter" return (const char *) NULL; } else { return cstr(filter); } }(); // Convert attributes list to NULL-terminated array char **attributes_array; QList<QByteArray> attr_bytearray_list; if (attributes.isEmpty()) { // Pass NULL so LDAP gets all attributes attributes_array = NULL; } else { attributes_array = (char **) malloc((attributes.size() + 1) * sizeof(char *)); if (attributes_array != NULL) { for (int i = 0; i < attributes.size(); i++) { attr_bytearray_list.append(attributes[i].toUtf8()); attributes_array[i] = strdup(attr_bytearray_list.last().constData()); } attributes_array[attributes.size()] = NULL; } } const bool search_success = d->search_paged_internal(base_cstr, scope_int, filter_cstr, attributes_array, results, cookie, get_sacl); if (!search_success) { results->clear(); return false; } if (attributes_array != NULL) { for (int i = 0; attributes_array[i] != NULL; i++) { free(attributes_array[i]); } free(attributes_array); } return true; } AdObject AdInterface::search_object(const QString &dn, const QList<QString> &attributes, const bool get_sacl) { const QString base = dn; const SearchScope scope = SearchScope_Object; const QString filter = QString(); const QHash<QString, AdObject> results = search(base, scope, filter, attributes, get_sacl); if (results.contains(dn)) { return results[dn]; } else { return AdObject(); } } bool AdInterface::attribute_replace_values(const QString &dn, const QString &attribute, const QList<QByteArray> &values, const DoStatusMsg do_msg, const bool set_dacl) { const AdObject object = search_object(dn, {attribute}); const QList<QByteArray> old_values = object.get_values(attribute); const QString name = dn_get_name(dn); const QString values_display = attribute_display_values(attribute, values, d->adconfig); const QString old_values_display = attribute_display_values(attribute, old_values, d->adconfig); // Do nothing if both new and old values are empty if (old_values.isEmpty() && values.isEmpty()) { return true; } // NOTE: store bvalues in array instead of dynamically allocating ptrs struct berval bvalues_storage[values.size()]; struct berval *bvalues[values.size() + 1]; bvalues[values.size()] = NULL; for (int i = 0; i < values.size(); i++) { const QByteArray value = values[i]; struct berval *bvalue = &(bvalues_storage[i]); bvalue->bv_val = (char *) value.constData(); bvalue->bv_len = (size_t) value.size(); bvalues[i] = bvalue; } LDAPMod attr; attr.mod_op = (LDAP_MOD_REPLACE | LDAP_MOD_BVALUES); attr.mod_type = (char *) cstr(attribute); attr.mod_bvalues = bvalues; LDAPMod *attrs[] = {&attr, NULL}; int result; LDAPControl *server_controls[2] = {NULL, NULL}; if (set_dacl) { LDAPControl *sd_control = NULL; const int is_critical = 1; result = create_sd_control(false, is_critical, &sd_control, set_dacl); if (result != LDAP_SUCCESS) { qDebug() << "Failed to create sd control: " << ldap_err2string(result); ldap_control_free(sd_control); return false; } server_controls[0] = sd_control; } result = ldap_modify_ext_s(d->ld, cstr(dn), attrs, server_controls, NULL); if (result == LDAP_SUCCESS) { d->success_message(QString(tr("Attribute %1 of object %2 was changed from \"%3\" to \"%4\".")).arg(attribute, name, old_values_display, values_display), do_msg); return true; } else { const QString context = QString(tr("Failed to change attribute %1 of object %2 from \"%3\" to \"%4\".")).arg(attribute, name, old_values_display, values_display); d->error_message(context, d->default_error(), do_msg); return false; } } bool AdInterface::attribute_replace_value(const QString &dn, const QString &attribute, const QByteArray &value, const DoStatusMsg do_msg, const bool set_dacl) { const QList<QByteArray> values = [=]() -> QList<QByteArray> { if (value.isEmpty()) { return QList<QByteArray>(); } else { return {value}; } }(); return attribute_replace_values(dn, attribute, values, do_msg, set_dacl); } bool AdInterface::attribute_add_value(const QString &dn, const QString &attribute, const QByteArray &value, const DoStatusMsg do_msg) { char *data_copy = (char *) malloc(value.size()); if (data_copy == NULL) { return false; } memcpy(data_copy, value.constData(), value.size()); struct berval ber_data; ber_data.bv_val = data_copy; ber_data.bv_len = value.size(); struct berval *values[] = {&ber_data, NULL}; LDAPMod attr; attr.mod_op = LDAP_MOD_ADD | LDAP_MOD_BVALUES; attr.mod_type = (char *) cstr(attribute); attr.mod_bvalues = values; LDAPMod *attrs[] = {&attr, NULL}; const int result = ldap_modify_ext_s(d->ld, cstr(dn), attrs, NULL, NULL); free(data_copy); const QString name = dn_get_name(dn); const QString new_display_value = attribute_display_value(attribute, value, d->adconfig); if (result == LDAP_SUCCESS) { const QString context = QString(tr("Value \"%1\" was added for attribute %2 of object %3.")).arg(new_display_value, attribute, name); d->success_message(context, do_msg); return true; } else { const QString context = QString(tr("Failed to add value \"%1\" for attribute %2 of object %3.")).arg(new_display_value, attribute, name); d->error_message(context, d->default_error(), do_msg); return false; } } bool AdInterface::attribute_delete_value(const QString &dn, const QString &attribute, const QByteArray &value, const DoStatusMsg do_msg) { const QString name = dn_get_name(dn); const QString value_display = attribute_display_value(attribute, value, d->adconfig); char *data_copy = (char *) malloc(value.size()); if (data_copy == NULL) { return false; } memcpy(data_copy, value.constData(), value.size()); struct berval ber_data; ber_data.bv_val = data_copy; ber_data.bv_len = value.size(); LDAPMod attr; struct berval *values[] = {&ber_data, NULL}; attr.mod_op = LDAP_MOD_DELETE | LDAP_MOD_BVALUES; attr.mod_type = (char *) cstr(attribute); attr.mod_bvalues = values; LDAPMod *attrs[] = {&attr, NULL}; const int result = ldap_modify_ext_s(d->ld, cstr(dn), attrs, NULL, NULL); free(data_copy); if (result == LDAP_SUCCESS) { const QString context = QString(tr("Value \"%1\" for attribute %2 of object %3 was deleted.")).arg(value_display, attribute, name); d->success_message(context, do_msg); return true; } else { const QString context = QString(tr("Failed to delete value \"%1\" for attribute %2 of object %3.")).arg(value_display, attribute, name); d->error_message(context, d->default_error(), do_msg); return false; } } bool AdInterface::attribute_replace_string(const QString &dn, const QString &attribute, const QString &value, const DoStatusMsg do_msg) { const QByteArray value_bytes = value.toUtf8(); return attribute_replace_value(dn, attribute, value_bytes, do_msg); } bool AdInterface::attribute_replace_int(const QString &dn, const QString &attribute, const int value, const DoStatusMsg do_msg) { const QString value_string = QString::number(value); const bool result = attribute_replace_string(dn, attribute, value_string, do_msg); return result; } bool AdInterface::attribute_replace_datetime(const QString &dn, const QString &attribute, const QDateTime &datetime) { const QString datetime_string = datetime_qdatetime_to_string(attribute, datetime, d->adconfig); const bool result = attribute_replace_string(dn, attribute, datetime_string); return result; } bool AdInterface::object_add(const QString &dn, const QHash<QString, QList<QString>> &attrs_map) { LDAPMod **attrs = [&attrs_map]() { LDAPMod **out = (LDAPMod **) malloc((attrs_map.size() + 1) * sizeof(LDAPMod *)); const QList<QString> attrs_map_keys = attrs_map.keys(); for (int i = 0; i < attrs_map_keys.size(); i++) { LDAPMod *attr = (LDAPMod *) malloc(sizeof(LDAPMod)); const QString attr_name = attrs_map_keys[i]; const QList<QString> value_list = attrs_map[attr_name]; char **value_array = (char **) malloc((value_list.size() + 1) * sizeof(char *)); for (int j = 0; j < value_list.size(); j++) { const QString value = value_list[j]; value_array[j] = (char *) strdup(cstr(value)); } value_array[value_list.size()] = NULL; attr->mod_type = (char *) strdup(cstr(attr_name)); attr->mod_op = LDAP_MOD_ADD; attr->mod_values = value_array; out[i] = attr; } out[attrs_map.size()] = NULL; return out; }(); const int result = ldap_add_ext_s(d->ld, cstr(dn), attrs, NULL, NULL); ldap_mods_free(attrs, 1); if (result == LDAP_SUCCESS) { d->success_message(QString(tr("Object %1 was created.")).arg(dn)); return true; } else { const QString context = QString(tr("Failed to create object %1.")).arg(dn); const QString error = [this, dn]() { const bool wrong_ou_parent = [&]() { const int ldap_result = d->get_ldap_result(); const bool is_ou = dn.startsWith("OU="); const QString parent = dn_get_parent(dn); const bool bad_parent = parent.startsWith("CN="); const bool out = (ldap_result == LDAP_NAMING_VIOLATION && is_ou && bad_parent); return out; }(); if (wrong_ou_parent) { return tr("Can't create OU under this object type."); } else { return d->default_error(); } }(); d->error_message(context, error); return false; } } bool AdInterface::object_add(const QString &dn, const QString &object_class) { const QHash<QString, QList<QString>> attrs_map = { {"objectClass", {object_class}}, }; const bool success = object_add(dn, attrs_map); return success; } bool AdInterface::object_delete(const QString &dn, const DoStatusMsg do_msg) { int result; LDAPControl *tree_delete_control = NULL; auto cleanup = [tree_delete_control]() { ldap_control_free(tree_delete_control); }; const QString name = dn_get_name(dn); const QString error_context = QString(tr("Failed to delete object %1.")).arg(name); // Use a tree delete control to enable recursive delete result = ldap_control_create(LDAP_CONTROL_X_TREE_DELETE, 1, NULL, 0, &tree_delete_control); if (result != LDAP_SUCCESS) { d->error_message(error_context, tr("LDAP Operation error - Failed to create tree delete control.")); cleanup(); return false; } LDAPControl *server_controls[2] = {NULL, NULL}; const bool tree_delete_is_supported = adconfig()->control_is_supported(LDAP_CONTROL_X_TREE_DELETE); if (tree_delete_is_supported) { server_controls[0] = tree_delete_control; } result = ldap_delete_ext_s(d->ld, cstr(dn), server_controls, NULL); cleanup(); if (result == LDAP_SUCCESS) { d->success_message(QString(tr("Object %1 was deleted.")).arg(name), do_msg); return true; } else { d->error_message(error_context, d->default_error(), do_msg); return false; } } bool AdInterface::object_move(const QString &dn, const QString &new_container) { const QString rdn = dn.split(',')[0]; const QString new_dn = rdn + "," + new_container; const QString object_name = dn_get_name(dn); const QString container_name = dn_get_name(new_container); const int result = ldap_rename_s(d->ld, cstr(dn), cstr(rdn), cstr(new_container), 1, NULL, NULL); if (result == LDAP_SUCCESS) { d->success_message(QString(tr("Object %1 was moved to %2.")).arg(object_name, container_name)); return true; } else { const QString context = QString(tr("Failed to move object %1 to %2.")).arg(object_name, container_name); d->error_message(context, d->default_error()); return false; } } bool AdInterface::object_rename(const QString &dn, const QString &new_name) { const QString new_dn = dn_rename(dn, new_name); const QString new_rdn = new_dn.split(",")[0]; const QString old_name = dn_get_name(dn); const int result = ldap_rename_s(d->ld, cstr(dn), cstr(new_rdn), NULL, 1, NULL, NULL); if (result == LDAP_SUCCESS) { d->success_message(QString(tr("Object %1 was renamed to %2.")).arg(old_name, new_name)); return true; } else { const QString context = QString(tr("Failed to rename object %1 to %2.")).arg(old_name, new_name); d->error_message(context, d->default_error()); return false; } } bool AdInterface::group_add_member(const QString &group_dn, const QString &user_dn) { const QByteArray user_dn_bytes = user_dn.toUtf8(); const bool success = attribute_add_value(group_dn, ATTRIBUTE_MEMBER, user_dn_bytes, DoStatusMsg_No); const QString user_name = dn_get_name(user_dn); const QString group_name = dn_get_name(group_dn); if (success) { d->success_message(QString(tr("Object %1 was added to group %2.")).arg(user_name, group_name)); return true; } else { const QString context = QString(tr("Failed to add object %1 to group %2.")).arg(user_name, group_name); d->error_message(context, d->default_error()); return false; } } bool AdInterface::group_remove_member(const QString &group_dn, const QString &user_dn) { const QByteArray user_dn_bytes = user_dn.toUtf8(); const bool success = attribute_delete_value(group_dn, ATTRIBUTE_MEMBER, user_dn_bytes, DoStatusMsg_No); const QString user_name = dn_get_name(user_dn); const QString group_name = dn_get_name(group_dn); if (success) { d->success_message(QString(tr("Object %1 was removed from group %2.")).arg(user_name, group_name)); return true; } else { const QString context = QString(tr("Failed to remove object %1 from group %2.")).arg(user_name, group_name); d->error_message(context, d->default_error()); return false; } } bool AdInterface::group_set_scope(const QString &dn, GroupScope scope, const DoStatusMsg do_msg) { // NOTE: it is not possible to change scope from // global<->domainlocal directly, so have to switch to // universal first. const bool need_to_switch_to_universal = [=]() { const AdObject object = search_object(dn, {ATTRIBUTE_GROUP_TYPE}); const GroupScope current_scope = object.get_group_scope(); return (current_scope == GroupScope_Global && scope == GroupScope_DomainLocal) || (current_scope == GroupScope_DomainLocal && scope == GroupScope_Global); }(); if (need_to_switch_to_universal) { group_set_scope(dn, GroupScope_Universal, DoStatusMsg_No); } const AdObject object = search_object(dn, {ATTRIBUTE_GROUP_TYPE}); int group_type = object.get_int(ATTRIBUTE_GROUP_TYPE); // Unset all scope bits, because scope bits are exclusive for (int i = 0; i < GroupScope_COUNT; i++) { const GroupScope this_scope = (GroupScope) i; const int this_scope_bit = group_scope_bit(this_scope); group_type = bitmask_set(group_type, this_scope_bit, false); } // Set given scope bit const int scope_bit = group_scope_bit(scope); group_type = bitmask_set(group_type, scope_bit, true); const QString name = dn_get_name(dn); const QString scope_string = group_scope_string(scope); const bool result = attribute_replace_int(dn, ATTRIBUTE_GROUP_TYPE, group_type); if (result) { d->success_message(QString(tr("Group scope for %1 was changed to \"%2\".")).arg(name, scope_string), do_msg); return true; } else { const QString context = QString(tr("Failed to change group scope for %1 to \"%2\".")).arg(name, scope_string); d->error_message(context, d->default_error(), do_msg); return false; } } bool AdInterface::group_set_type(const QString &dn, GroupType type) { const AdObject object = search_object(dn, {ATTRIBUTE_GROUP_TYPE}); const int group_type = object.get_int(ATTRIBUTE_GROUP_TYPE); const bool set_security_bit = type == GroupType_Security; const int update_group_type = bitmask_set(group_type, GROUP_TYPE_BIT_SECURITY, set_security_bit); const QString update_group_type_string = QString::number(update_group_type); const QString name = dn_get_name(dn); const QString type_string = group_type_string(type); const bool result = attribute_replace_string(dn, ATTRIBUTE_GROUP_TYPE, update_group_type_string); if (result) { d->success_message(QString(tr("Group type for %1 was changed to \"%2\".")).arg(name, type_string)); return true; } else { const QString context = QString(tr("Failed to change group type for %1 to \"%2\".")).arg(name, type_string); d->error_message(context, d->default_error()); return false; } } bool AdInterface::user_set_primary_group(const QString &group_dn, const QString &user_dn) { const AdObject group_object = search_object(group_dn, {ATTRIBUTE_OBJECT_SID, ATTRIBUTE_MEMBER}); // NOTE: need to add user to group before it can become primary const QList<QString> group_members = group_object.get_strings(ATTRIBUTE_MEMBER); const bool user_is_in_group = group_members.contains(user_dn); if (!user_is_in_group) { group_add_member(group_dn, user_dn); } const QByteArray group_sid = group_object.get_value(ATTRIBUTE_OBJECT_SID); const QString group_rid = extract_rid_from_sid(group_sid, d->adconfig); const bool success = attribute_replace_string(user_dn, ATTRIBUTE_PRIMARY_GROUP_ID, group_rid, DoStatusMsg_No); const QString user_name = dn_get_name(user_dn); const QString group_name = dn_get_name(group_dn); if (success) { d->success_message(QString(tr("Primary group for object %1 was changed to %2.")).arg(user_name, group_name)); return true; } else { const QString context = QString(tr("Failed to change primary group for user %1 to %2.")).arg(user_name, group_name); d->error_message(context, d->default_error()); return false; } } bool AdInterface::user_set_pass(const QString &dn, const QString &password, const DoStatusMsg do_msg) { // NOTE: AD requires that the password: // 1. is surrounded by quotes // 2. is encoded as UTF16-LE // 3. has no Byte Order Mark const QString quoted_password = QString("\"%1\"").arg(password); const auto codec = QTextCodec::codecForName("UTF-16LE"); QByteArray password_bytes = codec->fromUnicode(quoted_password); // Remove BOM // NOTE: gotta be a way to tell codec not to add BOM // but couldn't find it, only QTextStream has // setGenerateBOM() if (password_bytes[0] != '\"') { password_bytes.remove(0, 2); } const bool success = attribute_replace_value(dn, ATTRIBUTE_PASSWORD, password_bytes, DoStatusMsg_No); const QString name = dn_get_name(dn); if (success) { d->success_message(QString(tr("Password for object %1 was changed.")).arg(name), do_msg); return true; } else { const QString context = QString(tr("Failed to change password for object %1.")).arg(name); const QString error = [this]() { const int ldap_result = d->get_ldap_result(); if (ldap_result == LDAP_CONSTRAINT_VIOLATION) { return tr("Password doesn't match rules."); } else { return d->default_error(); } }(); d->error_message(context, error, do_msg); return false; } } bool AdInterface::user_set_account_option(const QString &dn, AccountOption option, bool set) { if (dn.isEmpty()) { return false; } bool success = false; switch (option) { case AccountOption_CantChangePassword: { success = ad_security_set_user_cant_change_pass(this, dn, set); break; } case AccountOption_PasswordExpired: { QString pwdLastSet_value; if (set) { pwdLastSet_value = AD_PWD_LAST_SET_EXPIRED; } else { pwdLastSet_value = AD_PWD_LAST_SET_RESET; } success = attribute_replace_string(dn, ATTRIBUTE_PWD_LAST_SET, pwdLastSet_value, DoStatusMsg_No); break; } default: { const int uac = [this, dn]() { const AdObject object = search_object(dn, {ATTRIBUTE_USER_ACCOUNT_CONTROL}); return object.get_int(ATTRIBUTE_USER_ACCOUNT_CONTROL); }(); const int bit = account_option_bit(option); const int updated_uac = bitmask_set(uac, bit, set); success = attribute_replace_int(dn, ATTRIBUTE_USER_ACCOUNT_CONTROL, updated_uac, DoStatusMsg_No); } } const QString name = dn_get_name(dn); if (success) { const QString success_context = [option, set, name]() { switch (option) { case AccountOption_Disabled: { if (set) { return QString(tr("Object %1 has been disabled.")).arg(name); } else { return QString(tr("Object %1 has been enabled.")).arg(name); } } default: { const QString description = account_option_string(option); if (set) { return QString(tr("Account option \"%1\" was turned ON for object %2.")).arg(description, name); } else { return QString(tr("Account option \"%1\" was turned OFF for object %2.")).arg(description, name); } } } }(); d->success_message(success_context); return true; } else { const QString context = [option, set, name]() { switch (option) { case AccountOption_Disabled: { if (set) { return QString(tr("Failed to disable object %1.")).arg(name); } else { return QString(tr("Failed to enable object %1.")).arg(name); } } default: { const QString description = account_option_string(option); if (set) { return QString(tr("Failed to turn ON account option \"%1\" for object %2.")).arg(description, name); } else { return QString(tr("Failed to turn OFF account option \"%1\" for object %2.")).arg(description, name); } } } }(); d->error_message(context, d->default_error()); return false; } } bool AdInterface::user_unlock(const QString &dn) { const bool result = attribute_replace_string(dn, ATTRIBUTE_LOCKOUT_TIME, LOCKOUT_UNLOCKED_VALUE); const QString name = dn_get_name(dn); if (result) { d->success_message(QString(tr("User \"%1\" was unlocked.")).arg(name)); return true; } else { const QString context = QString(tr("Failed to unlock user %1.")).arg(name); d->error_message(context, d->default_error()); return result; } } bool AdInterface::computer_reset_account(const QString &dn) { const QString name = dn_get_name(dn); const QString reset_password = QString("%1$").arg(name); const bool success = user_set_pass(dn, reset_password, DoStatusMsg_No); if (success) { d->success_message(QString(tr("Computer \"%1\" was reset.")).arg(name)); return true; } else { const QString context = QString(tr("Failed to reset computer %1.")).arg(name); d->error_message(context, d->default_error()); return false; } } bool AdInterface::gpo_add(const QString &display_name, QString &dn_out) { const bool is_domain_admin = logged_in_as_domain_admin(); auto error_message = [&](const QString &error) { if (!is_domain_admin) { d->error_message_plain(tr("Warning: User is not domain administrator.")); } d->error_message(tr("Failed to create GPO."), error); }; // // Generate UUID used for directory and object names // const QString uuid = []() { uuid_t uuid_struct; uuid_generate_random(uuid_struct); char uuid_cstr[UUID_STR_LEN]; uuid_unparse_upper(uuid_struct, uuid_cstr); const QString out = "{" + QString(uuid_cstr) + "}"; return out; }(); // Ex: "\\domain.alt\sysvol\domain.alt\Policies\{FF7E0880-F3AD-4540-8F1D-4472CB4A7044}" const QString filesys_path = QString("\\\\%1\\sysvol\\%2\\Policies\\%3").arg(d->domain.toLower(), d->domain.toLower(), uuid); const QString gpt_path = filesys_path_to_smb_path(filesys_path); const QString gpc_dn = QString("CN=%1,CN=Policies,CN=System,%2").arg(uuid, adconfig()->domain_dn()); // After each error case we need to clean up whatever we // have created successfully so far. Don't just use // gpo_delete() because we want to delete partially in // some error cases and that shouldn't print any error // messages. auto cleanup = [&]() { const AdObject gpc_object = search_object(gpc_dn); const bool gpc_exists = !gpc_object.is_empty(); if (gpc_exists) { object_delete(gpc_dn); } struct stat filestat; const int stat_result = smbc_stat(cstr(gpt_path), &filestat); const bool gpt_exists = (stat_result == 0); if (gpt_exists) { d->delete_gpt(gpt_path); } }; // // Create GPT // // Create root dir // "smb://domain.alt/sysvol/domain.alt/Policies/{FF7E0880-F3AD-4540-8F1D-4472CB4A7044}" const int result_mkdir_gpt = smbc_mkdir(cstr(gpt_path), 0755); if (result_mkdir_gpt != 0) { error_message(tr("Failed to create GPT root dir.")); cleanup(); return false; } const QString gpt_machine_path = gpt_path + "/Machine"; const int result_mkdir_machine = smbc_mkdir(cstr(gpt_machine_path), 0755); if (result_mkdir_machine != 0) { error_message(tr("Failed to create GPT machine dir.")); cleanup(); return false; } const QString gpt_user_path = gpt_path + "/User"; const int result_mkdir_user = smbc_mkdir(cstr(gpt_user_path), 0755); if (result_mkdir_user != 0) { error_message(tr("Failed to create GPT user dir.")); cleanup(); return false; } const QString gpt_ini_path = gpt_path + "/GPT.INI"; const int ini_file = smbc_open(cstr(gpt_ini_path), O_WRONLY | O_CREAT, 0644); if (ini_file < 0) { error_message(tr("Failed to open GPT ini file.")); cleanup(); return false; } const char *ini_contents = "[General]\r\nVersion=0\r\n"; const int bytes_written = smbc_write(ini_file, ini_contents, strlen(ini_contents)); smbc_close(ini_file); if (bytes_written < 0) { error_message(tr("Failed to write GPT ini file.")); cleanup(); return false; } // // Create AD object for gpo // const bool result_add = object_add(gpc_dn, CLASS_GP_CONTAINER); if (!result_add) { error_message(tr("Failed to create GPC object.")); cleanup(); return false; } const QHash<QString, QString> attribute_value_map = { {ATTRIBUTE_DISPLAY_NAME, display_name}, {ATTRIBUTE_GPC_FILE_SYS_PATH, filesys_path}, // NOTE: samba defaults to 1, ADUC defaults to 0. Figure out what's this supposed to be. {ATTRIBUTE_FLAGS, "0"}, {ATTRIBUTE_VERSION_NUMBER, "0"}, {ATTRIBUTE_SHOW_IN_ADVANCED_VIEW_ONLY, "TRUE"}, {ATTRIBUTE_GPC_FUNCTIONALITY_VERSION, "2"}, }; for (const QString &attribute : attribute_value_map.keys()) { const QString value = attribute_value_map[attribute]; const bool replace_success = attribute_replace_string(gpc_dn, attribute, value); if (!replace_success) { error_message(QString(tr("Failed to set GPC attribute %1.")).arg(attribute)); cleanup(); return false; } } // User object const QString user_dn = "CN=User," + gpc_dn; const bool result_add_user = object_add(user_dn, CLASS_CONTAINER); attribute_replace_string(gpc_dn, ATTRIBUTE_SHOW_IN_ADVANCED_VIEW_ONLY, "TRUE"); if (!result_add_user) { error_message(tr("Failed to create user folder object for GPO.")); cleanup(); return false; } // Machine object const QString machine_dn = "CN=Machine," + gpc_dn; const bool result_add_machine = object_add(machine_dn, CLASS_CONTAINER); attribute_replace_string(gpc_dn, ATTRIBUTE_SHOW_IN_ADVANCED_VIEW_ONLY, "TRUE"); if (!result_add_machine) { error_message(tr("Failed to create machine folder object for GPO.")); cleanup(); return false; } const bool sync_perms_success = gpo_sync_perms(gpc_dn); if (!sync_perms_success) { // NOTE: don't fail if failed to sync perms, user // can retry it later } dn_out = gpc_dn; return true; } QList<QString> AdInterfacePrivate::gpo_get_gpt_contents(const QString &gpt_root_path, bool *ok) { // Collect all contents of the path into a list QList<QString> explore_stack; QList<QString> seen_stack; explore_stack.append(gpt_root_path); seen_stack.append(gpt_root_path); const QString error_context = QString(tr("Failed to get contents of GPT \"%1\".")).arg(gpt_root_path); while (!explore_stack.isEmpty()) { const QString path = explore_stack.takeLast(); const int dirp = smbc_opendir(cstr(path)); if (dirp < 0) { *ok = false; error_message(error_context, tr("Failed to open dir.")); return QList<QString>(); } // NOTE: set errno to 0, so that we know // when readdir() fails because it will // change errno. errno = 0; smbc_dirent *child_dirent; while ((child_dirent = smbc_readdir(dirp)) != NULL) { const QString child_name = QString(child_dirent->name); const bool is_dot_path = (child_name == "." || child_name == ".."); if (is_dot_path) { continue; } else { const QString child_path = path + "/" + child_name; seen_stack.append(child_path); const bool child_is_dir = smb_path_is_dir(child_path, ok); if (!*ok) { return QList<QString>(); } if (child_is_dir) { explore_stack.append(child_path); } } } if (errno != 0) { *ok = false; error_message(error_context, tr("Failed to read dir.")); return QList<QString>(); } smbc_closedir(dirp); } return seen_stack; } bool AdInterface::gpo_delete(const QString &dn, bool *deleted_object) { // NOTE: try to execute both steps, even if first one // (deleting gpc) fails // NOTE: get filesys path before deleting object, // otherwise it won't be available! const AdObject object = search_object(dn, {ATTRIBUTE_GPC_FILE_SYS_PATH, ATTRIBUTE_DISPLAY_NAME}); const QString filesys_path = object.get_string(ATTRIBUTE_GPC_FILE_SYS_PATH); const QString name = object.get_string(ATTRIBUTE_DISPLAY_NAME); const QString smb_path = filesys_path_to_smb_path(filesys_path); const bool delete_gpc_success = object_delete(dn); if (!delete_gpc_success) { d->error_message(tr("Failed to delete GPC."), d->default_error()); } const bool delete_gpt_success = d->delete_gpt(smb_path); if (!delete_gpt_success) { d->error_message_plain(tr("Failed to delete GPT.")); } // Unlink policy const QString base = adconfig()->domain_dn(); const SearchScope scope = SearchScope_All; const QList<QString> attributes = {ATTRIBUTE_GPLINK}; const QString filter = filter_CONDITION(Condition_Contains, ATTRIBUTE_GPLINK, dn); const QHash<QString, AdObject> results = search(base, scope, filter, attributes); for (const AdObject &linked_object : results.values()) { const QString gplink_old_string = linked_object.get_string(ATTRIBUTE_GPLINK); Gplink gplink = Gplink(gplink_old_string); gplink.remove(dn); attribute_replace_string(linked_object.get_dn(), ATTRIBUTE_GPLINK, gplink.to_string()); } const bool total_success = (delete_gpc_success && delete_gpt_success); if (total_success) { d->success_message(QString(tr("Group policy %1 was deleted.")).arg(name)); } else { const bool partial_success = (delete_gpc_success || delete_gpt_success); if (partial_success) { d->success_message(QString(tr("Errors happened while trying to delete policy %1.")).arg(name)); } else { d->success_message(QString(tr("Failed to delete policy %1.")).arg(name)); } } *deleted_object = delete_gpc_success; return total_success; } QString AdInterface::filesys_path_to_smb_path(const QString &filesys_path) const { QString out = filesys_path; // NOTE: sysvol paths created by windows have this weird // capitalization and smbclient does NOT like it out.replace("\\SysVol\\", "\\sysvol\\"); out.replace("\\", "/"); const int sysvol_i = out.indexOf("/sysvol/"); out.remove(0, sysvol_i); out = QString("smb://%1%2").arg(d->dc, out); return out; } bool AdInterface::ldap_init() { const QString connect_error_context = tr("Failed to connect."); const QString uri = [&]() { QString out; if (!d->dc.isEmpty()) { out = "ldap://" + d->dc; if (AdInterfacePrivate::s_port > 0) { out = out + ":" + AdInterfacePrivate::s_port; } } return out; }(); if (uri.isEmpty()) { return false; } int result; // NOTE: this doesn't leak memory. False positive. result = ldap_initialize(&d->ld, cstr(uri)); if (result != LDAP_SUCCESS) { ldap_memfree(d->ld); d->error_message(tr("Failed to initialize LDAP library."), strerror(errno)); return false; } auto option_error = [&](const QString &option) { d->error_message(connect_error_context, QString(tr("Failed to set ldap option %1.")).arg(option)); }; // Set version const int version = LDAP_VERSION3; result = ldap_set_option(d->ld, LDAP_OPT_PROTOCOL_VERSION, &version); if (result != LDAP_OPT_SUCCESS) { option_error("LDAP_OPT_PROTOCOL_VERSION"); return false; } // Disable referrals result = ldap_set_option(d->ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF); if (result != LDAP_OPT_SUCCESS) { option_error("LDAP_OPT_REFERRALS"); return false; } // Set SASL propertry min_ssf to the minimum acceptable security layer strength. // SSF is a rough indication of how secure the connection is. A connection // secured by 56-bit DES would have an SSF of 56. const char *sasl_secprops = "minssf=56"; result = ldap_set_option(d->ld, LDAP_OPT_X_SASL_SECPROPS, sasl_secprops); if (result != LDAP_SUCCESS) { option_error("LDAP_OPT_X_SASL_SECPROPS"); return false; } result = ldap_set_option(d->ld, LDAP_OPT_X_SASL_NOCANON, AdInterfacePrivate::s_sasl_nocanon); if (result != LDAP_SUCCESS) { option_error("LDAP_OPT_X_SASL_NOCANON"); return false; } const int cert_strategy = [&]() { switch (AdInterfacePrivate::s_cert_strat) { case CertStrategy_Never: return LDAP_OPT_X_TLS_NEVER; case CertStrategy_Hard: return LDAP_OPT_X_TLS_HARD; case CertStrategy_Demand: return LDAP_OPT_X_TLS_DEMAND; case CertStrategy_Allow: return LDAP_OPT_X_TLS_ALLOW; case CertStrategy_Try: return LDAP_OPT_X_TLS_TRY; } return LDAP_OPT_X_TLS_NEVER; }(); ldap_set_option(d->ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &cert_strategy); if (result != LDAP_SUCCESS) { option_error("LDAP_OPT_X_TLS_REQUIRE_CERT"); return false; } // Setup sasl_defaults_gssapi struct sasl_defaults_gssapi defaults; defaults.mech = (char *) "GSSAPI"; ldap_get_option(d->ld, LDAP_OPT_X_SASL_REALM, &defaults.realm); ldap_get_option(d->ld, LDAP_OPT_X_SASL_AUTHCID, &defaults.authcid); ldap_get_option(d->ld, LDAP_OPT_X_SASL_AUTHZID, &defaults.authzid); defaults.passwd = NULL; // Perform bind operation unsigned sasl_flags = LDAP_SASL_QUIET; result = ldap_sasl_interactive_bind_s(d->ld, NULL, defaults.mech, NULL, NULL, sasl_flags, sasl_interact_gssapi, &defaults); ldap_memfree(defaults.realm); ldap_memfree(defaults.authcid); ldap_memfree(defaults.authzid); if (result != LDAP_SUCCESS) { d->error_message_plain(tr("Failed to connect to server. Check your connection and make sure you have initialized your credentials using kinit.")); d->error_message_plain(d->default_error()); return false; } d->client_user = [&]() { char *out_cstr = NULL; ldap_get_option(d->ld, LDAP_OPT_X_SASL_USERNAME, &out_cstr); if (out_cstr == NULL) { return QString(); } QString out = QString(out_cstr); out = out.toLower(); ldap_memfree(out_cstr); return out; }(); return true; } void AdInterface::ldap_free() { if (d->is_connected) { ldap_unbind_ext(d->ld, NULL, NULL); } else { ldap_memfree(d->ld); } } bool AdInterface::gpo_check_perms(const QString &gpo, bool *ok) { // NOTE: skip perms check for non-admins, because don't // have enough rights to get full sd if (!logged_in_as_domain_admin()) { return true; } const QList<QString> attributes = QList<QString>(); const bool get_sacl = true; const AdObject gpc_object = search_object(gpo, attributes, get_sacl); const QString name = gpc_object.get_string(ATTRIBUTE_DISPLAY_NAME); const QString error_context = QString(tr("Failed to check permissions for GPO \"%1\".")).arg(name); const QString gpc_sd = [&]() { const QString out = get_gpt_sd_string(gpc_object, AceMaskFormat_Hexadecimal); if (out.isEmpty()) { d->error_message(error_context, tr("Failed to get GPT security descriptor.")); return QString(); } return out; }(); const QString gpt_sd = [&]() { const QString filesys_path = gpc_object.get_string(ATTRIBUTE_GPC_FILE_SYS_PATH); const QString smb_path = filesys_path_to_smb_path(filesys_path); const char *smb_path_cstr = cstr(smb_path); // NOTE: the length of gpt sd string doesn't have a // well defined bound, so we have to use an // expanding buffer size_t buffer_size = 1024 * sizeof(char); char *buffer = (char *) malloc(buffer_size); while (true) { const int getxattr_result = smbc_getxattr(smb_path_cstr, "system.nt_sec_desc.*", buffer, buffer_size); // NOTE: for some reason getxattr() returns positive // non-zero return code on success, even though f-n // description says it "returns 0 on success" const bool success = (getxattr_result >= 0); if (success) { break; } else { const bool buffer_is_too_small = (errno == ERANGE); if (buffer_is_too_small) { // Error occured, but it is due to // insufficient buffer size, so try // again with bigger buffer buffer_size = 2 * buffer_size; buffer = (char *) realloc(buffer, buffer_size); } else { const QString text = QString(tr("Failed to get GPT security descriptor, %1.")).arg(strerror(errno)); d->error_message(error_context, text); free(buffer); return QString(); } } } const QString out = QString(buffer); free(buffer); return out; }(); qDebug() << "--------"; qDebug() << "gpc_sd:"; for (auto e : QString(gpc_sd).split(",")) { qDebug() << e; } qDebug() << "--------"; qDebug() << "gpt_sd:"; for (auto e : QString(gpt_sd).split(",")) { qDebug() << e; } if (gpc_sd.isEmpty() || gpt_sd.isEmpty()) { *ok = false; return false; } // SD's match if they both contain all lines of the // other one. Order doesn't matter. Note that // simple equality doesn't work because entry order // may not match. // // NOTE: there's also a weird thing where RSAT // creates GPO's with duplicate ace's for Domain // Admins. Not sure why that happens but this // matching method ignores that quirk. const bool sd_match = [&]() { const QList<QString> gpt_list = QString(gpt_sd).split(","); const QList<QString> gpc_list = QString(gpc_sd).split(","); for (const QString &line : gpt_list) { if (!gpc_list.contains(line)) { return false; } } for (const QString &line : gpc_list) { if (!gpt_list.contains(line)) { return false; } } return true; }(); return sd_match; } bool AdInterface::gpo_sync_perms(const QString &dn) { // First get GPC descriptor const QList<QString> attributes = QList<QString>(); const bool get_sacl = true; const AdObject gpc_object = search_object(dn, attributes, get_sacl); const QString name = gpc_object.get_string(ATTRIBUTE_DISPLAY_NAME); const QString gpt_sd_string = get_gpt_sd_string(gpc_object, AceMaskFormat_Decimal); const QString error_context = QString(tr("Failed to sync permissions of GPO \"%1\".")).arg(name); if (gpt_sd_string.isEmpty()) { d->error_message(error_context, tr("Failed to generate GPT security descriptor.")); return false; } // Get list of GPT contents // NOTE: order is important, have to set perms of parent // folders before their contents, otherwise fails to // set! Default gpo_get_gpt_contents() order is good. const QString filesys_path = gpc_object.get_string(ATTRIBUTE_GPC_FILE_SYS_PATH); const QString smb_path = filesys_path_to_smb_path(filesys_path); bool ok = true; const QList<QString> path_list = d->gpo_get_gpt_contents(smb_path, &ok); if (!ok || path_list.isEmpty()) { d->error_message(error_context, QString(tr("Failed to read GPT contents of \"%1\".")).arg(smb_path)); return false; } // Set descriptor on all GPT contents for (const QString &path : path_list) { const int set_sd_result = smbc_setxattr(cstr(path), "system.nt_sec_desc.*", cstr(gpt_sd_string), strlen(cstr(gpt_sd_string)), 0); if (set_sd_result != 0) { const QString error = QString(tr("Failed to set permissions, %1.")).arg(strerror(errno)); d->error_message(error_context, error); return false; } } d->success_message(QString(tr("Synced permissions of GPO \"%1\".")).arg(name)); return true; } bool AdInterface::gpo_get_sysvol_version(const AdObject &gpc_object, int *version_out) { const QString error_context = tr("Failed to load GPO's sysvol version."); const QString ini_contents = [&]() { const QString filesys_path = gpc_object.get_string(ATTRIBUTE_GPC_FILE_SYS_PATH); const QString smb_path = filesys_path_to_smb_path(filesys_path); const QString ini_path = smb_path + "/GPT.INI"; const int ini_fd = smbc_open(cstr(ini_path), O_RDONLY, 0); if (ini_fd < 0) { const QString error_text = QString(tr("Failed to open GPT.INI, %1.")).arg(strerror(errno)); d->error_message(error_context, error_text); return QString(); } const size_t buffer_size = 2000; char buffer[buffer_size]; const ssize_t bytes_read = smbc_read(ini_fd, buffer, buffer_size); if (bytes_read < 0) { const QString error_text = QString(tr("Failed to open GPT.INI, %1.")).arg(strerror(errno)); d->error_message(error_context, error_text); return QString(); } smbc_close(ini_fd); return QString(buffer); }(); if (ini_contents.isEmpty()) { return false; } const int version = [&]() { int out; const int scan_result = sscanf(cstr(ini_contents), "[General]\r\nVersion=%i\r\n", &out); const bool scan_success = (scan_result > 0); if (!scan_success) { const QString error_text = QString(tr("Failed to extract version from GPT.INI, %1.")).arg(strerror(errno)); d->error_message(error_context, error_text); return -1; } return out; }(); if (version >= 0) { *version_out = version; return true; } else { return false; } } void AdInterfacePrivate::success_message(const QString &msg, const DoStatusMsg do_msg) { if (do_msg == DoStatusMsg_No) { return; } const AdMessage message(msg, AdMessageType_Success); messages.append(message); } void AdInterfacePrivate::error_message(const QString &context, const QString &error, const DoStatusMsg do_msg) { if (do_msg == DoStatusMsg_No) { return; } QString msg = context; if (!error.isEmpty()) { msg += QString(tr(" Error: \"%1\"")).arg(error); // Add period if needed, because some error strings, // like the ones from LDAP, might not have one if (!msg.endsWith(".")) { msg += "."; } } const AdMessage message(msg, AdMessageType_Error); messages.append(message); } void AdInterfacePrivate::error_message_plain(const QString &text, const DoStatusMsg do_msg) { if (do_msg == DoStatusMsg_No) { return; } const AdMessage message(text, AdMessageType_Error); messages.append(message); } QString AdInterfacePrivate::default_error() const { const int ldap_result = get_ldap_result(); switch (ldap_result) { case LDAP_NO_SUCH_OBJECT: return tr("No such object"); case LDAP_CONSTRAINT_VIOLATION: return tr("Constraint violation"); case LDAP_UNWILLING_TO_PERFORM: return tr("Server is unwilling to perform"); case LDAP_ALREADY_EXISTS: return tr("Already exists"); default: { char *ldap_err = ldap_err2string(ldap_result); const QString ldap_err_qstr(ldap_err); return QString(tr("Server error: %1")).arg(ldap_err_qstr); } } } int AdInterfacePrivate::get_ldap_result() const { int result; ldap_get_option(ld, LDAP_OPT_RESULT_CODE, &result); return result; } bool AdInterfacePrivate::delete_gpt(const QString &parent_path) { bool ok = true; QList<QString> path_list = gpo_get_gpt_contents(parent_path, &ok); if (!ok) { return false; } // NOTE: have to reverse so deepest paths are first to // delete correctly std::reverse(path_list.begin(), path_list.end()); for (const QString &path : path_list) { const bool is_dir = smb_path_is_dir(path, &ok); if (!ok) { return false; } if (is_dir) { const int result_rmdir = smbc_rmdir(cstr(path)); if (result_rmdir != 0) { error_message(QString(tr("Failed to delete GPT folder %1.")).arg(path), strerror(errno)); return false; } } else { const int result_unlink = smbc_unlink(cstr(path)); if (result_unlink != 0) { error_message(QString(tr("Failed to delete GPT file %1.")).arg(path), strerror(errno)); return false; } } } return true; } bool AdInterfacePrivate::smb_path_is_dir(const QString &path, bool *ok) { struct stat filestat; const int stat_result = smbc_stat(cstr(path), &filestat); if (stat_result != 0) { error_message(QString(tr("Failed to get filestat for \"%1\".")).arg(path), strerror(errno)); *ok = false; return false; } else { *ok = true; const bool is_dir = S_ISDIR(filestat.st_mode); return is_dir; } } // NOTE: this f-n is analogous to // ldap_create_page_control() and others. See pagectl.c // in ldap sources for examples. Extracted to contain // the C madness. int create_sd_control(bool get_sacl, int is_critical, LDAPControl **ctrlp, bool set_dacl) { // NOTE: SACL part of the sd can only be obtained // by administrators. For most operations we don't // need SACL. Some operations, like creating a GPO, // do require SACL, so for those operations we turn // on the "get_sacl" options. int flags = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; if (get_sacl) { flags |= SACL_SECURITY_INFORMATION; } else if (set_dacl) { flags = DACL_SECURITY_INFORMATION; } BerElement *value_be = NULL; struct berval value; value_be = ber_alloc_t(LBER_USE_DER); ber_printf(value_be, "{i}", flags); ber_flatten2(value_be, &value, 1); // Create control const int result = ldap_control_create(LDAP_SERVER_SD_FLAGS_OID, is_critical, &value, 0, ctrlp); if (result != LDAP_SUCCESS) { ber_memfree(value.bv_val); } ber_free(value_be, 1); return result; } bool AdInterface::logged_in_as_domain_admin() { const QString sam_account_name = d->client_user.split('@')[0]; const QString client_user_filter = filter_CONDITION(Condition_Equals, ATTRIBUTE_SAM_ACCOUNT_NAME, sam_account_name); const QHash<QString, AdObject> client_user_results = search(adconfig()->domain_dn(), SearchScope_All, client_user_filter, {ATTRIBUTE_PRIMARY_GROUP_ID}); if (client_user_results.isEmpty()) { return false; } const QString user_dn = client_user_results.keys()[0]; if (user_dn.isEmpty()) { return false; } int primary_group_id = client_user_results.values()[0].get_int(ATTRIBUTE_PRIMARY_GROUP_ID); const int domain_admins_rid = 512; if (primary_group_id == domain_admins_rid) { return true; } const QString domain_admins_sid = adconfig()->domain_sid() + "-" + QString::number(domain_admins_rid); const QString filter_group = filter_CONDITION(Condition_Equals, ATTRIBUTE_OBJECT_CLASS, CLASS_GROUP); const QString filter_sid = filter_CONDITION(Condition_Equals, ATTRIBUTE_OBJECT_SID, domain_admins_sid); const QString filter = filter_AND({filter_group, filter_sid}); const QHash<QString, AdObject> admin_group_results = search(adconfig()->domain_dn(), SearchScope_All, filter, QList<QString>()); if (admin_group_results.isEmpty()) { d->error_message(tr("Failed to check user permissions."), tr("Can't find domain admins group with SID ") + domain_admins_sid); return false; } const AdObject domain_admins_object = admin_group_results.values()[0]; const QString rule_in_chain_filter = filter_matching_rule_in_chain(ATTRIBUTE_MEMBER_OF, domain_admins_object.get_dn()); const QHash<QString, AdObject> res = search(user_dn, SearchScope_Object, rule_in_chain_filter, QList<QString>()); return res.keys().contains(user_dn); } QString AdInterface::get_dc() const { return d->dc; } QString AdInterface::get_domain() const { return d->domain; } void AdInterface::update_dc() { d->dc = AdInterfacePrivate::s_dc; // Reinit ldap connection with updated DC ldap_free(); ldap_init(); } QList<QString> get_domain_hosts(const QString &domain, const QString &site) { QList<QString> hosts; // Query site hosts if (!site.isEmpty()) { char dname[1000]; snprintf(dname, sizeof(dname), "_ldap._tcp.%s._sites.%s", cstr(site), cstr(domain)); const QList<QString> site_hosts = query_server_for_hosts(dname); hosts.append(site_hosts); } // Query default hosts char dname_default[1000]; snprintf(dname_default, sizeof(dname_default), "_ldap._tcp.%s", cstr(domain)); const QList<QString> default_hosts = query_server_for_hosts(dname_default); hosts.append(default_hosts); hosts.removeDuplicates(); return hosts; } /** * Perform a query for dname and output hosts * dname is a combination of protocols (d->ldap, tcp), domain and site * NOTE: this is rewritten from * https://github.com/paleg/libadclient/blob/master/adclient.cpp * which itself is copied from * https://www.ccnx.org/releases/latest/doc/ccode/html/ccndc-srv_8c_source.html * Another example of similar procedure: * https://www.gnu.org/software/shishi/coverage/shishi/lib/resolv.c.gcov.html */ QList<QString> query_server_for_hosts(const char *dname) { union dns_msg { HEADER header; unsigned char buf[NS_MAXMSG]; } msg; auto error = []() { return QList<QString>(); }; const long unsigned msg_len = res_search(dname, ns_c_in, ns_t_srv, msg.buf, sizeof(msg.buf)); const bool message_error = (msg_len < sizeof(HEADER)); if (message_error) { error(); } const int packet_count = ntohs(msg.header.qdcount); const int answer_count = ntohs(msg.header.ancount); unsigned char *curr = msg.buf + sizeof(msg.header); const unsigned char *eom = msg.buf + msg_len; // Skip over packet records for (int i = packet_count; i > 0 && curr < eom; i--) { const int packet_len = dn_skipname(curr, eom); const bool packet_error = (packet_len < 0); if (packet_error) { error(); } curr = curr + packet_len + QFIXEDSZ; } QList<QString> hosts; // Process answers by collecting hosts into list for (int i = 0; i < answer_count; i++) { // Get server char server[NS_MAXDNAME]; const int server_len = dn_expand(msg.buf, eom, curr, server, sizeof(server)); const bool server_error = (server_len < 0); if (server_error) { error(); } curr = curr + server_len; int record_type; int UNUSED(record_class); int UNUSED(ttl); int record_len; GETSHORT(record_type, curr); GETSHORT(record_class, curr); GETLONG(ttl, curr); GETSHORT(record_len, curr); unsigned char *record_end = curr + record_len; if (record_end > eom) { error(); } // Skip non-server records if (record_type != ns_t_srv) { curr = record_end; continue; } int UNUSED(priority); int UNUSED(weight); int UNUSED(port); GETSHORT(priority, curr); GETSHORT(weight, curr); GETSHORT(port, curr); // Get host char host[NS_MAXDNAME]; const int host_len = dn_expand(msg.buf, eom, curr, host, sizeof(host)); const bool host_error = (host_len < 0); if (host_error) { error(); } hosts.append(QString(host)); curr = record_end; } return hosts; } /** * Callback for ldap_sasl_interactive_bind_s */ int sasl_interact_gssapi(LDAP *ld, unsigned flags, void *indefaults, void *in) { UNUSED_ARG(flags); sasl_defaults_gssapi *defaults = (sasl_defaults_gssapi *) indefaults; sasl_interact_t *interact = (sasl_interact_t *) in; if (ld == NULL) { return LDAP_PARAM_ERROR; } while (interact->id != SASL_CB_LIST_END) { const char *dflt = interact->defresult; switch (interact->id) { case SASL_CB_GETREALM: if (defaults) dflt = defaults->realm; break; case SASL_CB_AUTHNAME: if (defaults) dflt = defaults->authcid; break; case SASL_CB_PASS: if (defaults) dflt = defaults->passwd; break; case SASL_CB_USER: if (defaults) dflt = defaults->authzid; break; case SASL_CB_NOECHOPROMPT: break; case SASL_CB_ECHOPROMPT: break; } if (dflt && !*dflt) { dflt = NULL; } /* input must be empty */ interact->result = (dflt && *dflt) ? dflt : ""; interact->len = strlen((const char *) interact->result); interact++; } return LDAP_SUCCESS; } // NOTE: decimal format option is provided to deal with this // bug in libsmbclient: // https://bugzilla.samba.org/show_bug.cgi?id=14303. You // only need to use decimal format when making the string to // pass to smbc_setxattr(), otherwise you should use hex // format. QString get_gpt_sd_string(const AdObject &gpc_object, const AceMaskFormat format_enum) { TALLOC_CTX *mem_ctx = talloc_new(NULL); security_descriptor *gpc_sd = gpc_object.get_security_descriptor(mem_ctx); struct security_descriptor *gpt_sd; const NTSTATUS create_sd_status = gp_create_gpt_security_descriptor(mem_ctx, gpc_sd, &gpt_sd); if (!NT_STATUS_IS_OK(create_sd_status)) { qDebug() << "Failed to create gpt sd"; talloc_free(mem_ctx); return QString(); } security_descriptor_sort_dacl(gpt_sd); QList<QString> all_elements; all_elements.append(QString("REVISION:%1").arg(gpt_sd->revision)); const QString owner_sid_string = dom_sid_string(mem_ctx, gpt_sd->owner_sid); all_elements.append(QString("OWNER:%1").arg(owner_sid_string)); const QString group_sid_string = dom_sid_string(mem_ctx, gpt_sd->group_sid); all_elements.append(QString("GROUP:%1").arg(group_sid_string)); // NOTE: don't need sacl for (uint32_t i = 0; i < gpt_sd->dacl->num_aces; i++) { struct security_ace ace = gpt_sd->dacl->aces[i]; char access_mask_string[100]; static const char *hex_format = "0x%08x"; static const char *dec_format = "%d"; const char *format = [&]() { switch (format_enum) { case AceMaskFormat_Hexadecimal: return hex_format; case AceMaskFormat_Decimal: return dec_format; } return hex_format; }(); snprintf(access_mask_string, sizeof(access_mask_string), format, ace.access_mask); const char *trustee_string = dom_sid_string(mem_ctx, &ace.trustee); all_elements.append(QString("ACL:%1:%2/%3/%4").arg(trustee_string, QString::number(ace.type), QString::number(ace.flags), access_mask_string)); } // NOTE: can get duplicate ace's because ace's are // modified for gpt format, so remove duplicates QList<QString> without_duplicates; for (const QString &element : all_elements) { if (!without_duplicates.contains(element)) { without_duplicates.append(element); } } const QString out = without_duplicates.join(","); talloc_free(mem_ctx); return out; } AdCookie::AdCookie() { cookie = NULL; } bool AdCookie::more_pages() const { return (cookie != NULL); } AdCookie::~AdCookie() { ber_bvfree(cookie); } AdMessage::AdMessage(const QString &text, const AdMessageType &type) { m_text = text; m_type = type; } QString AdMessage::text() const { return m_text; } AdMessageType AdMessage::type() const { return m_type; }
75,640
C++
.cpp
1,805
34.419391
209
0.62573
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,749
gplink.cpp
altlinux_admc/src/adldap/gplink.cpp
#include "gplink.h" #include "adldap.h" #include <QObject> #define LDAP_PREFIX "LDAP://" Gplink::Gplink() { } Gplink::Gplink(const Gplink &other) : gpo_list(other.gpo_list), options(other.options) { } Gplink::Gplink(const QString &gplink_string) { if (gplink_string.isEmpty()) { return; } // "[gpo_1;option_1][gpo_2;option_2][gpo_3;option_3]..." // => // {"gpo_1;option_1", "gpo_2;option_2", "gpo_3;option_3"} QString gplink_string_without_brackets = gplink_string; gplink_string_without_brackets.replace("[", ""); const QList<QString> gplink_string_split = gplink_string_without_brackets.split(']'); for (auto part : gplink_string_split) { if (part.isEmpty()) { continue; } // "gpo;option" // => // gpo and option const QList<QString> part_split = part.split(';'); if (part_split.size() != 2) { continue; } // "LDAP://cn={UUID},cn=something,DC=a,DC=b" // => // "cn={uuid},cn=something,dc=a,dc=b" const QString gpo = [&]() { QString out; out = part_split[0]; out.remove(LDAP_PREFIX); out = out.toLower(); return out; }(); const int option = [&]() { const QString option_string = part_split[1]; const int option_int = option_string.toInt(); return option_int; }(); gpo_list.prepend(gpo); options[gpo] = option; } } Gplink &Gplink::operator=(const Gplink &other) { if (this == &other) { return *this; } gpo_list = other.gpo_list; options = other.options; return *this; } // Transform into gplink format. Have to uppercase some // parts of the output. QString Gplink::to_string() const { QList<QString> part_list; QList<QString>::const_reverse_iterator i; for (i = gpo_list.rbegin(); i != gpo_list.rend(); ++i) { // Convert gpo dn from lower case to gplink case // format const QString gpo_case = [&]() { const QList<QString> rdn_list = i->split(","); QList<QString> rdn_list_case; for (const QString &rdn : rdn_list) { const QString rdn_case = [&]() { const QList<QString> attribute_value = rdn.split("="); // Do no processing if data is malformed if (attribute_value.size() != 2) { return rdn; } const QString attribute = attribute_value[0]; const QString value = attribute_value[1]; const QString attribute_case = [&]() { // "DC" attribute is upper-cased if (attribute == "dc") { return attribute.toUpper(); } else { return attribute; } }(); const QString value_case = [&]() { // uuid (the first rdn) is upper-cased if (rdn_list.indexOf(rdn) == 0) { return value.toUpper(); } else { return value; } }(); const QList<QString> attribute_value_case = { attribute_case, value_case, }; const QString out = attribute_value_case.join("="); return out; }(); rdn_list_case.append(rdn_case); } const QString out = rdn_list_case.join(","); return out; }(); const int option = options[*i]; const QString option_string = QString::number(option); const QString part = QString("[%1%2;%3]").arg(LDAP_PREFIX, gpo_case, option_string); part_list.append(part); } const QString out = part_list.join(""); return out; } bool Gplink::contains(const QString &gpo_case) const { const QString gpo = gpo_case.toLower(); return options.contains(gpo); } QList<QString> Gplink::get_gpo_list() const { QList<QString> gpo_list_case; for (auto gpo : gpo_list) { const QString gpo_case = [&]() { QList<QString> rdn_list = gpo.split(","); const bool rdn_list_is_malformed = rdn_list.isEmpty(); if (rdn_list_is_malformed) { return gpo; } const QString guid_rdn = rdn_list[0]; rdn_list[0] = guid_rdn.toUpper(); for (int i = 1; i < rdn_list.size(); i++) { const QString rdn = rdn_list[i]; QList<QString> rdn_split = rdn.split("="); const bool rdn_is_malformed = (rdn_split.size() != 2); if (rdn_is_malformed) { continue; } // Uppercase all rdn left halves rdn_split[0] = rdn_split[0].toUpper(); // Modify some right halves if (rdn_split[1] == "system") { rdn_split[1] = "System"; } else if (rdn_split[1] == "policies") { rdn_split[1] = "Policies"; } rdn_list[i] = rdn_split.join("="); } const QString out = rdn_list.join(","); return out; }(); gpo_list_case.append(gpo_case); } return gpo_list_case; } void Gplink::add(const QString &gpo_case) { const QString gpo = gpo_case.toLower(); const bool gpo_already_in_link = contains(gpo); if (gpo_already_in_link) { return; } gpo_list.append(gpo); options[gpo] = 0; } void Gplink::remove(const QString &gpo_case) { const QString gpo = gpo_case.toLower(); if (!contains(gpo)) { return; } gpo_list.removeAll(gpo); options.remove(gpo); } void Gplink::move_up(const QString &gpo_case) { const QString gpo = gpo_case.toLower(); if (!contains(gpo)) { return; } const int current_index = gpo_list.indexOf(gpo); if (current_index > 0) { const int new_index = current_index - 1; gpo_list.move(current_index, new_index); } } void Gplink::move_down(const QString &gpo_case) { const QString gpo = gpo_case.toLower(); if (!contains(gpo)) { return; } const int current_index = gpo_list.indexOf(gpo); if (current_index < gpo_list.size() - 1) { const int new_index = current_index + 1; gpo_list.move(current_index, new_index); } } void Gplink::move(int from_order, int to_order) { if (from_order > (int)gpo_list.size() || to_order > (int)gpo_list.size() || from_order < 1 || to_order < 1) { return; } gpo_list.move(from_order - 1, to_order - 1); } bool Gplink::get_option(const QString &gpo_case, const GplinkOption option) const { const QString gpo = gpo_case.toLower(); if (!contains(gpo)) { return false; } const int option_bits = options[gpo]; const bool is_set = bitmask_is_set(option_bits, (int) option); return is_set; } void Gplink::set_option(const QString &gpo_case, const GplinkOption option, const bool value) { const QString gpo = gpo_case.toLower(); if (!contains(gpo)) { return; } const int option_bits = options[gpo]; const int option_bits_new = bitmask_set(option_bits, (int) option, value); options[gpo] = option_bits_new; } bool Gplink::equals(const Gplink &other) const { return (to_string() == other.to_string()); } int Gplink::get_gpo_order(const QString &gpo_case) const { const QString gpo = gpo_case.toLower(); const int out = gpo_list.indexOf(gpo) + 1; return out; } int Gplink::get_max_order() const { return gpo_list.size(); } QStringList Gplink::enforced_gpo_dn_list() const { QStringList enforced_dn_list; for (QString gpo_dn : get_gpo_list()) { if (get_option(gpo_dn, GplinkOption_Enforced)) enforced_dn_list.append(gpo_dn); } return enforced_dn_list; } QStringList Gplink::disabled_gpo_dn_list() const { QStringList disabled_dn_list; for (QString gpo_dn : get_gpo_list()) { if (get_option(gpo_dn, GplinkOption_Disabled)) disabled_dn_list.append(gpo_dn); } return disabled_dn_list; }
8,564
C++
.cpp
244
25.663934
95
0.539815
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,750
ad_object.cpp
altlinux_admc/src/adldap/ad_object.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "ad_object.h" #include "ad_config.h" #include "ad_display.h" #include "ad_security.h" #include "ad_utils.h" #include "samba/ndr_security.h" #include <QByteArray> #include <QDateTime> #include <QHash> #include <QList> #include <QMap> #include <QString> #include <algorithm> AdObject::AdObject() { } void AdObject::load(const QString &dn_arg, const QHash<QString, QList<QByteArray>> &attributes_data_arg) { dn = dn_arg; attributes_data = attributes_data_arg; } QString AdObject::get_dn() const { return dn; } QHash<QString, QList<QByteArray>> AdObject::get_attributes_data() const { return attributes_data; } bool AdObject::is_empty() const { return attributes_data.isEmpty(); } bool AdObject::contains(const QString &attribute) const { return attributes_data.contains(attribute); } QList<QString> AdObject::attributes() const { return attributes_data.keys(); } QList<QByteArray> AdObject::get_values(const QString &attribute) const { if (contains(attribute)) { return attributes_data[attribute]; } else { return QList<QByteArray>(); } } QByteArray AdObject::get_value(const QString &attribute) const { const QList<QByteArray> values = get_values(attribute); if (!values.isEmpty()) { return values.first(); } else { return QByteArray(); } } QList<QString> AdObject::get_strings(const QString &attribute) const { const QList<QByteArray> values = get_values(attribute); QList<QString> strings; for (const auto &value : values) { const QString string = QString(value); strings.append(string); } return strings; } QString AdObject::get_string(const QString &attribute) const { const QList<QString> strings = get_strings(attribute); // NOTE: return last object class because that is the most derived one and is what's needed most of the time if (!strings.isEmpty()) { if (attribute == ATTRIBUTE_OBJECT_CLASS) { return strings.last(); } else { return strings.first(); } } else { return QString(); } } QList<int> AdObject::get_ints(const QString &attribute) const { const QList<QString> strings = get_strings(attribute); QList<int> ints; for (const auto &string : strings) { const int int_value = string.toInt(); ints.append(int_value); } return ints; } int AdObject::get_int(const QString &attribute) const { const QList<int> ints = get_ints(attribute); if (!ints.isEmpty()) { return ints.first(); } else { return 0; } } QDateTime AdObject::get_datetime(const QString &attribute, const AdConfig *adconfig) const { const QString datetime_string = get_string(attribute); const QDateTime datetime = datetime_string_to_qdatetime(attribute, datetime_string, adconfig); return datetime; } QList<bool> AdObject::get_bools(const QString &attribute) const { const QList<QString> strings = get_strings(attribute); QList<bool> bools; for (const auto &string : strings) { const bool bool_value = ad_string_to_bool(string); bools.append(bool_value); } return bools; } bool AdObject::get_bool(const QString &attribute) const { const QList<bool> bools = get_bools(attribute); if (!bools.isEmpty()) { return bools.first(); } else { return false; } } bool AdObject::get_system_flag(const SystemFlagsBit bit) const { if (contains(ATTRIBUTE_SYSTEM_FLAGS)) { const int system_flags_bits = get_int(ATTRIBUTE_SYSTEM_FLAGS); const bool is_set = bitmask_is_set(system_flags_bits, bit); return is_set; } else { return false; } } bool AdObject::get_account_option(AccountOption option, AdConfig *adconfig) const { switch (option) { case AccountOption_CantChangePassword: { const bool out = ad_security_get_user_cant_change_pass(this, adconfig); return out; } case AccountOption_PasswordExpired: { if (contains(ATTRIBUTE_PWD_LAST_SET)) { const QString pwdLastSet_value = get_string(ATTRIBUTE_PWD_LAST_SET); const bool expired = (pwdLastSet_value == AD_PWD_LAST_SET_EXPIRED); return expired; } else { return false; } } default: { // Account option is a UAC bit if (contains(ATTRIBUTE_USER_ACCOUNT_CONTROL)) { const int control = get_int(ATTRIBUTE_USER_ACCOUNT_CONTROL); const int bit = account_option_bit(option); const bool set = ((control & bit) != 0); return set; } else { return false; } } } } // NOTE: "group type" is really only the last bit of the groupType attribute, yeah it's confusing GroupType AdObject::get_group_type() const { const int group_type = get_int(ATTRIBUTE_GROUP_TYPE); const bool security_bit_set = ((group_type & GROUP_TYPE_BIT_SECURITY) != 0); if (security_bit_set) { return GroupType_Security; } else { return GroupType_Distribution; } } GroupScope AdObject::get_group_scope() const { const int group_type = get_int(ATTRIBUTE_GROUP_TYPE); for (int i = 0; i < GroupScope_COUNT; i++) { const GroupScope this_scope = (GroupScope) i; const int scope_bit = group_scope_bit(this_scope); if (bitmask_is_set(group_type, scope_bit)) { return this_scope; } } return GroupScope_Global; } bool AdObject::is_class(const QString &object_class) const { const QString this_object_class = get_string(ATTRIBUTE_OBJECT_CLASS); const bool is_class = (this_object_class == object_class); return is_class; } QList<QString> AdObject::get_split_upn() const { const QString upn = get_string(ATTRIBUTE_USER_PRINCIPAL_NAME); const int split_index = upn.lastIndexOf('@'); const QString prefix = upn.left(split_index); const QString suffix = upn.mid(split_index + 1); const QList<QString> upn_split = {prefix, suffix}; return upn_split; } QString AdObject::get_upn_prefix() const { const QList<QString> upn_split = get_split_upn(); return upn_split[0]; } QString AdObject::get_upn_suffix() const { const QList<QString> upn_split = get_split_upn(); return upn_split[1]; } security_descriptor *AdObject::get_security_descriptor(TALLOC_CTX *mem_ctx_arg) const { TALLOC_CTX *mem_ctx = [&]() -> void * { if (mem_ctx_arg != nullptr) { return mem_ctx_arg; } else { return NULL; } }(); const QByteArray sd_bytes = get_value(ATTRIBUTE_SECURITY_DESCRIPTOR); security_descriptor *out = security_descriptor_make_from_bytes(mem_ctx, sd_bytes); return out; }
7,664
C++
.cpp
220
29.336364
112
0.666757
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,751
ad_filter.cpp
altlinux_admc/src/adldap/ad_filter.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "ad_filter.h" #include "ad_defines.h" #include <QCoreApplication> const QList<QString> filter_classes = { CLASS_USER, CLASS_GROUP, CLASS_CONTACT, CLASS_COMPUTER, CLASS_PRINTER, CLASS_OU, CLASS_TRUSTED_DOMAIN, CLASS_DOMAIN, CLASS_CONTAINER, CLASS_INET_ORG_PERSON, CLASS_FOREIGN_SECURITY_PRINCIPAL, CLASS_SHARED_FOLDER, CLASS_RPC_SERVICES, CLASS_CERTIFICATE_TEMPLATE, CLASS_MSMQ_GROUP, CLASS_MSMQ_QUEUE_ALIAS, CLASS_REMOTE_STORAGE_SERVICE, }; QList<QString> process_subfilters(const QList<QString> &in); QString filter_CONDITION(const Condition condition, const QString &attribute, const QString &value) { switch (condition) { case Condition_Equals: return QString("(%1=%2)").arg(attribute, value); case Condition_NotEquals: return QString("(!(%1=%2))").arg(attribute, value); case Condition_StartsWith: return QString("(%1=%2*)").arg(attribute, value); case Condition_EndsWith: return QString("(%1=*%2)").arg(attribute, value); case Condition_Contains: return QString("(%1=*%2*)").arg(attribute, value); case Condition_Set: return QString("(%1=*)").arg(attribute); case Condition_Unset: return QString("(!(%1=*))").arg(attribute); case Condition_COUNT: return QString(); } return QString(); } // {x, y, z ...} => (&(x)(y)(z)...) QString filter_AND(const QList<QString> &subfilters_raw) { const QList<QString> subfilters = process_subfilters(subfilters_raw); if (subfilters.size() > 1) { QString filter = "(&"; for (const QString &subfilter : subfilters) { filter += subfilter; } filter += ")"; return filter; } else if (subfilters.size() == 1) { return subfilters[0]; } else { return QString(); } } // {x, y, z ...} => (|(x)(y)(z)...) QString filter_OR(const QList<QString> &subfilters_raw) { const QList<QString> subfilters = process_subfilters(subfilters_raw); if (subfilters.size() > 1) { QString filter = "(|"; for (const QString &subfilter : subfilters) { filter += subfilter; } filter += ")"; return filter; } else if (subfilters.size() == 1) { return subfilters[0]; } else { return QString(); } } QString condition_to_display_string(const Condition condition) { switch (condition) { case Condition_Equals: return QCoreApplication::translate("filter", "Is (exactly)"); case Condition_NotEquals: return QCoreApplication::translate("filter", "Is not"); case Condition_StartsWith: return QCoreApplication::translate("filter", "Starts with"); case Condition_EndsWith: return QCoreApplication::translate("filter", "Ends with"); case Condition_Contains: return QCoreApplication::translate("filter", "Contains"); case Condition_Set: return QCoreApplication::translate("filter", "Present"); case Condition_Unset: return QCoreApplication::translate("filter", "Not present"); case Condition_COUNT: return QString(); } return QString(); } QList<QString> process_subfilters(const QList<QString> &in) { QList<QString> out = in; out.removeAll(""); return out; } QString filter_dn_list(const QList<QString> &dn_list) { const QList<QString> subfilter_list = [&]() { QList<QString> subfilter_list_out; for (const QString &dn : dn_list) { const QString subfilter = filter_CONDITION(Condition_Equals, ATTRIBUTE_DN, dn); subfilter_list_out.append(subfilter); } return subfilter_list_out; }(); const QString out = filter_OR(subfilter_list); return out; } QString filter_matching_rule_in_chain(const QString &attribute, const QString &dn_value) { const QString filter = attribute + ":" + QString(MATCHING_RULE_IN_CHAIN_OID) + ":=" + dn_value; return QString("(" + filter + ")"); }
4,756
C++
.cpp
121
33.950413
101
0.667534
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,752
ad_security.cpp
altlinux_admc/src/adldap/ad_security.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "ad_security.h" #include "adldap.h" #include "samba/dom_sid.h" #include "samba/libsmb_xattr.h" #include "samba/ndr_security.h" #include "samba/security_descriptor.h" #include "ad_filter.h" #include <QDebug> #define UNUSED_ARG(x) (void) (x) QByteArray dom_sid_to_bytes(const dom_sid &sid); dom_sid dom_sid_from_bytes(const QByteArray &bytes); QByteArray dom_sid_string_to_bytes(const dom_sid &sid); bool check_ace_match(const security_ace &ace, const QByteArray &trustee, const QByteArray &object_type, const bool allow, const bool inherited); QList<security_ace> security_descriptor_get_dacl(const security_descriptor *sd); void ad_security_replace_dacl(security_descriptor *sd, const QList<security_ace> &new_dacl); uint32_t ad_security_map_access_mask(const uint32_t access_mask); int ace_compare_simplified(const security_ace &ace1, const security_ace &ace2); // NOTE: these "base" f-ns are used by the full // versions of add/remove right f-ns. Base f-ns do only // the bare minimum, just adding/removing matching ace, // without handling opposites, subordinates, superiors, // etc. They also don't sort ACL, callers need to // handle sorting themselves. void security_descriptor_add_right_base(security_descriptor *sd, const QByteArray &trustee, const uint32_t access_mask, const QByteArray &object_type, const bool allow); void security_descriptor_remove_right_base(security_descriptor *sd, const QByteArray &trustee, const uint32_t access_mask, const QByteArray &object_type, const bool allow); const QList<int> ace_types_with_object = { SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT, SEC_ACE_TYPE_ACCESS_DENIED_OBJECT, SEC_ACE_TYPE_SYSTEM_AUDIT_OBJECT, SEC_ACE_TYPE_SYSTEM_ALARM_OBJECT, }; const QList<QString> well_known_sid_list = { SID_WORLD_DOMAIN, SID_WORLD, SID_WORLD, SID_CREATOR_OWNER_DOMAIN, SID_CREATOR_OWNER, SID_CREATOR_GROUP, SID_OWNER_RIGHTS, SID_NT_AUTHORITY, SID_NT_DIALUP, SID_NT_NETWORK, SID_NT_BATCH, SID_NT_INTERACTIVE, SID_NT_SERVICE, SID_NT_ANONYMOUS, SID_NT_PROXY, SID_NT_ENTERPRISE_DCS, SID_NT_SELF, SID_NT_AUTHENTICATED_USERS, SID_NT_RESTRICTED, SID_NT_TERMINAL_SERVER_USERS, SID_NT_REMOTE_INTERACTIVE, SID_NT_THIS_ORGANISATION, SID_NT_IUSR, SID_NT_SYSTEM, SID_NT_LOCAL_SERVICE, SID_NT_NETWORK_SERVICE, SID_NT_DIGEST_AUTHENTICATION, SID_NT_NTLM_AUTHENTICATION, SID_NT_SCHANNEL_AUTHENTICATION, SID_NT_OTHER_ORGANISATION, }; const QHash<QString, QString> trustee_name_map = { {SID_WORLD_DOMAIN, "Everyone in Domain"}, {SID_WORLD, "Everyone"}, {SID_CREATOR_OWNER_DOMAIN, "CREATOR OWNER DOMAIN"}, {SID_CREATOR_OWNER, "CREATOR OWNER"}, {SID_CREATOR_GROUP, "CREATOR GROUP"}, {SID_OWNER_RIGHTS, "OWNER RIGHTS"}, {SID_NT_AUTHORITY, "AUTHORITY"}, {SID_NT_DIALUP, "DIALUP"}, {SID_NT_NETWORK, "NETWORK"}, {SID_NT_BATCH, "BATCH"}, {SID_NT_INTERACTIVE, "INTERACTIVE"}, {SID_NT_SERVICE, "SERVICE"}, {SID_NT_ANONYMOUS, "ANONYMOUS LOGON"}, {SID_NT_PROXY, "PROXY"}, {SID_NT_ENTERPRISE_DCS, "ENTERPRISE DOMAIN CONTROLLERS"}, {SID_NT_SELF, "SELF"}, {SID_NT_AUTHENTICATED_USERS, "Authenticated Users"}, {SID_NT_RESTRICTED, "RESTRICTED"}, {SID_NT_TERMINAL_SERVER_USERS, "TERMINAL SERVER USERS"}, {SID_NT_REMOTE_INTERACTIVE, "REMOTE INTERACTIVE LOGON"}, {SID_NT_THIS_ORGANISATION, "This Organization"}, {SID_NT_IUSR, "IUSR"}, {SID_NT_SYSTEM, "SYSTEM"}, {SID_NT_LOCAL_SERVICE, "LOCAL SERVICE"}, {SID_NT_NETWORK_SERVICE, "NETWORK SERVICE"}, {SID_NT_DIGEST_AUTHENTICATION, "Digest Authentication"}, {SID_NT_NTLM_AUTHENTICATION, "NTLM Authentication"}, {SID_NT_SCHANNEL_AUTHENTICATION, "SChannel Authentication"}, {SID_NT_OTHER_ORGANISATION, "Other Organization"}, }; const QList<QString> cant_change_pass_trustee_cn_list = { SID_NT_SELF, SID_WORLD, }; const QList<uint32_t> protect_deletion_mask_list = { SEC_STD_DELETE, SEC_ADS_DELETE_TREE, }; const QSet<security_ace_type> ace_type_allow_set = { SEC_ACE_TYPE_ACCESS_ALLOWED, SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT, }; const QSet<security_ace_type> ace_type_deny_set = { SEC_ACE_TYPE_ACCESS_DENIED, SEC_ACE_TYPE_ACCESS_DENIED_OBJECT, }; // NOTE: this is also used for display order const QList<uint32_t> common_rights_list = { SEC_ADS_GENERIC_ALL, SEC_ADS_GENERIC_READ, SEC_ADS_GENERIC_WRITE, SEC_ADS_CREATE_CHILD, SEC_ADS_DELETE_CHILD, }; // NOTE: This is needed because for some reason, // security editing in RSAT has a different value for // generic read, without the "list object" right. Need // to remove that bit both when setting generic read // and when reading it. #define GENERIC_READ_FIXED (SEC_ADS_GENERIC_READ & ~SEC_ADS_LIST_OBJECT) SecurityRightState::SecurityRightState(const bool data_arg[SecurityRightStateInherited_COUNT][SecurityRightStateType_COUNT]) { for (int inherited = 0; inherited < SecurityRightStateInherited_COUNT; inherited++) { for (int type = 0; type < SecurityRightStateType_COUNT; type++) { data[inherited][type] = data_arg[inherited][type]; } } } bool SecurityRightState::get(const SecurityRightStateInherited inherited, const SecurityRightStateType type) const { return data[inherited][type]; } security_descriptor *security_descriptor_make_from_bytes(TALLOC_CTX *mem_ctx, const QByteArray &sd_bytes) { DATA_BLOB blob = data_blob_const(sd_bytes.data(), sd_bytes.size()); security_descriptor *out = talloc(mem_ctx, struct security_descriptor); ndr_pull_struct_blob(&blob, out, out, (ndr_pull_flags_fn_t) ndr_pull_security_descriptor); return out; } security_descriptor *security_descriptor_make_from_bytes(const QByteArray &sd_bytes) { security_descriptor *out = security_descriptor_make_from_bytes(NULL, sd_bytes); return out; } void security_descriptor_free(security_descriptor *sd) { talloc_free(sd); } security_descriptor *security_descriptor_copy(security_descriptor *sd) { security_descriptor *out = talloc(NULL, struct security_descriptor); out = security_descriptor_copy(out, sd); return out; } QString ad_security_get_well_known_trustee_name(const QByteArray &trustee) { const QString trustee_string = object_sid_display_value(trustee); return trustee_name_map.value(trustee_string, QString()); } QString ad_security_get_trustee_name(AdInterface &ad, const QByteArray &trustee) { const QString trustee_string = object_sid_display_value(trustee); if (trustee_name_map.contains(trustee_string)) { return trustee_name_map[trustee_string]; } else { // Try to get name of trustee by finding it's DN const QString filter = filter_CONDITION(Condition_Equals, ATTRIBUTE_OBJECT_SID, trustee_string); const QList<QString> attributes = { ATTRIBUTE_DISPLAY_NAME, ATTRIBUTE_SAM_ACCOUNT_NAME, }; const auto trustee_search = ad.search(ad.adconfig()->domain_dn(), SearchScope_All, filter, QList<QString>()); if (!trustee_search.isEmpty()) { // NOTE: this is some weird name selection logic // but that's how microsoft does it. Maybe need // to use this somewhere else as well? const QString name = [&]() { const AdObject object = trustee_search.values()[0]; if (object.contains(ATTRIBUTE_DISPLAY_NAME)) { return object.get_string(ATTRIBUTE_DISPLAY_NAME); } else if (object.contains(ATTRIBUTE_SAM_ACCOUNT_NAME)) { return object.get_string(ATTRIBUTE_SAM_ACCOUNT_NAME); } else { return dn_get_name(object.get_dn()); } }(); return name; } else { // Return raw sid as last option return trustee_string; } } } bool ad_security_replace_security_descriptor(AdInterface &ad, const QString &dn, security_descriptor *new_sd) { const QByteArray new_descriptor_bytes = [&]() { TALLOC_CTX *tmp_ctx = talloc_new(NULL); DATA_BLOB blob; ndr_push_struct_blob(&blob, tmp_ctx, new_sd, (ndr_push_flags_fn_t) ndr_push_security_descriptor); const QByteArray out = QByteArray((char *) blob.data, blob.length); talloc_free(tmp_ctx); return out; }(); const bool set_dacl = true; const bool apply_success = ad.attribute_replace_value(dn, ATTRIBUTE_SECURITY_DESCRIPTOR, new_descriptor_bytes, DoStatusMsg_Yes, set_dacl); return apply_success; } QByteArray dom_sid_to_bytes(const dom_sid &sid) { const QByteArray bytes = QByteArray((char *) &sid, sizeof(struct dom_sid)); return bytes; } // Copy sid bytes into dom_sid struct and adds padding // if necessary dom_sid dom_sid_from_bytes(const QByteArray &bytes) { dom_sid out; memset(&out, '\0', sizeof(dom_sid)); memcpy(&out, bytes.data(), sizeof(dom_sid)); return out; } QByteArray dom_sid_string_to_bytes(const QString &string) { dom_sid sid; dom_sid_parse(cstr(string), &sid); const QByteArray bytes = dom_sid_to_bytes(sid); return bytes; } void security_descriptor_sort_dacl(security_descriptor *sd) { qsort(sd->dacl->aces, sd->dacl->num_aces, sizeof(security_ace), ace_compare); } bool ad_security_get_protected_against_deletion(const AdObject &object) { security_descriptor *sd = object.get_security_descriptor(); const QByteArray trustee_everyone = sid_string_to_bytes(SID_WORLD); const bool is_enabled_for_trustee = [&]() { for (const uint32_t &mask : protect_deletion_mask_list) { const SecurityRightState state = security_descriptor_get_right(sd, trustee_everyone, mask, QByteArray()); const bool deny = state.get(SecurityRightStateInherited_No, SecurityRightStateType_Deny); if (!deny) { return false; } } return true; }(); security_descriptor_free(sd); return is_enabled_for_trustee; } bool ad_security_get_user_cant_change_pass(const AdObject *object, AdConfig *adconfig) { security_descriptor *sd = object->get_security_descriptor(); const bool enabled = [&]() { bool out = false; for (const QString &trustee_cn : cant_change_pass_trustee_cn_list) { const bool is_denied = [&]() { const QByteArray trustee = sid_string_to_bytes(trustee_cn); const QByteArray change_pass_right = adconfig->get_right_guid("User-Change-Password"); const SecurityRightState state = security_descriptor_get_right(sd, trustee, SEC_ADS_CONTROL_ACCESS, change_pass_right); const bool out_denied = state.get(SecurityRightStateInherited_No, SecurityRightStateType_Deny); return out_denied; }(); // Enabled if enabled for either of the // trustee's. Both don't have to be // enabled if (is_denied) { out = true; break; } } return out; }(); security_descriptor_free(sd); return enabled; } bool ad_security_set_user_cant_change_pass(AdInterface *ad, const QString &dn, const bool enabled) { security_descriptor *sd = [&]() { const AdObject object = ad->search_object(dn, {ATTRIBUTE_SECURITY_DESCRIPTOR}); security_descriptor *out = object.get_security_descriptor(); return out; }(); for (const QString &trustee_cn : cant_change_pass_trustee_cn_list) { const QByteArray trustee = sid_string_to_bytes(trustee_cn); const QByteArray change_pass_right = ad->adconfig()->get_right_guid("User-Change-Password"); // NOTE: the logic is a bit confusing here with // all the layers of negation but: "enabled" // means "denied", so we remove the opposite of // what we want, and add the type of right that // we want // NOTE: using "base" f-ns because we don't want // to touch superiors/subordinates const bool allow = !enabled; security_descriptor_remove_right_base(sd, trustee, SEC_ADS_CONTROL_ACCESS, change_pass_right, !allow); security_descriptor_add_right_base(sd, trustee, SEC_ADS_CONTROL_ACCESS, change_pass_right, allow); } security_descriptor_sort_dacl(sd); const bool success = ad_security_replace_security_descriptor(*ad, dn, sd); security_descriptor_free(sd); return success; } bool ad_security_set_protected_against_deletion(AdInterface &ad, const QString dn, const bool enabled) { const AdObject object = ad.search_object(dn); const bool is_enabled = ad_security_get_protected_against_deletion(object); const bool dont_need_to_change = (is_enabled == enabled); if (dont_need_to_change) { return true; } security_descriptor *new_sd = [&]() { security_descriptor *out = object.get_security_descriptor(); const QByteArray trustee_everyone = sid_string_to_bytes(SID_WORLD); // NOTE: we only add/remove deny entries. If // there are any allow entries, they are // untouched. for (const uint32_t &mask : protect_deletion_mask_list) { if (enabled) { security_descriptor_add_right_base(out, trustee_everyone, mask, QByteArray(), false); } else { security_descriptor_remove_right_base(out, trustee_everyone, mask, QByteArray(), false); } } return out; }(); security_descriptor_sort_dacl(new_sd); const bool apply_success = ad_security_replace_security_descriptor(ad, dn, new_sd); security_descriptor_free(new_sd); return apply_success; } QList<QByteArray> security_descriptor_get_trustee_list(security_descriptor *sd) { const QSet<QByteArray> trustee_set = [&]() { QSet<QByteArray> out; const QList<security_ace> dacl = security_descriptor_get_dacl(sd); for (const security_ace &ace : dacl) { const QByteArray trustee = dom_sid_to_bytes(ace.trustee); out.insert(trustee); } return out; }(); const QList<QByteArray> trustee_list = QList<QByteArray>(trustee_set.begin(), trustee_set.end()); return trustee_list; } QList<security_ace> security_descriptor_get_dacl(const security_descriptor *sd) { QList<security_ace> out; security_acl *dacl = sd->dacl; for (size_t i = 0; i < dacl->num_aces; i++) { security_ace ace = dacl->aces[i]; out.append(ace); } return out; } SecurityRightState security_descriptor_get_right(const security_descriptor *sd, const QByteArray &trustee, const uint32_t access_mask_arg, const QByteArray &object_type) { bool out_data[SecurityRightStateInherited_COUNT][SecurityRightStateType_COUNT]; const uint32_t access_mask = ad_security_map_access_mask(access_mask_arg); for (int x = 0; x < SecurityRightStateInherited_COUNT; x++) { for (int y = 0; y < SecurityRightStateType_COUNT; y++) { out_data[x][y] = false; } } const QList<security_ace> dacl = security_descriptor_get_dacl(sd); for (const security_ace &ace : dacl) { const bool match = [&]() { const bool trustee_match = [&]() { const dom_sid trustee_sid = dom_sid_from_bytes(trustee); const bool trustees_are_equal = (dom_sid_compare(&ace.trustee, &trustee_sid) == 0); return trustees_are_equal; }(); const bool access_mask_match = bitmask_is_set(ace.access_mask, access_mask); const bool object_match = [&]() { const bool object_present = ace_types_with_object.contains(ace.type); if (object_present) { const GUID out_guid = ace.object.object.type.type; const QByteArray ace_object_type = QByteArray((char *) &out_guid, sizeof(GUID)); const bool types_are_equal = (ace_object_type == object_type); return types_are_equal; } else { // NOTE: if compared ace doesn't // have an object it can still // match if it's access mask // matches with given ace. Example: // ace that allows "generic read" // (mask contains bit for "read // property" and object is empty) // will also allow right for // reading personal info (mask *is* // "read property" and contains // some object) return access_mask_match; } }(); const bool out = (trustee_match && access_mask_match && object_match); return out; }(); if (match) { bool state_list[2]; state_list[SecurityRightStateType_Allow] = ace_type_allow_set.contains(ace.type); state_list[SecurityRightStateType_Deny] = ace_type_deny_set.contains(ace.type); const int inherit_i = [&]() { const bool ace_is_inherited = bitmask_is_set(ace.flags, SEC_ACE_FLAG_INHERITED_ACE); if (ace_is_inherited) { return SecurityRightStateInherited_Yes; } else { return SecurityRightStateInherited_No; } }(); for (int type_i = 0; type_i < SecurityRightStateType_COUNT; type_i++) { const bool right_state = state_list[type_i]; if (right_state) { out_data[inherit_i][type_i] = true; } } } } const SecurityRightState out = SecurityRightState(out_data); return out; } void security_descriptor_print(security_descriptor *sd, AdInterface &ad) { const QList<security_ace> dacl = security_descriptor_get_dacl(sd); for (const security_ace &ace : dacl) { qInfo() << "\nace:"; const QByteArray trustee_sid = dom_sid_to_bytes(ace.trustee); const QString trustee_name = ad_security_get_trustee_name(ad, trustee_sid); qInfo() << "trustee:" << trustee_name; qInfo() << "mask:" << int_to_hex_string(ace.access_mask); qInfo() << "type:" << ace.type; } } void security_descriptor_add_right_base(security_descriptor *sd, const QByteArray &trustee, const uint32_t access_mask_arg, const QByteArray &object_type, const bool allow) { const uint32_t access_mask = ad_security_map_access_mask(access_mask_arg); const QList<security_ace> dacl = security_descriptor_get_dacl(sd); const int matching_index = [&]() { for (int i = 0; i < dacl.size(); i++) { const security_ace ace = dacl[i]; // NOTE: access mask match doesn't matter // because we also want to add right to // existing ace, if it exists. In that case // such ace would not match by mask and // that's fine. const bool match = check_ace_match(ace, trustee, object_type, allow, false); if (match) { return i; } } return -1; }(); if (matching_index != -1) { const bool right_already_set = [&]() { const security_ace matching_ace = dacl[matching_index]; const bool out = bitmask_is_set(matching_ace.access_mask, access_mask); return out; }(); // Matching ace exists, so reuse it by adding // given mask to this ace, but only if it's not set already if (!right_already_set) { security_ace new_ace = dacl[matching_index]; new_ace.access_mask = bitmask_set(new_ace.access_mask, access_mask, true); sd->dacl->aces[matching_index] = new_ace; } } else { // No matching ace, so make a new ace for this // right const security_ace ace = [&]() { security_ace out; const bool object_present = !object_type.isEmpty(); out.type = [&]() { if (allow) { if (object_present) { return SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT; } else { return SEC_ACE_TYPE_ACCESS_ALLOWED; } } else { if (object_present) { return SEC_ACE_TYPE_ACCESS_DENIED_OBJECT; } else { return SEC_ACE_TYPE_ACCESS_DENIED; } } return SEC_ACE_TYPE_ACCESS_ALLOWED; }(); out.flags = 0x00; out.access_mask = access_mask; out.object.object.flags = [&]() { if (object_present) { return SEC_ACE_OBJECT_TYPE_PRESENT; } else { return 0; } }(); if (object_present) { out.object.object.type.type = [&]() { struct GUID type_guid; memcpy(&type_guid, object_type.data(), sizeof(GUID)); return type_guid; }(); } out.trustee = dom_sid_from_bytes(trustee); return out; }(); security_descriptor_dacl_add(sd, &ace); } } // Checks if ace matches given members. Note that // access masks are not compared. Compare them yourself // if you need to further filter by masks. bool check_ace_match(const security_ace &ace, const QByteArray &trustee, const QByteArray &object_type, const bool allow, const bool inherited) { const bool type_match = [&]() { const security_ace_type ace_type = ace.type; const bool ace_allow = ace_type_allow_set.contains(ace_type); const bool ace_deny = ace_type_deny_set.contains(ace_type); if (allow && ace_allow) { return true; } else if (!allow && ace_deny) { return true; } else { return false; } }(); const bool flags_match = [&]() { const bool ace_is_inherited = bitmask_is_set(ace.flags, SEC_ACE_FLAG_INHERITED_ACE); const bool out = (ace_is_inherited == inherited); return out; }(); const bool trustee_match = [&]() { const dom_sid trustee_sid = dom_sid_from_bytes(trustee); const bool trustees_are_equal = (dom_sid_compare(&ace.trustee, &trustee_sid) == 0); return trustees_are_equal; }(); const bool object_match = [&]() { const bool object_present = ace_types_with_object.contains(ace.type); if (object_present) { const GUID ace_object_type_guid = ace.object.object.type.type; const QByteArray ace_object_type = QByteArray((char *) &ace_object_type_guid, sizeof(GUID)); const bool types_are_equal = (ace_object_type == object_type); return types_are_equal; } else { return object_type.isEmpty(); } }(); const bool out_match = (type_match && flags_match && trustee_match && object_match); return out_match; } void security_descriptor_remove_right_base(security_descriptor *sd, const QByteArray &trustee, const uint32_t access_mask_arg, const QByteArray &object_type, const bool allow) { const uint32_t access_mask = ad_security_map_access_mask(access_mask_arg); const QList<security_ace> new_dacl = [&]() { QList<security_ace> out; const QList<security_ace> old_dacl = security_descriptor_get_dacl(sd); for (const security_ace &ace : old_dacl) { const bool match = check_ace_match(ace, trustee, object_type, allow, false); const bool ace_mask_contains_mask = bitmask_is_set(ace.access_mask, access_mask); if (match && ace_mask_contains_mask) { const security_ace edited_ace = [&]() { security_ace out_ace = ace; // NOTE: need to handle a special // case due to read and write // rights sharing the "read // control" bit. When setting // either read/write, don't change // that shared bit if the other of // these rights is set const uint32_t mask_to_unset = [&]() { const QHash<uint32_t, uint32_t> opposite_map = { {GENERIC_READ_FIXED, SEC_ADS_GENERIC_WRITE}, {SEC_ADS_GENERIC_WRITE, GENERIC_READ_FIXED}, }; if (opposite_map.contains(access_mask)) { const uint32_t opposite = opposite_map[access_mask]; const bool opposite_is_set = bitmask_is_set(ace.access_mask, opposite); if (opposite_is_set) { const uint32_t out_mask = (access_mask & ~SEC_STD_READ_CONTROL); return out_mask; } else { return access_mask; } } else { return access_mask; } }(); out_ace.access_mask = bitmask_set(ace.access_mask, mask_to_unset, false); return out_ace; }(); const bool edited_ace_became_empty = (edited_ace.access_mask == 0); if (!edited_ace_became_empty) { out.append(edited_ace); } } else { out.append(ace); } } return out; }(); ad_security_replace_dacl(sd, new_dacl); } void security_descriptor_remove_trustee(security_descriptor *sd, const QList<QByteArray> &trustee_list) { const QList<security_ace> new_dacl = [&]() { QList<security_ace> out; const QList<security_ace> old_dacl = security_descriptor_get_dacl(sd); for (const security_ace &ace : old_dacl) { const bool match = [&]() { const bool trustee_match = [&]() { for (const QByteArray &trustee : trustee_list) { const dom_sid trustee_sid = dom_sid_from_bytes(trustee); const bool trustees_are_equal = (dom_sid_compare(&ace.trustee, &trustee_sid) == 0); if (trustees_are_equal) { return true; } } return false; }(); const bool inherited = bitmask_is_set(ace.flags, SEC_ACE_FLAG_INHERITED_ACE); const bool out_match = trustee_match && !inherited; return out_match; }(); if (!match) { out.append(ace); } } return out; }(); ad_security_replace_dacl(sd, new_dacl); } // TODO: Need to verify SACL order as well, because // advanced security dialog(to be implemented) edits // SACL. bool security_descriptor_verify_acl_order(security_descriptor *sd) { security_descriptor *copy = security_descriptor_copy(sd); const bool order_is_correct = [&]() { bool out = true; QList<security_ace> dacl = security_descriptor_get_dacl(copy); security_ace curr = dacl.takeFirst(); while (!dacl.isEmpty()) { security_ace next = dacl.takeFirst(); const int comparison = ace_compare_simplified(curr, next); const bool order_is_good = (comparison <= 0); if (!order_is_good) { out = false; } curr = next; } return out; }(); security_descriptor_free(copy); return order_is_correct; } QString ad_security_get_right_name(AdConfig *adconfig, const uint32_t access_mask, const QByteArray &object_type, const QLocale::Language language) { const QString object_type_name = adconfig->get_right_name(object_type, language); if (access_mask == SEC_ADS_CONTROL_ACCESS) { return object_type_name; } else if (access_mask == SEC_ADS_READ_PROP) { return QString(QCoreApplication::translate("ad_security.cpp", "Read %1")).arg(object_type_name); } else if (access_mask == SEC_ADS_WRITE_PROP) { return QString(QCoreApplication::translate("ad_security.cpp", "Write %1")).arg(object_type_name); } else { const QHash<uint32_t, QString> common_right_name_map = { {SEC_ADS_GENERIC_ALL, QCoreApplication::translate("ad_security.cpp", "Full control")}, {SEC_ADS_GENERIC_READ, QCoreApplication::translate("ad_security.cpp", "Read")}, {SEC_ADS_GENERIC_WRITE, QCoreApplication::translate("ad_security.cpp", "Write")}, {SEC_STD_DELETE, QCoreApplication::translate("ad_security.cpp", "Delete")}, {SEC_ADS_CREATE_CHILD, QCoreApplication::translate("ad_security.cpp", "Create all child objects")}, {SEC_ADS_DELETE_CHILD, QCoreApplication::translate("ad_security.cpp", "Delete all child objects")}, }; return common_right_name_map.value(access_mask, QCoreApplication::translate("ad_security.cpp", "<unknown right>")); } } void security_descriptor_add_right(security_descriptor *sd, AdConfig *adconfig, const QList<QString> &class_list, const QByteArray &trustee, const uint32_t access_mask, const QByteArray &object_type, const bool allow) { const QList<SecurityRight> superior_list = ad_security_get_superior_right_list(access_mask, object_type); for (const SecurityRight &superior : superior_list) { const bool opposite_superior_is_set = [&]() { const SecurityRightState state = security_descriptor_get_right(sd, trustee, superior.access_mask, superior.object_type); const SecurityRightStateType type = [&]() { // NOTE: opposite! if (!allow) { return SecurityRightStateType_Allow; } else { return SecurityRightStateType_Deny; } }(); const bool out = state.get(SecurityRightStateInherited_No, type); return out; }(); // NOTE: skip superior if it's not set, so that // we don't add opposite subordinate rights // when not needed if (!opposite_superior_is_set) { continue; } // Remove opposite superior security_descriptor_remove_right_base(sd, trustee, superior.access_mask, superior.object_type, !allow); // Add opposite superior subordinates const QList<SecurityRight> superior_subordinate_list = ad_security_get_subordinate_right_list(adconfig, superior.access_mask, superior.object_type, class_list); for (const SecurityRight &subordinate : superior_subordinate_list) { security_descriptor_add_right_base(sd, trustee, subordinate.access_mask, subordinate.object_type, !allow); } } // Remove subordinates const QList<SecurityRight> subordinate_list = ad_security_get_subordinate_right_list(adconfig, access_mask, object_type, class_list); for (const SecurityRight &subordinate : subordinate_list) { security_descriptor_remove_right_base(sd, trustee, subordinate.access_mask, subordinate.object_type, allow); } // Remove opposite security_descriptor_remove_right_base(sd, trustee, access_mask, object_type, !allow); // Remove opposite subordinates for (const SecurityRight &subordinate : subordinate_list) { security_descriptor_remove_right_base(sd, trustee, subordinate.access_mask, subordinate.object_type, !allow); } // Add target security_descriptor_add_right_base(sd, trustee, access_mask, object_type, allow); security_descriptor_sort_dacl(sd); } void security_descriptor_remove_right(security_descriptor *sd, AdConfig *adconfig, const QList<QString> &class_list, const QByteArray &trustee, const uint32_t access_mask, const QByteArray &object_type, const bool allow) { const QList<SecurityRight> target_superior_list = ad_security_get_superior_right_list(access_mask, object_type); // Remove superiors for (const SecurityRight &superior : target_superior_list) { const bool superior_is_set = [&]() { const SecurityRightState state = security_descriptor_get_right(sd, trustee, superior.access_mask, superior.object_type); const SecurityRightStateType type = [&]() { if (allow) { return SecurityRightStateType_Allow; } else { return SecurityRightStateType_Deny; } }(); const bool out = state.get(SecurityRightStateInherited_No, type); return out; }(); // NOTE: skip superior if it's not set, so that we don't add opposite subordinate rights when not needed if (!superior_is_set) { continue; } security_descriptor_remove_right_base(sd, trustee, superior.access_mask, superior.object_type, allow); const QList<SecurityRight> superior_subordinate_list = ad_security_get_subordinate_right_list(adconfig, superior.access_mask, superior.object_type, class_list); // Add opposite subordinate rights for (const SecurityRight &subordinate : superior_subordinate_list) { security_descriptor_add_right_base(sd, trustee, subordinate.access_mask, subordinate.object_type, allow); } } // Remove target right security_descriptor_remove_right_base(sd, trustee, access_mask, object_type, allow); // Add target subordinate rights const QList<SecurityRight> tarad_security_get_subordinate_right_list = ad_security_get_subordinate_right_list(adconfig, access_mask, object_type, class_list); for (const SecurityRight &subordinate : tarad_security_get_subordinate_right_list) { security_descriptor_add_right_base(sd, trustee, subordinate.access_mask, subordinate.object_type, allow); } security_descriptor_sort_dacl(sd); } QList<SecurityRight> ad_security_get_right_list_for_class(AdConfig *adconfig, const QList<QString> &class_list) { QList<SecurityRight> out; for (const uint32_t &access_mask : common_rights_list) { SecurityRight right; right.access_mask = access_mask; right.object_type = QByteArray(); out.append(right); } const QList<QString> extended_rights_list = adconfig->get_extended_rights_list(class_list); for (const QString &rights : extended_rights_list) { const int valid_accesses = adconfig->get_rights_valid_accesses(rights); const QByteArray rights_guid = adconfig->get_right_guid(rights); const QList<uint32_t> access_mask_list = { SEC_ADS_CONTROL_ACCESS, SEC_ADS_READ_PROP, SEC_ADS_WRITE_PROP, }; for (const uint32_t &access_mask : access_mask_list) { const bool mask_match = bitmask_is_set(valid_accesses, access_mask); if (mask_match) { SecurityRight right; right.access_mask = access_mask; right.object_type = rights_guid; out.append(right); } } } return out; } QList<SecurityRight> ad_security_get_superior_right_list(const uint32_t access_mask, const QByteArray &object_type) { QList<SecurityRight> out; const bool object_present = !object_type.isEmpty(); const SecurityRight generic_all = {SEC_ADS_GENERIC_ALL, QByteArray()}; const SecurityRight generic_read = {SEC_ADS_GENERIC_READ, QByteArray()}; const SecurityRight generic_write = {SEC_ADS_GENERIC_WRITE, QByteArray()}; const SecurityRight all_extended_rights = {SEC_ADS_CONTROL_ACCESS, QByteArray()}; // NOTE: order is important, because we want to // process "more superior" rights first. "Generic // all" is more superior than others. if (object_present) { if (access_mask == SEC_ADS_READ_PROP) { out.append(generic_all); out.append(generic_read); } else if (access_mask == SEC_ADS_WRITE_PROP) { out.append(generic_all); out.append(generic_write); } else if (access_mask == SEC_ADS_CONTROL_ACCESS) { out.append(generic_all); out.append(all_extended_rights); } } else { if (access_mask == SEC_ADS_GENERIC_READ || access_mask == SEC_ADS_GENERIC_WRITE) { out.append(generic_all); } } return out; } QList<SecurityRight> ad_security_get_subordinate_right_list(AdConfig *adconfig, const uint32_t access_mask, const QByteArray &object_type, const QList<QString> &class_list) { QList<SecurityRight> out; const bool object_present = !object_type.isEmpty(); const QList<SecurityRight> right_list_for_target = ad_security_get_right_list_for_class(adconfig, class_list); for (const SecurityRight &right : right_list_for_target) { const bool match = [&]() { const bool right_object_present = !right.object_type.isEmpty(); if (object_present) { return false; } else { if (access_mask == SEC_ADS_GENERIC_ALL) { // All except full control return (right.access_mask != access_mask); } else if (access_mask == SEC_ADS_GENERIC_READ) { // All read property rights return (right.access_mask == SEC_ADS_READ_PROP && right_object_present); } else if (access_mask == SEC_ADS_GENERIC_WRITE) { // All write property rights return (right.access_mask == SEC_ADS_WRITE_PROP && right_object_present); } else if (access_mask == SEC_ADS_CONTROL_ACCESS) { // All extended rights return (right.access_mask == SEC_ADS_CONTROL_ACCESS && right_object_present); } else { return false; } } }(); if (match) { out.append(right); } } return out; } void ad_security_replace_dacl(security_descriptor *sd, const QList<security_ace> &new_dacl) { // Free old dacl talloc_free(sd->dacl); sd->dacl = NULL; // Fill new dacl // NOTE: dacl_add() allocates new dacl for (const security_ace &ace : new_dacl) { security_descriptor_dacl_add(sd, &ace); } } // This f-n is only necessary to band-aid one problem // with generic read. uint32_t ad_security_map_access_mask(const uint32_t access_mask) { const bool is_generic_read = (access_mask == SEC_ADS_GENERIC_READ); if (is_generic_read) { return GENERIC_READ_FIXED; } else { return access_mask; } } // This simplified version of ace_compare() for // verifying ACL order. Only includes necessary // comparisons specified by Microsoft here: // https://docs.microsoft.com/en-us/windows/win32/secauthz/order-of-aces-in-a-dacl // // TODO: currently missing one comparison: // // "Inherited ACE's are placed in the order in which // they are inherited" // // Not a big problem because inherited ACE's are added // to ACL by the server. Clients cannot manually add // such ACE's, so theoretically their order should // always be correct. But do implement this at some // point, just in case. Using order requirements listed // here: int ace_compare_simplified(const security_ace &ace1, const security_ace &ace2) { bool b1; bool b2; /* If the ACEs are equal, we have nothing more to do. */ if (security_ace_equal(&ace1, &ace2)) { return 0; } /* Inherited follow non-inherited */ b1 = ((ace1.flags & SEC_ACE_FLAG_INHERITED_ACE) != 0); b2 = ((ace2.flags & SEC_ACE_FLAG_INHERITED_ACE) != 0); if (b1 != b2) { return (b1 ? 1 : -1); } /* Allowed ACEs follow denied ACEs */ b1 = (ace1.type == SEC_ACE_TYPE_ACCESS_ALLOWED || ace1.type == SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT); b2 = (ace2.type == SEC_ACE_TYPE_ACCESS_ALLOWED || ace2.type == SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT); if (b1 != b2) { return (b1 ? 1 : -1); } return 0; }
41,520
C++
.cpp
900
36.984444
222
0.625545
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,753
ad_config.cpp
altlinux_admc/src/adldap/ad_config.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "ad_config.h" #include "ad_config_p.h" #include "ad_filter.h" #include "ad_interface.h" #include "ad_object.h" #include "ad_security.h" #include "ad_utils.h" #include "ad_display.h" #include "samba/ndr_security.h" #include <QCoreApplication> #include <QDebug> #include <QLocale> #include <algorithm> #define ATTRIBUTE_ATTRIBUTE_DISPLAY_NAMES "attributeDisplayNames" #define ATTRIBUTE_EXTRA_COLUMNS "extraColumns" #define ATTRIBUTE_FILTER_CONTAINERS "msDS-FilterContainers" #define ATTRIBUTE_LDAP_DISPLAY_NAME "lDAPDisplayName" #define ATTRIBUTE_POSSIBLE_SUPERIORS "possSuperiors" #define ATTRIBUTE_SYSTEM_POSSIBLE_SUPERIORS "systemPossSuperiors" #define ATTRIBUTE_ATTRIBUTE_SYNTAX "attributeSyntax" #define ATTRIBUTE_OM_SYNTAX "oMSyntax" #define ATTRIBUTE_CLASS_DISPLAY_NAME "classDisplayName" #define ATTRIBUTE_MAY_CONTAIN "mayContain" #define ATTRIBUTE_SYSTEM_MAY_CONTAIN "systemMayContain" #define ATTRIBUTE_MUST_CONTAIN "mustContain" #define ATTRIBUTE_SYSTEM_MUST_CONTAIN "systemMustContain" #define ATTRIBUTE_IS_SINGLE_VALUED "isSingleValued" #define ATTRIBUTE_SYSTEM_ONLY "systemOnly" #define ATTRIBUTE_RANGE_UPPER "rangeUpper" #define ATTRIBUTE_AUXILIARY_CLASS "auxiliaryClass" #define ATTRIBUTE_SYSTEM_FLAGS "systemFlags" #define ATTRIBUTE_LINK_ID "linkID" #define ATTRIBUTE_SYSTEM_AUXILIARY_CLASS "systemAuxiliaryClass" #define ATTRIBUTE_SUB_CLASS_OF "subClassOf" #define CLASS_ATTRIBUTE_SCHEMA "attributeSchema" #define CLASS_CLASS_SCHEMA "classSchema" #define CLASS_CONTROL_ACCESS_RIGHT "controlAccessRight" #define FLAG_ATTR_IS_CONSTRUCTED 0x00000004 AdConfigPrivate::AdConfigPrivate() { } AdConfig::AdConfig() { d = new AdConfigPrivate(); } AdConfig::~AdConfig() { delete d; } void AdConfig::load(AdInterface &ad, const QLocale &locale) { d->domain = ad.get_domain(); d->filter_containers.clear(); d->columns.clear(); d->column_display_names.clear(); d->class_display_names.clear(); d->find_attributes.clear(); d->attribute_display_names.clear(); d->attribute_schemas.clear(); d->class_schemas.clear(); const AdObject rootDSE_object = ad.search_object(ROOT_DSE); d->domain_dn = rootDSE_object.get_string(ATTRIBUTE_ROOT_DOMAIN_NAMING_CONTEXT); d->schema_dn = rootDSE_object.get_string(ATTRIBUTE_SCHEMA_NAMING_CONTEXT); d->configuration_dn = rootDSE_object.get_string(ATTRIBUTE_CONFIGURATION_NAMING_CONTEXT); d->supported_control_list = rootDSE_object.get_strings(ATTRIBUTE_SUPPORTED_CONTROL); const AdObject domain_object = ad.search_object(domain_dn()); d->domain_sid = object_sid_display_value(domain_object.get_value(ATTRIBUTE_OBJECT_SID)); const QString locale_dir = [this, locale]() { const QString locale_code = [locale]() { if (locale.language() == QLocale::Russian) { return "419"; } else { // English return "409"; } }(); return QString("CN=%1,CN=DisplaySpecifiers,%2").arg(locale_code, configuration_dn()); }(); // Attribute schemas { const QString filter = filter_CONDITION(Condition_Equals, ATTRIBUTE_OBJECT_CLASS, CLASS_ATTRIBUTE_SCHEMA); const QList<QString> attributes = { ATTRIBUTE_LDAP_DISPLAY_NAME, ATTRIBUTE_ATTRIBUTE_SYNTAX, ATTRIBUTE_OM_SYNTAX, ATTRIBUTE_IS_SINGLE_VALUED, ATTRIBUTE_SYSTEM_ONLY, ATTRIBUTE_RANGE_UPPER, ATTRIBUTE_LINK_ID, ATTRIBUTE_SYSTEM_FLAGS, ATTRIBUTE_SCHEMA_ID_GUID, }; const QHash<QString, AdObject> results = ad.search(schema_dn(), SearchScope_Children, filter, attributes); for (const AdObject &object : results.values()) { const QString attribute = object.get_string(ATTRIBUTE_LDAP_DISPLAY_NAME); d->attribute_schemas[attribute] = object; const QByteArray guid = object.get_value(ATTRIBUTE_SCHEMA_ID_GUID); d->guid_to_attribute_map[guid] = attribute; } } // Class schemas { const QString filter = filter_CONDITION(Condition_Equals, ATTRIBUTE_OBJECT_CLASS, CLASS_CLASS_SCHEMA); const QList<QString> attributes = { ATTRIBUTE_LDAP_DISPLAY_NAME, ATTRIBUTE_POSSIBLE_SUPERIORS, ATTRIBUTE_SYSTEM_POSSIBLE_SUPERIORS, ATTRIBUTE_MAY_CONTAIN, ATTRIBUTE_SYSTEM_MAY_CONTAIN, ATTRIBUTE_MUST_CONTAIN, ATTRIBUTE_SYSTEM_MUST_CONTAIN, ATTRIBUTE_AUXILIARY_CLASS, ATTRIBUTE_SYSTEM_AUXILIARY_CLASS, ATTRIBUTE_SCHEMA_ID_GUID, ATTRIBUTE_SUB_CLASS_OF, }; const QHash<QString, AdObject> results = ad.search(schema_dn(), SearchScope_Children, filter, attributes); for (const AdObject &object : results.values()) { const QString object_class = object.get_string(ATTRIBUTE_LDAP_DISPLAY_NAME); d->class_schemas[object_class] = object; const QByteArray guid = object.get_value(ATTRIBUTE_SCHEMA_ID_GUID); d->guid_to_class_map[guid] = object_class; const QString sub_class_of = object.get_string(ATTRIBUTE_SUB_CLASS_OF); d->sub_class_of_map[object_class] = sub_class_of; } } // Class display specifiers // NOTE: can't just store objects for these because the values require a decent amount of preprocessing which is best done once here, not everytime value is requested { const QString filter = QString(); const QList<QString> search_attributes = { ATTRIBUTE_CLASS_DISPLAY_NAME, ATTRIBUTE_ATTRIBUTE_DISPLAY_NAMES, }; const QHash<QString, AdObject> results = ad.search(locale_dir, SearchScope_Children, filter, search_attributes); for (const AdObject &object : results) { const QString dn = object.get_dn(); // Display specifier DN is "CN=object-class-Display,CN=..." // Get "object-class" from that const QString object_class = [dn]() { const QString rdn = dn.split(",")[0]; QString out = rdn; out.remove("CN=", Qt::CaseInsensitive); out.remove("-Display"); return out; }(); if (object.contains(ATTRIBUTE_CLASS_DISPLAY_NAME)) { d->class_display_names[object_class] = object.get_string(ATTRIBUTE_CLASS_DISPLAY_NAME); } if (object.contains(ATTRIBUTE_ATTRIBUTE_DISPLAY_NAMES)) { const QList<QString> display_names = object.get_strings(ATTRIBUTE_ATTRIBUTE_DISPLAY_NAMES); for (const auto &display_name_pair : display_names) { const QList<QString> split = display_name_pair.split(","); const QString attribute_name = split[0]; const QString display_name = split[1]; d->attribute_display_names[object_class][attribute_name] = display_name; } d->find_attributes[object_class] = [object_class, display_names]() { QList<QString> out; for (const auto &display_name_pair : display_names) { const QList<QString> split = display_name_pair.split(","); const QString attribute = split[0]; out.append(attribute); } return out; }(); } } } // Columns { const QList<QString> columns_values = [&] { const QString dn = QString("CN=default-Display,%1").arg(locale_dir); const AdObject object = ad.search_object(dn, {ATTRIBUTE_EXTRA_COLUMNS}); // NOTE: order as stored in attribute is reversed. Order is not sorted alphabetically so can't just sort. QList<QString> extra_columns = object.get_strings(ATTRIBUTE_EXTRA_COLUMNS); std::reverse(extra_columns.begin(), extra_columns.end()); return extra_columns; }(); // ATTRIBUTE_EXTRA_COLUMNS value is // "$attribute,$display_name,..." // Get attributes out of that for (const QString &value : columns_values) { const QList<QString> column_split = value.split(','); if (column_split.size() < 2) { continue; } const QString attribute = column_split[0]; const QString attribute_display_name = column_split[1]; d->columns.append(attribute); d->column_display_names[attribute] = attribute_display_name; } // Insert some columns manually auto add_custom = [=](const Attribute &attribute, const QString &display_name) { d->columns.prepend(attribute); d->column_display_names[attribute] = display_name; }; add_custom(ATTRIBUTE_DN, QCoreApplication::translate("AdConfig", "Distinguished name")); add_custom(ATTRIBUTE_DESCRIPTION, QCoreApplication::translate("AdConfig", "Description")); add_custom(ATTRIBUTE_OBJECT_CLASS, QCoreApplication::translate("AdConfig", "Class")); add_custom(ATTRIBUTE_NAME, QCoreApplication::translate("AdConfig", "Name")); } d->filter_containers = [&] { QList<QString> out; const QString ui_settings_dn = QString("CN=DS-UI-Default-Settings,%1").arg(locale_dir); const AdObject object = ad.search_object(ui_settings_dn, {ATTRIBUTE_FILTER_CONTAINERS}); // NOTE: dns-Zone category is mispelled in // ATTRIBUTE_FILTER_CONTAINERS, no idea why, might // just be on this domain version const QList<QString> categories = [object]() { QList<QString> categories_out = object.get_strings(ATTRIBUTE_FILTER_CONTAINERS); categories_out.replaceInStrings("dns-Zone", "Dns-Zone"); return categories_out; }(); // NOTE: ATTRIBUTE_FILTER_CONTAINERS contains object // *categories* not classes, so need to get object // class from category object for (const auto &object_category : categories) { const QString category_dn = QString("CN=%1,%2").arg(object_category, schema_dn()); const AdObject category_object = ad.search_object(category_dn, {ATTRIBUTE_LDAP_DISPLAY_NAME}); const QString object_class = category_object.get_string(ATTRIBUTE_LDAP_DISPLAY_NAME); out.append(object_class); } // NOTE: domain and pso container are not included for some reason, so add it manually out.append(CLASS_DOMAIN); out.append(CLASS_PSO_CONTAINER); // Make configuration and schema pass filter in dev mode so they are visible and can be fetched out.append({CLASS_CONFIGURATION, CLASS_dMD}); return out; }(); // Extended rights { const QString filter = filter_CONDITION(Condition_Equals, ATTRIBUTE_OBJECT_CLASS, CLASS_CONTROL_ACCESS_RIGHT); const QList<QString> attributes = { ATTRIBUTE_CN, ATTRIBUTE_DISPLAY_NAME, ATTRIBUTE_RIGHTS_GUID, ATTRIBUTE_APPLIES_TO, ATTRIBUTE_VALID_ACCESSES, }; const QString search_base = extended_rights_dn(); const QHash<QString, AdObject> search_results = ad.search(search_base, SearchScope_Children, filter, attributes); for (const AdObject &object : search_results.values()) { const QString cn = object.get_string(ATTRIBUTE_CN); const QString guid_string = object.get_string(ATTRIBUTE_RIGHTS_GUID); const QByteArray guid = guid_string_to_bytes(guid_string); const QByteArray display_name = object.get_value(ATTRIBUTE_DISPLAY_NAME); const QList<QString> applies_to = [this, object]() { QList<QString> out; const QList<QString> class_guid_string_list = object.get_strings(ATTRIBUTE_APPLIES_TO); for (const QString &class_guid_string : class_guid_string_list) { const QByteArray class_guid = guid_string_to_bytes(class_guid_string); const QString object_class = guid_to_class(class_guid); out.append(object_class); } return out; }(); const int valid_accesses = object.get_int(ATTRIBUTE_VALID_ACCESSES); d->right_to_guid_map[cn] = guid; d->right_guid_to_cn_map[guid] = cn; d->rights_guid_to_name_map[guid] = display_name; d->rights_name_to_guid_map[cn] = guid; d->rights_applies_to_map[guid] = applies_to; d->extended_rights_list.append(cn); d->rights_valid_accesses_map[cn] = valid_accesses; } } } QString AdConfig::domain() const { return d->domain; } QString AdConfig::domain_dn() const { return d->domain_dn; } QString AdConfig::configuration_dn() const { return d->configuration_dn; } QString AdConfig::schema_dn() const { return d->schema_dn; } QString AdConfig::partitions_dn() const { return QString("CN=Partitions,%1").arg(configuration_dn()); } QString AdConfig::extended_rights_dn() const { return QString("CN=Extended-Rights,%1").arg(configuration_dn()); } QString AdConfig::policies_dn() const { return QString("CN=Policies,CN=System,%1").arg(domain_dn()); } bool AdConfig::control_is_supported(const QString &control_oid) const { const bool supported = d->supported_control_list.contains(control_oid); return supported; } QString AdConfig::domain_sid() const { return d->domain_sid; } QString AdConfig::get_attribute_display_name(const Attribute &attribute, const ObjectClass &objectClass) const { if (d->attribute_display_names.contains(objectClass) && d->attribute_display_names[objectClass].contains(attribute)) { const QString display_name = d->attribute_display_names[objectClass][attribute]; return display_name; } // NOTE: display specifier doesn't cover all attributes for all classes, so need to hardcode some of them here static const QHash<Attribute, QString> fallback_display_names = { {ATTRIBUTE_NAME, QCoreApplication::translate("AdConfig", "Name")}, {ATTRIBUTE_DN, QCoreApplication::translate("AdConfig", "Distinguished name")}, {ATTRIBUTE_OBJECT_CLASS, QCoreApplication::translate("AdConfig", "Object class")}, {ATTRIBUTE_WHEN_CREATED, QCoreApplication::translate("AdConfig", "Created")}, {ATTRIBUTE_WHEN_CHANGED, QCoreApplication::translate("AdConfig", "Changed")}, {ATTRIBUTE_USN_CREATED, QCoreApplication::translate("AdConfig", "USN created")}, {ATTRIBUTE_USN_CHANGED, QCoreApplication::translate("AdConfig", "USN changed")}, {ATTRIBUTE_ACCOUNT_EXPIRES, QCoreApplication::translate("AdConfig", "Account expires")}, {ATTRIBUTE_OBJECT_CATEGORY, QCoreApplication::translate("AdConfig", "Type")}, {ATTRIBUTE_PROFILE_PATH, QCoreApplication::translate("AdConfig", "Profile path")}, {ATTRIBUTE_SCRIPT_PATH, QCoreApplication::translate("AdConfig", "Logon script")}, {ATTRIBUTE_SAM_ACCOUNT_NAME, QCoreApplication::translate("AdConfig", "Logon name (pre-Windows 2000)")}, {ATTRIBUTE_MAIL, QCoreApplication::translate("AdConfig", "E-mail")}, {ATTRIBUTE_LOCATION, QCoreApplication::translate("AdConfig", "Location")}, {ATTRIBUTE_MANAGED_BY, QCoreApplication::translate("managedBy", "Managed by")}, }; return fallback_display_names.value(attribute, attribute); } QString AdConfig::get_class_display_name(const QString &objectClass) const { return d->class_display_names.value(objectClass, objectClass); } QList<QString> AdConfig::get_columns() const { return d->columns; } QString AdConfig::get_column_display_name(const Attribute &attribute) const { return d->column_display_names.value(attribute, attribute); } int AdConfig::get_column_index(const QString &attribute) const { if (!d->columns.contains(attribute)) { qWarning() << "ADCONFIG columns missing attribute:" << attribute; } return d->columns.indexOf(attribute); } QList<QString> AdConfig::get_filter_containers() const { return d->filter_containers; } QList<QString> AdConfig::get_possible_superiors(const QList<ObjectClass> &object_classes) const { QList<QString> out; for (const QString &object_class : object_classes) { const AdObject schema = d->class_schemas[object_class]; out += schema.get_strings(ATTRIBUTE_POSSIBLE_SUPERIORS); out += schema.get_strings(ATTRIBUTE_SYSTEM_POSSIBLE_SUPERIORS); } out.removeDuplicates(); return out; } ObjectClass AdConfig::get_parent_class(const ObjectClass &object_class) const { const ObjectClass out = d->sub_class_of_map.value(object_class); return out; } QList<ObjectClass> AdConfig::get_inherit_chain(const ObjectClass &object_class) const { QList<QString> out; ObjectClass current_class = object_class; while (true) { out.append(current_class); const QString parent_class = get_parent_class(current_class); const bool chain_ended = (parent_class == current_class); if (chain_ended) { break; } else { current_class = parent_class; } } return out; } QList<QString> AdConfig::get_optional_attributes(const QList<QString> &object_classes) const { const QList<QString> all_classes = d->add_auxiliary_classes(object_classes); QList<QString> attributes; for (const auto &object_class : all_classes) { const AdObject schema = d->class_schemas[object_class]; attributes += schema.get_strings(ATTRIBUTE_MAY_CONTAIN); attributes += schema.get_strings(ATTRIBUTE_SYSTEM_MAY_CONTAIN); } attributes.removeDuplicates(); return attributes; } QList<QString> AdConfig::get_mandatory_attributes(const QList<QString> &object_classes) const { const QList<QString> all_classes = d->add_auxiliary_classes(object_classes); QList<QString> attributes; for (const auto &object_class : all_classes) { const AdObject schema = d->class_schemas[object_class]; attributes += schema.get_strings(ATTRIBUTE_MUST_CONTAIN); attributes += schema.get_strings(ATTRIBUTE_SYSTEM_MUST_CONTAIN); } attributes.removeDuplicates(); return attributes; } QList<QString> AdConfig::get_find_attributes(const QString &object_class) const { return d->find_attributes.value(object_class, QList<QString>()); } AttributeType AdConfig::get_attribute_type(const QString &attribute) const { // NOTE: replica of: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/7cda533e-d7a4-4aec-a517-91d02ff4a1aa // syntax -> om syntax list -> type static QHash<QString, QHash<QString, AttributeType>> type_map = { {"2.5.5.8", {{"1", AttributeType_Boolean}}}, {"2.5.5.9", { {"10", AttributeType_Enumeration}, {"2", AttributeType_Integer}, }}, {"2.5.5.16", {{"65", AttributeType_LargeInteger}}}, {"2.5.5.3", {{"27", AttributeType_StringCase}}}, {"2.5.5.5", {{"22", AttributeType_IA5}}}, {"2.5.5.15", {{"66", AttributeType_NTSecDesc}}}, {"2.5.5.6", {{"18", AttributeType_Numeric}}}, {"2.5.5.2", {{"6", AttributeType_ObjectIdentifier}}}, {"2.5.5.10", { {"4", AttributeType_Octet}, {"127", AttributeType_ReplicaLink}, }}, {"2.5.5.5", {{"19", AttributeType_Printable}}}, {"2.5.5.17", {{"4", AttributeType_Sid}}}, {"2.5.5.4", {{"20", AttributeType_Teletex}}}, {"2.5.5.12", {{"64", AttributeType_Unicode}}}, {"2.5.5.11", { {"23", AttributeType_UTCTime}, {"24", AttributeType_GeneralizedTime}, }}, {"2.5.5.14", {{"127", AttributeType_DNString}}}, {"2.5.5.7", {{"127", AttributeType_DNBinary}}}, {"2.5.5.1", {{"127", AttributeType_DSDN}}}, }; const AdObject schema = d->attribute_schemas[attribute]; const QString attribute_syntax = schema.get_string(ATTRIBUTE_ATTRIBUTE_SYNTAX); const QString om_syntax = schema.get_string(ATTRIBUTE_OM_SYNTAX); if (type_map.contains(attribute_syntax) && type_map[attribute_syntax].contains(om_syntax)) { return type_map[attribute_syntax][om_syntax]; } else { return AttributeType_StringCase; } } LargeIntegerSubtype AdConfig::get_attribute_large_integer_subtype(const QString &attribute) const { // Manually remap large integer types to subtypes static const QList<QString> datetimes = { ATTRIBUTE_ACCOUNT_EXPIRES, ATTRIBUTE_LAST_LOGON, ATTRIBUTE_LAST_LOGON_TIMESTAMP, ATTRIBUTE_PWD_LAST_SET, ATTRIBUTE_LOCKOUT_TIME, ATTRIBUTE_BAD_PWD_TIME, ATTRIBUTE_CREATION_TIME, }; static const QList<QString> timespans = { ATTRIBUTE_MAX_PWD_AGE, ATTRIBUTE_MIN_PWD_AGE, ATTRIBUTE_LOCKOUT_DURATION, ATTRIBUTE_LOCKOUT_OBSERVATION_WINDOW, ATTRIBUTE_FORCE_LOGOFF, ATTRIBUTE_MS_DS_LOCKOUT_DURATION, ATTRIBUTE_MS_DS_LOCKOUT_OBSERVATION_WINDOW, ATTRIBUTE_MS_DS_MAX_PASSWORD_AGE, ATTRIBUTE_MS_DS_MIN_PASSWORD_AGE }; if (datetimes.contains(attribute)) { return LargeIntegerSubtype_Datetime; } else if (timespans.contains(attribute)) { return LargeIntegerSubtype_Timespan; } else { return LargeIntegerSubtype_Integer; } } bool AdConfig::get_attribute_is_number(const QString &attribute) const { static const QList<AttributeType> number_types = { AttributeType_Integer, AttributeType_LargeInteger, AttributeType_Enumeration, AttributeType_Numeric, }; const AttributeType type = get_attribute_type(attribute); return number_types.contains(type); } bool AdConfig::get_attribute_is_single_valued(const QString &attribute) const { return d->attribute_schemas[attribute].get_bool(ATTRIBUTE_IS_SINGLE_VALUED); } bool AdConfig::get_attribute_is_system_only(const QString &attribute) const { return d->attribute_schemas[attribute].get_bool(ATTRIBUTE_SYSTEM_ONLY); } int AdConfig::get_attribute_range_upper(const QString &attribute) const { return d->attribute_schemas[attribute].get_int(ATTRIBUTE_RANGE_UPPER); } bool AdConfig::get_attribute_is_backlink(const QString &attribute) const { if (d->attribute_schemas[attribute].contains(ATTRIBUTE_LINK_ID)) { const int link_id = d->attribute_schemas[attribute].get_int(ATTRIBUTE_LINK_ID); const bool link_id_is_odd = (link_id % 2 != 0); return link_id_is_odd; } else { return false; } } bool AdConfig::get_attribute_is_constructed(const QString &attribute) const { const int system_flags = d->attribute_schemas[attribute].get_int(ATTRIBUTE_SYSTEM_FLAGS); return bitmask_is_set(system_flags, FLAG_ATTR_IS_CONSTRUCTED); } QByteArray AdConfig::get_right_guid(const QString &right_cn) const { const QByteArray out = d->right_to_guid_map.value(right_cn, QByteArray()); return out; } // NOTE: technically, Active Directory provides // translations for right names but it's not // accessible, so have to translate these ourselves. On // Windows, you would use the localizationDisplayId // retrieved from schema to get translation from // dssec.dll. And we don't have dssec.dll, nor do we // have the ability to interact with it! QString AdConfig::get_right_name(const QByteArray &right_guid, const QLocale::Language language) const { const QHash<QString, QString> cn_to_map_russian = { {"DS-Replication-Get-Changes", QCoreApplication::translate("AdConfig", "DS Replication Get Changes")}, {"DS-Replication-Get-Changes-All", QCoreApplication::translate("AdConfig", "DS Replication Get Changes All")}, {"Email-Information", QCoreApplication::translate("AdConfig", "Phone and Mail Options")}, {"DS-Bypass-Quota", QCoreApplication::translate("AdConfig", "Bypass the quota restrictions during creation.")}, {"Receive-As", QCoreApplication::translate("AdConfig", "Receive As")}, {"Unexpire-Password", QCoreApplication::translate("AdConfig", "Unexpire Password")}, {"Do-Garbage-Collection", QCoreApplication::translate("AdConfig", "Do Garbage Collection")}, {"Allowed-To-Authenticate", QCoreApplication::translate("AdConfig", "Allowed To Authenticate")}, {"Change-PDC", QCoreApplication::translate("AdConfig", "Change PDC")}, {"Reanimate-Tombstones", QCoreApplication::translate("AdConfig", "Reanimate Tombstones")}, {"msmq-Peek-Dead-Letter", QCoreApplication::translate("AdConfig", "msmq Peek Dead Letter")}, {"Certificate-AutoEnrollment", QCoreApplication::translate("AdConfig", "AutoEnrollment")}, {"DS-Install-Replica", QCoreApplication::translate("AdConfig", "DS Install Replica")}, {"Domain-Password", QCoreApplication::translate("AdConfig", "Domain Password & Lockout Policies")}, {"Generate-RSoP-Logging", QCoreApplication::translate("AdConfig", "Generate RSoP Logging")}, {"Run-Protect-Admin-Groups-Task", QCoreApplication::translate("AdConfig", "Run Protect Admin Groups Task")}, {"Self-Membership", QCoreApplication::translate("AdConfig", "Self Membership")}, {"DS-Clone-Domain-Controller", QCoreApplication::translate("AdConfig", "Allow a DC to create a clone of itself")}, {"Domain-Other-Parameters", QCoreApplication::translate("AdConfig", "Other Domain Parameters (for use by SAM)")}, {"SAM-Enumerate-Entire-Domain", QCoreApplication::translate("AdConfig", "SAM Enumerate Entire Domain")}, {"DS-Write-Partition-Secrets", QCoreApplication::translate("AdConfig", "Write secret attributes of objects in a Partition")}, {"Send-As", QCoreApplication::translate("AdConfig", "Send As")}, {"DS-Replication-Manage-Topology", QCoreApplication::translate("AdConfig", "DS Replication Manage Topology")}, {"DS-Set-Owner", QCoreApplication::translate("AdConfig", "Set Owner of an object during creation.")}, {"Generate-RSoP-Planning", QCoreApplication::translate("AdConfig", "Generate RSoP Planning")}, {"Certificate-Enrollment", QCoreApplication::translate("AdConfig", "Certificate Enrollment")}, {"Web-Information", QCoreApplication::translate("AdConfig", "Web Information")}, {"Create-Inbound-Forest-Trust", QCoreApplication::translate("AdConfig", "Create Inbound Forest Trust")}, {"Migrate-SID-History", QCoreApplication::translate("AdConfig", "Migrate SID History")}, {"Update-Password-Not-Required-Bit", QCoreApplication::translate("AdConfig", "Update Password Not Required Bit")}, {"MS-TS-GatewayAccess", QCoreApplication::translate("AdConfig", "MS-TS-GatewayAccess")}, {"Validated-MS-DS-Additional-DNS-Host-Name", QCoreApplication::translate("AdConfig", "Validated write to MS DS Additional DNS Host Name")}, {"msmq-Receive", QCoreApplication::translate("AdConfig", "msmq Receive")}, {"Validated-DNS-Host-Name", QCoreApplication::translate("AdConfig", "Validated DNS Host Name")}, {"Send-To", QCoreApplication::translate("AdConfig", "Send To")}, {"DS-Replication-Get-Changes-In-Filtered-Set", QCoreApplication::translate("AdConfig", "DS Replication Get Changes In Filtered Set")}, {"Read-Only-Replication-Secret-Synchronization", QCoreApplication::translate("AdConfig", "Read Only Replication Secret Synchronization")}, {"Validated-MS-DS-Behavior-Version", QCoreApplication::translate("AdConfig", "Validated write to MS DS behavior version")}, {"msmq-Open-Connector", QCoreApplication::translate("AdConfig", "msmq Open Connector")}, {"Terminal-Server-License-Server", QCoreApplication::translate("AdConfig", "Terminal Server License Server")}, {"Change-Schema-Master", QCoreApplication::translate("AdConfig", "Change Schema Master")}, {"Recalculate-Hierarchy", QCoreApplication::translate("AdConfig", "Recalculate Hierarchy")}, {"DS-Check-Stale-Phantoms", QCoreApplication::translate("AdConfig", "DS Check Stale Phantoms")}, {"msmq-Receive-computer-Journal", QCoreApplication::translate("AdConfig", "msmq Receive computer Journal")}, {"User-Force-Change-Password", QCoreApplication::translate("AdConfig", "User Force Change Password")}, {"Domain-Administer-Server", QCoreApplication::translate("AdConfig", "Domain Administer Server")}, {"DS-Replication-Synchronize", QCoreApplication::translate("AdConfig", "DS Replication Synchronize")}, {"Personal-Information", QCoreApplication::translate("AdConfig", "Personal Information")}, {"msmq-Peek", QCoreApplication::translate("AdConfig", "msmq Peek")}, {"General-Information", QCoreApplication::translate("AdConfig", "General Information")}, {"Membership", QCoreApplication::translate("AdConfig", "Group Membership")}, {"Add-GUID", QCoreApplication::translate("AdConfig", "Add GUID")}, {"RAS-Information", QCoreApplication::translate("AdConfig", "Remote Access Information")}, {"DS-Execute-Intentions-Script", QCoreApplication::translate("AdConfig", "DS Execute Intentions Script")}, {"Allocate-Rids", QCoreApplication::translate("AdConfig", "Allocate Rids")}, {"Update-Schema-Cache", QCoreApplication::translate("AdConfig", "Update Schema Cache")}, {"Apply-Group-Policy", QCoreApplication::translate("AdConfig", "Apply Group Policy")}, {"User-Account-Restrictions", QCoreApplication::translate("AdConfig", "Account Restrictions")}, {"Validated-SPN", QCoreApplication::translate("AdConfig", "Validated SPN")}, {"DS-Read-Partition-Secrets", QCoreApplication::translate("AdConfig", "Read secret attributes of objects in a Partition")}, {"User-Logon", QCoreApplication::translate("AdConfig", "Logon Information")}, {"DS-Query-Self-Quota", QCoreApplication::translate("AdConfig", "DS Query Self Quota")}, {"Change-Infrastructure-Master", QCoreApplication::translate("AdConfig", "Change Infrastructure Master")}, {"Open-Address-Book", QCoreApplication::translate("AdConfig", "Open Address Book")}, {"User-Change-Password", QCoreApplication::translate("AdConfig", "User Change Password")}, {"msmq-Peek-computer-Journal", QCoreApplication::translate("AdConfig", "msmq Peek computer Journal")}, {"Change-Domain-Master", QCoreApplication::translate("AdConfig", "Change Domain Master")}, {"msmq-Send", QCoreApplication::translate("AdConfig", "msmq Send")}, {"Change-Rid-Master", QCoreApplication::translate("AdConfig", "Change Rid Master")}, {"Recalculate-Security-Inheritance", QCoreApplication::translate("AdConfig", "Recalculate Security Inheritance")}, {"Refresh-Group-Cache", QCoreApplication::translate("AdConfig", "Refresh Group Cache")}, {"Manage-Optional-Features", QCoreApplication::translate("AdConfig", "Manage Optional Features")}, {"Reload-SSL-Certificate", QCoreApplication::translate("AdConfig", "Reload SSL Certificate")}, {"Enable-Per-User-Reversibly-Encrypted-Password", QCoreApplication::translate("AdConfig", "Enable Per User Reversibly Encrypted Password")}, {"DS-Replication-Monitor-Topology", QCoreApplication::translate("AdConfig", "DS Replication Monitor Topology")}, {"Public-Information", QCoreApplication::translate("AdConfig", "Public Information")}, {"Private-Information", QCoreApplication::translate("AdConfig", "Private Information")}, {"msmq-Receive-Dead-Letter", QCoreApplication::translate("AdConfig", "msmq Receive Dead Letter")}, {"msmq-Receive-journal", QCoreApplication::translate("AdConfig", "msmq Receive journal")}, {"DNS-Host-Name-Attributes", QCoreApplication::translate("AdConfig", "DNS Host Name Attributes")}, }; const QString right_cn = d->right_guid_to_cn_map[right_guid]; if (language == QLocale::Russian && cn_to_map_russian.contains(right_cn)) { const QString out = cn_to_map_russian[right_cn]; return out; } const QString out = d->rights_guid_to_name_map.value(right_guid, QCoreApplication::translate("AdConfig", "<unknown rights>")); return out; } QList<QString> AdConfig::get_extended_rights_list(const QList<QString> &class_list) const { QList<QString> out; for (const QString &rights : d->extended_rights_list) { const bool applies_to = rights_applies_to_class(rights, class_list); if (applies_to) { out.append(rights); } } return out; } int AdConfig::get_rights_valid_accesses(const QString &rights_cn) const { // NOTE: awkward exception. Can't write group // membership because target attribute is // constructed. For some reason valid accesses for // membership right does allow writing. if (rights_cn == "Membership") { return SEC_ADS_READ_PROP; } const int out = d->rights_valid_accesses_map.value(rights_cn, 0); return out; } QString AdConfig::guid_to_attribute(const QByteArray &guid) const { const QString out = d->guid_to_attribute_map.value(guid, "<unknown attribute>"); return out; } QString AdConfig::guid_to_class(const QByteArray &guid) const { const QString out = d->guid_to_class_map.value(guid, "<unknown class>"); return out; } // (noncontainer classes) = (all classes) - (container classes) QList<QString> AdConfig::get_noncontainer_classes() { QList<QString> out = filter_classes; const QList<QString> container_classes = get_filter_containers(); for (const QString &container_class : container_classes) { out.removeAll(container_class); } return out; } bool AdConfig::rights_applies_to_class(const QString &rights_cn, const QList<QString> &class_list) const { const QByteArray rights_guid = d->rights_name_to_guid_map[rights_cn]; const QList<QString> applies_to_list = d->rights_applies_to_map[rights_guid]; const QSet<QString> applies_to_set = QSet<QString>(applies_to_list.begin(), applies_to_list.end()); const QSet<QString> class_set = QSet<QString>(class_list.begin(), class_list.end()); const bool applies = applies_to_set.intersects(class_set); return applies; } QList<QString> AdConfigPrivate::add_auxiliary_classes(const QList<QString> &object_classes) const { QList<QString> out; out += object_classes; for (const auto &object_class : object_classes) { const AdObject schema = class_schemas[object_class]; out += schema.get_strings(ATTRIBUTE_AUXILIARY_CLASS); out += schema.get_strings(ATTRIBUTE_SYSTEM_AUXILIARY_CLASS); } out.removeDuplicates(); return out; }
35,900
C++
.cpp
673
45.683507
170
0.679515
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,754
ad_display.cpp
altlinux_admc/src/adldap/ad_display.cpp
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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 "ad_display.h" #include "ad_config.h" #include "ad_defines.h" #include "ad_utils.h" #include "samba/dom_sid.h" #include <QByteArray> #include <QCoreApplication> #include <QDateTime> #include <QList> #include <QString> #include <algorithm> const qint64 SECONDS_TO_MILLIS = 1000LL; const qint64 MINUTES_TO_SECONDS = 60LL; const qint64 HOURS_TO_SECONDS = MINUTES_TO_SECONDS * 60LL; const qint64 DAYS_TO_SECONDS = HOURS_TO_SECONDS * 24LL; QString large_integer_datetime_display_value(const QString &attribute, const QByteArray &bytes, const AdConfig *adconfig); QString datetime_display_value(const QString &attribute, const QByteArray &bytes, const AdConfig *adconfig); QString timespan_display_value(const QByteArray &bytes); QString octet_display_value(const QByteArray &bytes); QString guid_to_display_value(const QByteArray &bytes); QString uac_to_display_value(const QByteArray &bytes); QString samaccounttype_to_display_value(const QByteArray &bytes); QString primarygrouptype_to_display_value(const QByteArray &bytes); QString msds_supported_etypes_to_display_value(const QByteArray &bytes); QString attribute_hex_displayed_value(const QString &attribute, const QByteArray &bytes); QString attribute_display_value(const QString &attribute, const QByteArray &value, const AdConfig *adconfig) { if (adconfig == nullptr) { return value; } const AttributeType type = adconfig->get_attribute_type(attribute); switch (type) { case AttributeType_Integer: { if (attribute == ATTRIBUTE_USER_ACCOUNT_CONTROL) { return uac_to_display_value(value); } else if (attribute == ATTRIBUTE_SAM_ACCOUNT_TYPE) { return samaccounttype_to_display_value(value); } else if (attribute == ATTRIBUTE_PRIMARY_GROUP_ID) { return primarygrouptype_to_display_value(value); } else if (attribute == ATTRIBUTE_GROUP_TYPE || attribute == ATTRIBUTE_SYSTEM_FLAGS) { return attribute_hex_displayed_value(attribute, value); } else if (attribute == ATTRIBUTE_MS_DS_SUPPORTED_ETYPES) { return msds_supported_etypes_to_display_value(value); } else { return QString(value); } } case AttributeType_LargeInteger: { const LargeIntegerSubtype subtype = adconfig->get_attribute_large_integer_subtype(attribute); switch (subtype) { case LargeIntegerSubtype_Datetime: return large_integer_datetime_display_value(attribute, value, adconfig); case LargeIntegerSubtype_Timespan: return timespan_display_value(value); case LargeIntegerSubtype_Integer: return QString(value); } return QString(); } case AttributeType_UTCTime: return datetime_display_value(attribute, value, adconfig); case AttributeType_GeneralizedTime: return datetime_display_value(attribute, value, adconfig); case AttributeType_Sid: return object_sid_display_value(value); case AttributeType_Octet: { if (attribute == ATTRIBUTE_OBJECT_GUID) { return guid_to_display_value(value); } else { return octet_display_value(value); } } case AttributeType_NTSecDesc: { return QCoreApplication::translate("attribute_display", "<BINARY VALUE>"); } default: { return QString(value); } } } QString attribute_display_values(const QString &attribute, const QList<QByteArray> &values, const AdConfig *adconfig) { if (values.isEmpty()) { return QCoreApplication::translate("attribute_display", "<unset>"); } else { QString out; // Convert values list to // "display_value1;display_value2;display_value3..." for (int i = 0; i < values.size(); i++) { if (i > 0) { out += ";"; } const QByteArray value = values[i]; const QString display_value = attribute_display_value(attribute, value, adconfig); out += display_value; } return out; } } QString object_sid_display_value(const QByteArray &sid_bytes) { dom_sid *sid = (dom_sid *) sid_bytes.data(); TALLOC_CTX *tmp_ctx = talloc_new(NULL); const char *sid_cstr = dom_sid_string(tmp_ctx, sid); const QString out = QString(sid_cstr); talloc_free(tmp_ctx); return out; } QString large_integer_datetime_display_value(const QString &attribute, const QByteArray &value, const AdConfig *adconfig) { const QString value_string = QString(value); if (large_integer_datetime_is_never(value_string)) { return QCoreApplication::translate("attribute_display", "(never)"); } else { QDateTime datetime = datetime_string_to_qdatetime(attribute, value_string, adconfig); const QString display = datetime.toLocalTime().toString(DATETIME_DISPLAY_FORMAT); return display; } } QString datetime_display_value(const QString &attribute, const QByteArray &bytes, const AdConfig *adconfig) { const QString value_string = QString(bytes); const QDateTime datetime = datetime_string_to_qdatetime(attribute, value_string, adconfig); const QDateTime datetime_local = datetime.toLocalTime(); const QString display = datetime_local.toString(DATETIME_DISPLAY_FORMAT) + datetime.toLocalTime().timeZoneAbbreviation(); return display; } QString timespan_display_value(const QByteArray &bytes) { // Timespan = integer value of hundred nanosecond quantities // (also negated) // Convert to dd:hh:mm:ss const QString value_string = QString(bytes); const qint64 hundred_nanos_negative = value_string.toLongLong(); if (hundred_nanos_negative == LLONG_MIN) { return "(never)"; } if (hundred_nanos_negative == 0) { return "(none)"; } qint64 seconds_total = [hundred_nanos_negative]() { const qint64 hundred_nanos = -hundred_nanos_negative; const qint64 millis = hundred_nanos / MILLIS_TO_100_NANOS; const qint64 seconds = millis / SECONDS_TO_MILLIS; return seconds; }(); const qint64 days = seconds_total / DAYS_TO_SECONDS; seconds_total -= days * DAYS_TO_SECONDS; const qint64 hours = seconds_total / HOURS_TO_SECONDS; seconds_total -= hours * HOURS_TO_SECONDS; const qint64 minutes = seconds_total / MINUTES_TO_SECONDS; seconds_total -= minutes * MINUTES_TO_SECONDS; const qint64 seconds = seconds_total; // Convert arbitrary time unit value to string with format // "00-99" with leading zero if needed const auto time_unit_to_string = [](qint64 time) -> QString { if (time > 99) { time = 99; } const QString time_string = QString::number(time); if (time == 0) { return "00"; } else if (time < 10) { return "0" + time_string; } else { return time_string; } }; const QString days_string = QString::number(days); const QString hours_string = time_unit_to_string(hours); const QString minutes_string = time_unit_to_string(minutes); const QString seconds_string = time_unit_to_string(seconds); const QString display = QString("%1:%2:%3:%4").arg(days_string, hours_string, minutes_string, seconds_string); return display; } QString guid_to_display_value(const QByteArray &bytes) { // NOTE: have to do some weird pre-processing to match // how Windows displays GUID's. The GUID is broken down // into 5 segments, each separated by '-': // "0000-11-22-33-444444". Byte order for first 3 // segments is also reversed (why?), so reverse it again // for display. const int segments_count = 5; QByteArray segments[segments_count]; segments[0] = bytes.mid(0, 4); segments[1] = bytes.mid(4, 2); segments[2] = bytes.mid(6, 2); segments[3] = bytes.mid(8, 2); segments[4] = bytes.mid(10, 6); std::reverse(segments[0].begin(), segments[0].end()); std::reverse(segments[1].begin(), segments[1].end()); std::reverse(segments[2].begin(), segments[2].end()); const QString guid_display_string = [&]() { QString out; for (int i = 0; i < segments_count; i++) { const QByteArray segment = segments[i]; if (i > 0) { out += '-'; } out += segment.toHex(); } return out; }(); return guid_display_string; } QString octet_display_value(const QByteArray &bytes) { const QByteArray bytes_hex = bytes.toHex(); QByteArray out = bytes_hex; // Add " 0x" before each byte (every 2 indexes) for (int i = out.size() - 2; i >= 0; i -= 2) { out.insert(i, "0x"); if (i != 0) { out.insert(i, " "); } } return QString(out); } QString uac_to_display_value(const QByteArray &bytes) { bool uac_toInt_ok; const int uac = bytes.toInt(&uac_toInt_ok); if (!uac_toInt_ok) { return QCoreApplication::translate("attribute_display", "<invalid UAC value>"); } // Create string of the form "X | Y | Z", where X, // Y, Z are names of masks that are set in given UAC const QString masks_string = [&]() { // NOTE: using separate list instead of map's // keys() because keys() is unordered and we need // order so that display string is consistent const QList<int> mask_list = { UAC_SCRIPT, UAC_ACCOUNTDISABLE, UAC_HOMEDIR_REQUIRED, UAC_LOCKOUT, UAC_PASSWD_NOTREQD, UAC_PASSWD_CANT_CHANGE, UAC_ENCRYPTED_TEXT_PASSWORD_ALLOWED, UAC_TEMP_DUPLICATE_ACCOUNT, UAC_NORMAL_ACCOUNT, UAC_INTERDOMAIN_TRUST_ACCOUNT, UAC_WORKSTATION_TRUST_ACCOUNT, UAC_SERVER_TRUST_ACCOUNT, UAC_DONT_EXPIRE_PASSWORD, UAC_MNS_LOGON_ACCOUNT, UAC_SMARTCARD_REQUIRED, UAC_TRUSTED_FOR_DELEGATION, UAC_NOT_DELEGATED, UAC_USE_DES_KEY_ONLY, UAC_DONT_REQUIRE_PREAUTH, UAC_ERROR_PASSWORD_EXPIRED, UAC_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION, UAC_PARTIAL_SECRETS_ACCOUNT, UAC_USER_USE_AES_KEYS, }; const QHash<int, QString> mask_name_map = { {UAC_SCRIPT, "SCRIPT"}, {UAC_ACCOUNTDISABLE, "ACCOUNTDISABLE"}, {UAC_HOMEDIR_REQUIRED, "HOMEDIR_REQUIRED"}, {UAC_LOCKOUT, "LOCKOUT"}, {UAC_PASSWD_NOTREQD, "PASSWD_NOTREQD"}, {UAC_PASSWD_CANT_CHANGE, "PASSWD_CANT_CHANGE"}, {UAC_ENCRYPTED_TEXT_PASSWORD_ALLOWED, "ENCRYPTED_TEXT_PASSWORD_ALLOWED"}, {UAC_TEMP_DUPLICATE_ACCOUNT, "TEMP_DUPLICATE_ACCOUNT"}, {UAC_NORMAL_ACCOUNT, "NORMAL_ACCOUNT"}, {UAC_INTERDOMAIN_TRUST_ACCOUNT, "INTERDOMAIN_TRUST_ACCOUNT"}, {UAC_WORKSTATION_TRUST_ACCOUNT, "WORKSTATION_TRUST_ACCOUNT"}, {UAC_SERVER_TRUST_ACCOUNT, "SERVER_TRUST_ACCOUNT"}, {UAC_DONT_EXPIRE_PASSWORD, "DONT_EXPIRE_PASSWORD"}, {UAC_MNS_LOGON_ACCOUNT, "MNS_LOGON_ACCOUNT"}, {UAC_SMARTCARD_REQUIRED, "SMARTCARD_REQUIRED"}, {UAC_TRUSTED_FOR_DELEGATION, "TRUSTED_FOR_DELEGATION"}, {UAC_NOT_DELEGATED, "NOT_DELEGATED"}, {UAC_USE_DES_KEY_ONLY, "USE_DES_KEY_ONLY"}, {UAC_DONT_REQUIRE_PREAUTH, "DONT_REQUIRE_PREAUTH"}, {UAC_ERROR_PASSWORD_EXPIRED, "ERROR_PASSWORD_EXPIRED"}, {UAC_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION, "TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION"}, {UAC_PARTIAL_SECRETS_ACCOUNT, "PARTIAL_SECRETS_ACCOUNT"}, {UAC_USER_USE_AES_KEYS, "USER_USE_AES_KEYS"}, }; const QList<QString> set_mask_name_list = [&]() { QList<QString> out_list; for (const int mask : mask_list) { const bool mask_is_set = bitmask_is_set(uac, mask); if (mask_is_set) { const QString mask_name = mask_name_map[mask]; out_list.append(mask_name); } } return out_list; }(); const QString out_string = set_mask_name_list.join(" | "); return out_string; }(); const QString out = QString("0x%1 = ( %2 )").arg(QString::number((quint32)uac, 16), masks_string); return out; } QString samaccounttype_to_display_value(const QByteArray &bytes) { bool toInt_ok; const int value_int = bytes.toInt(&toInt_ok); if (!toInt_ok) { return QCoreApplication::translate("attribute_display", "<invalid value>"); } const QHash<int, QString> mask_name_map = { {SAM_DOMAIN_OBJECT, "DOMAIN_OBJECT"}, {SAM_GROUP_OBJECT, "GROUP_OBJECT"}, {SAM_NON_SECURITY_GROUP_OBJECT, "NON_SECURITY_GROUP_OBJECT"}, {SAM_ALIAS_OBJECT, "ALIAS_OBJECT"}, {SAM_NON_SECURITY_ALIAS_OBJECT, "NON_SECURITY_ALIAS_OBJECT"}, {SAM_USER_OBJECT, "USER_OBJECT"}, {SAM_NORMAL_USER_ACCOUNT, "NORMAL_USER_ACCOUNT"}, {SAM_MACHINE_ACCOUNT, "MACHINE_ACCOUNT"}, {SAM_TRUST_ACCOUNT, "TRUST_ACCOUNT"}, {SAM_APP_BASIC_GROUP, "APP_BASIC_GROUP"}, {SAM_APP_QUERY_GROUP, "APP_QUERY_GROUP"}, {SAM_ACCOUNT_TYPE_MAX, "ACCOUNT_TYPE_MAX"}, }; const QString mask_name = mask_name_map.value(value_int, ""); const QString out = QString("%1 = ( %2 )").arg(QString(bytes), mask_name); return out; } QString primarygrouptype_to_display_value(const QByteArray &bytes) { bool toInt_ok; const int value_int = bytes.toInt(&toInt_ok); if (!toInt_ok) { return QCoreApplication::translate("attribute_display", "<invalid value>"); } // NOTE: builtin group rid's are not included // because they can't be primary const QHash<int, QString> mask_name_map = { {DOMAIN_RID_ADMINS, "GROUP_RID_ADMINS"}, {DOMAIN_RID_USERS, "GROUP_RID_USERS"}, {DOMAIN_RID_GUESTS, "GROUP_RID_GUESTS"}, {DOMAIN_RID_DOMAIN_MEMBERS, "GROUP_RID_DOMAIN_MEMBERS"}, {DOMAIN_RID_DCS, "GROUP_RID_DCS"}, {DOMAIN_RID_CERT_ADMINS, "GROUP_RID_CERT_ADMINS"}, {DOMAIN_RID_SCHEMA_ADMINS, "GROUP_RID_SCHEMA_ADMINS"}, {DOMAIN_RID_ENTERPRISE_ADMINS, "GROUP_RID_ENTERPRISE_ADMINS"}, {DOMAIN_RID_POLICY_ADMINS, "GROUP_RID_POLICY_ADMINS"}, {DOMAIN_RID_READONLY_DCS, "GROUP_RID_READONLY_DCS"}, {DOMAIN_RID_RAS_SERVERS, "GROUP_RID_RAS_SERVERS"}, }; if (mask_name_map.contains(value_int)) { const QString mask_name = mask_name_map[value_int]; const QString out = QString("%1 = ( %2 )").arg(QString(bytes), mask_name); return out; } else { return QString::number(value_int); } } bool attribute_value_is_hex_displayed(const QString &attribute) { //TODO: Add here attributes with hex displayed values return (attribute == ATTRIBUTE_GROUP_TYPE || attribute == ATTRIBUTE_USER_ACCOUNT_CONTROL || attribute == ATTRIBUTE_MS_DS_SUPPORTED_ETYPES || attribute == ATTRIBUTE_SYSTEM_FLAGS); } QString msds_supported_etypes_to_display_value(const QByteArray &bytes) { bool toInt_ok; const int value_int = bytes.toInt(&toInt_ok); if (!toInt_ok) { return QCoreApplication::translate("attribute_display", "<invalid value>"); } // NOTE: using separate list instead of map's // keys() because keys() is unordered and we need // order so that display string is consistent const QList<int> mask_list = { ETYPES_DES_CBC_CRC, ETYPES_DES_CBC_MD5, ETYPES_RC4_HMAC_MD5, ETYPES_AES128_CTS_HMAC_SHA1_96, ETYPES_AES256_CTS_HMAC_SHA1_96 }; const QHash<int, QString> mask_name_map = { {ETYPES_DES_CBC_CRC, "DES_CBC_CRC"}, {ETYPES_DES_CBC_MD5, "DES_CBC_MD5"}, {ETYPES_RC4_HMAC_MD5, "RC4_HMAC_MD5"}, {ETYPES_AES128_CTS_HMAC_SHA1_96, "AES128_CTS_HMAC_SHA1_96"}, {ETYPES_AES256_CTS_HMAC_SHA1_96, "AES256_CTS_HMAC_SHA1_96"}, }; QStringList masks_strings; for (const int mask : mask_list) { if (bitmask_is_set(value_int, mask)) masks_strings.append(mask_name_map[mask]); } QString display_value = QString("0x%1 = ( %2 )").arg(QString::number((quint32)value_int, 16), masks_strings.join(" | ")); return display_value; } QString attribute_hex_displayed_value(const QString &attribute, const QByteArray &bytes) { bool toInt_ok; const int value_int = bytes.toInt(&toInt_ok); if (!toInt_ok) { return QCoreApplication::translate("attribute_display", "<invalid value>"); } const QHash<int, QString> mask_name_map = attribute_value_bit_string_map(attribute); QStringList masks_strings; for (const int mask : mask_name_map.keys()) { if (bitmask_is_set(value_int, mask)) masks_strings.append(mask_name_map[mask]); } QString display_value = QString("0x%1 = ( %2 )").arg(QString::number((quint32)value_int, 16), masks_strings.join(" | ")); return display_value; }
18,078
C++
.cpp
407
36.702703
125
0.644108
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,755
admc_test_string_large_edit.h
altlinux_admc/tests/admc_test_string_large_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_STRING_LARGE_EDIT_H #define ADMC_TEST_STRING_LARGE_EDIT_H #include "admc_test.h" class StringLargeEdit; class QPlainTextEdit; class ADMCTestStringLargeEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void test_emit_edited_signal(); void load(); void apply_unmodified(); void apply(); private: StringLargeEdit *edit; QPlainTextEdit *text_edit; QString dn; }; #endif /* ADMC_TEST_STRING_LARGE_EDIT_H */
1,259
C++
.h
38
30.5
72
0.747733
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,756
admc_test_bool_attribute_dialog.h
altlinux_admc/tests/admc_test_bool_attribute_dialog.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_BOOL_ATTRIBUTE_DIALOG_H #define ADMC_TEST_BOOL_ATTRIBUTE_DIALOG_H #include "admc_test.h" class BoolAttributeDialog; class QRadioButton; enum ADMCTestBoolAttributeDialogButton { ADMCTestBoolAttributeDialogButton_True }; class ADMCTestBoolAttributeDialog : public ADMCTest { Q_OBJECT private slots: void initTestCase_data(); void init(); void display_value(); void get_value_list(); private: BoolAttributeDialog *dialog; QRadioButton *button; }; #endif /* ADMC_TEST_BOOL_ATTRIBUTE_DIALOG_H */
1,324
C++
.h
39
31.435897
72
0.76489
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,757
admc_test_datetime_edit.h
altlinux_admc/tests/admc_test_datetime_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_DATETIME_EDIT_H #define ADMC_TEST_DATETIME_EDIT_H #include "admc_test.h" class DateTimeEdit; class QDateTimeEdit; class ADMCTestDateTimeEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void load(); private: DateTimeEdit *edit; QString dn; QDateTimeEdit *qedit; }; #endif /* ADMC_TEST_DATETIME_EDIT_H */
1,149
C++
.h
35
30.4
72
0.75226
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,758
admc_test_unlock_edit.h
altlinux_admc/tests/admc_test_unlock_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_UNLOCK_EDIT_H #define ADMC_TEST_UNLOCK_EDIT_H #include "admc_test.h" class UnlockEdit; class QCheckBox; class ADMCTestUnlockEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void test_emit_edited_signal(); void unchecked_after_load(); void apply_unmodified(); void test_apply_unchecked(); void test_apply_checked(); void uncheck_after_apply(); private: UnlockEdit *unlock_edit; QCheckBox *checkbox; QString dn; bool user_is_unlocked(); void load_locked_user_into_edit(); }; #endif /* ADMC_TEST_UNLOCK_EDIT_H */
1,385
C++
.h
42
30.095238
72
0.738381
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,759
admc_test_find_object_dialog.h
altlinux_admc/tests/admc_test_find_object_dialog.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_FIND_OBJECT_DIALOG_H #define ADMC_TEST_FIND_OBJECT_DIALOG_H #include "admc_test.h" class ADMCTestFindObjectDialog : public ADMCTest { Q_OBJECT private slots: void simple_tab(); void advanced_tab(); }; #endif /* ADMC_TEST_FIND_OBJECT_DIALOG_H */
1,054
C++
.h
29
34.137931
72
0.751961
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,760
admc_test_member_of_tab.h
altlinux_admc/tests/admc_test_member_of_tab.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_MEMBER_OF_TAB_H #define ADMC_TEST_MEMBER_OF_TAB_H #include "admc_test.h" class QTreeView; class AttributeEdit; class QStandardItemModel; class QPushButton; class ADMCTestMemberOfTab : public ADMCTest { Q_OBJECT private slots: void init() override; void load_empty(); void load(); void remove(); void add(); private: AttributeEdit *edit; QTreeView *view; QStandardItemModel *model; QString user_dn; QString group_dn; QPushButton *add_button; QPushButton *remove_button; int get_group_row(const QString &dn); }; #endif /* ADMC_TEST_MEMBER_OF_TAB_H */
1,406
C++
.h
45
28.4
72
0.741124
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,761
admc_test_logon_hours_dialog.h
altlinux_admc/tests/admc_test_logon_hours_dialog.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_LOGON_HOURS_DIALOG_H #define ADMC_TEST_LOGON_HOURS_DIALOG_H #include "admc_test.h" class LogonHoursDialog; class QStandardItemModel; class QTableView; class QItemSelectionModel; class QRadioButton; class ADMCTestLogonHoursDialog : public ADMCTest { Q_OBJECT private slots: void conversion_funs(); void load_data(); void load(); void load_empty(); void select(); void handle_timezone(); private: LogonHoursDialog *dialog; QStandardItemModel *model; QTableView *view; QItemSelectionModel *selection_model; QRadioButton *local_time_button; QRadioButton *utc_time_button; void open_dialog(const QByteArray &value); }; #endif /* ADMC_TEST_LOGON_HOURS_DIALOG_H */
1,514
C++
.h
46
30.130435
72
0.755479
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,762
admc_test_string_edit.h
altlinux_admc/tests/admc_test_string_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_STRING_EDIT_H #define ADMC_TEST_STRING_EDIT_H #include "admc_test.h" class StringEdit; class QLineEdit; class ADMCTestStringEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void test_emit_edited_signal(); void load(); void apply_unmodified(); void apply_modified(); void apply_trim(); private: StringEdit *edit; QLineEdit *line_edit; QString dn; }; #endif /* ADMC_TEST_STRING_EDIT_H */
1,248
C++
.h
39
29.307692
72
0.739384
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,763
admc_test_gplink.h
altlinux_admc/tests/admc_test_gplink.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_GPLINK_H #define ADMC_TEST_GPLINK_H #include <QObject> #include <QTest> class ADMCTestGplink : public QObject { Q_OBJECT public slots: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); private slots: void to_string(); void equals(); void contains_data(); void contains(); void add_data(); void add(); void remove_data(); void remove(); void move_up_data(); void move_up(); void move_down_data(); void move_down(); void get_option_data(); void get_option(); void set_option_data(); void set_option(); void get_gpo_list_data(); void get_gpo_list(); void get_gpo_order_data(); void get_gpo_order(); }; #endif /* ADMC_TEST_GPLINK_H */
1,553
C++
.h
53
25.962264
72
0.698126
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,764
admc_test_sam_name_edit.h
altlinux_admc/tests/admc_test_sam_name_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_SAM_NAME_EDIT_H #define ADMC_TEST_SAM_NAME_EDIT_H #include "admc_test.h" class SamNameEdit; class QLineEdit; class ADMCTestSamNameEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void verify_data(); void verify(); void trim(); private: SamNameEdit *edit; QLineEdit *line_edit; }; #endif /* ADMC_TEST_SAM_NAME_EDIT_H */
1,169
C++
.h
36
29.972222
72
0.743111
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,765
admc_test_create_object_dialog.h
altlinux_admc/tests/admc_test_create_object_dialog.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_CREATE_OBJECT_DIALOG_H #define ADMC_TEST_CREATE_OBJECT_DIALOG_H #include "admc_test.h" class ADMCTestCreateObjectDialog : public ADMCTest { Q_OBJECT private slots: void create_user_data(); void create_user(); void create_user_autofill(); void create_ou(); void create_computer(); void create_computer_autofill(); void create_group(); void create_group_autofill(); void create_shared_folder(); void create_contact(); void create_contact_autofill(); void trim(); }; #endif /* ADMC_TEST_CREATE_OBJECT_DIALOG_H */
1,359
C++
.h
39
31.923077
72
0.735361
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,766
admc_test_country_edit.h
altlinux_admc/tests/admc_test_country_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_COUNTRY_EDIT_H #define ADMC_TEST_COUNTRY_EDIT_H #include "admc_test.h" class CountryEdit; class QComboBox; class ADMCTestCountryEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void loaded_csv_file(); void emit_edited_signal(); void load(); void apply_unmodified(); void apply_modified(); private: CountryEdit *edit; QComboBox *combo; QString dn; }; #endif /* ADMC_TEST_COUNTRY_EDIT_H */
1,250
C++
.h
39
29.358974
72
0.740648
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,767
admc_test_upn_edit.h
altlinux_admc/tests/admc_test_upn_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_UPN_EDIT_H #define ADMC_TEST_UPN_EDIT_H #include "admc_test.h" class UpnEdit; class QLineEdit; class QComboBox; class ADMCTestUpnEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void length_limit(); void test_load(); void test_emit_edited(); void apply_unmodified(); void test_apply_suffix(); void test_apply_prefix(); void test_apply_prefix_and_suffix(); void test_reset(); void verify_bad_chars_data(); void verify_bad_chars(); void verify_conflict(); private: UpnEdit *upn_edit; QLineEdit *prefix_edit; QComboBox *suffix_edit; QString dn; QString get_upn(); QString get_current_upn(); bool edit_state_equals_to_server_state(); void change_suffix_in_edit(); }; #endif /* ADMC_TEST_UPN_EDIT_H */
1,604
C++
.h
51
28.27451
72
0.72215
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,768
admc_test_ad_security.h
altlinux_admc/tests/admc_test_ad_security.h
/* * ADMC - AD Management Center * * Copyright (C) 2020 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_AD_SECURITY_H #define ADMC_TEST_AD_SECURITY_H #include "admc_test.h" struct security_descriptor; enum TestAdSecurityType { TestAdSecurityType_Allow, TestAdSecurityType_Deny, TestAdSecurityType_None, }; Q_DECLARE_METATYPE(TestAdSecurityType) class ADMCTestAdSecurity : public ADMCTest { Q_OBJECT private slots: void initTestCase() override; void init() override; void cleanup() override; void add_right(); void remove_right(); void remove_trustee(); void handle_generic_read_and_write_sharing_bit(); void protected_against_deletion_data(); void protected_against_deletion(); void cant_change_pass_data(); void cant_change_pass(); void add_to_unset_opposite_data(); void add_to_unset_opposite(); void remove_to_set_subordinates_data(); void remove_to_set_subordinates(); void remove_to_unset_superior_data(); void remove_to_unset_superior(); void add_to_unset_opposite_superior_data(); void add_to_unset_opposite_superior(); private: QString test_user_dn; QString test_trustee_dn; QByteArray test_trustee; security_descriptor *sd; const QList<QString> class_list = {CLASS_USER}; void check_state(const QByteArray &trustee, const uint32_t access_mask, const QByteArray &object_type, const TestAdSecurityType type) const; void load_sd(); }; #endif /* ADMC_TEST_AD_SECURITY_H */
2,191
C++
.h
61
32.491803
144
0.740094
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,769
admc_test_protect_deletion_edit.h
altlinux_admc/tests/admc_test_protect_deletion_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_PROTECT_DELETION_EDIT_H #define ADMC_TEST_PROTECT_DELETION_EDIT_H #include "admc_test.h" class ProtectDeletionEdit; class QCheckBox; class ADMCTestProtectDeletionEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void edited_signal_data(); void edited_signal(); void apply_data(); void apply(); private: ProtectDeletionEdit *edit; QCheckBox *checkbox; QString dn; }; #endif /* ADMC_TEST_PROTECT_DELETION_EDIT_H */
1,270
C++
.h
38
30.789474
72
0.750817
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,770
admc_test_select_classes_widget.h
altlinux_admc/tests/admc_test_select_classes_widget.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_SELECT_CLASSES_WIDGET_H #define ADMC_TEST_SELECT_CLASSES_WIDGET_H #include "admc_test.h" class SelectClassesWidget; class QPushButton; class QLineEdit; class ADMCTestSelectClassesWidget : public ADMCTest { Q_OBJECT private slots: void init() override; void test_foo_data(); void test_foo(); private: SelectClassesWidget *select_classes_widget; QPushButton *select_button; QLineEdit *classes_display; }; #endif /* ADMC_TEST_SELECT_CLASSES_WIDGET_H */
1,278
C++
.h
37
32.081081
72
0.760746
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,771
admc_test_find_policy_dialog.h
altlinux_admc/tests/admc_test_find_policy_dialog.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_FIND_POLICY_DIALOG_H #define ADMC_TEST_FIND_POLICY_DIALOG_H #include "admc_test.h" class FindPolicyDialog; class ADMCTestFindPolicyDialog : public ADMCTest { Q_OBJECT private slots: void init() override; void add_filter_data(); void add_filter(); private: FindPolicyDialog *dialog; }; #endif /* ADMC_TEST_FIND_POLICY_DIALOG_H */
1,149
C++
.h
33
32.424242
72
0.75361
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,772
admc_test_list_attribute_dialog.h
altlinux_admc/tests/admc_test_list_attribute_dialog.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_MULTI_EDITOR_H #define ADMC_TEST_MULTI_EDITOR_H #include "admc_test.h" class ListAttributeDialog; class QListWidget; class QPushButton; class ADMCTestListAttributeDialog : public ADMCTest { Q_OBJECT private slots: void initTestCase_data(); void init(); void display_value(); void get_value_list(); void add(); void remove(); private: ListAttributeDialog *dialog; QListWidget *list_widget; QPushButton *add_button; QPushButton *remove_button; }; #endif /* ADMC_TEST_MULTI_EDITOR_H */
1,327
C++
.h
41
29.658537
72
0.748044
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,773
admc_test_manager_edit.h
altlinux_admc/tests/admc_test_manager_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_MANAGER_EDIT_H #define ADMC_TEST_MANAGER_EDIT_H #include "admc_test.h" class ManagerEdit; class QPushButton; class QLineEdit; class ADMCTestManagerEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void load_empty(); void load(); void apply_unmodified(); void apply_after_change(); void apply_after_clear(); void properties(); private: ManagerEdit *edit; QString dn; QString manager_dn; QPushButton *change_button; QPushButton *clear_button; QPushButton *properties_button; QLineEdit *manager_display; }; #endif /* ADMC_TEST_MANAGER_EDIT_H */
1,423
C++
.h
45
28.711111
72
0.741606
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,774
admc_test_group_type_edit.h
altlinux_admc/tests/admc_test_group_type_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_GROUP_TYPE_EDIT_H #define ADMC_TEST_GROUP_TYPE_EDIT_H #include "admc_test.h" class GroupTypeEdit; class QComboBox; class ADMCTestGroupTypeEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void edited_signal(); void load(); void apply_unmodified(); void apply(); private: GroupTypeEdit *edit; QString dn; QComboBox *combo; }; #endif /* ADMC_TEST_GROUP_TYPE_EDIT_H */
1,223
C++
.h
38
29.552632
72
0.742566
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,775
admc_test_number_attribute_dialog.h
altlinux_admc/tests/admc_test_number_attribute_dialog.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_NUMBER_ATTRIBUTE_DIALOG_H #define ADMC_TEST_NUMBER_ATTRIBUTE_DIALOG_H #include "admc_test.h" class NumberAttributeDialog; class QLineEdit; class ADMCTestNumberAttributeDialog : public ADMCTest { Q_OBJECT private slots: void display_value_data(); void display_value(); void get_value_list_data(); void get_value_list(); void validate_data(); void validate(); private: NumberAttributeDialog *dialog; QLineEdit *line_edit; void init_edit(const QList<QByteArray> &value_list); }; #endif /* ADMC_TEST_NUMBER_ATTRIBUTE_DIALOG_H */
1,365
C++
.h
39
32.307692
72
0.751897
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,776
admc_test_filter_widget.h
altlinux_admc/tests/admc_test_filter_widget.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_FILTER_WIDGET_H #define ADMC_TEST_FILTER_WIDGET_H #include "admc_test.h" class FilterWidget; class QTabWidget; class FilterWidgetSimpleTab; class FilterWidgetNormalTab; class FilterWidgetAdvancedTab; class ADMCTestFilterWidget : public ADMCTest { Q_OBJECT private slots: void init() override; void test_simple_tab(); void test_normal_tab(); void test_advanced_tab(); private: FilterWidget *filter_widget; QTabWidget *tab_widget; FilterWidgetSimpleTab *simple_tab; FilterWidgetNormalTab *normal_tab; FilterWidgetAdvancedTab *advanced_tab; }; #endif /* ADMC_TEST_FILTER_WIDGET_H */
1,420
C++
.h
42
31.238095
72
0.764964
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,777
admc_test_rename_object_dialog.h
altlinux_admc/tests/admc_test_rename_object_dialog.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_RENAME_OBJECT_DIALOG_H #define ADMC_TEST_RENAME_OBJECT_DIALOG_H #include "admc_test.h" class ADMCTestRenameObjectDialog : public ADMCTest { Q_OBJECT private slots: void rename(); void rename_user_autofill(); void trim(); }; #endif /* ADMC_TEST_RENAME_OBJECT_DIALOG_H */
1,083
C++
.h
30
33.8
72
0.750954
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,778
admc_test_password_edit.h
altlinux_admc/tests/admc_test_password_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_PASSWORD_EDIT_H #define ADMC_TEST_PASSWORD_EDIT_H #include "admc_test.h" class PasswordEdit; class QLineEdit; class ADMCTestPasswordEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void edited_signal(); void load(); void verify_data(); void verify(); void apply(); private: PasswordEdit *edit; QString dn; QLineEdit *main_edit; QLineEdit *confirm_edit; }; #endif /* ADMC_TEST_PASSWORD_EDIT_H */
1,261
C++
.h
40
28.775
72
0.738664
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,779
admc_test_dn_edit.h
altlinux_admc/tests/admc_test_dn_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_DN_EDIT_H #define ADMC_TEST_DN_EDIT_H #include "admc_test.h" class DNEdit; class QLineEdit; class ADMCTestDNEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void load(); private: DNEdit *edit; QLineEdit *line_edit; QString dn; }; #endif /* ADMC_TEST_DN_EDIT_H */
1,109
C++
.h
35
29.257143
72
0.742026
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,780
admc_test_expiry_edit.h
altlinux_admc/tests/admc_test_expiry_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_EXPIRY_EDIT_H #define ADMC_TEST_EXPIRY_EDIT_H #include "admc_test.h" class ExpiryEdit; class QRadioButton; class QDateEdit; class ADMCTestExpiryEdit : public ADMCTest { Q_OBJECT private slots: void initTestCase_data(); void init() override; void edited_signal(); void load(); void apply_unmodified(); void apply(); private: ExpiryEdit *edit; QString dn; QRadioButton *button; QDateEdit *date_edit; }; #endif /* ADMC_TEST_EXPIRY_EDIT_H */
1,282
C++
.h
41
28.560976
72
0.741281
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,781
admc_test_ad_interface.h
altlinux_admc/tests/admc_test_ad_interface.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_AD_INTERFACE_H #define ADMC_TEST_AD_INTERFACE_H #include "admc_test.h" class ADMCTestAdInterface : public ADMCTest { Q_OBJECT private slots: void cleanup() override; void create_and_gpo_delete(); void gpo_check_perms(); void object_add(); void object_delete(); void object_move(); void object_rename(); void group_add_member(); void group_remove_member(); void group_set_scope(); void group_set_type(); void user_set_account_option(); private: }; #endif /* ADMC_TEST_AD_INTERFACE_H */
1,339
C++
.h
40
30.475
72
0.728472
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,782
admc_test_octet_attribute_dialog.h
altlinux_admc/tests/admc_test_octet_attribute_dialog.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_OCTET_EDIT_H #define ADMC_TEST_OCTET_EDIT_H #include "admc_test.h" class OctetAttributeDialog; class QComboBox; class QPlainTextEdit; class ADMCTestOctetAttributeDialog : public ADMCTest { Q_OBJECT private slots: void initTestCase_data(); void init(); void display_value(); void get_value_list(); void handle_incorrect_input(); private: OctetAttributeDialog *dialog; QComboBox *format_combo; QPlainTextEdit *text_edit; }; #endif /* ADMC_TEST_OCTET_EDIT_H */
1,294
C++
.h
39
30.589744
72
0.753007
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,783
admc_test_delegation_edit.h
altlinux_admc/tests/admc_test_delegation_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_DELEGATION_EDIT_H #define ADMC_TEST_DELEGATION_EDIT_H #include "admc_test.h" class DelegationEdit; class QRadioButton; class ADMCTestDelegationEdit : public ADMCTest { Q_OBJECT private slots: void initTestCase_data(); void init() override; void emit_edited_signal(); void load(); void apply_unmodified(); void apply(); private: QString dn; DelegationEdit *edit; QRadioButton *button; }; #endif /* ADMC_TEST_DELEGATION_EDIT_H */
1,268
C++
.h
39
29.820513
72
0.74611
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,784
admc_test_account_option_edit.h
altlinux_admc/tests/admc_test_account_option_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_ACCOUNT_OPTION_H #define ADMC_TEST_ACCOUNT_OPTION_H #include "admc_test.h" #include "ad_defines.h" class QCheckBox; class AccountOptionEdit; class ADMCTestAccountOptionEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void test_emit_edited_signal(); void load_data(); void load(); void apply_data(); void apply(); void conflicts_data(); void conflicts(); private: QMap<AccountOption, AccountOptionEdit *> edit_map; QHash<AccountOption, QCheckBox *> check_map; QString dn; }; #endif /* ADMC_TEST_ACCOUNT_OPTION_H */
1,385
C++
.h
42
30.190476
72
0.74063
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,785
admc_test_members_tab.h
altlinux_admc/tests/admc_test_members_tab.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_MEMBERS_TAB_H #define ADMC_TEST_MEMBERS_TAB_H #include "admc_test.h" class QTreeView; class AttributeEdit; class QStandardItemModel; class QPushButton; class ADMCTestMembersTab : public ADMCTest { Q_OBJECT private slots: void init() override; void load_empty(); void load(); void remove(); void add(); private: AttributeEdit *edit; QTreeView *view; QStandardItemModel *model; QString user_dn; QString group_dn; QPushButton *add_button; QPushButton *remove_button; }; #endif /* ADMC_TEST_MEMBERS_TAB_H */
1,356
C++
.h
44
28.045455
72
0.743865
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,786
admc_test_edit_query_item_widget.h
altlinux_admc/tests/admc_test_edit_query_item_widget.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_EDIT_QUERY_ITEM_WIDGET_H #define ADMC_TEST_EDIT_QUERY_ITEM_WIDGET_H #include "admc_test.h" class EditQueryItemWidget; class QLineEdit; class QCheckBox; class QComboBox; class QPushButton; class QTextEdit; class ADMCTestEditQueryItemWidget : public ADMCTest { Q_OBJECT private slots: void init() override; void save_and_load(); private: EditQueryItemWidget *widget; QLineEdit *name_edit; QLineEdit *description_edit; QCheckBox *scope_checkbox; QComboBox *base_combo; QPushButton *edit_filter_button; QTextEdit *filter_display; }; #endif /* ADMC_TEST_EDIT_QUERY_ITEM_WIDGET_H */
1,417
C++
.h
43
30.418605
72
0.761347
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,787
admc_test_logon_computers_edit.h
altlinux_admc/tests/admc_test_logon_computers_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_LOGON_COMPUTERS_EDIT_H #define ADMC_TEST_LOGON_COMPUTERS_EDIT_H #include "admc_test.h" class LogonComputersEdit; class LogonComputersDialog; class QPushButton; class QListWidget; class ADMCTestLogonComputersEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void load_empty(); void load(); void emit_edited_signal(); void add(); void remove(); void apply_unmodified(); void apply(); private: LogonComputersEdit *edit; LogonComputersDialog *dialog; QListWidget *list; QLineEdit *value_edit; QPushButton *open_dialog_button; QPushButton *add_button; QPushButton *remove_button; QString dn; void test_list_item(const int row, const QString &text); void load_and_open_dialog(); void open_dialog(); }; #endif /* ADMC_TEST_LOGON_COMPUTERS_EDIT_H */
1,644
C++
.h
51
29.137255
72
0.741162
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,788
admc_test_gpoptions_edit.h
altlinux_admc/tests/admc_test_gpoptions_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_GPOPTIONS_EDIT_H #define ADMC_TEST_GPOPTIONS_EDIT_H #include "admc_test.h" class GpoptionsEdit; class QCheckBox; class ADMCTestGpoptionsEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void test_emit_edited_signal(); void load(); void apply(); private: GpoptionsEdit *edit; QCheckBox *check; QString dn; }; #endif /* ADMC_TEST_GPOPTIONS_EDIT_H */
1,201
C++
.h
37
29.891892
72
0.74654
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,789
admc_test_string_other_edit.h
altlinux_admc/tests/admc_test_string_other_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_STRING_OTHER_EDIT_H #define ADMC_TEST_STRING_OTHER_EDIT_H #include "admc_test.h" class StringOtherEdit; class QLineEdit; class QPushButton; class ADMCTestStringOtherEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void test_emit_edited_signal(); void load(); void apply_unmodified(); void apply_modified_main_value(); void apply_modified_other_value(); private: StringOtherEdit *edit; QLineEdit *line_edit; QPushButton *other_button; QString dn; void add_new_other_value(); }; #endif /* ADMC_TEST_STRING_OTHER_EDIT_H */
1,391
C++
.h
42
30.333333
72
0.745522
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,790
admc_test_string_attribute_dialog.h
altlinux_admc/tests/admc_test_string_attribute_dialog.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_STRING_EDITOR_H #define ADMC_TEST_STRING_EDITOR_H #include "admc_test.h" class StringAttributeDialog; class QPlainTextEdit; class ADMCTestStringAttributeDialog : public ADMCTest { Q_OBJECT private slots: void display_value_data(); void display_value(); void get_value_list_data(); void get_value_list(); void limit_length(); private: StringAttributeDialog *dialog; QPlainTextEdit *text_edit; void init_edit(const QList<QByteArray> &value_list); }; #endif /* ADMC_TEST_STRING_EDITOR_H */
1,323
C++
.h
38
32.184211
72
0.752545
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,791
admc_test_select_base_widget.h
altlinux_admc/tests/admc_test_select_base_widget.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_SELECT_BASE_WIDGET_H #define ADMC_TEST_SELECT_BASE_WIDGET_H #include "admc_test.h" class QComboBox; class QPushButton; class SelectBaseWidget; class ADMCTestSelectBaseWidget : public ADMCTest { Q_OBJECT private slots: void init() override; void default_to_domain_dn(); void select_base(); void no_duplicates(); void select_base_of_already_added(); void select_base_multiple(); void save_state(); private: SelectBaseWidget *select_base_widget; QComboBox *combo; QList<QString> dn_list; }; #endif /* ADMC_TEST_SELECT_BASE_WIDGET_H */
1,376
C++
.h
41
30.853659
72
0.746797
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,792
admc_test_group_scope_edit.h
altlinux_admc/tests/admc_test_group_scope_edit.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_GROUP_SCOPE_EDIT_H #define ADMC_TEST_GROUP_SCOPE_EDIT_H #include "admc_test.h" class GroupScopeEdit; class QComboBox; class ADMCTestGroupScopeEdit : public ADMCTest { Q_OBJECT private slots: void init() override; void edited_signal(); void load(); void apply_unmodified(); void apply(); private: GroupScopeEdit *edit; QString dn; QComboBox *combo; }; #endif /* ADMC_TEST_GROUP_SCOPE_EDIT_H */
1,229
C++
.h
38
29.710526
72
0.743872
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,793
admc_test.h
altlinux_admc/tests/admc_test.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_H #define ADMC_TEST_H /** * Base test class for testing ADMC. Implements init and * cleanup f-ns that create a fresh testing environment for * each test. */ #include <QTest> #include "adldap.h" class QTreeView; class SelectObjectDialog; class SelectBaseWidget; class QFormLayout; class AttributeEdit; #define TEST_USER "ADMCTEST-test-user" #define TEST_USER_LOGON "ADMCTEST-test-user-logon" #define TEST_PASSWORD "ADMCTEST-pass123!" #define TEST_OU "ADMCTEST-test-ou" #define TEST_GROUP "ADMCTEST-test-group" // NOTE: use shorter length for computer to fit within // 16 char length limit for sam account name #define TEST_COMPUTER "ADMCTEST-pc" #define TEST_OBJECT "ADMCTEST-object" class ADMCTest : public QObject { Q_OBJECT public slots: // NOTE: initTestCase(), cleanupTestCase(), init() and // cleanup() are special slots called by QTest. // Called before first test virtual void initTestCase(); // Called after last test virtual void cleanupTestCase(); // Called before and after each test virtual void init(); virtual void cleanup(); protected: AdInterface ad; // Use this as parents for widgets used inside tests. // For every test a new parent will be created and after // test completes, parent is deleted which deletes all // child widgets as well. QWidget *parent_widget = nullptr; // This list is just for passing to edit ctors QList<AttributeEdit *> edits; // For easy setup and cleanup of each test, we use an // object named "test-arena" which is an OU. It is // created before every test and deleted after every // test. All test activity should happen inside this // object. QString test_arena_dn(); // Creates dn for object with given name whose parent is // test arena. Class is used to determine suffix. QString test_object_dn(const QString &name, const QString &object_class); // Tests object's existance on the server. bool object_exists(const QString &dn); // Call this after pressing "Find" button. Needed // because find results are loaded in separate thread. void wait_for_find_results_to_load(QTreeView *view); void select_in_select_dialog(SelectObjectDialog *select_dialog, const QString &dn); // This is for closing message boxes opened using // open(). Won't work for QMessageBox static f-ns void close_message_box(); bool message_box_is_open() const; // Selects an object via an already open select object // dialog. Object must be inside test arena void select_object_dialog_select(const QString &dn); // Adds a widget to layout in parent widget void add_widget(QWidget *widget); void test_edit_apply_unmodified(AttributeEdit *edit, const QString &dn); // Add a base to the base combo. Note that it is also // automatically selected. void select_base_widget_add(SelectBaseWidget *widget, const QString &dn); private: QFormLayout *layout; }; void navigate_until_object(QTreeView *view, const QString &target_dn, const int dn_role); void test_lineedit_autofill(QLineEdit *src_edit, QLineEdit *dest_edit); #endif /* ADMC_TEST_H */
3,971
C++
.h
97
37.494845
89
0.737198
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,794
admc_test_select_object_dialog.h
altlinux_admc/tests/admc_test_select_object_dialog.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_SELECT_OBJECT_DIALOG_H #define ADMC_TEST_SELECT_OBJECT_DIALOG_H #include "admc_test.h" class QLineEdit; class QPushButton; class SelectObjectDialog; class ADMCTestSelectObjectDialog : public ADMCTest { Q_OBJECT private slots: void init() override; void empty(); void no_matches(); void one_match(); void multiple_matches(); void one_match_duplicate(); void multiple_match_duplicate(); private: SelectObjectDialog *dialog; QLineEdit *edit; QPushButton *add_button; void select_object_in_multi_match_dialog(const QString &name, const QString &dn); }; #endif /* ADMC_TEST_SELECT_OBJECT_DIALOG_H */
1,444
C++
.h
42
31.595238
85
0.749462
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,795
admc_test_attributes_tab.h
altlinux_admc/tests/admc_test_attributes_tab.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_ATTRIBUTES_TAB_H #define ADMC_TEST_ATTRIBUTES_TAB_H #include "admc_test.h" #include "settings.h" #include "tabs/attributes_tab.h" #include "tabs/attributes_tab_filter_menu.h" class QStandardItemModel; class QSortFilterProxyModel; class QPushButton; class QTreeView; class AttributesFilterMenu; class ADMCTestAttributesTab : public ADMCTest { Q_OBJECT private slots: void init() override; void cleanup() override; void apply(); void load(); void filter_data(); void filter(); private: AttributeEdit *edit; AttributesTabFilterMenu *filter_menu; QTreeView *view; QStandardItemModel *model; QSortFilterProxyModel *proxy; QPushButton *filter_button; QPushButton *edit_button; QString dn; QList<AttributeEdit *> edit_list; QPushButton *load_optional_attrs_button; void set_filter(const QList<AttributeFilter> &filter_list, const bool state); }; #endif /* ADMC_TEST_ATTRIBUTES_TAB_H */
1,753
C++
.h
53
30.188679
81
0.755621
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,796
admc_test_datetime_attribute_dialog.h
altlinux_admc/tests/admc_test_datetime_attribute_dialog.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_DATE_TIME_EDITOR_H #define ADMC_TEST_DATE_TIME_EDITOR_H #include "admc_test.h" class DatetimeAttributeDialog; class QDateTimeEdit; class ADMCTestDatetimeAttributeDialog : public ADMCTest { Q_OBJECT private slots: void initTestCase_data(); void init(); void display_value(); void get_value_list(); private: DatetimeAttributeDialog *dialog; QDateTimeEdit *datetime_edit; }; #endif /* ADMC_TEST_DATE_TIME_EDITOR_H */
1,242
C++
.h
36
32
72
0.757095
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,797
admc_test_policy_results_widget.h
altlinux_admc/tests/admc_test_policy_results_widget.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef ADMC_TEST_POLICY_RESULTS_WIDGET_H #define ADMC_TEST_POLICY_RESULTS_WIDGET_H #include "admc_test.h" class PolicyResultsWidget; class QTreeView; class QStandardItemModel; class ADMCTestPolicyResultsWidget : public ADMCTest { Q_OBJECT private slots: void initTestCase() override; void cleanupTestCase() override; void init() override; void load_empty(); void load(); void delete_link(); private: PolicyResultsWidget *widget; QTreeView *view; QStandardItemModel *model; QString gpo; }; #endif /* ADMC_TEST_POLICY_RESULTS_WIDGET_H */
1,364
C++
.h
41
30.536585
72
0.754947
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538,798
tab_widget.h
altlinux_admc/src/admc/tab_widget.h
/* * ADMC - AD Management Center * * Copyright (C) 2020-2022 BaseALT Ltd. * Copyright (C) 2020-2022 Dmitry Degtyarev * * 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/>. */ #ifndef TAB_WIDGET_H #define TAB_WIDGET_H /** * Shows tabs in a horizontal list to the left and current * tab to the right. Used as a replacement for QTabWidget * because it doesn't have multi-line tabs. */ #include <QWidget> namespace Ui { class TabWidget; } class TabWidget final : public QWidget { Q_OBJECT public: Ui::TabWidget *ui; TabWidget(QWidget *parent = nullptr); ~TabWidget(); QWidget *get_tab(const int index) const; QWidget *get_current_tab() const; void set_current_tab(const int index); void add_tab(QWidget *tab, const QString &title); // By default tab is automatically switches when // user selects different tab in tab list. If this // is disabled, then parent widget needs to connect // to current_changed() signal and manually change // tab using set_current_tab(). This is useful in // cases where you want to forbid switching tabs. void enable_auto_switch_tab(const bool enabled); signals: void current_changed(const int prev, const int current); private: void on_list_current_row_changed(int index); bool auto_switch_tab; bool ignore_current_row_signal; }; #endif /* TAB_WIDGET_H */
1,974
C++
.h
55
32.890909
72
0.734137
altlinux/admc
36
14
14
GPL-3.0
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false