// RequestTargetPort returns the port targeted by the client
// in req. If not present, it returns 80, or 443 if TLS is used.
967175
func RequestTargetPort(req *http.Request) int {
	_, portStr, err := net.SplitHostPort(req.Host)
	if err == nil && portStr != "" {
		port, err := strconv.ParseInt(portStr, 0, 64)
		if err == nil {
			return int(port)
		}
	}
	if req.TLS != nil {
		return 443
	}
	return 80
}
989279
func (res *Resolver) RestPorts(req *restful.Request, resp *restful.Response) {
	err := resp.WriteErrorString(http.StatusNotImplemented, "To be implemented...")
	if err != nil {
		logging.Error.Println(err)
	}
}
336400
func ParsePort(portString string) (uint16, error) {
	port, err := strconv.ParseUint(portString, 10, 16)
	return uint16(port), err
}
457682
func allocatePort(port, min, max uint16) (uint16, error) {
	// Get a snapshot of the TCP and UDP ports already open locally.
	openLocalPorts, err := readOpenLocalPorts(append(procNetTCPFiles, procNetUDPFiles...))
	if err != nil {
		return 0, fmt.Errorf("couldn't read local ports from /proc: %s", err)
	}

	if isPortAvailable(openLocalPorts, port) {
		return port, nil
	}

	// TODO: Maybe not create a large permutation each time?
	for _, r := range portRandomizer.Perm(int(max - min + 1)) {
		resPort := uint16(r) + min

		if isPortAvailable(openLocalPorts, resPort) {
			return resPort, nil
		}
	}

	return 0, fmt.Errorf("no available proxy ports")
}
206920
func Ports() ([]ListenTarget, error) {
	ssport := os.Getenv("SERVER_STARTER_PORT")
	if ssport == "" {
		return nil, fmt.Errorf("error: No environment variable SERVER_STARTER_PORT available")
	}

	return ParsePorts(ssport)
}
667843
func (va *ValidationAuthorityImpl) newHTTPValidationTarget(
	ctx context.Context,
	host string,
	port int,
	path string,
	query string) (*httpValidationTarget, error) {
	// Resolve IP addresses for the hostname
	addrs, err := va.getAddrs(ctx, host)
	if err != nil {
		// Convert the error into a ConnectionFailureError so it is presented to the
		// end user in a problem after being fed through detailedError.
		return nil, berrors.ConnectionFailureError(err.Error())
	}

	target := &httpValidationTarget{
		host:      host,
		port:      port,
		path:      path,
		query:     query,
		available: addrs,
	}

	// Separate the addresses into the available v4 and v6 addresses
	v4Addrs, v6Addrs := availableAddresses(addrs)
	hasV6Addrs := len(v6Addrs) > 0
	hasV4Addrs := len(v4Addrs) > 0

	if !hasV6Addrs && !hasV4Addrs {
		// If there are no v6 addrs and no v4addrs there was a bug with getAddrs or
		// availableAddresses and we need to return an error.
		return nil, fmt.Errorf("host %q has no IPv4 or IPv6 addresses", host)
	} else if !hasV6Addrs && hasV4Addrs {
		// If there are no v6 addrs and there are v4 addrs then use the first v4
		// address. There's no fallback address.
		target.next = []net.IP{v4Addrs[0]}
	} else if hasV6Addrs && hasV4Addrs {
		// If there are both v6 addrs and v4 addrs then use the first v6 address and
		// fallback with the first v4 address.
		target.next = []net.IP{v6Addrs[0], v4Addrs[0]}
	} else if hasV6Addrs && !hasV4Addrs {
		// If there are just v6 addrs then use the first v6 address. There's no
		// fallback address.
		target.next = []net.IP{v6Addrs[0]}
	}

	// Advance the target using nextIP to populate the cur IP before returning
	_ = target.nextIP()
	return target, nil
}
1015687
func (sc *ServiceCheck) RequiresPort() bool {
	switch sc.Type {
	case ServiceCheckGRPC, ServiceCheckHTTP, ServiceCheckTCP:
		return true
	default:
		return false
	}
}
554946
func (d *domainClient) GetTargetInfo(ctx context.Context, args *GetTargetInfoArgs) (reply *GetTargetInfoReply, err error) {
	reply = new(GetTargetInfoReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "Target.getTargetInfo", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Target.getTargetInfo", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "GetTargetInfo", Err: err}
	}
	return
}
1203395
func parseDialTarget(target string) (net string, addr string) {
	net = "tcp"

	m1 := strings.Index(target, ":")
	m2 := strings.Index(target, ":/")

	// handle unix:addr which will fail with url.Parse
	if m1 >= 0 && m2 < 0 {
		if n := target[0:m1]; n == "unix" {
			net = n
			addr = target[m1+1:]
			return net, addr
		}
	}
	if m2 >= 0 {
		t, err := url.Parse(target)
		if err != nil {
			return net, target
		}
		scheme := t.Scheme
		addr = t.Path
		if scheme == "unix" {
			net = scheme
			if addr == "" {
				addr = t.Host
			}
			return net, addr
		}
	}

	return net, target
}
1127722
func (c *Context) Port() int {
	parts := strings.Split(c.Request().Host(), ":")
	if len(parts) == 2 {
		port, _ := strconv.Atoi(parts[1])
		return port
	}
	return 80
}
371632
func (obj *GCSObject) IsImportTarget(c context.Context, r *http.Request, bucketName string, kindNames []string) bool {
	if bucketName != "" && obj.Bucket != bucketName {
		log.Infof(c, "ds2bq: %s is unexpected bucket", obj.Bucket)
		return false
	}
	gcsHeader := NewGCSHeader(r)
	if gcsHeader.ResourceState != "exists" {
		log.Infof(c, "ds2bq: %s is unexpected state", gcsHeader.ResourceState)
		return false
	}
	if obj.ExtractKindName() == "" {
		log.Infof(c, "ds2bq: this is not backup file: %s", obj.Name)
		return false
	}
	if !obj.IsRequiredKind(kindNames) {
		log.Infof(c, "ds2bq: %s is not required kind", obj.ExtractKindName())
		return false
	}
	log.Infof(c, "ds2bq: %s should imports", obj.Name)
	return true
}
427480
func (i *Issuer) RequestImport(tokensToIssue []*token.TokenToIssue) (*token.TokenTransaction, error) {
	var outputs []*token.PlainOutput
	for _, tti := range tokensToIssue {
		outputs = append(outputs, &token.PlainOutput{
			Owner:    tti.Recipient,
			Type:     tti.Type,
			Quantity: tti.Quantity,
		})
	}

	return &token.TokenTransaction{
		Action: &token.TokenTransaction_PlainAction{
			PlainAction: &token.PlainTokenAction{
				Data: &token.PlainTokenAction_PlainImport{
					PlainImport: &token.PlainImport{
						Outputs: outputs,
					},
				},
			},
		},
	}, nil
}
285124
func (s *PortMapping) SetHostPort(v int64) *PortMapping {
	s.HostPort = &v
	return s
}
960935
func (tsv *TabletServer) verifyTarget(ctx context.Context, target *querypb.Target) error {
	tsv.mu.Lock()
	defer tsv.mu.Unlock()

	if target != nil {
		// a valid target needs to be used
		switch {
		case target.Keyspace != tsv.target.Keyspace:
			return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid keyspace %v", target.Keyspace)
		case target.Shard != tsv.target.Shard:
			return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid shard %v", target.Shard)
		case target.TabletType != tsv.target.TabletType:
			for _, otherType := range tsv.alsoAllow {
				if target.TabletType == otherType {
					return nil
				}
			}
			return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "invalid tablet type: %v, want: %v or %v", target.TabletType, tsv.target.TabletType, tsv.alsoAllow)
		}
	} else if !tabletenv.IsLocalContext(ctx) {
		return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "No target")
	}
	return nil
}
891822
func (tc *TeleportClient) getTargetNodes(ctx context.Context, proxy *ProxyClient) ([]string, error) {
	var (
		err    error
		nodes  []services.Server
		retval = make([]string, 0)
	)
	if tc.Labels != nil && len(tc.Labels) > 0 {
		nodes, err = proxy.FindServersByLabels(ctx, tc.Namespace, tc.Labels)
		if err != nil {
			return nil, trace.Wrap(err)
		}
		for i := 0; i < len(nodes); i++ {
			retval = append(retval, nodes[i].GetAddr())
		}
	}
	if len(nodes) == 0 {
		retval = append(retval, net.JoinHostPort(tc.Host, strconv.Itoa(tc.HostPort)))
	}
	return retval, nil
}
348294
func translateServicePortToTargetPort(ports []string, svc corev1.Service, pod corev1.Pod) ([]string, error) {
	var translated []string
	for _, port := range ports {
		localPort, remotePort := splitPort(port)

		portnum, err := strconv.Atoi(remotePort)
		if err != nil {
			svcPort, err := util.LookupServicePortNumberByName(svc, remotePort)
			if err != nil {
				return nil, err
			}
			portnum = int(svcPort)

			if localPort == remotePort {
				localPort = strconv.Itoa(portnum)
			}
		}
		containerPort, err := util.LookupContainerPortNumberByServicePort(svc, pod, int32(portnum))
		if err != nil {
			// can't resolve a named port, or Service did not declare this port, return an error
			return nil, err
		}

		if int32(portnum) != containerPort {
			translated = append(translated, fmt.Sprintf("%s:%d", localPort, containerPort))
		} else {
			translated = append(translated, port)
		}
	}
	return translated, nil
}
1019910
func (res *Resolver) LaunchHTTP() <-chan error {
	defer util.HandleCrash()

	res.configureHTTP()
	listenAddress := net.JoinHostPort(res.config.HTTPListener, strconv.Itoa(res.config.HTTPPort))

	errCh := make(chan error, 1)
	go func() {
		var err error
		defer func() { errCh <- err }()

		if err = http.ListenAndServe(listenAddress, nil); err != nil {
			err = fmt.Errorf("failed to setup http server: %v", err)
		} else {
			logging.Error.Println("Not serving http requests any more.")
		}
	}()
	return errCh
}