ppp.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2012 Google, Inc. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the LICENSE file in the root of the source
  5. // tree.
  6. package layers
  7. import (
  8. "encoding/binary"
  9. "errors"
  10. "github.com/google/gopacket"
  11. )
  12. // PPP is the layer for PPP encapsulation headers.
  13. type PPP struct {
  14. BaseLayer
  15. PPPType PPPType
  16. }
  17. // PPPEndpoint is a singleton endpoint for PPP. Since there is no actual
  18. // addressing for the two ends of a PPP connection, we use a singleton value
  19. // named 'point' for each endpoint.
  20. var PPPEndpoint = gopacket.NewEndpoint(EndpointPPP, nil)
  21. // PPPFlow is a singleton flow for PPP. Since there is no actual addressing for
  22. // the two ends of a PPP connection, we use a singleton value to represent the
  23. // flow for all PPP connections.
  24. var PPPFlow = gopacket.NewFlow(EndpointPPP, nil, nil)
  25. // LayerType returns LayerTypePPP
  26. func (p *PPP) LayerType() gopacket.LayerType { return LayerTypePPP }
  27. // LinkFlow returns PPPFlow.
  28. func (p *PPP) LinkFlow() gopacket.Flow { return PPPFlow }
  29. func decodePPP(data []byte, p gopacket.PacketBuilder) error {
  30. ppp := &PPP{}
  31. if data[0]&0x1 == 0 {
  32. if data[1]&0x1 == 0 {
  33. return errors.New("PPP has invalid type")
  34. }
  35. ppp.PPPType = PPPType(binary.BigEndian.Uint16(data[:2]))
  36. ppp.Contents = data[:2]
  37. ppp.Payload = data[2:]
  38. } else {
  39. ppp.PPPType = PPPType(data[0])
  40. ppp.Contents = data[:1]
  41. ppp.Payload = data[1:]
  42. }
  43. p.AddLayer(ppp)
  44. p.SetLinkLayer(ppp)
  45. return p.NextDecoder(ppp.PPPType)
  46. }
  47. // SerializeTo writes the serialized form of this layer into the
  48. // SerializationBuffer, implementing gopacket.SerializableLayer.
  49. // See the docs for gopacket.SerializableLayer for more info.
  50. func (p *PPP) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error {
  51. if p.PPPType&0x100 == 0 {
  52. bytes, err := b.PrependBytes(2)
  53. if err != nil {
  54. return err
  55. }
  56. binary.BigEndian.PutUint16(bytes, uint16(p.PPPType))
  57. } else {
  58. bytes, err := b.PrependBytes(1)
  59. if err != nil {
  60. return err
  61. }
  62. bytes[0] = uint8(p.PPPType)
  63. }
  64. return nil
  65. }