utils.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2023 The frp Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  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. package nathole
  15. import (
  16. "bytes"
  17. "net"
  18. "strconv"
  19. "github.com/fatedier/golib/crypto"
  20. "github.com/pion/stun"
  21. "github.com/fatedier/frp/pkg/msg"
  22. )
  23. func EncodeMessage(m msg.Message, key []byte) ([]byte, error) {
  24. buffer := bytes.NewBuffer(nil)
  25. if err := msg.WriteMsg(buffer, m); err != nil {
  26. return nil, err
  27. }
  28. buf, err := crypto.Encode(buffer.Bytes(), key)
  29. if err != nil {
  30. return nil, err
  31. }
  32. return buf, nil
  33. }
  34. func DecodeMessageInto(data, key []byte, m msg.Message) error {
  35. buf, err := crypto.Decode(data, key)
  36. if err != nil {
  37. return err
  38. }
  39. if err := msg.ReadMsgInto(bytes.NewReader(buf), m); err != nil {
  40. return err
  41. }
  42. return nil
  43. }
  44. type ChangedAddress struct {
  45. IP net.IP
  46. Port int
  47. }
  48. func (s *ChangedAddress) GetFrom(m *stun.Message) error {
  49. a := (*stun.MappedAddress)(s)
  50. return a.GetFromAs(m, stun.AttrChangedAddress)
  51. }
  52. func (s *ChangedAddress) String() string {
  53. return net.JoinHostPort(s.IP.String(), strconv.Itoa(s.Port))
  54. }