Move StripLocalAddresses to a common util

Trac: 19026
This commit is contained in:
Arlo Breault 2020-03-26 13:05:24 -04:00
parent 5fa7578655
commit 670e4ba438
4 changed files with 72 additions and 63 deletions

View file

@ -14,12 +14,10 @@ import (
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"git.torproject.org/pluggable-transports/snowflake.git/common/util"
"github.com/pion/sdp/v2"
"github.com/pion/webrtc/v2"
)
@ -81,49 +79,6 @@ func limitedRead(r io.Reader, limit int64) ([]byte, error) {
return p, err
}
// Stolen from https://github.com/golang/go/pull/30278
func IsLocal(ip net.IP) bool {
if ip4 := ip.To4(); ip4 != nil {
// Local IPv4 addresses are defined in https://tools.ietf.org/html/rfc1918
return ip4[0] == 10 ||
(ip4[0] == 172 && ip4[1]&0xf0 == 16) ||
(ip4[0] == 192 && ip4[1] == 168)
}
// Local IPv6 addresses are defined in https://tools.ietf.org/html/rfc4193
return len(ip) == net.IPv6len && ip[0]&0xfe == 0xfc
}
// Removes local LAN address ICE candidates
func stripLocalAddresses(str string) string {
var desc sdp.SessionDescription
err := desc.Unmarshal([]byte(str))
if err != nil {
return str
}
for _, m := range desc.MediaDescriptions {
attrs := make([]sdp.Attribute, 0)
for _, a := range m.Attributes {
if a.IsICECandidate() {
ice, err := a.ToICECandidate()
if err == nil && ice.Typ == "host" {
ip := net.ParseIP(ice.Address)
if ip != nil && (IsLocal(ip) || ip.IsUnspecified() || ip.IsLoopback()) {
/* no append in this case */
continue
}
}
}
attrs = append(attrs, a)
}
m.Attributes = attrs
}
bts, err := desc.Marshal()
if err != nil {
return str
}
return string(bts)
}
// Roundtrip HTTP POST using WebRTC SessionDescriptions.
//
// Send an SDP offer to the broker, which assigns a proxy and responds
@ -138,7 +93,7 @@ func (bc *BrokerChannel) Negotiate(offer *webrtc.SessionDescription) (
if !bc.keepLocalAddresses {
offer = &webrtc.SessionDescription{
Type: offer.Type,
SDP: stripLocalAddresses(offer.SDP),
SDP: util.StripLocalAddresses(offer.SDP),
}
}
data := bytes.NewReader([]byte(util.SerializeSessionDescription(offer)))