setup.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. globalThis.HAVE_GNOME = GLib.getenv('GSCONNECT_MODE')?.toLowerCase() !== 'cli' && (GLib.getenv('GNOME_SETUP_DISPLAY') !== null || GLib.getenv('XDG_CURRENT_DESKTOP')?.toUpperCase()?.includes('GNOME') || GLib.getenv('XDG_SESSION_DESKTOP')?.toLowerCase() === 'gnome');
  81. /**
  82. * A custom debug function that logs at LEVEL_MESSAGE to avoid the need for env
  83. * variables to be set.
  84. *
  85. * @param {Error|string} message - A string or Error to log
  86. * @param {string} [prefix] - An optional prefix for the warning
  87. */
  88. const _debugCallerMatch = new RegExp(/([^@]*)@([^:]*):([^:]*)/);
  89. // eslint-disable-next-line func-style
  90. const _debugFunc = function (error, prefix = null) {
  91. let caller, message;
  92. if (error.stack) {
  93. caller = error.stack.split('\n')[0];
  94. message = `${error.message}\n${error.stack}`;
  95. } else {
  96. caller = (new Error()).stack.split('\n')[1];
  97. message = JSON.stringify(error, null, 2);
  98. }
  99. if (prefix)
  100. message = `${prefix}: ${message}`;
  101. const [, func, file, line] = _debugCallerMatch.exec(caller);
  102. const script = file.replace(Config.PACKAGE_DATADIR, '');
  103. GLib.log_structured('GSConnect', GLib.LogLevelFlags.LEVEL_MESSAGE, {
  104. 'MESSAGE': `[${script}:${func}:${line}]: ${message}`,
  105. 'SYSLOG_IDENTIFIER': 'org.gnome.Shell.Extensions.GSConnect',
  106. 'CODE_FILE': file,
  107. 'CODE_FUNC': func,
  108. 'CODE_LINE': line,
  109. });
  110. };
  111. // Swap the function out for a no-op anonymous function for speed
  112. const settings = new Gio.Settings({
  113. settings_schema: Config.GSCHEMA.lookup(Config.APP_ID, true),
  114. });
  115. settings.connect('changed::debug', (settings, key) => {
  116. globalThis.debug = settings.get_boolean(key) ? _debugFunc : () => {};
  117. });
  118. if (settings.get_boolean('debug'))
  119. globalThis.debug = _debugFunc;
  120. else
  121. globalThis.debug = () => {};
  122. /**
  123. * Start wl_clipboard if not under Gnome
  124. */
  125. if (!globalThis.HAVE_GNOME) {
  126. debug('Not running as a Gnome extension');
  127. imports.wl_clipboard.watchService();
  128. }
  129. /**
  130. * A simple (for now) pre-comparison sanitizer for phone numbers
  131. * See: https://github.com/KDE/kdeconnect-kde/blob/master/smsapp/conversationlistmodel.cpp#L200-L210
  132. *
  133. * @return {string} Return the string stripped of leading 0, and ' ()-+'
  134. */
  135. String.prototype.toPhoneNumber = function () {
  136. const strippedNumber = this.replace(/^0*|[ ()+-]/g, '');
  137. if (strippedNumber.length)
  138. return strippedNumber;
  139. return this;
  140. };
  141. /**
  142. * A simple equality check for phone numbers based on `toPhoneNumber()`
  143. *
  144. * @param {string} number - A phone number string to compare
  145. * @return {boolean} If `this` and @number are equivalent phone numbers
  146. */
  147. String.prototype.equalsPhoneNumber = function (number) {
  148. const a = this.toPhoneNumber();
  149. const b = number.toPhoneNumber();
  150. return (a.length && b.length && (a.endsWith(b) || b.endsWith(a)));
  151. };
  152. /**
  153. * An implementation of `rm -rf` in Gio
  154. *
  155. * @param {Gio.File|string} file - a GFile or filepath
  156. */
  157. Gio.File.rm_rf = function (file) {
  158. try {
  159. if (typeof file === 'string')
  160. file = Gio.File.new_for_path(file);
  161. try {
  162. const iter = file.enumerate_children(
  163. 'standard::name',
  164. Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
  165. null
  166. );
  167. let info;
  168. while ((info = iter.next_file(null)))
  169. Gio.File.rm_rf(iter.get_child(info));
  170. iter.close(null);
  171. } catch (e) {
  172. // Silence errors
  173. }
  174. file.delete(null);
  175. } catch (e) {
  176. // Silence errors
  177. }
  178. };
  179. /**
  180. * Extend GLib.Variant with a static method to recursively pack a variant
  181. *
  182. * @param {*} [obj] - May be a GLib.Variant, Array, standard Object or literal.
  183. * @return {GLib.Variant} The resulting GVariant
  184. */
  185. function _full_pack(obj) {
  186. let packed;
  187. const type = typeof obj;
  188. switch (true) {
  189. case (obj instanceof GLib.Variant):
  190. return obj;
  191. case (type === 'string'):
  192. return GLib.Variant.new('s', obj);
  193. case (type === 'number'):
  194. return GLib.Variant.new('d', obj);
  195. case (type === 'boolean'):
  196. return GLib.Variant.new('b', obj);
  197. case (obj instanceof Uint8Array):
  198. return GLib.Variant.new('ay', obj);
  199. case (obj === null):
  200. return GLib.Variant.new('mv', null);
  201. case (typeof obj.map === 'function'):
  202. return GLib.Variant.new(
  203. 'av',
  204. obj.filter(e => e !== undefined).map(e => _full_pack(e))
  205. );
  206. case (obj instanceof Gio.Icon):
  207. return obj.serialize();
  208. case (type === 'object'):
  209. packed = {};
  210. for (const [key, val] of Object.entries(obj)) {
  211. if (val !== undefined)
  212. packed[key] = _full_pack(val);
  213. }
  214. return GLib.Variant.new('a{sv}', packed);
  215. default:
  216. throw Error(`Unsupported type '${type}': ${obj}`);
  217. }
  218. }
  219. GLib.Variant.full_pack = _full_pack;
  220. /**
  221. * Extend GLib.Variant with a method to recursively deepUnpack() a variant
  222. *
  223. * @param {*} [obj] - May be a GLib.Variant, Array, standard Object or literal.
  224. * @return {*} The resulting object
  225. */
  226. function _full_unpack(obj) {
  227. obj = (obj === undefined) ? this : obj;
  228. const unpacked = {};
  229. switch (true) {
  230. case (obj === null):
  231. return obj;
  232. case (obj instanceof GLib.Variant):
  233. return _full_unpack(obj.deepUnpack());
  234. case (obj instanceof Uint8Array):
  235. return obj;
  236. case (typeof obj.map === 'function'):
  237. return obj.map(e => _full_unpack(e));
  238. case (typeof obj === 'object'):
  239. for (const [key, value] of Object.entries(obj)) {
  240. // Try to detect and deserialize GIcons
  241. try {
  242. if (key === 'icon' && value.get_type_string() === '(sv)')
  243. unpacked[key] = Gio.Icon.deserialize(value);
  244. else
  245. unpacked[key] = _full_unpack(value);
  246. } catch (e) {
  247. unpacked[key] = _full_unpack(value);
  248. }
  249. }
  250. return unpacked;
  251. default:
  252. return obj;
  253. }
  254. }
  255. GLib.Variant.prototype.full_unpack = _full_unpack;
  256. /**
  257. * Creates a GTlsCertificate from the PEM-encoded data in @cert_path and
  258. * @key_path. If either are missing a new pair will be generated.
  259. *
  260. * Additionally, the private key will be added using ssh-add to allow sftp
  261. * connections using Gio.
  262. *
  263. * See: https://github.com/KDE/kdeconnect-kde/blob/master/core/kdeconnectconfig.cpp#L119
  264. *
  265. * @param {string} certPath - Absolute path to a x509 certificate in PEM format
  266. * @param {string} keyPath - Absolute path to a private key in PEM format
  267. * @param {string} commonName - A unique common name for the certificate
  268. * @return {Gio.TlsCertificate} A TLS certificate
  269. */
  270. Gio.TlsCertificate.new_for_paths = function (certPath, keyPath, commonName = null) {
  271. // Check if the certificate/key pair already exists
  272. const certExists = GLib.file_test(certPath, GLib.FileTest.EXISTS);
  273. const keyExists = GLib.file_test(keyPath, GLib.FileTest.EXISTS);
  274. // Create a new certificate and private key if necessary
  275. if (!certExists || !keyExists) {
  276. // If we weren't passed a common name, generate a random one
  277. if (!commonName)
  278. commonName = GLib.uuid_string_random();
  279. const proc = new Gio.Subprocess({
  280. argv: [
  281. Config.OPENSSL_PATH, 'req',
  282. '-new', '-x509', '-sha256',
  283. '-out', certPath,
  284. '-newkey', 'rsa:4096', '-nodes',
  285. '-keyout', keyPath,
  286. '-days', '3650',
  287. '-subj', `/O=andyholmes.github.io/OU=GSConnect/CN=${commonName}`,
  288. ],
  289. flags: (Gio.SubprocessFlags.STDOUT_SILENCE |
  290. Gio.SubprocessFlags.STDERR_SILENCE),
  291. });
  292. proc.init(null);
  293. proc.wait_check(null);
  294. }
  295. return Gio.TlsCertificate.new_from_files(certPath, keyPath);
  296. };
  297. Object.defineProperties(Gio.TlsCertificate.prototype, {
  298. /**
  299. * The common name of the certificate.
  300. */
  301. 'common_name': {
  302. get: function () {
  303. if (!this.__common_name) {
  304. const proc = new Gio.Subprocess({
  305. argv: [Config.OPENSSL_PATH, 'x509', '-noout', '-subject', '-inform', 'pem'],
  306. flags: Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE,
  307. });
  308. proc.init(null);
  309. const stdout = proc.communicate_utf8(this.certificate_pem, null)[1];
  310. this.__common_name = /(?:cn|CN) ?= ?([^,\n]*)/.exec(stdout)[1];
  311. }
  312. return this.__common_name;
  313. },
  314. configurable: true,
  315. enumerable: true,
  316. },
  317. /**
  318. * Get just the pubkey as a DER ByteArray of a certificate.
  319. *
  320. * @return {GLib.Bytes} The pubkey as DER of the certificate.
  321. */
  322. 'pubkey_der': {
  323. value: function () {
  324. if (!this.__pubkey_der) {
  325. let proc = new Gio.Subprocess({
  326. argv: [Config.OPENSSL_PATH, 'x509', '-noout', '-pubkey', '-inform', 'pem'],
  327. flags: Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE,
  328. });
  329. proc.init(null);
  330. const pubkey = proc.communicate_utf8(this.certificate_pem, null)[1];
  331. proc = new Gio.Subprocess({
  332. argv: [Config.OPENSSL_PATH, 'pkey', '-pubin', '-inform', 'pem', '-outform', 'der'],
  333. flags: Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE,
  334. });
  335. proc.init(null);
  336. this.__pubkey_der = proc.communicate(new TextEncoder().encode(pubkey), null)[1];
  337. }
  338. return this.__pubkey_der;
  339. },
  340. configurable: true,
  341. enumerable: false,
  342. },
  343. });