See https://tools.ietf.org/html/rfc4880#section-6.1 for details.
15700
def crc24(blob):
    """"""
    CRC24_INIT = 0x0B704CE
    CRC24_POLY = 0x1864CFB

    crc = CRC24_INIT
    for octet in bytearray(blob):
        crc ^= (octet << 16)
        for _ in range(8):
            crc <<= 1
            if crc & 0x1000000:
                crc ^= CRC24_POLY
    assert 0 <= crc < 0x1000000
    crc_bytes = struct.pack('>L', crc)
    assert crc_bytes[:1] == b'\x00'
    return crc_bytes[1:]
1187191
def is_reserved(self):
        
        reserved_nets = [IPv6Network(u'::/8'), IPv6Network(u'100::/8'),
                         IPv6Network(u'200::/7'), IPv6Network(u'400::/6'),
                         IPv6Network(u'800::/5'), IPv6Network(u'1000::/4'),
                         IPv6Network(u'4000::/3'), IPv6Network(u'6000::/3'),
                         IPv6Network(u'8000::/3'), IPv6Network(u'A000::/3'),
                         IPv6Network(u'C000::/3'), IPv6Network(u'E000::/4'),
                         IPv6Network(u'F000::/5'), IPv6Network(u'F800::/6'),
                         IPv6Network(u'FE00::/9')]

        return any(self in x for x in reserved_nets)
159039
def is_reserved(self):
        
        reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
                             IPv6Network('200::/7'), IPv6Network('400::/6'),
                             IPv6Network('800::/5'), IPv6Network('1000::/4'),
                             IPv6Network('4000::/3'), IPv6Network('6000::/3'),
                             IPv6Network('8000::/3'), IPv6Network('A000::/3'),
                             IPv6Network('C000::/3'), IPv6Network('E000::/4'),
                             IPv6Network('F000::/5'), IPv6Network('F800::/6'),
                             IPv6Network('FE00::/9')]

        return any(self in x for x in reserved_networks)
455809
def routingAreaUpdateRequest(PTmsiSignature_presence=0,
                             GprsTimer_presence=0,
                             DrxParameter_presence=0,
                             TmsiStatus_presence=0):
    """"""
    a = TpPd(pd=0x3)
    b = MessageType(mesType=0x8)  # 00001000
    c = UpdateTypeAndCiphKeySeqNr()
    e = RoutingAreaIdentification()
    f = MsNetworkCapability()
    packet = a / b / c / e / f
    if PTmsiSignature_presence is 1:
        g = PTmsiSignature(ieiPTS=0x19)
        packet = packet / g
    if GprsTimer_presence is 1:
        h = GprsTimer(ieiGT=0x17)
        packet = packet / h
    if DrxParameter_presence is 1:
        i = DrxParameter(ieiDP=0x27)
        packet = packet / i
    if TmsiStatus_presence is 1:
        j = TmsiStatus(ieiTS=0x9)
        packet = packet / j
    return packet
773849
def allow(ip,
        port=None,
        proto='tcp',
        direction='in',
        port_origin='d',
        ip_origin='s',
        ttl=None,
        comment=''):
    '''
    
    '''
    return _access_rule('allow',
                        ip,
                        port=port,
                        proto=proto,
                        direction=direction,
                        port_origin=port_origin,
                        ip_origin=ip_origin,
                        comment=comment)
648268
async def on_isupport_chanmodes(self, value):
        
        list, param, param_set, noparams = [ set(modes) for modes in value.split(',')[:4] ]
        self._channel_modes.update(set(value.replace(',', '')))

        # The reason we have to do it like this is because other ISUPPORTs (e.g. PREFIX) may update these values as well.
        if not rfc1459.protocol.BEHAVIOUR_LIST in self._channel_modes_behaviour:
            self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_LIST] = set()
        self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_LIST].update(list)

        if not rfc1459.protocol.BEHAVIOUR_PARAMETER in self._channel_modes_behaviour:
            self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_PARAMETER] = set()
        self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_PARAMETER].update(param)

        if not rfc1459.protocol.BEHAVIOUR_PARAMETER_ON_SET in self._channel_modes_behaviour:
            self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_PARAMETER_ON_SET] = set()
        self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_PARAMETER_ON_SET].update(param_set)

        if not rfc1459.protocol.BEHAVIOUR_NO_PARAMETER in self._channel_modes_behaviour:
            self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_NO_PARAMETER] = set()
        self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_NO_PARAMETER].update(noparams)
