'use strict'; var child_process = require('child_process'); var util = require('util'); var fs = require('fs'); var os = require('os'); var path = require('path'); var execRoot = require('exec-root'); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var _this = undefined; var nonSudoExec = util.promisify(child_process.exec); var readFileAsync = util.promisify(fs.readFile); var writeFileAsync = util.promisify(fs.writeFile); var readlinkAsync = util.promisify(fs.readlink); var unlinkAsync = util.promisify(fs.unlink); var existsAsync = util.promisify(fs.exists); var readFileAsLines = function (path$$1) { return __awaiter(_this, void 0, void 0, function () { var data; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, readFileAsync(path$$1, 'utf8')]; case 1: data = _a.sent(); return [2 /*return*/, data.split('\n')]; } }); }); }; var escapeRegExp = function (text) { return text.replace(/["]/g, '\\$&'); }; var mkkdirRecursive = function (targetDir) { var sep = path.sep; var initDir = path.isAbsolute(targetDir) ? sep : ''; var baseDir = '.'; return targetDir.split(sep).reduce(function (parentDir, childDir) { var curDir = path.resolve(baseDir, parentDir, childDir); try { fs.mkdirSync(curDir); } catch (err) { if (err.code === 'EEXIST') { // curDir already exists! return curDir; } // To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows. if (err.code === 'ENOENT') { // Throw the original parentDir error on curDir `ENOENT` failure. throw new Error("EACCES: permission denied, mkdir '" + parentDir + "'"); } var caughtErr = ['EACCES', 'EPERM', 'EISDIR'].indexOf(err.code) > -1; if (!caughtErr || (caughtErr && curDir === path.resolve(targetDir))) { throw err; // Throw if it's just the last created dir. } } return curDir; }, initDir); }; var homedir = os.homedir(); var tmpdir = os.tmpdir(); var env = process.env; var macos = function (name) { var library = path.join(homedir, 'Library'); return { data: path.join(library, 'Application Support', name), config: path.join(library, 'Preferences', name), cache: path.join(library, 'Caches', name), log: path.join(library, 'Logs', name), temp: path.join(tmpdir, name) }; }; var windows = function (name) { var appData = env.APPDATA || path.join(homedir, 'AppData', 'Roaming'); var localAppData = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local'); return { // Data/config/cache/log are invented by me as Windows isn't opinionated about this data: path.join(localAppData, name, 'Data'), config: path.join(appData, name, 'Config'), cache: path.join(localAppData, name, 'Cache'), log: path.join(localAppData, name, 'Log'), temp: path.join(tmpdir, name) }; }; // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html var linux = function (name) { var username = path.basename(homedir); return { data: path.join(env.XDG_DATA_HOME || path.join(homedir, '.local', 'share'), name), config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, '.config'), name), cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, '.cache'), name), // https://wiki.debian.org/XDGBaseDirectorySpecification#state log: path.join(env.XDG_STATE_HOME || path.join(homedir, '.local', 'state'), name), temp: path.join(tmpdir, username, name) }; }; var envPaths = function (name, options) { options = Object.assign({ suffix: 'nodejs' }, options); if (options.suffix) { // Add suffix to prevent possible conflict with native apps name += "-" + options.suffix; } if (process.platform === 'darwin') { return macos(name); } if (process.platform === 'win32') { return windows(name); } return linux(name); }; var Editor = /** @class */ (function () { function Editor(name) { if (name === void 0) { name = 'DefaultDns'; } this.addedNameservers = []; this.savedNameservers = []; this.savedResolvFileLines = []; this.savedResolvSymlink = ''; this.networkInterface = ''; this.appName = ''; this.dataPath = ''; this.appName = name; this.paths = envPaths(name); this.dataPath = path.join(this.paths.data, name + ".json"); } Editor.prototype.saveDataToFile = function () { return __awaiter(this, void 0, void 0, function () { var data; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.dataFileExists()]; case 1: if (!(_a.sent())) { mkkdirRecursive(this.paths.data); } data = JSON.stringify({ pid: process.pid, addedNameservers: this.addedNameservers, savedNameservers: this.savedNameservers, savedResolvFileLines: this.savedResolvFileLines, savedResolvSymlink: this.savedResolvSymlink, networkInterface: this.networkInterface, appName: this.appName }, null, 2); return [4 /*yield*/, writeFileAsync(this.dataPath, data, 'utf-8')]; case 2: _a.sent(); return [2 /*return*/]; } }); }); }; Editor.prototype.loadDataFromFile = function () { return __awaiter(this, void 0, void 0, function () { var data, _a, _b, _i, _c, _d, key, value; return __generator(this, function (_e) { switch (_e.label) { case 0: return [4 /*yield*/, this.dataFileExists()]; case 1: if (!(_e.sent())) return [2 /*return*/]; _b = (_a = JSON).parse; return [4 /*yield*/, readFileAsync(this.dataPath, 'utf-8')]; case 2: data = _b.apply(_a, [_e.sent()]); for (_i = 0, _c = Object.entries(data); _i < _c.length; _i++) { _d = _c[_i], key = _d[0], value = _d[1]; this[key] = value; } return [2 /*return*/]; } }); }); }; Editor.prototype.deleteDataFile = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.dataFileExists()]; case 1: if (!(_a.sent())) return [2 /*return*/]; return [4 /*yield*/, unlinkAsync(this.dataPath)]; case 2: _a.sent(); return [2 /*return*/]; } }); }); }; Editor.prototype.dataFileExists = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, existsAsync(this.dataPath)]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; return Editor; }()); var MacosEditor = /** @class */ (function (_super) { __extends(MacosEditor, _super); function MacosEditor(name) { if (name === void 0) { name = 'DefaultDns'; } return _super.call(this, name) || this; } /** * Sets current network interface's DNS * * @param dnsList List of new DNS addresses to apply */ MacosEditor.prototype.load = function (dnsList) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.updateNetworkInterface()]; case 1: _a.sent(); return [4 /*yield*/, this.setDns(this.networkInterface, dnsList)]; case 2: _a.sent(); this.addedNameservers = dnsList; return [2 /*return*/]; } }); }); }; /** * Saves current user's list of DNs addresses */ MacosEditor.prototype.save = function () { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, this.updateNetworkInterface()]; case 1: _b.sent(); _a = this; return [4 /*yield*/, this.getDns(this.networkInterface)]; case 2: _a.savedNameservers = _b.sent(); return [4 /*yield*/, this.saveDataToFile()]; case 3: _b.sent(); return [2 /*return*/]; } }); }); }; /** * Set's DNS list to currently saved list */ MacosEditor.prototype.recover = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.loadDataFromFile()]; case 1: _a.sent(); return [4 /*yield*/, this.setDns(this.networkInterface, this.savedNameservers)]; case 2: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Check if name server exists * * @param nameserver Name of the nameserver to find if exists */ MacosEditor.prototype.exists = function (nameserver) { return __awaiter(this, void 0, void 0, function () { var currentInterface, _a, nameservers; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!this.networkInterface) return [3 /*break*/, 1]; _a = this.networkInterface; return [3 /*break*/, 3]; case 1: return [4 /*yield*/, this.getNetworkInterface()]; case 2: _a = _b.sent(); _b.label = 3; case 3: currentInterface = _a; return [4 /*yield*/, this.getDns(currentInterface)]; case 4: nameservers = _b.sent(); return [2 /*return*/, nameservers.find(function (ns) { return ns === nameserver; })]; } }); }); }; /** * Fetches the current network interface and updates class object */ MacosEditor.prototype.updateNetworkInterface = function () { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = this; return [4 /*yield*/, this.getNetworkInterface()]; case 1: _a.networkInterface = _b.sent(); return [2 /*return*/]; } }); }); }; /** * Updates the list of DNS addresses for a particular network interface * * @param networkInterface Network interface to update * @param dnsList List of DNS addresses to set */ MacosEditor.prototype.setDns = function (networkInterface, dnsList) { return __awaiter(this, void 0, void 0, function () { var joinedDnsList; return __generator(this, function (_a) { joinedDnsList = dnsList.length ? dnsList.join(' ') : 'empty'; return [2 /*return*/, nonSudoExec("networksetup -setdnsservers \"" + networkInterface + "\" " + joinedDnsList)]; }); }); }; /** * Fetches list of DNS addresses * * @param networkInterface Network interface to read */ MacosEditor.prototype.getDns = function (networkInterface) { return __awaiter(this, void 0, void 0, function () { var stdout; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, nonSudoExec("networksetup -getdnsservers \"" + networkInterface + "\"")]; case 1: stdout = (_a.sent()).stdout; if (stdout && !/'/.test(stdout)) { return [2 /*return*/, stdout.split('\n').filter(function (line) { return line; })]; } else { return [2 /*return*/, []]; } return [2 /*return*/]; } }); }); }; /** * Get current network interface */ MacosEditor.prototype.getNetworkInterface = function () { return __awaiter(this, void 0, void 0, function () { var stdout; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, nonSudoExec("networksetup -listnetworkserviceorder | grep $(route get example.com | grep interface | awk '{print $2}') | awk 'gsub(/.*Hardware Port: |,.*/,\"\")'")]; case 1: stdout = (_a.sent()).stdout; return [2 /*return*/, stdout.trim()]; } }); }); }; return MacosEditor; }(Editor)); var WindowsEditor = /** @class */ (function (_super) { __extends(WindowsEditor, _super); function WindowsEditor(name) { if (name === void 0) { name = 'DefaultDns'; } return _super.call(this, name) || this; } /** * * @param dnsList List of new DNS addresses to apply */ WindowsEditor.prototype.load = function (dnsList) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.updateNetworkInterface()]; case 1: _a.sent(); return [4 /*yield*/, this.setDns(this.networkInterface, dnsList)]; case 2: _a.sent(); this.addedNameservers = dnsList; return [4 /*yield*/, this.saveDataToFile()]; case 3: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Saves current user's list of DNs addresses */ WindowsEditor.prototype.save = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/]; }); }); }; /** * Set's DNS list to currently saved list */ WindowsEditor.prototype.recover = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.loadDataFromFile()]; case 1: _a.sent(); return [4 /*yield*/, this.removeDns(this.networkInterface, this.addedNameservers)]; case 2: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Check if name server exists * * @param nameserver Name of the nameserver to find if exists */ WindowsEditor.prototype.exists = function (nameserver) { return __awaiter(this, void 0, void 0, function () { var fullConfigLines, regexp; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.getDns(this.networkInterface)]; case 1: fullConfigLines = _a.sent(); regexp = new RegExp(nameserver); return [2 /*return*/, fullConfigLines.find(function (line) { return regexp.test(line); })]; } }); }); }; /** * Fetches the current network interface and updates class object */ WindowsEditor.prototype.updateNetworkInterface = function () { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = this; return [4 /*yield*/, this.getNetworkInterface()]; case 1: _a.networkInterface = _b.sent(); return [2 /*return*/]; } }); }); }; /** * Updates the list of DNS addresses for a particular network interface * * @param networkInterface Network interface to update * @param dnsList List of DNS addresses to set */ WindowsEditor.prototype.setDns = function (networkInterface, dnsList) { return __awaiter(this, void 0, void 0, function () { var idx, _i, dnsList_1, ns; return __generator(this, function (_a) { switch (_a.label) { case 0: idx = 1; _i = 0, dnsList_1 = dnsList; _a.label = 1; case 1: if (!(_i < dnsList_1.length)) return [3 /*break*/, 4]; ns = dnsList_1[_i]; return [4 /*yield*/, nonSudoExec("netsh interface ipv4 add dnsservers name=\"" + networkInterface + "\" " + ns + " index=" + idx + " validate=no")]; case 2: _a.sent(); idx++; _a.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: return [2 /*return*/]; } }); }); }; /** * Deletes the list of DNS addresses for a particular network interface * * @param networkInterface Network interface to update * @param dnsList List of DNS addresses to set */ WindowsEditor.prototype.removeDns = function (networkInterface, dnsList) { return __awaiter(this, void 0, void 0, function () { var _i, dnsList_2, ns; return __generator(this, function (_a) { switch (_a.label) { case 0: _i = 0, dnsList_2 = dnsList; _a.label = 1; case 1: if (!(_i < dnsList_2.length)) return [3 /*break*/, 4]; ns = dnsList_2[_i]; return [4 /*yield*/, nonSudoExec("netsh interface ipv4 delete dnsservers name=\"" + networkInterface + "\" " + ns + " validate=no")]; case 2: _a.sent(); _a.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: return [2 /*return*/]; } }); }); }; /** * Fetches list of DNS addresses * * @param networkInterface Network interface to read */ WindowsEditor.prototype.getDns = function (networkInterface) { return __awaiter(this, void 0, void 0, function () { var stdout; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, nonSudoExec("netsh interface ipv4 show config")]; case 1: stdout = (_a.sent()).stdout; console.log('Get DNS:', stdout); if (stdout) { return [2 /*return*/, stdout.split('\r\n').filter(function (line) { return line; })]; } else { return [2 /*return*/, []]; } return [2 /*return*/]; } }); }); }; /** * Get current network interface */ WindowsEditor.prototype.getNetworkInterface = function () { return __awaiter(this, void 0, void 0, function () { var _a, stdout, stderr, results, resultInterface; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, nonSudoExec("netsh interface show interface")]; case 1: _a = _b.sent(), stdout = _a.stdout, stderr = _a.stderr; console.log('Netint stdout:', stdout); console.log('Netint stderr:', stderr); results = stdout .split('\r\n') .filter(function (line) { return line; }) .map(function (line) { return line.split(/\s+/); }); console.log('Netint results:', results); resultInterface = results.find(function (result) { return result.length === 4 && result[0] === 'Enabled' && result[1] === 'Connected'; }) || ['', '', '', '']; console.log('Netint resultInterface:', resultInterface); return [2 /*return*/, resultInterface[3]]; } }); }); }; return WindowsEditor; }(Editor)); var RESOLV_PATH = '/etc/resolv.conf'; var LinuxEditor = /** @class */ (function (_super) { __extends(LinuxEditor, _super); function LinuxEditor(name) { if (name === void 0) { name = 'DefaultDns'; } return _super.call(this, name) || this; } /** * Sets current network interface's DNS * * @param dnsList List of new DNS addresses to apply */ LinuxEditor.prototype.load = function (dnsList) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.setDns(dnsList, this.savedResolvFileLines)]; case 1: _a.sent(); this.addedNameservers = dnsList; return [2 /*return*/]; } }); }); }; /** * Saves current user's list of DNs addresses */ LinuxEditor.prototype.save = function () { return __awaiter(this, void 0, void 0, function () { var _a, _b, e_1; return __generator(this, function (_c) { switch (_c.label) { case 0: _a = this; return [4 /*yield*/, this.getDns()]; case 1: _a.savedResolvFileLines = _c.sent(); _c.label = 2; case 2: _c.trys.push([2, 4, , 5]); _b = this; return [4 /*yield*/, readlinkAsync(RESOLV_PATH, 'utf8')]; case 3: _b.savedResolvSymlink = _c.sent(); return [3 /*break*/, 5]; case 4: e_1 = _c.sent(); console.log(e_1); return [3 /*break*/, 5]; case 5: return [4 /*yield*/, this.saveDataToFile()]; case 6: _c.sent(); return [2 /*return*/]; } }); }); }; /** * Set's DNS list to currently saved lists */ LinuxEditor.prototype.recover = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.loadDataFromFile()]; case 1: _a.sent(); return [4 /*yield*/, this.setDns([], this.savedResolvFileLines, this.savedResolvSymlink)]; case 2: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Check if name server exists * * @param nameserver Name of the nameserver to find if exists */ LinuxEditor.prototype.exists = function (nameserver) { return __awaiter(this, void 0, void 0, function () { var currentResolvLines, formattedNs; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.getDns()]; case 1: currentResolvLines = _a.sent(); formattedNs = this.formatNs(nameserver); return [2 /*return*/, currentResolvLines.find(function (ns) { return ns === formattedNs; })]; } }); }); }; /** * Updates the list of DNS addresses for a particular network interface * * @param networkInterface Network interface to update * @param dnsList List of DNS addresses to set */ LinuxEditor.prototype.setDns = function (dnsList, savedLines, savedResolvSymlink) { if (savedLines === void 0) { savedLines = []; } if (savedResolvSymlink === void 0) { savedResolvSymlink = ''; } return __awaiter(this, void 0, void 0, function () { var fullFileLines, text, command; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: fullFileLines = dnsList.map(function (ns) { return _this.formatNs(ns); }).concat(savedLines); text = fullFileLines.join('\n'); command = savedResolvSymlink !== '' ? "ln -s " + savedResolvSymlink + " " + RESOLV_PATH : "tee " + RESOLV_PATH + " <<< '" + escapeRegExp(text) + "'"; console.log('Setting DNS'); console.log("Symlink: " + savedResolvSymlink); console.log("Command: bash -c \"rm -f " + RESOLV_PATH + "; " + command + ";\""); return [4 /*yield*/, execRoot.exec("bash -c \"rm -f " + RESOLV_PATH + "; " + command + ";\"", { name: this.appName })]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Fetches resolve conf * * @param networkInterface Network interface to read */ LinuxEditor.prototype.getDns = function () { return __awaiter(this, void 0, void 0, function () { var _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: console.log('Get DNS'); _b = (_a = console).log; return [4 /*yield*/, readFileAsLines(RESOLV_PATH)]; case 1: _b.apply(_a, [_c.sent()]); return [2 /*return*/, readFileAsLines(RESOLV_PATH)]; } }); }); }; LinuxEditor.prototype.formatNs = function (nameserver) { return "nameserver " + nameserver; }; return LinuxEditor; }(Editor)); var editor; if (process.platform === 'darwin') { editor = MacosEditor; } else if (process.platform === 'win32') { editor = WindowsEditor; } else if (process.platform === 'linux') { editor = LinuxEditor; } else { console.error('Only Macos, Windows and Linux supported.'); } var editor$1 = editor; module.exports = editor$1; //# sourceMappingURL=edit-dns.cjs.map