Return a list of values from the IANA Service Name and Transport
    Protocol Port Number Registry, or an empty list if the IANA website is
    unreachable.
    Store it as a function attribute so that we only build the list once.
160084
def protocols():
    
    if not hasattr(protocols, 'protlist'):
        plist = []
        try:
            data = requests.get('http://www.iana.org/assignments/service-names'
                                '-port-numbers/service-names-port-numbers.csv')
        except requests.exceptions.RequestException:
            return []

        for line in data.iter_lines():
            if line:
                line = line.decode("utf-8")
                if line.count(',') > 0:
                    vals = line.split(',')
                    if vals[0]:
                        plist.append(vals[0])
                    if len(vals) > 2 and vals[2] and vals[2] not in plist:
                        plist.append(vals[2])

        plist.append('ipv4')
        plist.append('ipv6')
        plist.append('ssl')
        plist.append('tls')
        plist.append('dns')
        protocols.protlist = plist
    return protocols.protlist
137321
def portname_list(providername=None):
    
    _providername = providername
    if not _providername:
        _providername = provider_check()

    import_str = 'netshowlib.%s.iface' % _providername
    return import_module(import_str).portname_list()
858063
def dns_lookup(host, port, afi=socket.AF_UNSPEC):
    """"""
    # XXX: all DNS functions in Python are blocking. If we really
    # want to be non-blocking here, we need to use a 3rd-party
    # library like python-adns, or move resolution onto its
    # own thread. This will be subject to the default libc
    # name resolution timeout (5s on most Linux boxes)
    try:
        return list(filter(is_inet_4_or_6,
                           socket.getaddrinfo(host, port, afi,
                                              socket.SOCK_STREAM)))
    except socket.gaierror as ex:
        log.warning('DNS lookup failed for %s:%d,'
                    ' exception was %s. Is your'
                    ' advertised.listeners (called'
                    ' advertised.host.name before Kafka 9)'
                    ' correct and resolvable?',
                    host, port, ex)
        return []
176312
def p_instance_ports_list(self, p):
        ''
        p[0] = p[1] + (p[3],)
        p.set_lineno(0, p.lineno(1))
1200901
def _convert_addrinfo(cls, results: List[tuple]) -> Iterable[AddressInfo]:
        ''''''
        for result in results:
            family = result[0]
            address = result[4]
            ip_address = address[0]

            if family == socket.AF_INET6:
                flow_info = address[2]
                control_id = address[3]
            else:
                flow_info = None
                control_id = None

            yield AddressInfo(ip_address, family, flow_info, control_id)
1117522
def list_by_instance(self, instance_id):
        
        ports = port_list(self.request, device_id=instance_id)
        sg_ids = []
        for p in ports:
            sg_ids += p.security_groups
        return self._list(id=set(sg_ids)) if sg_ids else []
661931
def interfaces(self):
        
        if 'interfaces' not in self._cached_values:
            self._cached_values['interfaces'] = []
            for name, interface in six.iteritems(self.settings.INTERFACES):
                listen = interface.get('LISTEN')
                unix_socket = interface.get('UNIX_SOCKET')
                if not listen and not unix_socket:
                    raise ValueError(
                        'Interface MUST listen either on TCP '
                        'or UNIX socket or both')
                host, port = parse_host(listen) if listen else (None, None)
                processes = int(interface.get('PROCESSES', 1))
                urls_obj_name = interface.get('URLS', '')
                if urls_obj_name:
                    urls = import_object(urls_obj_name)
                else:
                    urls = ()
                self._cached_values['interfaces'].append(
                    self.Interface(
                        name, host, port, unix_socket, processes, urls)
                )
        return self._cached_values['interfaces']
696059
def _get_protocol_tuple(data: Dict[str, Any]) -> Tuple[str, List, Dict]:
    """"""
    return data['function'], data.get('args', []), data.get('kwargs', {})
843648
def _list_interface_private_addrs(eni_desc):
    '''
    
    '''
    primary = eni_desc.get('privateIpAddress')
    if not primary:
        return None

    addresses = [primary]

    lst = eni_desc.get('privateIpAddressesSet', {}).get('item', [])
    if not isinstance(lst, list):
        return addresses

    for entry in lst:
        if entry.get('primary') == 'true':
            continue
        if entry.get('privateIpAddress'):
            addresses.append(entry.get('privateIpAddress'))

    return addresses
