setup.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. // SPDX-FileCopyrightText: GSConnect Developers https://github.com/GSConnect
  2. //
  3. // SPDX-License-Identifier: GPL-2.0-or-later
  4. 'use strict';
  5. const Gio = imports.gi.Gio;
  6. const GIRepository = imports.gi.GIRepository;
  7. const GLib = imports.gi.GLib;
  8. const Config = imports.config;
  9. const {setup, setupGettext} = imports.utils.setup;
  10. // Promise Wrappers
  11. try {
  12. const {EBook, EDataServer} = imports.gi;
  13. Gio._promisify(EBook.BookClient, 'connect');
  14. Gio._promisify(EBook.BookClient.prototype, 'get_view');
  15. Gio._promisify(EBook.BookClient.prototype, 'get_contacts');
  16. Gio._promisify(EDataServer.SourceRegistry, 'new');
  17. } catch (e) {
  18. // Silence import errors
  19. }
  20. Gio._promisify(Gio.AsyncInitable.prototype, 'init_async');
  21. Gio._promisify(Gio.DBusConnection.prototype, 'call');
  22. Gio._promisify(Gio.DBusProxy.prototype, 'call');
  23. Gio._promisify(Gio.DataInputStream.prototype, 'read_line_async',
  24. 'read_line_finish_utf8');
  25. Gio._promisify(Gio.File.prototype, 'delete_async');
  26. Gio._promisify(Gio.File.prototype, 'enumerate_children_async');
  27. Gio._promisify(Gio.File.prototype, 'load_contents_async');
  28. Gio._promisify(Gio.File.prototype, 'mount_enclosing_volume');
  29. Gio._promisify(Gio.File.prototype, 'query_info_async');
  30. Gio._promisify(Gio.File.prototype, 'read_async');
  31. Gio._promisify(Gio.File.prototype, 'replace_async');
  32. Gio._promisify(Gio.File.prototype, 'replace_contents_bytes_async',
  33. 'replace_contents_finish');
  34. Gio._promisify(Gio.FileEnumerator.prototype, 'next_files_async');
  35. Gio._promisify(Gio.Mount.prototype, 'unmount_with_operation');
  36. Gio._promisify(Gio.InputStream.prototype, 'close_async');
  37. Gio._promisify(Gio.OutputStream.prototype, 'close_async');
  38. Gio._promisify(Gio.OutputStream.prototype, 'splice_async');
  39. Gio._promisify(Gio.OutputStream.prototype, 'write_all_async');
  40. Gio._promisify(Gio.SocketClient.prototype, 'connect_async');
  41. Gio._promisify(Gio.SocketListener.prototype, 'accept_async');
  42. Gio._promisify(Gio.Subprocess.prototype, 'communicate_utf8_async');
  43. Gio._promisify(Gio.Subprocess.prototype, 'wait_check_async');
  44. Gio._promisify(Gio.TlsConnection.prototype, 'handshake_async');
  45. Gio._promisify(Gio.DtlsConnection.prototype, 'handshake_async');
  46. // User Directories
  47. Config.CACHEDIR = GLib.build_filenamev([GLib.get_user_cache_dir(), 'gsconnect']);
  48. Config.CONFIGDIR = GLib.build_filenamev([GLib.get_user_config_dir(), 'gsconnect']);
  49. Config.RUNTIMEDIR = GLib.build_filenamev([GLib.get_user_runtime_dir(), 'gsconnect']);
  50. // Bootstrap
  51. setup(Config.PACKAGE_DATADIR);
  52. setupGettext();
  53. if (Config.IS_USER) {
  54. // Infer libdir by assuming gnome-shell shares a common prefix with gjs;
  55. // assume the parent directory if it's not there
  56. let libdir = GIRepository.Repository.get_search_path().find(path => {
  57. return path.endsWith('/gjs/girepository-1.0');
  58. }).replace('/gjs/girepository-1.0', '');
  59. const gsdir = GLib.build_filenamev([libdir, 'gnome-shell']);
  60. if (!GLib.file_test(gsdir, GLib.FileTest.IS_DIR)) {
  61. const currentDir = `/${GLib.path_get_basename(libdir)}`;
  62. libdir = libdir.replace(currentDir, '');
  63. }
  64. Config.GNOME_SHELL_LIBDIR = libdir;
  65. }
  66. // Load DBus interfaces
  67. Config.DBUS = (() => {
  68. const bytes = Gio.resources_lookup_data(
  69. GLib.build_filenamev([Config.APP_PATH, `${Config.APP_ID}.xml`]),
  70. Gio.ResourceLookupFlags.NONE
  71. );
  72. const xml = new TextDecoder().decode(bytes.toArray());
  73. const dbus = Gio.DBusNodeInfo.new_for_xml(xml);
  74. dbus.nodes.forEach(info => info.cache_build());
  75. return dbus;
  76. })();
  77. // Init User Directories
  78. for (const path of [Config.CACHEDIR, Config.CONFIGDIR, Config.RUNTIMEDIR])
  79. GLib.mkdir_with_parents(path, 0o755);
  80. /**
  81. * Check if we're in a Wayland session (mostly for input synthesis)
  82. * https://wiki.gnome.org/Accessibility/Wayland#Bugs.2FIssues_We_Must_Address
  83. */
  84. globalThis.HAVE_REMOTEINPUT = GLib.getenv('GDMSESSION') !== 'ubuntu-wayland';
  85. globalThis.HAVE_WAYLAND = GLib.getenv('XDG_SESSION_TYPE') === 'wayland';
  86. globalThis.HAVE_GNOME = GLib.getenv('GNOME_SETUP_DISPLAY') !== null;
  87. /**
  88. * A custom debug function that logs at LEVEL_MESSAGE to avoid the need for env
  89. * variables to be set.
  90. *
  91. * @param {Error|string} message - A string or Error to log
  92. * @param {string} [prefix] - An optional prefix for the warning
  93. */
  94. const _debugCallerMatch = new RegExp(/([^@]*)@([^:]*):([^:]*)/);
  95. // eslint-disable-next-line func-style
  96. const _debugFunc = function (error, prefix = null) {
  97. let caller, message;
  98. if (error.stack) {
  99. caller = error.stack.split('\n')[0];
  100. message = `${error.message}\n${error.stack}`;
  101. } else {
  102. caller = (new Error()).stack.split('\n')[1];
  103. message = JSON.stringify(error, null, 2);
  104. }
  105. if (prefix)
  106. message = `${prefix}: ${message}`;
  107. const [, func, file, line] = _debugCallerMatch.exec(caller);
  108. const script = file.replace(Config.PACKAGE_DATADIR, '');
  109. GLib.log_structured('GSConnect', GLib.LogLevelFlags.LEVEL_MESSAGE, {
  110. 'MESSAGE': `[${script}:${func}:${line}]: ${message}`,
  111. 'SYSLOG_IDENTIFIER': 'org.gnome.Shell.Extensions.GSConnect',
  112. 'CODE_FILE': file,
  113. 'CODE_FUNC': func,
  114. 'CODE_LINE': line,
  115. });
  116. };
  117. // Swap the function out for a no-op anonymous function for speed
  118. const settings = new Gio.Settings({
  119. settings_schema: Config.GSCHEMA.lookup(Config.APP_ID, true),
  120. });
  121. settings.connect('changed::debug', (settings, key) => {
  122. globalThis.debug = settings.get_boolean(key) ? _debugFunc : () => {};
  123. });
  124. if (settings.get_boolean('debug'))
  125. globalThis.debug = _debugFunc;
  126. else
  127. globalThis.debug = () => {};
  128. /**
  129. * Start wl_clipboard if not under Gnome
  130. */
  131. if (!globalThis.HAVE_GNOME) {
  132. debug('Not running as a Gnome extension');
  133. imports.wl_clipboard.watchService();
  134. }
  135. /**
  136. * A simple (for now) pre-comparison sanitizer for phone numbers
  137. * See: https://github.com/KDE/kdeconnect-kde/blob/master/smsapp/conversationlistmodel.cpp#L200-L210
  138. *
  139. * @return {string} Return the string stripped of leading 0, and ' ()-+'
  140. */
  141. String.prototype.toPhoneNumber = function () {
  142. const strippedNumber = this.replace(/^0*|[ ()+-]/g, '');
  143. if (strippedNumber.length)
  144. return strippedNumber;
  145. return this;
  146. };
  147. /**
  148. * A simple equality check for phone numbers based on `toPhoneNumber()`
  149. *
  150. * @param {string} number - A phone number string to compare
  151. * @return {boolean} If `this` and @number are equivalent phone numbers
  152. */
  153. String.prototype.equalsPhoneNumber = function (number) {
  154. const a = this.toPhoneNumber();
  155. const b = number.toPhoneNumber();
  156. return (a.length && b.length && (a.endsWith(b) || b.endsWith(a)));
  157. };
  158. /**
  159. * An implementation of `rm -rf` in Gio
  160. *
  161. * @param {Gio.File|string} file - a GFile or filepath
  162. */
  163. Gio.File.rm_rf = function (file) {
  164. try {
  165. if (typeof file === 'string')
  166. file = Gio.File.new_for_path(file);
  167. try {
  168. const iter = file.enumerate_children(
  169. 'standard::name',
  170. Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
  171. null
  172. );
  173. let info;
  174. while ((info = iter.next_file(null)))
  175. Gio.File.rm_rf(iter.get_child(info));
  176. iter.close(null);
  177. } catch (e) {
  178. // Silence errors
  179. }
  180. file.delete(null);
  181. } catch (e) {
  182. // Silence errors
  183. }
  184. };
  185. /**
  186. * Extend GLib.Variant with a static method to recursively pack a variant
  187. *
  188. * @param {*} [obj] - May be a GLib.Variant, Array, standard Object or literal.
  189. * @return {GLib.Variant} The resulting GVariant
  190. */
  191. function _full_pack(obj) {
  192. let packed;
  193. const type = typeof obj;
  194. switch (true) {
  195. case (obj instanceof GLib.Variant):
  196. return obj;
  197. case (type === 'string'):
  198. return GLib.Variant.new('s', obj);
  199. case (type === 'number'):
  200. return GLib.Variant.new('d', obj);
  201. case (type === 'boolean'):
  202. return GLib.Variant.new('b', obj);
  203. case (obj instanceof Uint8Array):
  204. return GLib.Variant.new('ay', obj);
  205. case (obj === null):
  206. return GLib.Variant.new('mv', null);
  207. case (typeof obj.map === 'function'):
  208. return GLib.Variant.new(
  209. 'av',
  210. obj.filter(e => e !== undefined).map(e => _full_pack(e))
  211. );
  212. case (obj instanceof Gio.Icon):
  213. return obj.serialize();
  214. case (type === 'object'):
  215. packed = {};
  216. for (const [key, val] of Object.entries(obj)) {
  217. if (val !== undefined)
  218. packed[key] = _full_pack(val);
  219. }
  220. return GLib.Variant.new('a{sv}', packed);
  221. default:
  222. throw Error(`Unsupported type '${type}': ${obj}`);
  223. }
  224. }
  225. GLib.Variant.full_pack = _full_pack;
  226. /**
  227. * Extend GLib.Variant with a method to recursively deepUnpack() a variant
  228. *
  229. * @param {*} [obj] - May be a GLib.Variant, Array, standard Object or literal.
  230. * @return {*} The resulting object
  231. */
  232. function _full_unpack(obj) {
  233. obj = (obj === undefined) ? this : obj;
  234. const unpacked = {};
  235. switch (true) {
  236. case (obj === null):
  237. return obj;
  238. case (obj instanceof GLib.Variant):
  239. return _full_unpack(obj.deepUnpack());
  240. case (obj instanceof Uint8Array):
  241. return obj;
  242. case (typeof obj.map === 'function'):
  243. return obj.map(e => _full_unpack(e));
  244. case (typeof obj === 'object'):
  245. for (const [key, value] of Object.entries(obj)) {
  246. // Try to detect and deserialize GIcons
  247. try {
  248. if (key === 'icon' && value.get_type_string() === '(sv)')
  249. unpacked[key] = Gio.Icon.deserialize(value);
  250. else
  251. unpacked[key] = _full_unpack(value);
  252. } catch (e) {
  253. unpacked[key] = _full_unpack(value);
  254. }
  255. }
  256. return unpacked;
  257. default:
  258. return obj;
  259. }
  260. }
  261. GLib.Variant.prototype.full_unpack = _full_unpack;
  262. /**
  263. * Creates a GTlsCertificate from the PEM-encoded data in @cert_path and
  264. * @key_path. If either are missing a new pair will be generated.
  265. *
  266. * Additionally, the private key will be added using ssh-add to allow sftp
  267. * connections using Gio.
  268. *
  269. * See: https://github.com/KDE/kdeconnect-kde/blob/master/core/kdeconnectconfig.cpp#L119
  270. *
  271. * @param {string} certPath - Absolute path to a x509 certificate in PEM format
  272. * @param {string} keyPath - Absolute path to a private key in PEM format
  273. * @param {string} commonName - A unique common name for the certificate
  274. * @return {Gio.TlsCertificate} A TLS certificate
  275. */
  276. Gio.TlsCertificate.new_for_paths = function (certPath, keyPath, commonName = null) {
  277. // Check if the certificate/key pair already exists
  278. const certExists = GLib.file_test(certPath, GLib.FileTest.EXISTS);
  279. const keyExists = GLib.file_test(keyPath, GLib.FileTest.EXISTS);
  280. // Create a new certificate and private key if necessary
  281. if (!certExists || !keyExists) {
  282. // If we weren't passed a common name, generate a random one
  283. if (!commonName)
  284. commonName = GLib.uuid_string_random();
  285. const proc = new Gio.Subprocess({
  286. argv: [
  287. Config.OPENSSL_PATH, 'req',
  288. '-new', '-x509', '-sha256',
  289. '-out', certPath,
  290. '-newkey', 'rsa:4096', '-nodes',
  291. '-keyout', keyPath,
  292. '-days', '3650',
  293. '-subj', `/O=andyholmes.github.io/OU=GSConnect/CN=${commonName}`,
  294. ],
  295. flags: (Gio.SubprocessFlags.STDOUT_SILENCE |
  296. Gio.SubprocessFlags.STDERR_SILENCE),
  297. });
  298. proc.init(null);
  299. proc.wait_check(null);
  300. }
  301. return Gio.TlsCertificate.new_from_files(certPath, keyPath);
  302. };
  303. Object.defineProperties(Gio.TlsCertificate.prototype, {
  304. /**
  305. * The common name of the certificate.
  306. */
  307. 'common_name': {
  308. get: function () {
  309. if (!this.__common_name) {
  310. const proc = new Gio.Subprocess({
  311. argv: [Config.OPENSSL_PATH, 'x509', '-noout', '-subject', '-inform', 'pem'],
  312. flags: Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE,
  313. });
  314. proc.init(null);
  315. const stdout = proc.communicate_utf8(this.certificate_pem, null)[1];
  316. this.__common_name = /(?:cn|CN) ?= ?([^,\n]*)/.exec(stdout)[1];
  317. }
  318. return this.__common_name;
  319. },
  320. configurable: true,
  321. enumerable: true,
  322. },
  323. /**
  324. * Get just the pubkey as a DER ByteArray of a certificate.
  325. *
  326. * @return {GLib.Bytes} The pubkey as DER of the certificate.
  327. */
  328. 'pubkey_der': {
  329. value: function () {
  330. if (!this.__pubkey_der) {
  331. let proc = new Gio.Subprocess({
  332. argv: [Config.OPENSSL_PATH, 'x509', '-noout', '-pubkey', '-inform', 'pem'],
  333. flags: Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE,
  334. });
  335. proc.init(null);
  336. const pubkey = proc.communicate_utf8(this.certificate_pem, null)[1];
  337. proc = new Gio.Subprocess({
  338. argv: [Config.OPENSSL_PATH, 'pkey', '-pubin', '-inform', 'pem', '-outform', 'der'],
  339. flags: Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE,
  340. });
  341. proc.init(null);
  342. this.__pubkey_der = proc.communicate(new TextEncoder().encode(pubkey), null)[1];
  343. }
  344. return this.__pubkey_der;
  345. },
  346. configurable: true,
  347. enumerable: false,
  348. },
  349. });