845002
def _convert_port_bindings(self, value):
        
        converted = {}

        if not value:
            return converted

        if isinstance(value, list):
            value = self._convert_port_bindings_from_list(value)

        if isinstance(value, dict):
            for port_protocol, host_bindings in six.iteritems(value):
                if '/' in port_protocol:
                    port, protocol = port_protocol.split('/')

                    if protocol not in ('tcp', 'udp'):
                        raise ValueError('only supported protocols are tcp and udp. {0} was passed.'.format(protocol))
                else:
                    port_protocol = "{0}/tcp".format(port_protocol)

                converted[port_protocol] = []

                if isinstance(host_bindings, list):
                    for host_binding in host_bindings:
                        if isinstance(host_binding, dict):
                            if "host_port" not in host_binding:
                                raise ValueError("host_port must be provided.")

                            if 'host_ip' not in host_binding:
                                host_binding['host_ip'] = ''

                            converted[port_protocol].append(host_binding)
                        else:
                            raise TypeError("The host binding information must be a dict.")
                else:
                    raise TypeError("The host binding information in port bindings must be in a list.")

        return converted
615900
private int getDatanodeHttpPort(Configuration conf) {
    String address = conf.get("dfs.datanode.http.address", "");
    if (address.equals("")) {
      return -1;
    }
    return Integer.parseInt(address.split(":")[1]);
  }
441670
function isIPv6(val) {
  const ipv6Block = /^[0-9A-F]{1,4}$/i;
  var blocks = val.split(':');
  var foundOmissionBlock = false; // marker to indicate ::

  // At least some OS accept the last 32 bits of an IPv6 address
  // (i.e. 2 of the blocks) in IPv4 notation, and RFC 3493 says
  // that '::ffff:a.b.c.d' is valid for IPv4-mapped IPv6 addresses,
  // and '::a.b.c.d' is deprecated, but also valid.
  var foundIPv4TransitionBlock = isIPv4(blocks[blocks.length - 1]);
  var expectedNumberOfBlocks = foundIPv4TransitionBlock ? 7 : 8;

  if (blocks.length > expectedNumberOfBlocks)
    return false;

  // initial or final ::
  if (val === '::') {
    return true;
  } else if (val.substr(0, 2) === '::') {
    blocks.shift();
    blocks.shift();
    foundOmissionBlock = true;
  } else if (val.substr(val.length - 2) === '::') {
    blocks.pop();
    blocks.pop();
    foundOmissionBlock = true;
  }

  for (var i = 0; i < blocks.length; ++i) {
    // test for a :: which can not be at the string start/end
    // since those cases have been handled above
    if (blocks[i] === '' && i > 0 && i < blocks.length -1) {
      if (foundOmissionBlock)
        return false; // multiple :: in address
      foundOmissionBlock = true;
    } else if (foundIPv4TransitionBlock && i == blocks.length - 1) {
      // it has been checked before that the last
      // block is a valid IPv4 address
    } else if (!ipv6Block.test(blocks[i])) {
      return false;
    }
  }

  if (foundOmissionBlock) {
    return blocks.length >= 1;
  }
  return blocks.length === expectedNumberOfBlocks;
}
1100312
public static String ipv6toStr(byte[] src) {
        assert src.length == 16;
        StringBuilder sb = new StringBuilder(39);
        ipv6toStr(sb, src, 0, 8);
        return sb.toString();
    }
