Debian Codegraph @

online-accounts-service/src/ui-proxy.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2014 Canonical Ltd.
3 *
4 * Contact: Alberto Mardegan <[email protected]>
5 *
6 * This file is part of lomiri-online-accounts-ui
7 *
8 * This program is free software: you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License version 3, as published
10 * by the Free Software Foundation.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranties of
14 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <online-accounts-common/debug.h>
22 #include <online-accounts-common/ipc.h>
23 #include "mir-helper.h"
24 #include "request.h"
25 #include "ui-proxy.h"
26
27 #include <Accounts/Manager>
28 #include <Accounts/Provider>
29 #include <QByteArray>
30 #include <QDataStream>
31 #include <QDir>
32 #include <QDomDocument>
33 #include <QDomElement>
34 #include <QFileInfo>
35 #include <QLocalServer>
36 #include <QLocalSocket>
37 #include <QProcess>
38 #include <QProcessEnvironment>
39 #include <QStandardPaths>
40 #include <QTimer>
41 #include <SignOn/uisessiondata_priv.h>
42
43 using namespace OnlineAccountsUi;
44
45 static int socketCounter = 1;
46
47 namespace OnlineAccountsUi {
48
49 class UiProxyPrivate: public QObject
50 {
51 Q_OBJECT
52 Q_DECLARE_PUBLIC(UiProxy)
53
54 public:
55 inline UiProxyPrivate(pid_t clientPid, UiProxy *pluginProxy);
56 inline ~UiProxyPrivate();
57
58 void setStatus(UiProxy::Status status);
59 bool setupSocket();
60 bool init();
61 void sendOperation(const QVariantMap &data);
62 void sendRequest(int requestId, Request *request);
63 bool setupPromptSession();
64 QString findAppArmorProfile();
65 void startProcess();
66
67 private Q_SLOTS:
68 void onNewConnection();
69 void onDisconnected();
70 void onDataReady(QByteArray &data);
71 void onRequestCompleted();
72 void onFinishedTimer();
73
74 private:
75 QProcess m_process;
76 UiProxy::Status m_status;
77 QLocalServer m_server;
78 QLocalSocket *m_socket;
79 OnlineAccountsUi::Ipc m_ipc;
80 QTimer m_finishedTimer;
81 int m_nextRequestId;
82 QMap<int,Request*> m_requests;
83 QStringList m_handlers;
84 pid_t m_clientPid;
85 QString m_providerId;
86 PromptSessionP m_promptSession;
87 QStringList m_arguments;
88 mutable UiProxy *q_ptr;
89 };
90
91 } // namespace
92
93 UiProxyPrivate::UiProxyPrivate(pid_t clientPid, UiProxy *uiProxy):
94 QObject(uiProxy),
95 m_status(UiProxy::Null),
96 m_socket(0),
97 m_nextRequestId(0),
98 m_clientPid(clientPid),
99 q_ptr(uiProxy)
100 {
101 QObject::connect(&m_server, SIGNAL(newConnection()),
102 this, SLOT(onNewConnection()));
103 QObject::connect(&m_ipc, SIGNAL(dataReady(QByteArray &)),
104 this, SLOT(onDataReady(QByteArray &)));
105 m_process.setProcessChannelMode(QProcess::ForwardedChannels);
106
107 m_finishedTimer.setSingleShot(true);
108 QObject::connect(&m_finishedTimer, SIGNAL(timeout()),
109 this, SLOT(onFinishedTimer()));
110 }
111
112 UiProxyPrivate::~UiProxyPrivate()
113 {
114 /* Cancel all requests */
115 Q_FOREACH(Request *request, m_requests) {
116 request->cancel();
117 }
118
119 if (m_socket) {
120 m_socket->abort();
121 delete m_socket;
122 }
123 m_server.close();
124 }
125
126 void UiProxyPrivate::setStatus(UiProxy::Status status)
127 {
128 Q_Q(UiProxy);
129 if (m_status == status) return;
130 m_status = status;
131 Q_EMIT q->statusChanged();
132 }
133
134 void UiProxyPrivate::sendOperation(const QVariantMap &data)
135 {
136 QByteArray ba;
137 QDataStream stream(&ba, QIODevice::WriteOnly);
138 stream << data;
139 m_ipc.write(ba);
140 }
141
142 void UiProxyPrivate::onDisconnected()
143 {
144 Q_Q(UiProxy);
145
146 if (!m_finishedTimer.isActive()) {
147 Q_EMIT q->finished();
148 }
149 }
150
151 void UiProxyPrivate::onNewConnection()
152 {
153 QLocalSocket *socket = m_server.nextPendingConnection();
154 if (Q_UNLIKELY(socket == 0)) return;
155
156 if (Q_UNLIKELY(m_socket != 0)) {
157 qWarning() << "A socket is already active!";
158 socket->deleteLater();
159 return;
160 }
161
162 m_socket = socket;
163 QObject::connect(socket, SIGNAL(disconnected()),
164 this, SLOT(onDisconnected()));
165 m_ipc.setChannels(socket, socket);
166 m_server.close(); // stop listening
167
168 setStatus(UiProxy::Ready);
169
170 /* Execute any pending requests */
171 QMapIterator<int, Request*> it(m_requests);
172 while (it.hasNext()) {
173 it.next();
174 sendRequest(it.key(), it.value());
175 }
176 }
177
178 void UiProxyPrivate::onDataReady(QByteArray &data)
179 {
180 QVariantMap map;
181 QDataStream stream(&data, QIODevice::ReadOnly);
182 stream >> map;
183
184 DEBUG() << map;
185
186 int requestId = map.value(OAU_OPERATION_ID, -1).toInt();
187 Request *request = m_requests.value(requestId, 0);
188
189 QString code = map.value(OAU_OPERATION_CODE).toString();
190 if (code == OAU_OPERATION_CODE_REQUEST_FINISHED) {
191 Q_ASSERT(request);
192 request->setDelay(map.value(OAU_OPERATION_DELAY).toInt());
193 request->setResult(map.value(OAU_OPERATION_DATA).toMap());
194 } else if (code == OAU_OPERATION_CODE_REQUEST_FAILED) {
195 Q_ASSERT(request);
196 request->fail(map.value(OAU_OPERATION_ERROR_NAME).toString(),
197 map.value(OAU_OPERATION_ERROR_MESSAGE).toString());
198 } else if (code == OAU_OPERATION_CODE_REGISTER_HANDLER) {
199 m_handlers.append(map.value(OAU_OPERATION_HANDLER_ID).toString());
200 } else {
201 qWarning() << "Invalid operation code: " << code;
202 }
203 }
204
205 bool UiProxyPrivate::setupSocket()
206 {
207 QString runtimeDir =
208 QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
209 QDir socketDir(runtimeDir + "/" LOA_UI);
210 if (!socketDir.exists()) socketDir.mkpath(".");
211
212 QString uniqueName = QString("ui-%1-%2").arg(socketCounter++).arg(m_providerId);
213
214 /* If the file exists, it's a stale file: <LOA_UI> is a single
215 * instance process, and the only one creating files in this directory. */
216 if (Q_UNLIKELY(socketDir.exists(uniqueName))) {
217 socketDir.remove(uniqueName);
218 }
219
220 /* Create the socket and set it into listen mode */
221 return m_server.listen(socketDir.filePath(uniqueName));
222 }
223
224 bool UiProxyPrivate::setupPromptSession()
225 {
226 Q_Q(UiProxy);
227
228 if (!m_clientPid) return false;
229
230 PromptSessionP session =
231 MirHelper::instance()->createPromptSession(m_clientPid);
232 if (!session) return false;
233
234 QString mirSocket = session->requestSocket();
235 if (mirSocket.isEmpty()) {
236 return false;
237 }
238
239 m_promptSession = session;
240 QObject::connect(m_promptSession.data(), SIGNAL(finished()),
241 q, SIGNAL(finished()));
242
243 QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
244 env.insert("MIR_SOCKET", mirSocket);
245 m_process.setProcessEnvironment(env);
246 return true;
247 }
248
249 bool UiProxyPrivate::init()
250 {
251 QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
252 if (env.value("QT_QPA_PLATFORM").startsWith("ubuntu")) {
253 if (!setupPromptSession()) {
254 qWarning() << "Couldn't setup prompt session";
255 return false;
256 }
257 } else {
258 env.insert("DESKTOP_FILE_HINT", LOA_UI);
259 m_process.setProcessEnvironment(env);
260 }
261
262 /* We also create ~/cache/<LOA_UI>/, since the plugin might not
263 * have permissions to do that. */
264 QString userCacheDir =
265 QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation);
266 QDir cacheDir(userCacheDir + "/" LOA_UI);
267 if (!cacheDir.exists()) cacheDir.mkpath(".");
268
269 return true;
270 }
271
272 QString UiProxyPrivate::findAppArmorProfile()
273 {
274 if (Q_UNLIKELY(m_providerId.isEmpty())) return QString();
275
276 /* Load the provider XML file */
277 Accounts::Manager manager;
278 Accounts::Provider provider = manager.provider(m_providerId);
279 if (Q_UNLIKELY(!provider.isValid())) {
280 qWarning() << "Provider not found:" << m_providerId;
281 return QString();
282 }
283
284 const QDomDocument doc = provider.domDocument();
285 QDomElement root = doc.documentElement();
286 return root.firstChildElement("profile").text();
287 }
288
289 void UiProxyPrivate::startProcess()
290 {
291 if (Q_UNLIKELY(!setupSocket())) {
292 qWarning() << "Couldn't setup IPC socket";
293 setStatus(UiProxy::Error);
294 return;
295 }
296 m_arguments.append("--socket");
297 m_arguments.append(m_server.fullServerName());
298
299 QString profile = findAppArmorProfile();
300 if (profile.isEmpty()) {
301 profile = "unconfined";
302 } else {
303 QProcessEnvironment env = m_process.processEnvironment();
304 env.insert("APP_ID", profile);
305 /* Set TMPDIR to a location which the confined process can actually
306 * use */
307 QString tmpdir =
308 QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation) +
309 "/" + profile.split('_')[0];
310 env.insert("TMPDIR", tmpdir);
311 m_process.setProcessEnvironment(env);
312 }
313
314 m_arguments.append("--profile");
315 m_arguments.append(profile);
316
317 QString processName;
318 QString wrapper = QString::fromUtf8(qgetenv("OAU_WRAPPER"));
319 QString accountsUi = QStringLiteral(INSTALL_BIN_DIR "/" LOA_UI);
320 if (wrapper.isEmpty()) {
321 processName = accountsUi;
322 } else {
323 processName = wrapper;
324 m_arguments.prepend(accountsUi);
325 }
326
327 setStatus(UiProxy::Loading);
328 m_process.start(processName, m_arguments);
329 if (Q_UNLIKELY(!m_process.waitForStarted())) {
330 qWarning() << "Couldn't start account plugin process";
331 setStatus(UiProxy::Error);
332 return;
333 }
334 }
335
336 void UiProxyPrivate::sendRequest(int requestId, Request *request)
337 {
338 QVariantMap operation;
339 operation.insert(OAU_OPERATION_CODE, OAU_OPERATION_CODE_PROCESS);
340 operation.insert(OAU_OPERATION_ID, requestId);
341 operation.insert(OAU_OPERATION_DATA, request->parameters());
342 operation.insert(OAU_OPERATION_INTERFACE, request->interface());
343 operation.insert(OAU_OPERATION_CLIENT_PROFILE,
344 request->clientApparmorProfile());
345 sendOperation(operation);
346 }
347
348 void UiProxyPrivate::onFinishedTimer()
349 {
350 Q_Q(UiProxy);
351
352 if (m_requests.isEmpty()) {
353 Q_EMIT q->finished();
354 }
355 }
356
357 void UiProxyPrivate::onRequestCompleted()
358 {
359 Request *request = qobject_cast<Request*>(sender());
360 Q_ASSERT(request);
361 m_finishedTimer.setInterval(request->delay());
362 m_finishedTimer.start();
363
364 int id = m_requests.key(request, -1);
365 if (id != -1) {
366 m_requests.remove(id);
367 }
368 }
369
370 UiProxy::UiProxy(pid_t clientPid, QObject *parent):
371 QObject(parent),
372 d_ptr(new UiProxyPrivate(clientPid, this))
373 {
374 }
375
376 UiProxy::~UiProxy()
377 {
378 DEBUG();
379 }
380
381 UiProxy::Status UiProxy::status() const
382 {
383 Q_D(const UiProxy);
384 return d->m_status;
385 }
386
387 bool UiProxy::init()
388 {
389 Q_D(UiProxy);
390 return d->init();
391 }
392
393 void UiProxy::handleRequest(Request *request)
394 {
395 Q_D(UiProxy);
396
397 if (d->m_providerId.isEmpty()) {
398 d->m_providerId = request->providerId();
399 }
400 int requestId = d->m_nextRequestId++;
401 d->m_requests.insert(requestId, request);
402 QObject::connect(request, SIGNAL(completed()),
403 d, SLOT(onRequestCompleted()));
404 request->setInProgress(true);
405
406 if (d->m_status == UiProxy::Ready) {
407 d->sendRequest(requestId, request);
408 } else if (d->m_status == UiProxy::Null) {
409 d->startProcess();
410 }
411 }
412
413 bool UiProxy::hasHandlerFor(const QVariantMap &parameters)
414 {
415 Q_D(UiProxy);
416
417 /* Find if there's any handlers expecting to handle the SignOnUi
418 * request having "parameters" as parameters.
419 * This is simply done by matching on the X-RequestHandler key (aka
420 * matchKey()), if present. We expect that account plugins add that field
421 * to their AuthSession requests which they want to handle themselves.
422 */
423 DEBUG() << parameters;
424 if (!parameters.contains(SSOUI_KEY_CLIENT_DATA)) return false;
425 QVariant variant = parameters[SSOUI_KEY_CLIENT_DATA];
426 QVariantMap clientData = variant.toMap();
427 QString matchId = clientData.value(OAU_REQUEST_MATCH_KEY).toString();
428 if (matchId.isEmpty()) return false;
429
430 return d->m_handlers.contains(matchId);
431 }
432
433 #include "ui-proxy.moc"