summaryrefslogtreecommitdiffhomepage
path: root/pkg/tcpip/link/tunnel/gre.go
blob: ef2f9c4de68613b8506268be83788e1731a37b5f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
// Copyright 2021 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tunnel

import (
	"context"
	"errors"
	"log"

	"gvisor.dev/gvisor/pkg/tcpip"
	"gvisor.dev/gvisor/pkg/tcpip/buffer"
	"gvisor.dev/gvisor/pkg/tcpip/header"
	"gvisor.dev/gvisor/pkg/tcpip/link/channel"
	"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
	"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
	"gvisor.dev/gvisor/pkg/tcpip/stack"
	"gvisor.dev/gvisor/pkg/tcpip/transport/gre"
	"gvisor.dev/gvisor/pkg/tcpip/transport/raw"
	"gvisor.dev/gvisor/pkg/waiter"
)

var SIZE = 16

type Endpoint struct {
	channel.Endpoint
	LocalAddr tcpip.Address
	RemoteAddr tcpip.Address
}

type writer Endpoint

func New(mtu uint32) *Endpoint {
	var linkAddress tcpip.LinkAddress

	ch := channel.New(SIZE, mtu, linkAddress)
	return &Endpoint{
		Endpoint: *ch,
	}
}

func (e *Endpoint) GetChannel() *channel.Endpoint {
	return &e.Endpoint
}

func (e *Endpoint) GetLocalAddress() tcpip.Address {
	return e.LocalAddr
}

func (e *Endpoint) GetRemoteAddress() tcpip.Address {
	return e.RemoteAddr
}

// Attach saves the stack network-layer dispatcher for use later when packets
// are injected.
func (e *Endpoint) Attach(dispatcher stack.NetworkDispatcher) {
	log.Println("GRE: Attach")

	e.Endpoint.Attach(dispatcher)
}

type GrePacketInfo struct {
	pi *channel.PacketInfo
}

func (g GrePacketInfo) Len() int {
	return g.pi.Pkt.Size()
}

func (g GrePacketInfo) Read(p []byte) (n int, err error){
	pkt := g.pi.Pkt
	size := pkt.Size()

	if size > len(p) {
		return 0, errors.New("Buffer too small")
	}
	vv := buffer.NewVectorisedView(size, pkt.Views())
	pos := 0
	for {
		copied, err := vv.Read(p[pos:])
		log.Printf("VectorisedView Read: %d %d %d %v", size, pos, copied, err)
		if err != nil {
			return 0, errors.New("&tcpip.ErrBadBuffer{}")
		}
		pos = pos + copied
		if pos == size {
			break
		}
	}

	return pos, nil
}

func (g GrePacketInfo) Payload(size int) ([]byte, tcpip.Error){
	log.Println("Payload")
	return nil, &tcpip.ErrNotSupported{}
}

type GreHandlerInfo struct {
	ChEp *channel.Endpoint
	Raw tcpip.Endpoint
	Raddr tcpip.FullAddress
	Stack *stack.Stack
	NIC tcpip.NICID
}

func (info *GreHandlerInfo) greHandler(req *gre.ForwarderRequest) {
	pkt := req.Pkt
	log.Println("greHandler: ", req.Pkt.Size(), req.Pkt.Views())
	greHdr := header.GRE(pkt.TransportHeader().View())
	proto := greHdr.ProtocolType()
	pktData := pkt.Data()
	views := pktData.Views()
	size := pktData.Size()
	data := buffer.NewVectorisedView(size, views)
	newPkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
		Data: data,
	})
	log.Printf("greHandler proto: %d cloned: %v", proto, newPkt.Views())

	info.ChEp.InjectInbound(proto, newPkt)
}

func ipAny(protocol tcpip.NetworkProtocolNumber) (tcpip.Address, tcpip.Error) {
	switch protocol {
	case header.IPv4ProtocolNumber:
		return header.IPv4Any, nil
	case header.IPv6ProtocolNumber:
		return header.IPv6Any, nil
	default:
		log.Printf("Unsupported protocol %v", protocol)
		return tcpip.Address([]byte{}), &tcpip.ErrNotSupported{}
	}
}

func (info *GreHandlerInfo) greRead(ep *channel.Endpoint) {
	for {
		pi, err := ep.ReadContext(context.Background());
		linkHdr := pi.Pkt.LinkHeader()
		greHdr := header.GRE(linkHdr.Push(header.GREHeaderSize))
		greHdr.SetProtocolType(pi.Proto)
		log.Printf("greRead %d %v %v %v", pi.Proto, pi, err, greHdr)
		opts := tcpip.WriteOptions{
			//To: &info.Raddr
		}
		if info.Raddr.Addr == header.IPv4Any {
			protocol := pi.Pkt.NetworkProtocolNumber
			nw := pi.Pkt.Network()
			addr := nw.DestinationAddress()
			laddr, err := ipAny(protocol); if err != nil {
				continue
			}

			err = info.Stack.GetLinkAddress(info.NIC, addr, laddr,  protocol, func (res stack.LinkResolutionResult) {

				if res.Err != nil {
					return
				}

				opts.To = &tcpip.FullAddress{
					NIC: 0,
					Addr: tcpip.Address(res.LinkAddress),
				}
			})
			if err != nil {
				continue
			}
		}
		info.Raw.Write(GrePacketInfo{&pi}, opts)
	}
}

func networkProtocolNumber(addr *tcpip.Address) tcpip.NetworkProtocolNumber {
	if addr.To4() != "" {
		return ipv4.ProtocolNumber
	} else {
		return ipv6.ProtocolNumber
	}
}

// ARPHardwareType implements stack.LinkEndpoint.ARPHardwareType.
func (*Endpoint) ARPHardwareType() header.ARPHardwareType {
	return header.ARPHardwareIPGRE
}

func (e *Endpoint) Start(s *stack.Stack, nic tcpip.NICID, laddr, raddr *tcpip.Address) tcpip.Error {
	proto := networkProtocolNumber(laddr)
	if proto != networkProtocolNumber(raddr) {
		return &tcpip.ErrBadAddress{}
	}

	// Create TCP endpoint.
	var rawWq waiter.Queue
	rawEp, tcperr := raw.NewEndpoint(s, proto, header.GREProtocolNumber, &rawWq)
	if tcperr != nil {
		return tcperr
	}
	log.Println("EP: %s", rawEp)

	e.LocalAddr = *laddr
	e.RemoteAddr = *raddr

	fraddr := tcpip.FullAddress{NIC: 0, Addr: *raddr}
	flAddr := tcpip.FullAddress{NIC: 0, Addr: *laddr}
	tcperr = rawEp.Bind(flAddr)
	if tcperr != nil {
		return tcperr
	}
	log.Printf("Remote: %v %v", raddr, fraddr)

	// Create GRE
	// greEP := grelink.New(mtu - 24)
	chEP := e.GetChannel()
	// TODO detect IPv4/IPv6
	e.NMaxHeaderLength = header.IPv6FixedHeaderSize + header.GREHeaderSize

	greInfo := GreHandlerInfo{
//		Ep: loEP,
		ChEp: chEP,
		Raw: rawEp,
		Raddr: fraddr,
		Stack: s,
		NIC: nic,
	}
	greFwd := gre.NewForwarder(s, greInfo.greHandler)
	s.SetTransportProtocolHandler(header.GREProtocolNumber, greFwd.HandlePacket)

	go greInfo.greRead(chEP)

	any, _ := ipAny(proto)
	if fraddr.Addr != any {
		tcperr = rawEp.Connect(fraddr)
		if tcperr != nil {
			return tcperr
		}
	}

	return nil
}