-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathcontroller.cpp
More file actions
326 lines (275 loc) · 11.5 KB
/
controller.cpp
File metadata and controls
326 lines (275 loc) · 11.5 KB
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
/*
* Copyright (c) 2020-2024 Estonian Information System Authority
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "controller.hpp"
#include "threads/cardeventmonitorthread.hpp"
#include "threads/commandhandlerconfirmthread.hpp"
#include "threads/commandhandlerrunthread.hpp"
#include "threads/waitforcardthread.hpp"
#include "utils/utils.hpp"
#include "application.hpp"
#include "inputoutputmode.hpp"
#include "writeresponse.hpp"
using namespace pcsc_cpp;
using namespace electronic_id;
namespace
{
const QString RESP_TECH_ERROR = QStringLiteral("ERR_WEBEID_NATIVE_FATAL");
const QString RESP_USER_CANCEL = QStringLiteral("ERR_WEBEID_USER_CANCELLED");
QVariantMap makeErrorObject(const QString& errorCode, const QString& errorMessage)
{
return {{QStringLiteral("error"),
QVariantMap {
{QStringLiteral("code"), errorCode},
{QStringLiteral("message"), errorMessage},
}}};
}
} // namespace
void Controller::run()
{
// If a command is passed, the application is in command-line mode, else in stdin/stdout mode.
const bool isInCommandLineMode = bool(command);
isInStdinMode = !isInCommandLineMode;
qInfo() << QCoreApplication::applicationName() << "app"
<< QCoreApplication::applicationVersion() << "running in"
<< (isInStdinMode ? "stdin/stdout" : "command-line") << "mode";
try {
// TODO: cut out stdin mode separate class to avoid bugs in safari mode
if (isInStdinMode) {
// In stdin/stdout mode we first output the version as required by the WebExtension
// and then wait for the actual command.
writeResponseToStdOut(
isInStdinMode,
{{QStringLiteral("version"), QCoreApplication::applicationVersion()}},
"get-version");
command = readCommandFromStdin();
}
REQUIRE_NON_NULL(command)
switch (command->first) {
case CommandType::ABOUT:
WebEidUI::showAboutPage();
return;
case CommandType::QUIT:
// If quit is requested, respond with empty JSON object and quit immediately.
qInfo() << "Quit requested, exiting";
writeResponseToStdOut(true, {}, "quit");
emit quit();
return;
default:
break;
}
commandHandler = getCommandHandler(*command);
// When the command handler run thread retrieves certificates successfully, call
// onCertificatesLoaded() that starts card event monitoring while user enters the PIN.
connect(commandHandler.get(), &CommandHandler::singleCertificateReady, this,
&Controller::onCertificatesLoaded);
connect(commandHandler.get(), &CommandHandler::multipleCertificatesReady, this,
&Controller::onCertificatesLoaded);
connect(commandHandler.get(), &CommandHandler::verifyPinFailed, this,
&Controller::onCertificatesLoaded);
startCommandExecution();
} catch (const std::exception& error) {
onCriticalFailure(error.what());
}
}
void Controller::startCommandExecution()
{
REQUIRE_NON_NULL(commandHandler)
// Reader monitor thread setup.
auto* waitForCardThread = new WaitForCardThread(this);
connect(this, &Controller::stopCardEventMonitorThread, waitForCardThread,
&WaitForCardThread::requestInterruption);
connect(waitForCardThread, &ControllerChildThread::failure, this,
&Controller::onCriticalFailure);
connect(waitForCardThread, &WaitForCardThread::statusUpdate, this, &Controller::statusUpdate);
connect(waitForCardThread, &WaitForCardThread::cardsAvailable, this,
&Controller::onCardsAvailable);
// UI setup.
createWindow();
// Finally, start the thread to wait for card insertion after everything is wired up.
waitForCardThread->start();
}
void Controller::createWindow()
{
window = WebEidUI::createAndShowDialog(commandHandler->commandType());
connect(this, &Controller::statusUpdate, window, &WebEidUI::onSmartCardStatusUpdate);
connect(this, &Controller::retry, window, &WebEidUI::onRetry);
connect(window, &WebEidUI::retry, this, &Controller::onRetry);
connect(window, &WebEidUI::accepted, this, &Controller::onDialogOK);
connect(window, &WebEidUI::rejected, this, &Controller::onDialogCancel);
connect(window, &WebEidUI::failure, this, &Controller::onCriticalFailure);
connect(window, &WebEidUI::waitingForPinPad, this, &Controller::onConfirmCommandHandler);
connect(window, &WebEidUI::destroyed, this, [this] { window = nullptr; });
}
void Controller::onCardsAvailable(
const std::vector<electronic_id::ElectronicID::ptr>& availableEids)
{
try {
REQUIRE_NON_NULL(commandHandler)
REQUIRE_NON_NULL(window)
REQUIRE_NOT_EMPTY_CONTAINS_NON_NULL_PTRS(availableEids)
for (const auto& card : availableEids) {
const auto protocol =
card->smartcard().protocol() == SmartCard::Protocol::T0 ? "T=0" : "T=1";
qInfo() << "Card" << card->name() << "in reader" << card->smartcard().readerName()
<< "using protocol" << protocol;
}
window->showWaitingForCardPage(commandHandler->commandType());
commandHandler->connectSignals(window);
runCommandHandler(availableEids);
} catch (const std::exception& error) {
onCriticalFailure(error.what());
}
}
void Controller::runCommandHandler(std::vector<ElectronicID::ptr> availableEids) noexcept
try {
auto* commandHandlerRunThread =
new CommandHandlerRunThread(this, *commandHandler, std::move(availableEids));
connectRetry(commandHandlerRunThread);
commandHandlerRunThread->start();
} catch (const std::exception& error) {
onCriticalFailure(error.what());
}
void Controller::onCertificatesLoaded()
{
auto* cardEventMonitorThread = new CardEventMonitorThread(this, commandType());
connect(this, &Controller::stopCardEventMonitorThread, cardEventMonitorThread,
&CardEventMonitorThread::requestInterruption);
connect(cardEventMonitorThread, &ControllerChildThread::failure, this,
&Controller::onCriticalFailure);
connect(cardEventMonitorThread, &CardEventMonitorThread::cardEvent, this, &Controller::onRetry);
cardEventMonitorThread->start();
}
void Controller::disposeUI()
{
if (window) {
window->disconnect();
window->forceClose();
window->deleteLater();
window = nullptr;
}
}
void Controller::onConfirmCommandHandler(const EidCertificateAndPinInfo& certAndPinInfo) noexcept
try {
emit stopCardEventMonitorThread();
auto* commandHandlerConfirmThread =
new CommandHandlerConfirmThread(this, *commandHandler, window, certAndPinInfo);
connect(commandHandlerConfirmThread, &CommandHandlerConfirmThread::completed, this,
&Controller::onCommandHandlerConfirmCompleted);
connectRetry(commandHandlerConfirmThread);
commandHandlerConfirmThread->start();
} catch (const std::exception& error) {
onCriticalFailure(error.what());
}
void Controller::onCommandHandlerConfirmCompleted(const QVariantMap& res)
{
REQUIRE_NON_NULL(window)
qDebug() << "Command completed";
// Schedule application exit when the UI dialog is destroyed.
connect(window, &WebEidUI::destroyed, this, &Controller::exit);
try {
_result = res;
writeResponseToStdOut(isInStdinMode, res, commandHandler->commandType());
} catch (const std::exception& error) {
qCritical() << "Command" << std::string(commandType())
<< "fatal error while writing response to stdout:" << error;
}
window->quit();
}
void Controller::onRetry()
{
try {
// Dispose the UI, it will be re-created during next execution.
disposeUI();
// Command handler signals are still connected, disconnect them so that they can be
// reconnected during next execution.
commandHandler->disconnect();
// Before restarting, wait until child threads finish.
waitForChildThreads();
startCommandExecution();
} catch (const std::exception& error) {
onCriticalFailure(error.what());
}
}
void Controller::connectRetry(const ControllerChildThread* childThread) const
{
REQUIRE_NON_NULL(childThread)
connect(childThread, &ControllerChildThread::failure, this, &Controller::onCriticalFailure);
connect(childThread, &ControllerChildThread::retry, this, &Controller::retry);
// This connection handles cancel events from PIN pad.
connect(childThread, &ControllerChildThread::cancel, this, &Controller::onDialogCancel);
}
void Controller::onDialogOK(const EidCertificateAndPinInfo& certAndPinInfo)
{
if (commandHandler) {
onConfirmCommandHandler(certAndPinInfo);
} else {
// This should not happen, and when it does, OK should be equivalent to cancel.
onDialogCancel();
}
}
void Controller::onDialogCancel()
{
qDebug() << "User cancelled";
_result = makeErrorObject(RESP_USER_CANCEL, QStringLiteral("User cancelled"));
writeResponseToStdOut(isInStdinMode, _result, commandType());
exit();
}
void Controller::onCriticalFailure(const QString& error)
{
emit stopCardEventMonitorThread();
qCritical() << "Exiting due to command" << std::string(commandType())
<< "fatal error:" << error;
_result =
makeErrorObject(RESP_TECH_ERROR, QStringLiteral("Technical error, see application logs"));
disposeUI();
if (qApp->isSafariExtensionContainingApp()) {
writeResponseToStdOut(isInStdinMode, _result, commandType());
}
WebEidUI::showFatalError();
if (!qApp->isSafariExtensionContainingApp()) {
// Write the error response to stdout after showing the fatal error dialog. Chrome will
// close the application immediately after this, so the UI dialog may not be visible to the
// user.
writeResponseToStdOut(isInStdinMode, _result, commandType());
}
exit();
}
void Controller::exit()
{
disposeUI();
waitForChildThreads();
emit quit();
}
void Controller::waitForChildThreads()
{
for (auto* thread : findChildren<QThread*>()) {
qDebug() << "Interrupting thread" << uintptr_t(thread);
thread->disconnect();
thread->requestInterruption();
ControllerChildThread::waitForControllerNotify.wakeAll();
thread->wait();
}
}
CommandType Controller::commandType()
{
return commandHandler ? commandHandler->commandType() : CommandType(CommandType::INSERT_CARD);
}