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

@ -3,7 +3,9 @@ package util
import (
"encoding/json"
"log"
"net"
"github.com/pion/sdp/v2"
"github.com/pion/webrtc/v2"
)
@ -56,3 +58,46 @@ func DeserializeSessionDescription(msg string) *webrtc.SessionDescription {
SDP: parsed["sdp"].(string),
}
}
// 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)
}