967403
def sni_certs(self):
		
		if not g_ssl_has_server_sni or self._ssl_sni_entries is None:
			return tuple()
		return tuple(entry.certificate for entry in self._ssl_sni_entries.values())
358076
def emit_iana_rels(rels_url):
    ''''''
    text = requests.get(rels_url).text.encode('ascii', 'ignore')
    xml = objectify.fromstring(text)
    iana_rels = {str(rec.value): str(rec.description)
                 for rec in xml.registry.record}
    keys = sorted(iana_rels)
    print('# IANA link relation registry last updated on:', xml.updated)
    print('# Obtained from', rels_url)
    print()
    print('iana_rels = {')
    for key in keys:
        print('    {0!r}: ('.format(key))
        desc_list = list(linewrap(iana_rels[key], width=68))
        for i, line in enumerate(desc_list):
            line_ = line.replace('"', '\\"')  # escape double quotes
            if i < len(desc_list) - 1:
                print('        "{0} "'.format(line_))
            else:
                print('        "{0}"'.format(line_))
        print('    ),')
    print('}')
254605
def to_dict(self):
        ''''''
        d = super(TargetPort, self).to_dict()
        d['portName'] = self.port_name
        return d
989971
def _get_valid_port(self, port):
        
        if '/' in port:
            port, protocol = port.split('/')
        else:
            protocol = 'tcp'

        try:
            int(port)
        except ValueError:
            raise ValueError("{0} isn't a valid port number.".format(port))

        if protocol not in ('tcp', 'udp'):
            raise ValueError("exposed ports only supports udp or tcp. {0} was passed".format(protocol))

        return "{0}/{1}".format(port, protocol)
229834
def GetValidHostsForCert(cert):
  
  if 'subjectAltName' in cert:
    return [x[1] for x in cert['subjectAltName'] if x[0].lower() == 'dns']
  else:
    return [x[0][1] for x in cert['subject']
            if x[0][0].lower() == 'commonname']
173297
def retrieveVals(self):
        """"""
        for iface in self._ifaceList:
            if self._reqIfaceList is None or iface in self._reqIfaceList:
                if (self.graphEnabled('wanpipe_traffic') 
                    or self.graphEnabled('wanpipe_errors')):
                    stats = self._ifaceStats.get(iface)
                    if stats:
                        graph_name = 'wanpipe_traffic_%s' % iface
                        if self.hasGraph(graph_name):
                            for field in ('rxpackets', 'txpackets'):
                                self.setGraphVal(graph_name, field, 
                                                 stats.get(field))
                        graph_name = 'wanpipe_errors_%s' % iface
                        if self.hasGraph(graph_name):
                            for field in ('rxerrs', 'txerrs', 'rxframe', 'txcarrier',
                                'rxdrop', 'txdrop', 'rxfifo', 'txfifo'):
                                self.setGraphVal(graph_name, field, 
                                                 stats.get(field))
                if (self.graphEnabled('wanpipe_pri_errors') 
                    or self.graphEnabled('wanpipe_rxlevel')):
                    try:
                        stats = self._wanpipeInfo.getPRIstats(iface)
                    except:
                        stats = None
                    if stats:
                        graph_name = 'wanpipe_pri_errors_%s' % iface
                        if self.hasGraph(graph_name):
                            for field in ('linecodeviolation', 
                                          'farendblockerrors',
                                          'crc4errors', 'faserrors'):
                                self.setGraphVal(graph_name, field, 
                                                 stats.get(field))
                        if self.hasGraph('wanpipe_rxlevel'):
                            self.setGraphVal('wanpipe_pri_rxlevel', 
                                             iface, stats.get('rxlevel'))
870258
def get_dict(self):
        
        return {'hostname': self.get_name(),
                'address':  self.get_address(),
                'protocol': self.get_protocol(),
                'port':     self.get_tcp_port()}
778270
def _iana_unassigned_port_ranges():
    
    page = urllib2.urlopen(IANA_DOWNLOAD_URL).read()
    xml = ElementTree.fromstring(page)
    records = xml.findall('{%s}record' % IANA_NS)
    for record in records:
        description = record.find('{%s}description' % IANA_NS).text
        if description == 'Unassigned':
            numbers = record.find('{%s}number' % IANA_NS).text
            yield numbers