Debian Codegraph @

click-hooks/online-accounts-hooks/main.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's click hooks
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 <Accounts/Manager>
22 #include <QCoreApplication>
23 #include <QDateTime>
24 #include <QDebug>
25 #include <QDir>
26 #include <QDomDocument>
27 #include <QDomElement>
28 #include <QFile>
29 #include <QFileInfo>
30 #include <QStandardPaths>
31 #include <QStringList>
32 #include <click.h>
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #include <unistd.h>
36 #include <utime.h>
37
38 static QString findPackageDir(const QString &appId)
39 {
40 /* For testing */
41 QByteArray packageDirEnv = qgetenv("OAH_CLICK_DIR");
42 if (!packageDirEnv.isEmpty()) {
43 return QString::fromUtf8(packageDirEnv);
44 }
45
46 QStringList components = appId.split('_');
47 QByteArray package = components.first().toUtf8();
48
49 GError *error = NULL;
50 ClickUser *user = click_user_new_for_user(NULL, NULL, &error);
51 if (Q_UNLIKELY(!user)) {
52 qWarning() << "Unable to read Click database:" << error->message;
53 g_error_free(error);
54 return QString();
55 }
56
57 gchar *pkgDir = click_user_get_path(user, package.constData(), &error);
58 if (Q_UNLIKELY(!pkgDir)) {
59 qWarning() << "Unable to get the Click package directory for" <<
60 package << ":" << error->message;
61 g_error_free(error);
62 g_object_unref(user);
63 return QString();
64 }
65
66 QString ret = QString::fromUtf8(pkgDir);
67 g_object_unref(user);
68 g_free(pkgDir);
69 return ret;
70 }
71
72 static QString stripVersion(const QString &appId)
73 {
74 QStringList components = appId.split('_');
75 if (components.count() != 3) return appId;
76
77 /* Click packages have a profile of the form
78 * $name_$application_$version
79 * (see https://wiki.ubuntu.com/SecurityTeam/Specifications/ApplicationConfinement/Manifest#Click)
80 *
81 * So we just need to strip out the last part.
82 */
83 components.removeLast();
84 return components.join('_');
85 }
86
87 /* Get the modification time of a file; this differs from
88 * QFileInfo::lastModified() in that if the file is a symlink here we take the
89 * info from the symlink itself. */
90 static QDateTime lastModified(const QFileInfo &fileInfo)
91 {
92 struct stat data;
93 if (lstat(fileInfo.filePath().toUtf8().constData(), &data) < 0) {
94 return QDateTime();
95 }
96 return QDateTime::fromSecsSinceEpoch(data.st_mtime);
97 }
98
99 class LibAccountsFile: public QDomDocument {
100 public:
101 explicit LibAccountsFile(const QFileInfo &hookFileInfo);
102
103 void checkId(const QString &shortAppId);
104 void addProfile(const QString &appId);
105 void addPackageDir(const QString &appId);
106 QString profile() const;
107 void addDesktopFile(const QString &appId);
108 void addServiceType(const QString &shortAppId);
109 void checkIconPath(const QString &appId);
110 bool writeTo(const QString &fileName) const;
111 void addCreatorMark();
112 bool createdByUs() const;
113 bool isValid() const { return m_isValid; }
114
115 private:
116 QFileInfo m_hookFileInfo;
117 bool m_isValid;
118 };
119
120 LibAccountsFile::LibAccountsFile(const QFileInfo &hookFileInfo):
121 QDomDocument(),
122 m_hookFileInfo(hookFileInfo),
123 m_isValid(false)
124 {
125 QFile file(hookFileInfo.filePath());
126 if (file.open(QIODevice::ReadOnly)) {
127 if (setContent(&file)) {
128 m_isValid = true;
129 }
130 file.close();
131 }
132 }
133
134 void LibAccountsFile::checkId(const QString &shortAppId)
135 {
136 /* checks that the root element's "id" attributes is consistent with the
137 * file name */
138 QDomElement root = documentElement();
139 root.setAttribute(QStringLiteral("id"), shortAppId);
140 }
141
142 void LibAccountsFile::addProfile(const QString &appId)
143 {
144 QDomElement root = documentElement();
145 QDomElement elem = createElement(QStringLiteral("profile"));
146 elem.appendChild(createTextNode(appId));
147 root.appendChild(elem);
148 }
149
150 void LibAccountsFile::addPackageDir(const QString &appId)
151 {
152 QString packageDir = findPackageDir(appId);
153 if (Q_UNLIKELY(packageDir.isEmpty())) return;
154
155 QDomElement root = documentElement();
156 QDomElement elem = createElement(QStringLiteral("package-dir"));
157 elem.appendChild(createTextNode(packageDir));
158 root.appendChild(elem);
159 }
160
161 QString LibAccountsFile::profile() const
162 {
163 QDomElement root = documentElement();
164 return root.firstChildElement("profile").text();
165 }
166
167 void LibAccountsFile::addDesktopFile(const QString &appId)
168 {
169 QString desktopEntryTag = QStringLiteral("desktop-entry");
170 QDomElement root = documentElement();
171 /* if a <desktop-entry> element already exists, don't touch it */
172 QDomElement elem = root.firstChildElement(desktopEntryTag);
173 if (!elem.isNull()) return;
174
175 elem = createElement(desktopEntryTag);
176 elem.appendChild(createTextNode(appId));
177 root.appendChild(elem);
178 }
179
180 void LibAccountsFile::addServiceType(const QString &shortAppId)
181 {
182 QString serviceTypeTag = QStringLiteral("type");
183 QDomElement root = documentElement();
184 /* if a <service-type> element already exists, don't touch it */
185 QDomElement elem = root.firstChildElement(serviceTypeTag);
186 if (!elem.isNull()) return;
187
188 elem = createElement(serviceTypeTag);
189 elem.appendChild(createTextNode(shortAppId));
190 root.appendChild(elem);
191 }
192
193 void LibAccountsFile::checkIconPath(const QString &appId)
194 {
195 QString iconTag = QStringLiteral("icon");
196 QDomElement root = documentElement();
197 /* if the <icon> element does not exist, do nothing*/
198 QDomElement elem = root.firstChildElement(iconTag);
199 if (elem.isNull()) return;
200
201 /* If the icon path is absolute, do nothing */
202 QString icon = elem.text();
203 if (QDir::isAbsolutePath(icon)) return;
204
205 /* Otherwise, try appending it to the click package install dir */
206 QString packageDir = findPackageDir(appId);
207 if (Q_UNLIKELY(packageDir.isEmpty())) return;
208
209 QFileInfo iconFile(packageDir + "/" + icon);
210 if (iconFile.exists()) {
211 while (elem.hasChildNodes()) {
212 elem.removeChild(elem.firstChild());
213 }
214 elem.appendChild(createTextNode(iconFile.canonicalFilePath()));
215 }
216 }
217
218 bool LibAccountsFile::writeTo(const QString &fileName) const
219 {
220 /* Make sure that the target directory exists */
221 QFileInfo fileInfo(fileName);
222 fileInfo.absoluteDir().mkpath(".");
223 /* Make sure there isn't a directory with the same name:
224 * Fixes: https://github.com/ubports/ubuntu-touch/issues/602
225 */
226 fileInfo.absoluteDir().rmdir(fileInfo.fileName());
227
228 QFile file(fileName);
229 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return false;
230
231 bool ok = (file.write(toByteArray(2)) > 0);
232 file.close();
233
234 if (ok) {
235 struct utimbuf sourceTime;
236 sourceTime.actime = sourceTime.modtime =
237 lastModified(m_hookFileInfo).toSecsSinceEpoch();
238 utime(fileName.toUtf8().constData(), &sourceTime);
239 return true;
240 } else {
241 QFile::remove(fileName);
242 return false;
243 }
244 }
245
246 void LibAccountsFile::addCreatorMark()
247 {
248 QString comment = QString("this file is auto-generated by %1; do not modify").
249 arg(QCoreApplication::applicationName());
250 appendChild(createComment(comment));
251 }
252
253 bool LibAccountsFile::createdByUs() const
254 {
255 QString creatorMark = QCoreApplication::applicationName() + ";";
256 for (QDomNode n = firstChild(); !n.isNull(); n = n.nextSibling()) {
257 if (n.isComment() && n.nodeValue().contains(creatorMark)) {
258 return true;
259 }
260 }
261 return false;
262 }
263
264 static void removeStaleAccounts(Accounts::Manager *manager,
265 const QString &providerName)
266 {
267 Q_FOREACH(Accounts::AccountId id, manager->accountList()) {
268 Accounts::Account *account = manager->account(id);
269 if (account->providerName() == providerName) {
270 account->remove();
271 account->syncAndBlock();
272 }
273 }
274 }
275
276 static void removeStaleFiles(Accounts::Manager *manager,
277 const QStringList &fileTypes,
278 const QString &localShare,
279 const QDir &hooksDirIn)
280 {
281 /* Walk through all of
282 * ~/.local/share/accounts/{providers,services,service-types,applications}/
283 * and remove files which are no longer present in hooksDirIn.
284 */
285 Q_FOREACH(const QString &fileType, fileTypes) {
286 QDir dir(QString("%1/accounts/%2s").arg(localShare).arg(fileType));
287 dir.setFilter(QDir::Files | QDir::Readable);
288 QStringList fileTypeFilter;
289 fileTypeFilter << "*." + fileType;
290 dir.setNameFilters(fileTypeFilter);
291
292 Q_FOREACH(const QFileInfo &fileInfo, dir.entryInfoList()) {
293 LibAccountsFile file(fileInfo);
294
295 /* If this file was not created by our hook let's ignore it. */
296 if (!file.createdByUs()) continue;
297
298 QString profile = file.profile();
299
300 /* Check that the hook file is still there; if it isn't, then it
301 * means that the click package was removed, and we must remove our
302 * copy as well. */
303 QString hookFileName = stripVersion(profile) + "_*." + fileType;
304 QStringList nameFilters = QStringList() << hookFileName;
305 if (!hooksDirIn.entryList(nameFilters).isEmpty()) continue;
306
307 QFile::remove(fileInfo.filePath());
308 /* If this is a provider, we must also remove any accounts
309 * associated with it */
310 if (fileType == QStringLiteral("provider")) {
311 removeStaleAccounts(manager, fileInfo.completeBaseName());
312 }
313 }
314 }
315 }
316
317 int main(int argc, char **argv)
318 {
319 QCoreApplication app(argc, argv);
320
321 Accounts::Manager::Options managerOptions;
322 if (qgetenv("DBUS_SESSION_BUS_ADDRESS").isEmpty()) {
323 managerOptions |= Accounts::Manager::DisableNotifications;
324 }
325 Accounts::Manager *manager = new Accounts::Manager(managerOptions);
326
327 /* Go through the hook files in ~/.local/share/online-accounts-hooks/ and
328 * check if they have already been processed into a file under
329 * ~/.local/share/accounts/{providers,services,service-types,applications}/;
330 * if not, open the hook file, write the APP_ID somewhere in it, and
331 * save the result in the location where libaccounts expects to find it.
332 */
333
334 QStringList fileTypes;
335 fileTypes << QStringLiteral("provider") <<
336 QStringLiteral("service") <<
337 QStringLiteral("service-type") <<
338 QStringLiteral("application");
339
340 // This is ~/.local/share/
341 const QString localShare =
342 QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
343 QDir hooksDirIn(localShare + "/" HOOK_FILES_SUBDIR);
344
345 removeStaleFiles(manager, fileTypes, localShare, hooksDirIn);
346
347 Q_FOREACH(const QFileInfo &fileInfo, hooksDirIn.entryInfoList()) {
348 const QString fileType = fileInfo.suffix();
349 // Filter out the files which we don't support
350 if (!fileTypes.contains(fileType)) continue;
351
352 // Our click hook sets the base name to the APP_ID
353 QString appId = fileInfo.completeBaseName();
354
355 /* When publishing this file for libaccounts, we want to strip
356 * the version number out. */
357 QString shortAppId = stripVersion(appId);
358
359 /* When building the destination file name, use the file suffix with an
360 * "s" appended: remember that libaccounts uses
361 * ~/.local/share/accounts/{providers,services,service-types,applications}.
362 * */
363 QString destination = QString("%1/accounts/%2s/%3.%2").
364 arg(localShare).arg(fileInfo.suffix()).arg(shortAppId);
365
366 QFileInfo destinationInfo(destination);
367 /* If the destination is there and up to date, we have nothing to do */
368 if (destinationInfo.exists() &&
369 destinationInfo.lastModified() == lastModified(fileInfo)) {
370 continue;
371 }
372
373 LibAccountsFile xml = LibAccountsFile(fileInfo);
374 if (!xml.isValid()) continue;
375
376 xml.addCreatorMark();
377 xml.checkId(shortAppId);
378 xml.addProfile(appId);
379 xml.addPackageDir(appId);
380 xml.checkIconPath(appId);
381 if (fileType == "application") {
382 xml.addDesktopFile(appId);
383 } else if (fileType == "service") {
384 xml.addServiceType(shortAppId);
385 }
386 xml.writeTo(destination);
387 }
388
389 /* To ensure that all the installed services are parsed into
390 * libaccounts' DB, we enumerate them now.
391 */
392 manager->serviceList();
393 delete manager;
394
395 return EXIT_SUCCESS;
396 }
397