| // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | package nathole |
| 16 |
| 17 | import ( |
| 18 | "bytes" |
| 19 | "fmt" |
| 20 | "net" |
| 21 | "strconv" |
| 22 |
| 23 | "github.com/fatedier/golib/crypto" |
| 24 | "github.com/pion/stun/v3" |
| 25 |
| 26 | "github.com/fatedier/frp/pkg/msg" |
| 27 | ) |
| 28 |
| 29 | func EncodeMessage(m msg.Message, key []byte) ([]byte, error) { |
| 30 | buffer := bytes.NewBuffer(nil) |
| 31 | if err := msg.WriteMsg(buffer, m); err != nil { |
| 32 | return nil, err |
| 33 | } |
| 34 |
| 35 | buf, err := crypto.Encode(buffer.Bytes(), key) |
| 36 | if err != nil { |
| 37 | return nil, err |
| 38 | } |
| 39 | return buf, nil |
| 40 | } |
| 41 |
| 42 | func DecodeMessageInto(data, key []byte, m msg.Message) error { |
| 43 | buf, err := crypto.Decode(data, key) |
| 44 | if err != nil { |
| 45 | return err |
| 46 | } |
| 47 |
| 48 | return msg.ReadMsgInto(bytes.NewReader(buf), m) |
| 49 | } |
| 50 |
| 51 | type ChangedAddress struct { |
| 52 | IP net.IP |
| 53 | Port int |
| 54 | } |
| 55 |
| 56 | func (s *ChangedAddress) GetFrom(m *stun.Message) error { |
| 57 | a := (*stun.MappedAddress)(s) |
| 58 | return a.GetFromAs(m, stun.AttrChangedAddress) |
| 59 | } |
| 60 |
| 61 | func (s *ChangedAddress) String() string { |
| 62 | return net.JoinHostPort(s.IP.String(), strconv.Itoa(s.Port)) |
| 63 | } |
| 64 |
| 65 | func ListAllLocalIPs() ([]net.IP, error) { |
| 66 | addrs, err := net.InterfaceAddrs() |
| 67 | if err != nil { |
| 68 | return nil, err |
| 69 | } |
| 70 | ips := make([]net.IP, 0, len(addrs)) |
| 71 | for _, addr := range addrs { |
| 72 | ip, _, err := net.ParseCIDR(addr.String()) |
| 73 | if err != nil { |
| 74 | continue |
| 75 | } |
| 76 | ips = append(ips, ip) |
| 77 | } |
| 78 | return ips, nil |
| 79 | } |
| 80 |
| 81 | func ListLocalIPsForNatHole(maxItems int) ([]string, error) { |
| 82 | if maxItems <= 0 { |
| 83 | return nil, fmt.Errorf("maxItems must be greater than 0") |
| 84 | } |
| 85 |
| 86 | ips, err := ListAllLocalIPs() |
| 87 | if err != nil { |
| 88 | return nil, err |
| 89 | } |
| 90 |
| 91 | filtered := make([]string, 0, maxItems) |
| 92 | for _, ip := range ips { |
| 93 | if len(filtered) >= maxItems { |
| 94 | break |
| 95 | } |
| 96 |
| 97 | // ignore ipv6 address |
| 98 | if ip.To4() == nil { |
| 99 | continue |
| 100 | } |
| 101 | // ignore localhost IP |
| 102 | if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() { |
| 103 | continue |
| 104 | } |
| 105 |
| 106 | filtered = append(filtered, ip.String()) |
| 107 | } |
| 108 | return filtered, nil |
| 109 | } |