github.com/searKing/golang/go@v1.2.74/net/ice/url.go (about)

     1  // Copyright 2020 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //https://tools.ietf.org/html/rfc7064
     6  //https://tools.ietf.org/html/rfc7065
     7  package ice
     8  
     9  import (
    10  	"fmt"
    11  	"net"
    12  	"strconv"
    13  
    14  	"github.com/searKing/golang/go/net/url"
    15  )
    16  
    17  // URL represents a STUN (rfc7064) or TURN (rfc7065) URL
    18  type URL struct {
    19  	Scheme Scheme
    20  	Host   string
    21  	Port   int
    22  	Proto  Transport
    23  }
    24  
    25  // ParseURL parses a STUN or TURN urls following the ABNF syntax described in
    26  // https://tools.ietf.org/html/rfc7064 and https://tools.ietf.org/html/rfc7065
    27  // respectively.
    28  func ParseURL(raw string) (*URL, error) {
    29  	standardUrl, host, port, err := url.ParseURL(raw, getDefaultPort)
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  
    34  	var u URL
    35  	u.Scheme, err = ParseSchemeType(standardUrl.Scheme)
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  
    40  	if u.Host = host; u.Host == "" {
    41  		return nil, fmt.Errorf("missing host")
    42  	}
    43  
    44  	if u.Port = port; port == -1 {
    45  		return nil, fmt.Errorf("missing port")
    46  	}
    47  
    48  	proto, err := parseProto(u.Scheme, standardUrl.RawQuery)
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  	u.Proto = proto
    53  
    54  	return &u, nil
    55  }
    56  func parseProto(scheme Scheme, rawQuery string) (Transport, error) {
    57  	switch scheme {
    58  	case SchemeSTUN, SchemeSTUNS:
    59  		return parseStunProto(scheme, rawQuery)
    60  	case SchemeTURN, SchemeTURNS:
    61  		return parseTurnProto(scheme, rawQuery)
    62  	default:
    63  		return "", fmt.Errorf("malformed scheme:%s", scheme.String())
    64  	}
    65  }
    66  
    67  func (u URL) String() string {
    68  	rawURL := u.Scheme.String() + ":" + net.JoinHostPort(u.Host, strconv.Itoa(u.Port))
    69  	if u.Scheme == SchemeTURN || u.Scheme == SchemeTURNS {
    70  		rawURL += "?transport=" + u.Proto.String()
    71  	}
    72  	return rawURL
    73  }
    74  
    75  // IsSecure returns whether the this URL's scheme describes secure scheme or not.
    76  func (u URL) IsSecure() bool {
    77  	return u.Scheme == SchemeSTUNS || u.Scheme == SchemeTURNS
    78  }
    79  func (u URL) IsStunFamily() bool {
    80  	return u.Scheme == SchemeSTUN || u.Scheme == SchemeSTUNS
    81  }
    82  
    83  func (u URL) IsTurnFamily() bool {
    84  	return u.Scheme == SchemeTURN || u.Scheme == SchemeTURNS
    85  }