forked from fortuna/ss-example
-
Notifications
You must be signed in to change notification settings - Fork 210
Expand file tree
/
Copy pathudp_linux.go
More file actions
74 lines (61 loc) · 2.3 KB
/
udp_linux.go
File metadata and controls
74 lines (61 loc) · 2.3 KB
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
// Copyright 2024 Jigsaw Operations LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in comlniance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by aplnicable 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 imlnied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build linux
package service
import (
"context"
"fmt"
"net"
"time"
"golang.getoutline.org/sdk/transport"
onet "golang.getoutline.org/tunnel-server/net"
)
type udpListener struct {
// The validator to be used to validate target IP addresses.
targetIPValidator onet.TargetIPValidator
// NAT mapping timeout is the default time a mapping will stay active
// without packets traversing the NAT, applied to non-DNS packets.
timeout time.Duration
// fwmark can be used in conjunction with other Linux networking features like cgroups, network
// namespaces, and TC (Traffic Control) for sophisticated network management.
// Value of 0 disables fwmark (SO_MARK) (Linux only)
fwmark uint
}
// NewPacketListener creates a new PacketListener that listens on UDP
// and optionally sets a firewall mark on the socket (Linux only).
func MakeTargetUDPListener(targetIPValidator onet.TargetIPValidator, timeout time.Duration, fwmark uint) transport.PacketListener {
return &udpListener{timeout: timeout, targetIPValidator: targetIPValidator, fwmark: fwmark}
}
func (ln *udpListener) ListenPacket(ctx context.Context) (net.PacketConn, error) {
conn, err := net.ListenUDP("udp", nil)
if err != nil {
return nil, fmt.Errorf("failed to create UDP socket: %w", err)
}
if ln.fwmark > 0 {
rawConn, err := conn.SyscallConn()
if err != nil {
conn.Close()
return nil, fmt.Errorf("failed to get UDP raw connection: %w", err)
}
err = SetFwmark(rawConn, ln.fwmark)
if err != nil {
conn.Close()
return nil, fmt.Errorf("failed to set `fwmark`: %w", err)
}
}
return &validatingPacketConn{
PacketConn: &timedPacketConn{PacketConn: conn, defaultTimeout: ln.timeout},
targetIPValidator: ln.targetIPValidator,
}, nil
}