// decodeCompactIPPortInfo decodes compactIP-address/port info in BitTorrent
// DHT Protocol. It returns the ip and port number.
779617
func decodeCompactIPPortInfo(info string) (ip net.IP, port int, err error) {
	if len(info) != 6 {
		err = errors.New("compact info should be 6-length long")
		return
	}

	ip = net.IPv4(info[0], info[1], info[2], info[3])
	port = int((uint16(info[4]) << 8) | uint16(info[5]))
	return
}
792334
func ParsePortForwardSpec(spec []string) (ports ForwardedPorts, err error) {
	if len(spec) == 0 {
		return ports, nil
	}
	const errTemplate = "Invalid port forwarding spec: '%s'. Could be like `80:remote.host:80`"
	ports = make([]ForwardedPort, len(spec), len(spec))

	for i, str := range spec {
		parts := strings.Split(str, ":")
		if len(parts) < 3 || len(parts) > 4 {
			return nil, fmt.Errorf(errTemplate, str)
		}
		if len(parts) == 3 {
			parts = append([]string{"127.0.0.1"}, parts...)
		}
		p := &ports[i]
		p.SrcIP = parts[0]
		p.SrcPort, err = strconv.Atoi(parts[1])
		if err != nil {
			return nil, fmt.Errorf(errTemplate, str)
		}
		p.DestHost = parts[2]
		p.DestPort, err = strconv.Atoi(parts[3])
		if err != nil {
			return nil, fmt.Errorf(errTemplate, str)
		}
	}
	return ports, nil
}
1316095
func InterfaceInfoFromDevices(nics map[string]device) ([]network.InterfaceInfo, error) {
	interfaces := make([]network.InterfaceInfo, len(nics))
	var i int
	for name, device := range nics {
		iInfo := network.InterfaceInfo{
			InterfaceName:       name,
			ParentInterfaceName: device["parent"],
			MACAddress:          device["hwaddr"],
			ConfigType:          network.ConfigDHCP,
		}
		if device["mtu"] != "" {
			mtu, err := strconv.Atoi(device["mtu"])
			if err != nil {
				return nil, errors.Annotate(err, "parsing device MTU")
			}
			iInfo.MTU = mtu
		}

		interfaces[i] = iInfo
		i++
	}

	sortInterfacesByName(interfaces)
	return interfaces, nil
}
771585
func HostPortToIP(hostport string, ctx *net.TCPAddr) (hostaddr *net.TCPAddr, err error) {
	host, port, err := net.SplitHostPort(hostport)
	if err != nil {
		return nil, err
	}
	iport, err := strconv.Atoi(port)
	if err != nil || iport < 0 || iport > 0xFFFF {
		return nil, fmt.Errorf("invalid port %d", iport)
	}
	var addr net.IP
	if ctx != nil && host == "localhost" {
		if ctx.IP.To4() != nil {
			addr = net.IPv4(127, 0, 0, 1)
		} else {
			addr = net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
		}
	} else if addr = net.ParseIP(host); addr == nil {
		return nil, fmt.Errorf("could not parse IP %s", host)
	}

	return &net.TCPAddr{IP: addr, Port: iport}, nil
}
974062
func encodeCompactIPPortInfo(ip net.IP, port int) (info string, err error) {
	if port > 65535 || port < 0 {
		err = errors.New(
			"port should be no greater than 65535 and no less than 0")
		return
	}

	p := int2bytes(uint64(port))
	if len(p) < 2 {
		p = append(p, p[0])
		p[0] = 0
	}

	info = string(append(ip, p...))
	return
}
757095
func (m *Maestro) GetSpecificExposedPort(service string, container string, port string) (uint16, error) {
	return m.getPortHelper(service, container, port, "INTERNAL_PORT")
}
909527
func serializeImportedAddress(encryptedPubKey, encryptedPrivKey []byte) []byte {
	// The serialized imported address raw data format is:
	//   <encpubkeylen><encpubkey><encprivkeylen><encprivkey>
	//
	// 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted
	// privkey len + encrypted privkey
	pubLen := uint32(len(encryptedPubKey))
	privLen := uint32(len(encryptedPrivKey))
	rawData := make([]byte, 8+pubLen+privLen)
	binary.LittleEndian.PutUint32(rawData[0:4], pubLen)
	copy(rawData[4:4+pubLen], encryptedPubKey)
	offset := 4 + pubLen
	binary.LittleEndian.PutUint32(rawData[offset:offset+4], privLen)
	offset += 4
	copy(rawData[offset:offset+privLen], encryptedPrivKey)
	return rawData
}
159067
func UncompactRows(compact []AddressRowCompact) []*AddressRow {
	rows := make([]*AddressRow, 0, len(compact))
	for i := range compact {
		r := &compact[i]
		// An unset matching hash is represented by the zero-value array.
		var matchingHash string
		if !txhelpers.IsZeroHash(r.MatchingTxHash) {
			matchingHash = r.MatchingTxHash.String()
		}
		rows = append(rows, &AddressRow{
			Address:        r.Address,
			ValidMainChain: r.ValidMainChain,
			MatchingTxHash: matchingHash,
			IsFunding:      r.IsFunding,
			TxBlockTime:    NewTimeDefFromUNIX(r.TxBlockTime),
			TxHash:         r.TxHash.String(),
			TxVinVoutIndex: r.TxVinVoutIndex,
			Value:          r.Value,
			// VinVoutDbID unknown. Do not use.
			TxType: r.TxType,
		})
	}
	return rows
}
1074476
func GetBytesProposalPayloadForTx(payload *peer.ChaincodeProposalPayload, visibility []byte) ([]byte, error) {
	// check for nil argument
	if payload == nil {
		return nil, errors.New("nil arguments")
	}

	// strip the transient bytes off the payload - this needs to be done no
	// matter the visibility mode
	cppNoTransient := &peer.ChaincodeProposalPayload{Input: payload.Input, TransientMap: nil}
	cppBytes, err := GetBytesChaincodeProposalPayload(cppNoTransient)
	if err != nil {
		return nil, err
	}

	// currently the fabric only supports full visibility: this means that
	// there are no restrictions on which parts of the proposal payload will
	// be visible in the final transaction; this default approach requires
	// no additional instructions in the PayloadVisibility field; however
	// the fabric may be extended to encode more elaborate visibility
	// mechanisms that shall be encoded in this field (and handled
	// appropriately by the peer)

	return cppBytes, nil
}
1145784
func (n *Networking) GetForwardableNetHostIP() (net.IP, error) {
	net, err := n.GetForwardableNet()
	if err != nil {
		return nil, err
	}
	return net.runtime.HostIP, nil
}
380307
func checkAtimeSupport(dir string) (err error) {
	file, err := ioutil.TempFile(dir, "prefix")
	if err != nil {
		return
	}
	defer os.Remove(file.Name())
	finfo1, err := os.Stat(file.Name())
	if err != nil {
		return
	}
	if _, err = io.Copy(ioutil.Discard, file); err != io.EOF {
		return
	}

	finfo2, err := os.Stat(file.Name())

	if atime.Get(finfo2).Equal(atime.Get(finfo1)) {
		return errors.New("Atime not supported")
	}
	return
}
1351547
func NewTCompactProtocol(trans TTransport) *TCompactProtocol {
	p := &TCompactProtocol{origTransport: trans, lastField: []int{}}
	if et, ok := trans.(TRichTransport); ok {
		p.trans = et
	} else {
		p.trans = NewTRichTransport(trans)
	}

	return p

}
107422
func (b *NexthopLookupBody) DecodeFromBytes(data []byte, version uint8) error {
	family := addressFamilyFromApi(b.Api, version)
	addrByteLen, err := addressByteLength(family)
	if err != nil {
		return err
	}

	if len(data) < addrByteLen {
		return fmt.Errorf("message length invalid")
	}

	buf := make([]byte, addrByteLen)
	copy(buf, data[0:addrByteLen])
	pos := addrByteLen
	b.Addr = ipFromFamily(family, buf)

	if version >= 4 {
		b.Distance = data[pos]
		pos++
	}

	if len(data[pos:]) > int(1+addrByteLen) {
		b.Metric = binary.BigEndian.Uint32(data[pos : pos+4])
		pos += 4
		b.Nexthops = []Nexthop{}
		if nexthopsByteLen, err := decodeNexthopsFromBytes(&b.Nexthops, data[pos:], family, version); err != nil {
			return err
		} else {
			pos += nexthopsByteLen
		}
	}

	return nil
}
631453
func (n *Network) PeerPort(p *Peer, portName PortName) uint16 {
	peerPorts := n.PortsByPeerID[p.ID()]
	Expect(peerPorts).NotTo(BeNil())
	return peerPorts[portName]
}
814849
func OptionDetectIP(path string) Option {
	return func(d *dcosInfo) error {
		if _, err := os.Stat(path); err != nil {
			return err
		}

		d.detectIPLocation = path
		return nil
	}
}
262546
func (client *WANPPPConnection1) GetSpecificPortMappingEntry(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) {
	// Request structure.
	request := &struct {
		NewRemoteHost   string
		NewExternalPort string
		NewProtocol     string
	}{}
	// BEGIN Marshal arguments into request.

	if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
		return
	}
	if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
		return
	}
	if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
		return
	}
	// END Marshal arguments into request.

	// Response structure.
	response := &struct {
		NewInternalPort           string
		NewInternalClient         string
		NewEnabled                string
		NewPortMappingDescription string
		NewLeaseDuration          string
	}{}

	// Perform the SOAP call.
	if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetSpecificPortMappingEntry", request, response); err != nil {
		return
	}

	// BEGIN Unmarshal arguments from response.

	if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil {
		return
	}
	if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil {
		return
	}
	if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil {
		return
	}
	if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil {
		return
	}
	if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil {
		return
	}
	// END Unmarshal arguments from response.
	return
}
1184296
func (rt *routingTable) GetNeighborCompactInfos(id *bitmap, size int) []string {
	neighbors := rt.GetNeighbors(id, size)
	infos := make([]string, len(neighbors))

	for i, no := range neighbors {
		infos[i] = no.CompactNodeInfo()
	}

	return infos
}