aboutsummaryrefslogtreecommitdiffstats
path: root/src/ui/main_window/MainWindowGpgOperaFunction.cpp
blob: dc65fd1cb948308406bb601ae5bb3e81ec666232 (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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/**
 * Copyright (C) 2021-2024 Saturneric <[email protected]>
 *
 * 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.
 *
 * GpgFrontend 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 GpgFrontend. If not, see <https://www.gnu.org/licenses/>.
 *
 * The initial version of the source code is inherited from
 * the gpg4usb project, which is under GPL-3.0-or-later.
 *
 * All the source code of GpgFrontend was modified and released by
 * Saturneric <[email protected]> starting on May 12, 2021.
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 */

#include "MainWindow.h"
#include "core/function/GlobalSettingStation.h"
#include "core/function/gpg/GpgKeyGetter.h"
#include "core/utils/GpgUtils.h"
#include "core/utils/IOUtils.h"
#include "ui/UserInterfaceUtils.h"
#include "ui/dialog/SignersPicker.h"
#include "ui/function/GpgOperaHelper.h"
#include "ui/struct/GpgOperaResultContext.h"
#include "ui/widgets/KeyList.h"
#include "ui/widgets/TextEdit.h"

namespace GpgFrontend::UI {

auto MainWindow::encrypt_operation_key_validate(
    const QSharedPointer<GpgOperaContextBasement>& contexts) -> bool {
  auto key_ids = m_key_list_->GetChecked();

  // symmetric encryption
  if (key_ids.isEmpty()) {
    auto ret = QMessageBox::information(
        this, tr("Symmetric Encryption"),
        tr("No Key Selected. Do you want to encrypt with a "
           "symmetric cipher using a passphrase?"),
        QMessageBox::Ok | QMessageBox::Cancel);
    if (ret == QMessageBox::Cancel) return false;

    contexts->keys = {};
  } else {
    contexts->keys = check_keys_helper(
        key_ids, [](const GpgKey& key) { return key.IsHasActualEncrCap(); },
        tr("The selected keypair cannot be used for encryption."));
    if (contexts->keys.empty()) return false;
  }

  return true;
}

auto MainWindow::sign_operation_key_validate(
    const QSharedPointer<GpgOperaContextBasement>& contexts) -> bool {
  auto* signers_picker =
      new SignersPicker(m_key_list_->GetCurrentGpgContextChannel(), this);
  QEventLoop loop;
  connect(signers_picker, &SignersPicker::finished, &loop, &QEventLoop::quit);
  loop.exec();

  // return when canceled
  if (!signers_picker->GetStatus()) return false;

  auto signer_key_ids = signers_picker->GetCheckedSigners();
  auto signer_keys =
      GpgKeyGetter::GetInstance(m_key_list_->GetCurrentGpgContextChannel())
          .GetKeys(signer_key_ids);
  assert(std::all_of(signer_keys.begin(), signer_keys.end(),
                     [](const auto& key) { return key.IsGood(); }));

  contexts->singer_keys = signer_keys;

  return true;
}

auto MainWindow::check_read_file_paths_helper(const QStringList& paths)
    -> bool {
  QStringList invalid_files;
  for (const auto& path : paths) {
    auto result = TargetFilePreCheck(path, true);
    if (!std::get<0>(result)) {
      invalid_files.append(path);
    }
  }

  if (!invalid_files.empty()) {
    QString error_file_names;
    for (const auto& file_path : invalid_files) {
      error_file_names += QFileInfo(file_path).fileName() + "\n";
    }

    QMessageBox::critical(this, tr("Error"),
                          tr("Cannot read from the following files:\n\n%1")
                              .arg(error_file_names.trimmed()));
    return false;
  }

  return true;
}

auto MainWindow::check_write_file_paths_helper(const QStringList& o_paths)
    -> bool {
  for (const auto& o_path : o_paths) {
    if (QFile::exists(o_path)) {
      auto out_file_name = tr("The target file %1 already exists, "
                              "do you need to overwrite it?")
                               .arg(QFileInfo(o_path).fileName());
      auto ret = QMessageBox::warning(this, tr("Warning"), out_file_name,
                                      QMessageBox::Ok | QMessageBox::Cancel);

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

  QStringList invalid_output_files;
  for (const auto& path : o_paths) {
    auto result = TargetFilePreCheck(path, false);
    if (!std::get<0>(result)) {
      invalid_output_files.append(path);
    }
  }

  if (!invalid_output_files.empty()) {
    QString error_file_names;
    for (const auto& file_path : invalid_output_files) {
      error_file_names += QFileInfo(file_path).fileName() + "\n";
    }

    QMessageBox::critical(this, tr("Error"),
                          tr("Cannot write to the following files:\n\n%1")
                              .arg(error_file_names.trimmed()));
    return false;
  }

  return true;
}

auto MainWindow::check_keys_helper(
    const KeyIdArgsList& key_ids,
    const std::function<bool(const GpgKey&)>& capability_check,
    const QString& capability_err_string) -> GpgKeyList {
  if (key_ids.empty()) {
    QMessageBox::critical(
        this, tr("No Key Checked"),
        tr("Please check the key in the key toolbox on the right."));
    return {};
  }

  auto keys =
      GpgKeyGetter::GetInstance(m_key_list_->GetCurrentGpgContextChannel())
          .GetKeys(key_ids);
  assert(std::all_of(keys.begin(), keys.end(),
                     [](const auto& key) { return key.IsGood(); }));

  // check key abilities
  for (const auto& key : keys) {
    if (!capability_check(key)) {
      QMessageBox::critical(nullptr, tr("Invalid KeyPair"),
                            capability_err_string + "<br/><br/>" +
                                tr("For example the Following Key:") +
                                " <br/>" + key.UIDs().front().GetUID());
      return {};
    }
  }

  return keys;
}

void MainWindow::SlotEncrypt() {
  if (edit_->CurPageTextEdit() == nullptr) return;

  auto contexts = QSharedPointer<GpgOperaContextBasement>::create();
  contexts->ascii = true;

  if (!encrypt_operation_key_validate(contexts)) return;

  contexts->GetContextBuffer(0).append(GFBuffer(edit_->CurPlainText()));
  GpgOperaHelper::BuildOperas(contexts, 0,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasEncrypt);

  exec_operas_helper(tr("Encrypting"), contexts);
}

void MainWindow::SlotSign() {
  if (edit_->CurPageTextEdit() == nullptr) return;

  auto contexts = QSharedPointer<GpgOperaContextBasement>::create();
  contexts->ascii = true;

  auto key_ids = m_key_list_->GetChecked();
  contexts->keys = check_keys_helper(
      key_ids, [](const GpgKey& key) { return key.IsHasActualSignCap(); },
      tr("The selected key contains a key that does not actually have a "
         "sign usage."));
  if (contexts->keys.empty()) return;

  contexts->GetContextBuffer(0).append(GFBuffer(edit_->CurPlainText()));
  GpgOperaHelper::BuildOperas(contexts, 0,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasSign);

  exec_operas_helper(tr("Signing"), contexts);
}

void MainWindow::SlotDecrypt() {
  if (edit_->CurPageTextEdit() == nullptr) return;

  auto contexts = QSharedPointer<GpgOperaContextBasement>::create();
  contexts->ascii = true;

  contexts->GetContextBuffer(0).append(GFBuffer(edit_->CurPlainText()));
  GpgOperaHelper::BuildOperas(contexts, 0,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasDecrypt);

  exec_operas_helper(tr("Decrypting"), contexts);
}

void MainWindow::SlotVerify() {
  if (edit_->CurPageTextEdit() == nullptr) return;

  auto contexts = QSharedPointer<GpgOperaContextBasement>::create();
  contexts->ascii = true;

  contexts->GetContextBuffer(0).append(GFBuffer(edit_->CurPlainText()));
  GpgOperaHelper::BuildOperas(contexts, 0,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasVerify);

  exec_operas_helper(tr("Verifying"), contexts);

  if (!contexts->unknown_fprs.isEmpty()) {
    slot_verifying_unknown_signature_helper(contexts->unknown_fprs);
  }
}

void MainWindow::SlotEncryptSign() {
  if (edit_->CurPageTextEdit() == nullptr) return;

  auto contexts = QSharedPointer<GpgOperaContextBasement>::create();
  contexts->ascii = true;

  auto key_ids = m_key_list_->GetChecked();
  contexts->keys = check_keys_helper(
      key_ids, [](const GpgKey& key) { return key.IsHasActualEncrCap(); },
      tr("The selected keypair cannot be used for encryption."));
  if (contexts->keys.empty()) return;

  if (!sign_operation_key_validate(contexts)) return;

  contexts->GetContextBuffer(0).append(GFBuffer(edit_->CurPlainText()));
  GpgOperaHelper::BuildOperas(contexts, 0,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasEncryptSign);

  exec_operas_helper(tr("Encrypting and Signing"), contexts);
}

void MainWindow::SlotDecryptVerify() {
  if (edit_->CurPageTextEdit() == nullptr) return;

  auto contexts = QSharedPointer<GpgOperaContextBasement>::create();
  contexts->ascii = true;

  contexts->GetContextBuffer(0).append(GFBuffer(edit_->CurPlainText()));
  GpgOperaHelper::BuildOperas(contexts, 0,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasDecryptVerify);

  exec_operas_helper(tr("Decrypting and Verifying"), contexts);

  if (!contexts->unknown_fprs.isEmpty()) {
    slot_verifying_unknown_signature_helper(contexts->unknown_fprs);
  }
}

void MainWindow::SlotFileEncrypt(const QStringList& paths, bool ascii) {
  auto contexts = QSharedPointer<GpgOperaContextBasement>::create();
  contexts->ascii = ascii;

  if (!encrypt_operation_key_validate(contexts)) return;

  if (!check_read_file_paths_helper(paths)) return;

  for (const auto& path : paths) {
    QFileInfo info(path);
    if (info.isDir()) {
      contexts->GetContextPath(1).append(path);
      contexts->GetContextOutPath(1).append(
          SetExtensionOfOutputFileForArchive(path, kENCRYPT, contexts->ascii));
    } else {
      contexts->GetContextPath(0).append(path);
      contexts->GetContextOutPath(0).append(
          SetExtensionOfOutputFile(path, kENCRYPT, contexts->ascii));
    }
  }

  if (!check_write_file_paths_helper(contexts->GetAllOutPath())) return;

  GpgOperaHelper::BuildOperas(contexts, 0,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasFileEncrypt);

  GpgOperaHelper::BuildOperas(contexts, 1,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasDirectoryEncrypt);

  exec_operas_helper(tr("Encrypting"), contexts);
}

void MainWindow::SlotFileDecrypt(const QStringList& paths) {
  auto contexts = QSharedPointer<GpgOperaContextBasement>::create();

  contexts->ascii = true;

  if (!check_read_file_paths_helper(paths)) return;

  for (const auto& path : paths) {
    QFileInfo info(path);
    const auto extension = info.completeSuffix();

    if (extension == "tar.gpg" || extension == "tar.asc") {
      contexts->GetContextPath(1).append(path);
      contexts->GetContextOutPath(1).append(
          SetExtensionOfOutputFileForArchive(path, kDECRYPT, contexts->ascii));
    } else {
      contexts->GetContextPath(0).append(path);
      contexts->GetContextOutPath(0).append(
          SetExtensionOfOutputFile(path, kDECRYPT, contexts->ascii));
    }
  }

  if (!check_write_file_paths_helper(contexts->GetAllOutPath())) return;

  GpgOperaHelper::BuildOperas(contexts, 0,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasFileDecrypt);

  GpgOperaHelper::BuildOperas(contexts, 1,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasArchiveDecrypt);

  exec_operas_helper(tr("Decrypting"), contexts);
}

void MainWindow::SlotFileSign(const QStringList& paths, bool ascii) {
  auto contexts = QSharedPointer<GpgOperaContextBasement>::create();

  contexts->ascii = ascii;

  auto key_ids = m_key_list_->GetChecked();
  contexts->keys = check_keys_helper(
      key_ids, [](const GpgKey& key) { return key.IsHasActualSignCap(); },
      tr("The selected key contains a key that does not actually have a "
         "sign usage."));
  if (contexts->keys.empty()) return;

  if (!check_read_file_paths_helper(paths)) return;

  for (const auto& path : paths) {
    QFileInfo info(path);
    contexts->GetContextPath(0).append(path);
    contexts->GetContextOutPath(0).append(
        SetExtensionOfOutputFile(path, kSIGN, contexts->ascii));
  }

  if (!check_write_file_paths_helper(contexts->GetAllOutPath())) return;

  GpgOperaHelper::BuildOperas(contexts, 0,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasFileSign);

  exec_operas_helper(tr("Signing"), contexts);
}

void MainWindow::SlotFileVerify(const QStringList& paths) {
  auto contexts = QSharedPointer<GpgOperaContextBasement>::create();

  if (!check_read_file_paths_helper(paths)) return;

  for (const auto& path : paths) {
    QFileInfo info(path);

    QString sign_file_path = path;
    QString data_file_path;

    bool const possible_singleton_target =
        info.suffix() == "gpg" || info.suffix() == "pgp";
    if (possible_singleton_target) {
      swap(data_file_path, sign_file_path);
    } else {
      data_file_path = info.path() + "/" + info.completeBaseName();
    }

    auto data_file_info = QFileInfo(data_file_path);
    if (!possible_singleton_target && !data_file_info.exists()) {
      bool ok;
      QString const text = QInputDialog::getText(
          this, tr("File to be Verified"),
          tr("Please provide An ABSOLUTE Path \n"
             "If Data And Signature is COMBINED within a single file, "
             "KEEP THIS EMPTY: "),
          QLineEdit::Normal, data_file_path, &ok);

      if (!ok) return;

      data_file_path = text.isEmpty() ? data_file_path : text;
      data_file_info = QFileInfo(data_file_path);
    }

    contexts->GetContextPath(0).append(sign_file_path);
    contexts->GetContextOutPath(0).append(data_file_path);
  }

  GpgOperaHelper::BuildOperas(contexts, 0,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasFileVerify);

  exec_operas_helper(tr("Verifying"), contexts);

  if (!contexts->unknown_fprs.isEmpty()) {
    slot_verifying_unknown_signature_helper(contexts->unknown_fprs);
  }
}

void MainWindow::SlotFileEncryptSign(const QStringList& paths, bool ascii) {
  auto contexts = QSharedPointer<GpgOperaContextBasement>::create();
  contexts->ascii = ascii;

  auto key_ids = m_key_list_->GetChecked();
  contexts->keys = check_keys_helper(
      key_ids, [](const GpgKey& key) { return key.IsHasActualEncrCap(); },
      tr("The selected keypair cannot be used for encryption."));
  if (contexts->keys.empty()) return;

  if (!sign_operation_key_validate(contexts)) return;

  if (!check_read_file_paths_helper(paths)) return;

  for (const auto& path : paths) {
    QFileInfo info(path);
    if (info.isDir()) {
      contexts->GetContextPath(1).append(path);
      contexts->GetContextOutPath(1).append(
          SetExtensionOfOutputFileForArchive(path, kENCRYPT, contexts->ascii));
    } else {
      contexts->GetContextPath(0).append(path);
      contexts->GetContextOutPath(0).append(
          SetExtensionOfOutputFile(path, kENCRYPT, contexts->ascii));
    }
  }

  if (!check_write_file_paths_helper(contexts->GetAllOutPath())) return;

  GpgOperaHelper::BuildOperas(contexts, 0,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasFileEncryptSign);

  GpgOperaHelper::BuildOperas(contexts, 1,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasDirectoryEncryptSign);

  exec_operas_helper(tr("Encrypting and Signing"), contexts);
}

void MainWindow::SlotFileDecryptVerify(const QStringList& paths) {
  auto contexts = QSharedPointer<GpgOperaContextBasement>::create();
  contexts->ascii = true;

  if (!check_read_file_paths_helper(paths)) return;

  for (const auto& path : paths) {
    QFileInfo info(path);
    const auto extension = info.completeSuffix();

    if (extension == "tar.gpg" || extension == "tar.asc") {
      contexts->GetContextPath(1).append(path);
      contexts->GetContextOutPath(1).append(
          SetExtensionOfOutputFileForArchive(path, kDECRYPT, contexts->ascii));
    } else {
      contexts->GetContextPath(0).append(path);
      contexts->GetContextOutPath(0).append(
          SetExtensionOfOutputFile(path, kDECRYPT, contexts->ascii));
    }
  }

  if (!check_write_file_paths_helper(contexts->GetAllOutPath())) return;

  GpgOperaHelper::BuildOperas(contexts, 0,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasFileDecryptVerify);

  GpgOperaHelper::BuildOperas(contexts, 1,
                              m_key_list_->GetCurrentGpgContextChannel(),
                              GpgOperaHelper::BuildOperasArchiveDecryptVerify);

  exec_operas_helper(tr("Decrypting and Verifying"), contexts);

  if (!contexts->unknown_fprs.isEmpty()) {
    slot_verifying_unknown_signature_helper(contexts->unknown_fprs);
  }
};

void MainWindow::SlotFileVerifyEML(const QString& path) {
  auto check_result = TargetFilePreCheck(path, true);
  if (!std::get<0>(check_result)) {
    QMessageBox::critical(this, tr("Error"),
                          tr("Cannot read from file: %1").arg(path));
    return;
  }

  QFileInfo file_info(path);
  if (file_info.size() > static_cast<qint64>(1024 * 1024 * 32)) {
    QMessageBox::warning(this, tr("EML File Too Large"),
                         tr("The EML file \"%1\" is larger than 32MB and "
                            "will not be opened.")
                             .arg(file_info.fileName()));
    return;
  }

  QFile eml_file(path);
  if (!eml_file.open(QIODevice::ReadOnly)) return;
  auto buffer = eml_file.readAll();

  // LOG_D() << "EML BUFFER (FILE): " << buffer;

  slot_verify_email_by_eml_data(buffer);
}

}  // namespace GpgFrontend::UI