171396
def attachRequest(PTmsiSignature_presence=0, GprsTimer_presence=0,
                  TmsiStatus_presence=0):
    """"""
    a = TpPd(pd=0x3)
    b = MessageType(mesType=0x1)  # 0000001
    c = MsNetworkCapability()
    d = AttachTypeAndCiphKeySeqNr()
    f = DrxParameter()
    g = MobileId()
    h = RoutingAreaIdentification()
    i = MsRadioAccessCapability()
    packet = a / b / c / d / f / g / h / i
    if PTmsiSignature_presence is 1:
        j = PTmsiSignature(ieiPTS=0x19)
        packet = packet / j
    if GprsTimer_presence is 1:
        k = GprsTimer(ieiGT=0x17)
        packet = packet / k
    if TmsiStatus_presence is 1:
        l = TmsiStatus(ieiTS=0x9)
        packet = packet / l
    return packet
948011
def prepare_socket(bind_addr, family, type, proto, nodelay, ssl_adapter):
        """"""
        sock = socket.socket(family, type, proto)
        prevent_socket_inheritance(sock)

        host, port = bind_addr[:2]
        IS_EPHEMERAL_PORT = port == 0

        if not (IS_WINDOWS or IS_EPHEMERAL_PORT):
            """Enable SO_REUSEADDR for the current socket.

            Skip for Windows (has different semantics)
            or ephemeral ports (can steal ports from others).

            Refs:
            * https://msdn.microsoft.com/en-us/library/ms740621(v=vs.85).aspx
            * https://github.com/cherrypy/cheroot/issues/114
            * https://gavv.github.io/blog/ephemeral-port-reuse/
            """
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if nodelay and not isinstance(bind_addr, str):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

        if ssl_adapter is not None:
            sock = ssl_adapter.bind(sock)

        # If listening on the IPV6 any address ('::' = IN6ADDR_ANY),
        # activate dual-stack. See
        # https://github.com/cherrypy/cherrypy/issues/871.
        listening_ipv6 = (
            hasattr(socket, 'AF_INET6')
            and family == socket.AF_INET6
            and host in ('::', '::0', '::0.0.0.0')
        )
        if listening_ipv6:
            try:
                sock.setsockopt(
                    socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0,
                )
            except (AttributeError, socket.error):
                # Apparently, the socket option is not available in
                # this machine's TCP stack
                pass

        return sock
43068
def rfc2822(self):

        ''' 
            
        '''

    # define format
        js_format = '%a, %d %b %Y %H:%M:%S GMT'
        utc_time = self.astimezone(pytz.utc)

        return format(utc_time, js_format)
60738
def inet_ntop(af, addr):
    """"""
    if af == socket.AF_INET:
        return inet_ntoa(addr)
    elif af == socket.AF_INET6:
        # IPv6 addresses have 128bits (16 bytes)
        if len(addr) != 16:
            raise Exception("Illegal syntax for IP address")
        parts = []
        for left in [0, 2, 4, 6, 8, 10, 12, 14]:
            try: 
                value = struct.unpack("!H", addr[left:left+2])[0]
                hexstr = hex(value)[2:]
            except TypeError:
                raise Exception("Illegal syntax for IP address")
            parts.append(hexstr.lstrip("0").lower())
        result = b":".join(parts)
        while b":::" in result:
            result = result.replace(b":::", b"::")
        # Leaving out leading and trailing zeros is only allowed with ::
        if result.endswith(b":") and not result.endswith(b"::"):
            result = result + b"0"
        if result.startswith(b":") and not result.startswith(b"::"):
            result = b"0" + result
        return result
    else:
        raise Exception("Address family not supported yet")
217340
def srp(x, promisc=None, iface=None, iface_hint=None, filter=None,
        nofilter=0, type=ETH_P_ALL, *args, **kargs):
    """"""
    if iface is None and iface_hint is not None:
        iface = conf.route.route(iface_hint)[0]
    s = conf.L2socket(promisc=promisc, iface=iface,
                      filter=filter, nofilter=nofilter, type=type)
    result = sndrcv(s, x, *args, **kargs)
    s.close()
    return result
