aboutsummaryrefslogtreecommitdiffstats
path: root/src/ui/main_window/MainWindowFileSlotFunction.cpp
blob: 19be9769e781e63502dc251d912a894729c422f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
/**
 * This file is part of GpgFrontend.
 *
 * GpgFrontend 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.
 *
 * Foobar 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 Foobar.  If not, see <https://www.gnu.org/licenses/>.
 *
 * The initial version of the source code is inherited from gpg4usb-team.
 * Their source code version also complies with GNU General Public License.
 *
 * The source code version of this software was modified and released
 * by Saturneric<[email protected]> starting on May 12, 2021.
 *
 */

#include "MainWindow.h"
#include "gpg/function/GpgFileOpera.h"
#include "gpg/function/GpgKeyGetter.h"
#include "ui/UserInterfaceUtils.h"
#include "ui/widgets/SignersPicker.h"

namespace GpgFrontend::UI {

bool file_pre_check(QWidget* parent, const QString& path) {
  QFileInfo file_info(path);
  QFileInfo path_info(file_info.absolutePath());
  if (!file_info.isFile()) {
    QMessageBox::critical(parent, _("Error"),
                          _("Select a file before doing it."));
    return false;
  }
  if (!file_info.isReadable()) {
    QMessageBox::critical(parent, _("Error"),
                          _("No permission to read this file."));
    return false;
  }
  if (!path_info.isWritable()) {
    QMessageBox::critical(parent, _("Error"),
                          _("No permission to create file."));
    return false;
  }
  return true;
}

void MainWindow::slotFileEncrypt() {
  auto fileTreeView = edit->slotCurPageFileTreeView();
  auto path = fileTreeView->getSelected();

  if (!file_pre_check(this, path)) return;

  if (QFile::exists(path + ".asc")) {
    auto ret = QMessageBox::warning(
        this, _("Warning"),
        _("The target file already exists, do you need to overwrite it?"),
        QMessageBox::Ok | QMessageBox::Cancel);

    if (ret == QMessageBox::Cancel) return;
  }

  auto key_ids = mKeyList->getChecked();
  auto keys = GpgKeyGetter::GetInstance().GetKeys(key_ids);
  if (keys->empty()) {
    QMessageBox::critical(this, _("No Key Selected"), _("No Key Selected"));
    return;
  }

  for (const auto& key : *keys) {
    if (!key.CanEncrActual()) {
      QMessageBox::information(
          this, _("Invalid Operation"),
          QString(
              _("The selected key contains a key that does not actually have a "
                "encrypt usage.")) +
              "<br/><br/>" + _("For example the Following Key:") + " <br/>" +
              QString::fromStdString(key.uids()->front().uid()));
      return;
    }
  }

  GpgEncrResult result = nullptr;
  GpgError error;
  bool if_error = false;
  process_operation(this, _("Encrypting"), [&]() {
    try {
      error = GpgFileOpera::EncryptFile(std::move(keys), path.toStdString(),
                                        result);
    } catch (const std::runtime_error& e) {
      if_error = true;
    }
  });

  if (!if_error) {
    auto resultAnalyse = EncryptResultAnalyse(error, std::move(result));
    resultAnalyse.analyse();
    process_result_analyse(edit, infoBoard, resultAnalyse);
    fileTreeView->update();
  } else {
    QMessageBox::critical(this, _("Error"),
                          _("An error occurred during operation."));
    return;
  }
}

void MainWindow::slotFileDecrypt() {
  auto fileTreeView = edit->slotCurPageFileTreeView();
  auto path = fileTreeView->getSelected();

  if (!file_pre_check(this, path)) return;

  QString outFileName, fileExtension = QFileInfo(path).suffix();

  if (fileExtension == "asc" || fileExtension == "gpg") {
    int pos = path.lastIndexOf(QChar('.'));
    outFileName = path.left(pos);
  } else {
    outFileName = path + ".out";
  }

  if (QFile::exists(outFileName)) {
    auto ret = QMessageBox::warning(
        this, _("Warning"),
        _("The target file already exists, do you need to overwrite it?"),
        QMessageBox::Ok | QMessageBox::Cancel);

    if (ret == QMessageBox::Cancel) return;
  }

  GpgDecrResult result = nullptr;
  gpgme_error_t error;
  bool if_error = false;
  process_operation(this, _("Decrypting"), [&]() {
    try {
      error = GpgFileOpera::DecryptFile(path.toStdString(), result);
    } catch (const std::runtime_error& e) {
      if_error = true;
    }
  });

  if (!if_error) {
    auto resultAnalyse = DecryptResultAnalyse(error, std::move(result));
    resultAnalyse.analyse();
    process_result_analyse(edit, infoBoard, resultAnalyse);

    fileTreeView->update();
  } else {
    QMessageBox::critical(this, _("Error"),
                          _("An error occurred during operation."));
    return;
  }
}

void MainWindow::slotFileSign() {
  auto fileTreeView = edit->slotCurPageFileTreeView();
  auto path = fileTreeView->getSelected();

  if (!file_pre_check(this, path)) return;

  auto key_ids = mKeyList->getChecked();
  auto keys = GpgKeyGetter::GetInstance().GetKeys(key_ids);

  if (keys->empty()) {
    QMessageBox::critical(this, _("No Key Selected"), _("No Key Selected"));
    return;
  }

  for (const auto& key : *keys) {
    if (!key.CanSignActual()) {
      QMessageBox::information(
          this, _("Invalid Operation"),
          QString(_("The selected key contains a key that does not actually "
                    "have a sign usage.")) +
              "<br/><br/>" + _("for example the Following Key:") + " <br/>" +
              QString::fromStdString(key.uids()->front().uid()));
      return;
    }
  }

  auto sig_file_path = boost::filesystem::path(path.toStdString() + ".sig");
  if (QFile::exists(sig_file_path.string().c_str())) {
    auto ret = QMessageBox::warning(
        this, _("Warning"),
        QString(_("The signature file \"%1\" exists, "
                  "do you need to overwrite it?"))
            .arg(sig_file_path.filename().string().c_str()),
        QMessageBox::Ok | QMessageBox::Cancel);

    if (ret == QMessageBox::Cancel) return;
  }

  GpgSignResult result = nullptr;
  gpgme_error_t error;
  bool if_error = false;

  process_operation(this, _("Signing"), [&]() {
    try {
      error =
          GpgFileOpera::SignFile(std::move(keys), path.toStdString(), result);
    } catch (const std::runtime_error& e) {
      if_error = true;
    }
  });

  if (!if_error) {
    auto resultAnalyse = SignResultAnalyse(error, std::move(result));
    resultAnalyse.analyse();
    process_result_analyse(edit, infoBoard, resultAnalyse);

    fileTreeView->update();

  } else {
    QMessageBox::critical(this, _("Error"),
                          _("An error occurred during operation."));
    return;
  }

  fileTreeView->update();
}

void MainWindow::slotFileVerify() {
  auto fileTreeView = edit->slotCurPageFileTreeView();
  auto path = fileTreeView->getSelected();

  QFileInfo fileInfo(path);

  QString signFilePath, dataFilePath;

  if (fileInfo.suffix() == "gpg") {
    dataFilePath = path;
    signFilePath = path;
  } else if (fileInfo.suffix() == "sig") {
    int pos = path.lastIndexOf(QChar('.'));
    dataFilePath = path.left(pos);
    signFilePath = path;
  } else {
    dataFilePath = path;
    signFilePath = path + ".sig";
  }

  bool ok;
  QString text =
      QInputDialog::getText(this, _("Origin file to verify"), _("Filepath"),
                            QLineEdit::Normal, dataFilePath, &ok);
  if (ok && !text.isEmpty()) {
    dataFilePath = text;
  } else {
    return;
  }

  QFileInfo dataFileInfo(dataFilePath), signFileInfo(signFilePath);

  if (!dataFileInfo.isFile() || !signFileInfo.isFile()) {
    QMessageBox::critical(
        this, _("Error"),
        _("Please select the appropriate origin file or signature file. "
          "Ensure that both are in this directory."));
    return;
  }
  if (!dataFileInfo.isReadable()) {
    QMessageBox::critical(this, _("Error"),
                          _("No permission to read target file."));
    return;
  }
  if (!fileInfo.isReadable()) {
    QMessageBox::critical(this, _("Error"),
                          _("No permission to read signature file."));
    return;
  }

  GpgVerifyResult result = nullptr;
  gpgme_error_t error;
  bool if_error = false;
  process_operation(this, _("Verifying"), [&]() {
    try {
      error = GpgFileOpera::VerifyFile(dataFilePath.toStdString(), result);
    } catch (const std::runtime_error& e) {
      if_error = true;
    }
  });

  if (!if_error) {
    auto result_analyse = VerifyResultAnalyse(error, std::move(result));
    result_analyse.analyse();
    process_result_analyse(edit, infoBoard, result_analyse);

    if (result_analyse.getStatus() == -2)
      import_unknown_key_from_keyserver(this, result_analyse);

    if (result_analyse.getStatus() >= 0)
      show_verify_details(this, infoBoard, error, result_analyse);

    fileTreeView->update();
  } else {
    QMessageBox::critical(this, _("Error"),
                          _("An error occurred during operation."));
    return;
  }
}

void MainWindow::slotFileEncryptSign() {
  auto fileTreeView = edit->slotCurPageFileTreeView();
  auto path = fileTreeView->getSelected();

  if (!file_pre_check(this, path)) return;

  if (QFile::exists(path + ".gpg")) {
    auto ret = QMessageBox::warning(
        this, _("Warning"),
        _("The target file already exists, do you need to overwrite it?"),
        QMessageBox::Ok | QMessageBox::Cancel);

    if (ret == QMessageBox::Cancel) return;
  }

  auto key_ids = mKeyList->getChecked();
  auto p_keys = GpgKeyGetter::GetInstance().GetKeys(key_ids);

  if (p_keys->empty()) {
    QMessageBox::critical(this, _("No Key Selected"), _("No Key Selected"));
    return;
  }

  for (const auto& key : *p_keys) {
    bool key_can_encrypt = key.CanEncrActual();

    if (!key_can_encrypt) {
      QMessageBox::critical(
          nullptr, _("Invalid KeyPair"),
          QString(_("The selected keypair cannot be used for encryption.")) +
              "<br/><br/>" + _("For example the Following Key:") + " <br/>" +
              QString::fromStdString(key.uids()->front().uid()));
      return;
    }
  }

  auto signersPicker = new SignersPicker(this);
  QEventLoop loop;
  connect(signersPicker, SIGNAL(finished(int)), &loop, SLOT(quit()));
  loop.exec();

  auto signer_key_ids = signersPicker->getCheckedSigners();
  auto p_signer_keys = GpgKeyGetter::GetInstance().GetKeys(signer_key_ids);

  for (const auto& key : *p_keys) {
    LOG(INFO) << "Keys " << key.email();
  }

  for (const auto& signer : *p_signer_keys) {
    LOG(INFO) << "Signers " << signer.email();
  }

  GpgEncrResult encr_result = nullptr;
  GpgSignResult sign_result = nullptr;

  gpgme_error_t error;
  bool if_error = false;

  process_operation(this, _("Encrypting and Signing"), [&]() {
    try {
      error = GpgFileOpera::EncryptSignFile(
          std::move(p_keys), std::move(p_signer_keys), path.toStdString(),
          encr_result, sign_result);
    } catch (const std::runtime_error& e) {
      if_error = true;
    }
  });

  if (!if_error) {
    auto encrypt_res = EncryptResultAnalyse(error, std::move(encr_result));
    auto sign_res = SignResultAnalyse(error, std::move(sign_result));
    encrypt_res.analyse();
    sign_res.analyse();
    process_result_analyse(edit, infoBoard, encrypt_res, sign_res);

    fileTreeView->update();

  } else {
    QMessageBox::critical(this, _("Error"),
                          _("An error occurred during operation."));
    return;
  }
}

void MainWindow::slotFileDecryptVerify() {
  auto fileTreeView = edit->slotCurPageFileTreeView();
  auto path = fileTreeView->getSelected();

  if (!file_pre_check(this, path)) return;

  QString outFileName, fileExtension = QFileInfo(path).suffix();

  if (fileExtension == "asc" || fileExtension == "gpg") {
    int pos = path.lastIndexOf(QChar('.'));
    outFileName = path.left(pos);
  } else {
    outFileName = path + ".out";
  }

  GpgDecrResult d_result = nullptr;
  GpgVerifyResult v_result = nullptr;
  gpgme_error_t error;
  bool if_error = false;
  process_operation(this, _("Decrypting and Verifying"), [&]() {
    try {
      error = GpgFileOpera::DecryptVerifyFile(path.toStdString(), d_result,
                                              v_result);
    } catch (const std::runtime_error& e) {
      if_error = true;
    }
  });

  if (!if_error) {
    auto decrypt_res = DecryptResultAnalyse(error, std::move(d_result));
    auto verify_res = VerifyResultAnalyse(error, std::move(v_result));
    decrypt_res.analyse();
    verify_res.analyse();
    process_result_analyse(edit, infoBoard, decrypt_res, verify_res);

    if (verify_res.getStatus() == -2)
      import_unknown_key_from_keyserver(this, verify_res);

    if (verify_res.getStatus() >= 0)
      show_verify_details(this, infoBoard, error, verify_res);

    fileTreeView->update();
  } else {
    QMessageBox::critical(this, _("Error"),
                          _("An error occurred during operation."));
    return;
  }
}

void MainWindow::slotFileEncryptCustom() {
  new FileEncryptionDialog(mKeyList->getChecked(),
                           FileEncryptionDialog::Encrypt, this);
}

void MainWindow::slotFileDecryptCustom() {
  new FileEncryptionDialog(mKeyList->getChecked(),
                           FileEncryptionDialog::Decrypt, this);
}

void MainWindow::slotFileSignCustom() {
  new FileEncryptionDialog(mKeyList->getChecked(), FileEncryptionDialog::Sign,
                           this);
}

void MainWindow::slotFileVerifyCustom() {
  new FileEncryptionDialog(mKeyList->getChecked(), FileEncryptionDialog::Verify,
                           this);
}

}  // namespace GpgFrontend::UI