Best Python code snippet using avocado_python
asyncdns.py
Source:asyncdns.py  
...214            return response215    except Exception as e:216        shell.print_exception(e)217        return None218def is_valid_hostname(hostname):219    if len(hostname) > 255:220        return False221    if hostname[-1] == b'.':222        hostname = hostname[:-1]223    return all(VALID_HOSTNAME.match(x) for x in hostname.split(b'.'))224class DNSResponse(object):225    def __init__(self):226        self.hostname = None227        self.questions = []  # each: (addr, type, class)228        self.answers = []  # each: (addr, type, class)229    def __str__(self):230        return '%s: %s' % (self.hostname, str(self.answers))231STATUS_IPV4 = 0232STATUS_IPV6 = 1233class DNSResolver(object):234    def __init__(self, black_hostname_list=None):235        self._loop = None236        self._hosts = {}237        self._hostname_status = {}238        self._hostname_to_cb = {}239        self._cb_to_hostname = {}240        self._cache = lru_cache.LRUCache(timeout=300)241        # read black_hostname_list from config242        if type(black_hostname_list) != list:243            self._black_hostname_list = []244        else:245            self._black_hostname_list = list(map(246                (lambda t: t if type(t) == bytes else t.encode('utf8')),247                black_hostname_list248            ))249        logging.info('black_hostname_list init as : ' + str(self._black_hostname_list))250        self._sock = None251        self._servers = None252        self._parse_resolv()253        self._parse_hosts()254        # TODO monitor hosts change and reload hosts255        # TODO parse /etc/gai.conf and follow its rules256    def _parse_resolv(self):257        self._servers = []258        try:259            with open('dns.conf', 'rb') as f:260                content = f.readlines()261                for line in content:262                    line = line.strip()263                    if line:264                        parts = line.split(b' ', 1)265                        if len(parts) >= 2:266                            server = parts[0]267                            port = int(parts[1])268                        else:269                            server = parts[0]270                            port = 53271                        if common.is_ip(server) == socket.AF_INET:272                            if type(server) != str:273                                server = server.decode('utf8')274                            self._servers.append((server, port))275        except IOError:276            pass277        if not self._servers:278            try:279                with open('/etc/resolv.conf', 'rb') as f:280                    content = f.readlines()281                    for line in content:282                        line = line.strip()283                        if line:284                            if line.startswith(b'nameserver'):285                                parts = line.split()286                                if len(parts) >= 2:287                                    server = parts[1]288                                    if common.is_ip(server) == socket.AF_INET:289                                        if type(server) != str:290                                            server = server.decode('utf8')291                                        self._servers.append((server, 53))292            except IOError:293                pass294        if not self._servers:295            self._servers = [('8.8.4.4', 53), ('8.8.8.8', 53)]296        logging.info('dns server: %s' % (self._servers,))297    def _parse_hosts(self):298        etc_path = '/etc/hosts'299        if 'WINDIR' in os.environ:300            etc_path = os.environ['WINDIR'] + '/system32/drivers/etc/hosts'301        try:302            with open(etc_path, 'rb') as f:303                for line in f.readlines():304                    line = line.strip()305                    if b"#" in line:306                        line = line[:line.find(b'#')]307                    parts = line.split()308                    if len(parts) >= 2:309                        ip = parts[0]310                        if common.is_ip(ip):311                            for i in range(1, len(parts)):312                                hostname = parts[i]313                                if hostname:314                                    self._hosts[hostname] = ip315        except IOError:316            self._hosts['localhost'] = '127.0.0.1'317    def add_to_loop(self, loop):318        if self._loop:319            raise Exception('already add to loop')320        self._loop = loop321        # TODO when dns server is IPv6322        self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,323                                   socket.SOL_UDP)324        self._sock.setblocking(False)325        loop.add(self._sock, eventloop.POLL_IN, self)326        loop.add_periodic(self.handle_periodic)327    def _call_callback(self, hostname, ip, error=None):328        callbacks = self._hostname_to_cb.get(hostname, [])329        for callback in callbacks:330            if callback in self._cb_to_hostname:331                del self._cb_to_hostname[callback]332            if ip or error:333                callback((hostname, ip), error)334            else:335                callback((hostname, None),336                         Exception('unable to parse hostname %s' % hostname))337        if hostname in self._hostname_to_cb:338            del self._hostname_to_cb[hostname]339        if hostname in self._hostname_status:340            del self._hostname_status[hostname]341    def _handle_data(self, data):342        response = parse_response(data)343        if response and response.hostname:344            hostname = response.hostname345            ip = None346            for answer in response.answers:347                if answer[1] in (QTYPE_A, QTYPE_AAAA) and \348                                answer[2] == QCLASS_IN:349                    ip = answer[0]350                    break351            if IPV6_CONNECTION_SUPPORT:352                if not ip and self._hostname_status.get(hostname, STATUS_IPV4) \353                        == STATUS_IPV6:354                    self._hostname_status[hostname] = STATUS_IPV4355                    self._send_req(hostname, QTYPE_A)356                else:357                    if ip:358                        self._cache[hostname] = ip359                        self._call_callback(hostname, ip)360                    elif self._hostname_status.get(hostname, None) == STATUS_IPV4:361                        for question in response.questions:362                            if question[1] == QTYPE_A:363                                self._call_callback(hostname, None)364                                break365            else:366                if not ip and self._hostname_status.get(hostname, STATUS_IPV6) \367                        == STATUS_IPV4:368                    self._hostname_status[hostname] = STATUS_IPV6369                    self._send_req(hostname, QTYPE_AAAA)370                else:371                    if ip:372                        self._cache[hostname] = ip373                        self._call_callback(hostname, ip)374                    elif self._hostname_status.get(hostname, None) == STATUS_IPV6:375                        for question in response.questions:376                            if question[1] == QTYPE_AAAA:377                                self._call_callback(hostname, None)378                                break379    def handle_event(self, sock, fd, event):380        if sock != self._sock:381            return382        if event & eventloop.POLL_ERR:383            logging.error('dns socket err')384            self._loop.remove(self._sock)385            self._sock.close()386            # TODO when dns server is IPv6387            self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,388                                       socket.SOL_UDP)389            self._sock.setblocking(False)390            self._loop.add(self._sock, eventloop.POLL_IN, self)391        else:392            data, addr = sock.recvfrom(1024)393            if addr not in self._servers:394                logging.warn('received a packet other than our dns')395                return396            self._handle_data(data)397    def handle_periodic(self):398        self._cache.sweep()399    def remove_callback(self, callback):400        hostname = self._cb_to_hostname.get(callback)401        if hostname:402            del self._cb_to_hostname[callback]403            arr = self._hostname_to_cb.get(hostname, None)404            if arr:405                arr.remove(callback)406                if not arr:407                    del self._hostname_to_cb[hostname]408                    if hostname in self._hostname_status:409                        del self._hostname_status[hostname]410    def _send_req(self, hostname, qtype):411        req = build_request(hostname, qtype)412        for server in self._servers:413            logging.debug('resolving %s with type %d using server %s',414                          hostname, qtype, server)415            self._sock.sendto(req, server)416    def resolve(self, hostname, callback):417        if type(hostname) != bytes:418            hostname = hostname.encode('utf8')419        if not hostname:420            callback(None, Exception('empty hostname'))421        elif common.is_ip(hostname):422            callback((hostname, hostname), None)423        elif hostname in self._hosts:424            logging.debug('hit hosts: %s', hostname)425            ip = self._hosts[hostname]426            callback((hostname, ip), None)427        elif hostname in self._cache:428            logging.debug('hit cache: %s ==>> %s', hostname, self._cache[hostname])429            ip = self._cache[hostname]430            callback((hostname, ip), None)431        elif any(hostname.endswith(t) for t in self._black_hostname_list):432            callback(None, Exception('hostname <%s> is block by the black hostname list' % hostname))433            return434        else:435            if not is_valid_hostname(hostname):436                callback(None, Exception('invalid hostname: %s' % hostname))437                return438            if False:439                addrs = socket.getaddrinfo(hostname, 0, 0,440                                           socket.SOCK_DGRAM, socket.SOL_UDP)441                if addrs:442                    af, socktype, proto, canonname, sa = addrs[0]443                    logging.debug('DNS resolve %s %s' % (hostname, sa[0]))444                    self._cache[hostname] = sa[0]445                    callback((hostname, sa[0]), None)446                    return447            arr = self._hostname_to_cb.get(hostname, None)448            if not arr:449                if IPV6_CONNECTION_SUPPORT:...dynamic-net-filtering.js
Source:dynamic-net-filtering.js  
1/*******************************************************************************2    uBlock Origin - a browser extension to block requests.3    Copyright (C) 2014-2017 Raymond Hill4    This program is free software: you can redistribute it and/or modify5    it under the terms of the GNU General Public License as published by6    the Free Software Foundation, either version 3 of the License, or7    (at your option) any later version.8    This program is distributed in the hope that it will be useful,9    but WITHOUT ANY WARRANTY; without even the implied warranty of10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the11    GNU General Public License for more details.12    You should have received a copy of the GNU General Public License13    along with this program.  If not, see {http://www.gnu.org/licenses/}.14    Home: https://github.com/gorhill/uBlock15*/16/* global punycode */17/* jshint bitwise: false */18'use strict';19/******************************************************************************/20µBlock.Firewall = (function() {21/******************************************************************************/22var magicId = 'chmdgxwtetgu';23/******************************************************************************/24var Matrix = function() {25    this.reset();26};27/******************************************************************************/28var supportedDynamicTypes = {29           '3p': true,30        'image': true,31'inline-script': true,32    '1p-script': true,33    '3p-script': true,34     '3p-frame': true35};36var typeBitOffsets = {37            '*':  0,38'inline-script':  2,39    '1p-script':  4,40    '3p-script':  6,41     '3p-frame':  8,42        'image': 10,43           '3p': 1244};45var actionToNameMap = {46    '1': 'block',47    '2': 'allow',48    '3': 'noop'49};50var nameToActionMap = {51    'block': 1,52    'allow': 2,53     'noop': 354};55/******************************************************************************/56// For performance purpose, as simple tests as possible57var reHostnameVeryCoarse = /[g-z_-]/;58var reIPv4VeryCoarse = /\.\d+$/;59var reBadHostname = /[^0-9a-z_.\[\]:-]/;60// http://tools.ietf.org/html/rfc595261// 4.3: "MUST be represented in lowercase"62// Also: http://en.wikipedia.org/wiki/IPv6_address#Literal_IPv6_addresses_in_network_resource_identifiers63var isIPAddress = function(hostname) {64    if ( reHostnameVeryCoarse.test(hostname) ) {65        return false;66    }67    if ( reIPv4VeryCoarse.test(hostname) ) {68        return true;69    }70    return hostname.startsWith('[');71};72var toBroaderHostname = function(hostname) {73    var pos = hostname.indexOf('.');74    if ( pos !== -1 ) {75        return hostname.slice(pos + 1);76    }77    return hostname !== '*' && hostname !== '' ? '*' : '';78};79var toBroaderIPAddress = function(ipaddress) {80    return ipaddress !== '*' && ipaddress !== '' ? '*' : '';81};82var selectHostnameBroadener = function(hostname) {83    return isIPAddress(hostname) ? toBroaderIPAddress : toBroaderHostname;84};85/******************************************************************************/86Matrix.prototype.reset = function() {87    this.r = 0;88    this.type = '';89    this.y = '';90    this.z = '';91    this.rules = {};92};93/******************************************************************************/94Matrix.prototype.assign = function(other) {95    var thisRules = this.rules;96    var otherRules = other.rules;97    var k;98    // Remove rules not in other99    for ( k in thisRules ) {100        if ( thisRules.hasOwnProperty(k) === false ) {101            continue;102        }103        if ( otherRules.hasOwnProperty(k) === false ) {104            delete thisRules[k];105        }106    }107    // Add/change rules in other108    for ( k in otherRules ) {109        if ( otherRules.hasOwnProperty(k) === false ) {110            continue;111        }112        thisRules[k] = otherRules[k];113    }114};115/******************************************************************************/116Matrix.prototype.copyRules = function(other, srcHostname, desHostnames) {117    var thisRules = this.rules;118    var otherRules = other.rules;119    var ruleKey, ruleValue;120    // Specific types121    ruleValue = otherRules['* *'] || 0;122    if ( ruleValue !== 0 ) {123        thisRules['* *'] = ruleValue;124    } else {125        delete thisRules['* *'];126    }127    ruleKey = srcHostname + ' *';128    ruleValue = otherRules[ruleKey] || 0;129    if ( ruleValue !== 0 ) {130        thisRules[ruleKey] = ruleValue;131    } else {132        delete thisRules[ruleKey];133    }134    // Specific destinations135    for ( var desHostname in desHostnames ) {136        if ( desHostnames.hasOwnProperty(desHostname) === false ) {137            continue;138        }139        ruleKey = '* ' + desHostname;140        ruleValue = otherRules[ruleKey] || 0;141        if ( ruleValue !== 0 ) {142            thisRules[ruleKey] = ruleValue;143        } else {144            delete thisRules[ruleKey];145        }146        ruleKey = srcHostname + ' ' + desHostname ;147        ruleValue = otherRules[ruleKey] || 0;148        if ( ruleValue !== 0 ) {149            thisRules[ruleKey] = ruleValue;150        } else {151            delete thisRules[ruleKey];152        }153    }154    return true;155};156/******************************************************************************/157// - *    *  type158// - from *  type159// - *    to *160// - from to *161Matrix.prototype.hasSameRules = function(other, srcHostname, desHostnames) {162    var thisRules = this.rules;163    var otherRules = other.rules;164    var ruleKey;165    // Specific types166    ruleKey = '* *';167    if ( (thisRules[ruleKey] || 0) !== (otherRules[ruleKey] || 0) ) {168        return false;169    }170    ruleKey = srcHostname + ' *';171    if ( (thisRules[ruleKey] || 0) !== (otherRules[ruleKey] || 0) ) {172        return false;173    }174    // Specific destinations175    for ( var desHostname in desHostnames ) {176        ruleKey = '* ' + desHostname;177        if ( (thisRules[ruleKey] || 0) !== (otherRules[ruleKey] || 0) ) {178            return false;179        }180        ruleKey = srcHostname + ' ' + desHostname ;181        if ( (thisRules[ruleKey] || 0) !== (otherRules[ruleKey] || 0) ) {182            return false;183        }184    }185    return true;186};187/******************************************************************************/188Matrix.prototype.setCell = function(srcHostname, desHostname, type, state) {189    var bitOffset = typeBitOffsets[type];190    var k = srcHostname + ' ' + desHostname;191    var oldBitmap = this.rules[k];192    if ( oldBitmap === undefined ) {193        oldBitmap = 0;194    }195    var newBitmap = oldBitmap & ~(3 << bitOffset) | (state << bitOffset);196    if ( newBitmap === oldBitmap ) {197        return false;198    }199    if ( newBitmap === 0 ) {200        delete this.rules[k];201    } else {202        this.rules[k] = newBitmap;203    }204    return true;205};206/******************************************************************************/207Matrix.prototype.unsetCell = function(srcHostname, desHostname, type) {208    this.evaluateCellZY(srcHostname, desHostname, type);209    if ( this.r === 0 ) {210        return false;211    }212    this.setCell(srcHostname, desHostname, type, 0);213    return true;214};215// https://www.youtube.com/watch?v=Csewb_eIStY216/******************************************************************************/217Matrix.prototype.evaluateCell = function(srcHostname, desHostname, type) {218    var key = srcHostname + ' ' + desHostname;219    var bitmap = this.rules[key];220    if ( bitmap === undefined ) {221        return 0;222    }223    return bitmap >> typeBitOffsets[type] & 3;224};225/******************************************************************************/226Matrix.prototype.clearRegisters = function() {227    this.r = 0;228    this.type = this.y = this.z = '';229    return this;230};231/******************************************************************************/232var is3rdParty = function(srcHostname, desHostname) {233    // If at least one is party-less, the relation can't be labelled234    // "3rd-party"235    if ( desHostname === '*' || srcHostname === '*' || srcHostname === '' ) {236        return false;237    }238    // No domain can very well occurs, for examples:239    // - localhost240    // - file-scheme241    // etc.242    var srcDomain = domainFromHostname(srcHostname) || srcHostname;243    if ( desHostname.endsWith(srcDomain) === false ) {244        return true;245    }246    // Do not confuse 'example.com' with 'anotherexample.com'247    return desHostname.length !== srcDomain.length &&248           desHostname.charAt(desHostname.length - srcDomain.length - 1) !== '.';249};250var domainFromHostname = µBlock.URI.domainFromHostname;251/******************************************************************************/252Matrix.prototype.evaluateCellZ = function(srcHostname, desHostname, type, broadener) {253    this.type = type;254    var bitOffset = typeBitOffsets[type];255    var s = srcHostname;256    var v;257    for (;;) {258        this.z = s;259        v = this.rules[s + ' ' + desHostname];260        if ( v !== undefined ) {261            v = v >>> bitOffset & 3;262            if ( v !== 0 ) {263                this.r = v;264                return v;265            }266        }267        s = broadener(s);268        if ( s === '' ) { break; }269    }270    // srcHostname is '*' at this point271    this.r = 0;272    return 0;273};274/******************************************************************************/275Matrix.prototype.evaluateCellZY = function(srcHostname, desHostname, type) {276    // Pathological cases.277    var d = desHostname;278    if ( d === '' ) {279        this.r = 0;280        return 0;281    }282    // Prepare broadening handlers -- depends on whether we are dealing with283    // a hostname or IP address.284    var broadenSource = selectHostnameBroadener(srcHostname),285        broadenDestination = selectHostnameBroadener(desHostname);286    // Precedence: from most specific to least specific287    // Specific-destination, any party, any type288    while ( d !== '*' ) {289        this.y = d;290        if ( this.evaluateCellZ(srcHostname, d, '*', broadenSource) !== 0 ) {291            return this.r;292        }293        d = broadenDestination(d);294    }295    var thirdParty = is3rdParty(srcHostname, desHostname);296    // Any destination297    this.y = '*';298    // Specific party299    if ( thirdParty ) {300        // 3rd-party, specific type301        if ( type === 'script' ) {302            if ( this.evaluateCellZ(srcHostname, '*', '3p-script', broadenSource) !== 0 ) {303                return this.r;304            }305        } else if ( type === 'sub_frame' ) {306            if ( this.evaluateCellZ(srcHostname, '*', '3p-frame', broadenSource) !== 0 ) {307                return this.r;308            }309        }310        // 3rd-party, any type311        if ( this.evaluateCellZ(srcHostname, '*', '3p', broadenSource) !== 0 ) {312            return this.r;313        }314    } else if ( type === 'script' ) {315        // 1st party, specific type316        if ( this.evaluateCellZ(srcHostname, '*', '1p-script', broadenSource) !== 0 ) {317            return this.r;318        }319    }320    // Any destination, any party, specific type321    if ( supportedDynamicTypes.hasOwnProperty(type) ) {322        if ( this.evaluateCellZ(srcHostname, '*', type, broadenSource) !== 0 ) {323            return this.r;324        }325    }326    // Any destination, any party, any type327    if ( this.evaluateCellZ(srcHostname, '*', '*', broadenSource) !== 0 ) {328        return this.r;329    }330    this.type = '';331    return 0;332};333// http://youtu.be/gSGk1bQ9rcU?t=25m6s334/******************************************************************************/335Matrix.prototype.mustAllowCellZY = function(srcHostname, desHostname, type) {336    return this.evaluateCellZY(srcHostname, desHostname, type) === 2;337};338/******************************************************************************/339Matrix.prototype.mustBlockOrAllow = function() {340    return this.r === 1 || this.r === 2;341};342/******************************************************************************/343Matrix.prototype.mustBlock = function() {344    return this.r === 1;345};346/******************************************************************************/347Matrix.prototype.mustAbort = function() {348    return this.r === 3;349};350/******************************************************************************/351Matrix.prototype.lookupRuleData = function(src, des, type) {352    var r = this.evaluateCellZY(src, des, type);353    if ( r === 0 ) {354        return null;355    }356    return {357        src: this.z,358        des: this.y,359        type: this.type,360        action: r === 1 ? 'block' : (r === 2 ? 'allow' : 'noop')361    };362};363/******************************************************************************/364Matrix.prototype.toLogData = function() {365    if ( this.r === 0  || this.type === '' ) {366        return;367    }368    var logData = {369        source: 'dynamicHost',370        result: this.r,371        raw: this.z + ' ' +372             this.y + ' ' +373             this.type + ' ' +374             this.intToActionMap.get(this.r)375    };376    return logData;377};378Matrix.prototype.intToActionMap = new Map([379    [ 1, ' block' ],380    [ 2, ' allow' ],381    [ 3, ' noop' ]382]);383/******************************************************************************/384Matrix.prototype.srcHostnameFromRule = function(rule) {385    return rule.slice(0, rule.indexOf(' '));386};387/******************************************************************************/388Matrix.prototype.desHostnameFromRule = function(rule) {389    return rule.slice(rule.indexOf(' ') + 1);390};391/******************************************************************************/392Matrix.prototype.toString = function() {393    var out = [],394        rule, type, val,395        srcHostname, desHostname,396        toUnicode = punycode.toUnicode;397    for ( rule in this.rules ) {398        if ( this.rules.hasOwnProperty(rule) === false ) {399            continue;400        }401        srcHostname = this.srcHostnameFromRule(rule);402        desHostname = this.desHostnameFromRule(rule);403        for ( type in typeBitOffsets ) {404            if ( typeBitOffsets.hasOwnProperty(type) === false ) {405                continue;406            }407            val = this.evaluateCell(srcHostname, desHostname, type);408            if ( val === 0 ) { continue; }409            if ( srcHostname.indexOf('xn--') !== -1 ) {410                srcHostname = toUnicode(srcHostname);411            }412            if ( desHostname.indexOf('xn--') !== -1 ) {413                desHostname = toUnicode(desHostname);414            }415            out.push(416                srcHostname + ' ' +417                desHostname + ' ' +418                type + ' ' +419                actionToNameMap[val]420            );421        }422    }423    return out.join('\n');424};425/******************************************************************************/426Matrix.prototype.fromString = function(text, append) {427    var lineIter = new µBlock.LineIterator(text),428        line, pos, fields,429        srcHostname, desHostname, type, action,430        reNotASCII = /[^\x20-\x7F]/,431        toASCII = punycode.toASCII;432    if ( append !== true ) {433        this.reset();434    }435    while ( lineIter.eot() === false ) {436        line = lineIter.next().trim();437        pos = line.indexOf('# ');438        if ( pos !== -1 ) {439            line = line.slice(0, pos).trim();440        }441        if ( line === '' ) {442            continue;443        }444        // URL net filtering rules445        if ( line.indexOf('://') !== -1 ) {446            continue;447        }448        // Valid rule syntax:449        // srcHostname desHostname type state450        //      type = a valid request type451        //      state = [`block`, `allow`, `noop`]452        // Lines with invalid syntax silently ignored453        fields = line.split(/\s+/);454        if ( fields.length !== 4 ) {455            continue;456        }457        // Ignore special rules:458        //   hostname-based switch rules459        if ( fields[0].endsWith(':') ) {460            continue;461        }462        // Performance: avoid punycoding if hostnames are made only of463        // ASCII characters.464        srcHostname = fields[0];465        if ( reNotASCII.test(srcHostname) ) {466            srcHostname = toASCII(srcHostname);467        }468        desHostname = fields[1];469        if ( reNotASCII.test(desHostname) ) {470            desHostname = toASCII(desHostname);471        }472        // https://github.com/chrisaljoudi/uBlock/issues/1082473        // Discard rules with invalid hostnames474        if ( (srcHostname !== '*' && reBadHostname.test(srcHostname)) ||475             (desHostname !== '*' && reBadHostname.test(desHostname))476        ) {477            continue;478        }479        type = fields[2];480        if ( typeBitOffsets.hasOwnProperty(type) === false ) {481            continue;482        }483        // https://github.com/chrisaljoudi/uBlock/issues/840484        // Discard invalid rules485        if ( desHostname !== '*' && type !== '*' ) {486            continue;487        }488        action = nameToActionMap[fields[3]];489        if ( typeof action !== 'number' || action < 0 || action > 3 ) {490            continue;491        }492        this.setCell(srcHostname, desHostname, type, action);493    }494};495/******************************************************************************/496Matrix.prototype.toSelfie = function() {497    return {498        magicId: magicId,499        rules: this.rules500    };501};502/******************************************************************************/503Matrix.prototype.fromSelfie = function(selfie) {504    this.rules = selfie.rules;505};506/******************************************************************************/507return Matrix;508/******************************************************************************/509// http://youtu.be/5-K8R1hDG9E?t=31m1s510})();511/******************************************************************************/512µBlock.sessionFirewall = new µBlock.Firewall();513µBlock.permanentFirewall = new µBlock.Firewall();...dns.d.ts
Source:dns.d.ts  
1declare module "dns" {2    // Supported getaddrinfo flags.3    const ADDRCONFIG: number;4    const V4MAPPED: number;5    interface LookupOptions {6        family?: number;7        hints?: number;8        all?: boolean;9        verbatim?: boolean;10    }11    interface LookupOneOptions extends LookupOptions {12        all?: false;13    }14    interface LookupAllOptions extends LookupOptions {15        all: true;16    }17    interface LookupAddress {18        address: string;19        family: number;20    }21    function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;22    function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;23    function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void;24    function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void;25    function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;26    // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.27    namespace lookup {28        function __promisify__(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;29        function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<LookupAddress>;30        function __promisify__(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;31    }32    function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void;33    namespace lookupService {34        function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>;35    }36    interface ResolveOptions {37        ttl: boolean;38    }39    interface ResolveWithTtlOptions extends ResolveOptions {40        ttl: true;41    }42    interface RecordWithTtl {43        address: string;44        ttl: number;45    }46    /** @deprecated Use AnyARecord or AnyAaaaRecord instead. */47    type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord;48    interface AnyARecord extends RecordWithTtl {49        type: "A";50    }51    interface AnyAaaaRecord extends RecordWithTtl {52        type: "AAAA";53    }54    interface MxRecord {55        priority: number;56        exchange: string;57    }58    interface AnyMxRecord extends MxRecord {59        type: "MX";60    }61    interface NaptrRecord {62        flags: string;63        service: string;64        regexp: string;65        replacement: string;66        order: number;67        preference: number;68    }69    interface AnyNaptrRecord extends NaptrRecord {70        type: "NAPTR";71    }72    interface SoaRecord {73        nsname: string;74        hostmaster: string;75        serial: number;76        refresh: number;77        retry: number;78        expire: number;79        minttl: number;80    }81    interface AnySoaRecord extends SoaRecord {82        type: "SOA";83    }84    interface SrvRecord {85        priority: number;86        weight: number;87        port: number;88        name: string;89    }90    interface AnySrvRecord extends SrvRecord {91        type: "SRV";92    }93    interface AnyTxtRecord {94        type: "TXT";95        entries: string[];96    }97    interface AnyNsRecord {98        type: "NS";99        value: string;100    }101    interface AnyPtrRecord {102        type: "PTR";103        value: string;104    }105    interface AnyCnameRecord {106        type: "CNAME";107        value: string;108    }109    type AnyRecord = AnyARecord |110        AnyAaaaRecord |111        AnyCnameRecord |112        AnyMxRecord |113        AnyNaptrRecord |114        AnyNsRecord |115        AnyPtrRecord |116        AnySoaRecord |117        AnySrvRecord |118        AnyTxtRecord;119    function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;120    function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;121    function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;122    function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void;123    function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;124    function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void;125    function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void;126    function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;127    function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;128    function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void;129    function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void;130    function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void;131    function resolve(132        hostname: string,133        rrtype: string,134        callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void,135    ): void;136    // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.137    namespace resolve {138        function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>;139        function __promisify__(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;140        function __promisify__(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;141        function __promisify__(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;142        function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;143        function __promisify__(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;144        function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>;145        function __promisify__(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>;146    }147    function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;148    function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void;149    function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void;150    // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.151    namespace resolve4 {152        function __promisify__(hostname: string): Promise<string[]>;153        function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;154        function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;155    }156    function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;157    function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void;158    function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void;159    // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.160    namespace resolve6 {161        function __promisify__(hostname: string): Promise<string[]>;162        function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;163        function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;164    }165    function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;166    namespace resolveCname {167        function __promisify__(hostname: string): Promise<string[]>;168    }169    function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void;170    namespace resolveMx {171        function __promisify__(hostname: string): Promise<MxRecord[]>;172    }173    function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void;174    namespace resolveNaptr {175        function __promisify__(hostname: string): Promise<NaptrRecord[]>;176    }177    function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;178    namespace resolveNs {179        function __promisify__(hostname: string): Promise<string[]>;180    }181    function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;182    namespace resolvePtr {183        function __promisify__(hostname: string): Promise<string[]>;184    }185    function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void;186    namespace resolveSoa {187        function __promisify__(hostname: string): Promise<SoaRecord>;188    }189    function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void;190    namespace resolveSrv {191        function __promisify__(hostname: string): Promise<SrvRecord[]>;192    }193    function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void;194    namespace resolveTxt {195        function __promisify__(hostname: string): Promise<string[][]>;196    }197    function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void;198    namespace resolveAny {199        function __promisify__(hostname: string): Promise<AnyRecord[]>;200    }201    function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void;202    function setServers(servers: ReadonlyArray<string>): void;203    function getServers(): string[];204    // Error codes205    const NODATA: string;206    const FORMERR: string;207    const SERVFAIL: string;208    const NOTFOUND: string;209    const NOTIMP: string;210    const REFUSED: string;211    const BADQUERY: string;212    const BADNAME: string;213    const BADFAMILY: string;214    const BADRESP: string;215    const CONNREFUSED: string;216    const TIMEOUT: string;217    const EOF: string;218    const FILE: string;219    const NOMEM: string;220    const DESTRUCTION: string;221    const BADSTR: string;222    const BADFLAGS: string;223    const NONAME: string;224    const BADHINTS: string;225    const NOTINITIALIZED: string;226    const LOADIPHLPAPI: string;227    const ADDRGETNETWORKPARAMS: string;228    const CANCELLED: string;229    class Resolver {230        getServers: typeof getServers;231        setServers: typeof setServers;232        resolve: typeof resolve;233        resolve4: typeof resolve4;234        resolve6: typeof resolve6;235        resolveAny: typeof resolveAny;236        resolveCname: typeof resolveCname;237        resolveMx: typeof resolveMx;238        resolveNaptr: typeof resolveNaptr;239        resolveNs: typeof resolveNs;240        resolvePtr: typeof resolvePtr;241        resolveSoa: typeof resolveSoa;242        resolveSrv: typeof resolveSrv;243        resolveTxt: typeof resolveTxt;244        reverse: typeof reverse;245        cancel(): void;246    }247    namespace promises {248        function getServers(): string[];249        function lookup(hostname: string, family: number): Promise<LookupAddress>;250        function lookup(hostname: string, options: LookupOneOptions): Promise<LookupAddress>;251        function lookup(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;252        function lookup(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;253        function lookup(hostname: string): Promise<LookupAddress>;254        function lookupService(address: string, port: number): Promise<{ hostname: string, service: string }>;255        function resolve(hostname: string): Promise<string[]>;256        function resolve(hostname: string, rrtype: "A"): Promise<string[]>;257        function resolve(hostname: string, rrtype: "AAAA"): Promise<string[]>;258        function resolve(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;259        function resolve(hostname: string, rrtype: "CNAME"): Promise<string[]>;260        function resolve(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;261        function resolve(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;262        function resolve(hostname: string, rrtype: "NS"): Promise<string[]>;263        function resolve(hostname: string, rrtype: "PTR"): Promise<string[]>;264        function resolve(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;265        function resolve(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;266        function resolve(hostname: string, rrtype: "TXT"): Promise<string[][]>;267        function resolve(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>;268        function resolve4(hostname: string): Promise<string[]>;269        function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;270        function resolve4(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;271        function resolve6(hostname: string): Promise<string[]>;272        function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;273        function resolve6(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;274        function resolveAny(hostname: string): Promise<AnyRecord[]>;275        function resolveCname(hostname: string): Promise<string[]>;276        function resolveMx(hostname: string): Promise<MxRecord[]>;277        function resolveNaptr(hostname: string): Promise<NaptrRecord[]>;278        function resolveNs(hostname: string): Promise<string[]>;279        function resolvePtr(hostname: string): Promise<string[]>;280        function resolveSoa(hostname: string): Promise<SoaRecord>;281        function resolveSrv(hostname: string): Promise<SrvRecord[]>;282        function resolveTxt(hostname: string): Promise<string[][]>;283        function reverse(ip: string): Promise<string[]>;284        function setServers(servers: ReadonlyArray<string>): void;285        class Resolver {286            getServers: typeof getServers;287            resolve: typeof resolve;288            resolve4: typeof resolve4;289            resolve6: typeof resolve6;290            resolveAny: typeof resolveAny;291            resolveCname: typeof resolveCname;292            resolveMx: typeof resolveMx;293            resolveNaptr: typeof resolveNaptr;294            resolveNs: typeof resolveNs;295            resolvePtr: typeof resolvePtr;296            resolveSoa: typeof resolveSoa;297            resolveSrv: typeof resolveSrv;298            resolveTxt: typeof resolveTxt;299            reverse: typeof reverse;300            setServers: typeof setServers;301        }302    }...index.ts
Source:index.ts  
1import { HostnameStorage } from "../../constant";2/**3 * Load data from Storage.4 * Type T is generics for return type.5 * @param hostname - A PRIMARY key for storage. Usually a hostname of Sakai LMS.6 * @param key - - A SECONDARY key for storage. Defined in `constant.ts`.7 * @param decoder - Decoder for generics type T.8 */9export const fromStorage = <T>(hostname: string, key: string, decoder: (data: any) => T): Promise<T> => {10    return new Promise(function (resolve) {11        chrome.storage.local.get(hostname, function (items: any) {12            if (hostname in items && key in items[hostname]) {13                resolve(decoder(items[hostname][key]));14            } else {15                resolve(decoder(undefined));16            }17        });18    });19};20/**21 * Get hostname from Storage.22 * Hostname is a primary key for storage. Usually a hostname of Sakai LMS.23 * @returns {Promise<string | undefined>}24 */25export const loadHostName = (): Promise<string | undefined> => {26    return new Promise(function (resolve) {27        chrome.storage.local.get(HostnameStorage, function (items: any) {28            if (typeof items[HostnameStorage] === "undefined") {29                resolve(undefined);30            } else resolve(items[HostnameStorage]);31        });32    });33};34/**35 * Save data to Storage.36 * @param hostname - A PRIMARY key for storage. Usually a hostname of Sakai LMS.37 * @param key - A SECONDARY key for storage. Defined in `constant.ts`.38 * @param value - A data to be stored.39 */40export const toStorage = (hostname: string, key: string, value: any): Promise<string> => {41    const entity: { [key: string]: [value: any] } = {};42    entity[key] = value;43    return new Promise(function (resolve) {44        chrome.storage.local.get(hostname, function (items: any) {45            if (typeof items[hostname] === "undefined") {46                items[hostname] = {};47            }48            items[hostname][key] = value;49            chrome.storage.local.set({ [hostname]: items[hostname] }, () => {50                resolve("saved");51            });52        });53    });54};55/**56 * Saves hostname to Storage.57 * @param hostname - A PRIMARY key for storage. Usually a hostname of Sakai LMS.58 */59export const saveHostName = (hostname: string): Promise<string> => {60    return new Promise(function (resolve) {61        chrome.storage.local.set({ [HostnameStorage]: hostname }, () => {62            resolve("saved");63        });64    });...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