480690
private boolean
toWire(DNSOutput out, int maxLength) {
	if (maxLength < Header.LENGTH)
		return false;

	Header newheader = null;

	int tempMaxLength = maxLength;
	if (tsigkey != null)
		tempMaxLength -= tsigkey.recordLength();

	OPTRecord opt = getOPT();
	byte [] optBytes = null;
        if (opt != null) {
		optBytes = opt.toWire(Section.ADDITIONAL);
		tempMaxLength -= optBytes.length;
	}

	int startpos = out.current();
	header.toWire(out);
	Compression c = new Compression();
	int flags = header.getFlagsByte();
	int additionalCount = 0;
	for (int i = 0; i < 4; i++) {
		int skipped;
		if (sections[i] == null)
			continue;
		skipped = sectionToWire(out, i, c, tempMaxLength);
		if (skipped != 0 && i != Section.ADDITIONAL) {
			flags = Header.setFlag(flags, Flags.TC, true);
			out.writeU16At(header.getCount(i) - skipped,
				       startpos + 4 + 2 * i);
			for (int j = i + 1; j < Section.ADDITIONAL; j++)
				out.writeU16At(0, startpos + 4 + 2 * j);
			break;
		}
		if (i == Section.ADDITIONAL)
			additionalCount = header.getCount(i) - skipped;
	}

	if (optBytes != null) {
		out.writeByteArray(optBytes);
		additionalCount++;
	}

	if (flags != header.getFlagsByte())
		out.writeU16At(flags, startpos + 2);

	if (additionalCount != header.getCount(Section.ADDITIONAL))
		out.writeU16At(additionalCount, startpos + 10);

	if (tsigkey != null) {
		TSIGRecord tsigrec = tsigkey.generate(this, out.toByteArray(),
						      tsigerror, querytsig);

		tsigrec.toWire(out, Section.ADDITIONAL, c);
		out.writeU16At(additionalCount + 1, startpos + 10);
	}

	return true;
}
165679
public void configureHttpPipeline(ChannelPipeline serverPipeline, String initialHttpScheme) {

        if (initialHttpScheme.equals(Constants.HTTP_SCHEME)) {
            serverPipeline.addLast(Constants.HTTP_ENCODER, new HttpResponseEncoder());
            serverPipeline.addLast(Constants.HTTP_DECODER,
                                   new HttpRequestDecoder(reqSizeValidationConfig.getMaxUriLength(),
                                                          reqSizeValidationConfig.getMaxHeaderSize(),
                                                          reqSizeValidationConfig.getMaxChunkSize()));

            serverPipeline.addLast(Constants.HTTP_COMPRESSOR, new CustomHttpContentCompressor());
            serverPipeline.addLast(Constants.HTTP_CHUNK_WRITER, new ChunkedWriteHandler());

            if (httpTraceLogEnabled) {
                serverPipeline.addLast(HTTP_TRACE_LOG_HANDLER, new HttpTraceLoggingHandler(TRACE_LOG_DOWNSTREAM));
            }
            if (httpAccessLogEnabled) {
                serverPipeline.addLast(HTTP_ACCESS_LOG_HANDLER, new HttpAccessLoggingHandler(ACCESS_LOG));
            }
        }
        serverPipeline.addLast("uriLengthValidator", new UriAndHeaderLengthValidator(this.serverName));
        if (reqSizeValidationConfig.getMaxEntityBodySize() > -1) {
            serverPipeline.addLast("maxEntityBodyValidator", new MaxEntityBodyValidator(this.serverName,
                    reqSizeValidationConfig.getMaxEntityBodySize()));
        }

        serverPipeline.addLast(Constants.WEBSOCKET_SERVER_HANDSHAKE_HANDLER,
                         new WebSocketServerHandshakeHandler(this.serverConnectorFuture, this.interfaceId));
        serverPipeline.addLast(Constants.BACK_PRESSURE_HANDLER, new BackPressureHandler());
        serverPipeline.addLast(Constants.HTTP_SOURCE_HANDLER,
                               new SourceHandler(this.serverConnectorFuture, this.interfaceId, this.chunkConfig,
                                                 keepAliveConfig, this.serverName, this.allChannels,
                                       this.pipeliningEnabled, this.pipeliningLimit, this.pipeliningGroup));
        if (socketIdleTimeout >= 0) {
            serverPipeline.addBefore(Constants.HTTP_SOURCE_HANDLER, Constants.IDLE_STATE_HANDLER,
                                     new IdleStateHandler(0, 0, socketIdleTimeout, TimeUnit.MILLISECONDS));
        }
    }