|
| 1 | +// Copyright 2018 Jigsaw Operations LLC |
| 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 | +// https://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 | + |
| 15 | +//go:build linux |
| 16 | + |
| 17 | +package service |
| 18 | + |
| 19 | +import ( |
| 20 | + "log/slog" |
| 21 | + "net" |
| 22 | + "os" |
| 23 | + "syscall" |
| 24 | + |
| 25 | + onet "github.com/Jigsaw-Code/outline-ss-server/net" |
| 26 | +) |
| 27 | + |
| 28 | +// fwmark can be used in conjunction with other Linux networking features like cgroups, network namespaces, and TC (Traffic Control) for sophisticated network management. |
| 29 | +// Value of 0 disables fwmark (SO_MARK) (Linux Only) |
| 30 | +func MakeTargetPacketListener(fwmark uint) UDPDialer { |
| 31 | + return func() (net.PacketConn, *onet.ConnectionError) { |
| 32 | + udpConn, err := net.ListenPacket("udp", "") |
| 33 | + if err != nil { |
| 34 | + return nil, onet.NewConnectionError("ERR_CREATE_SOCKET", "Failed to create UDP socket", err) |
| 35 | + } |
| 36 | + |
| 37 | + if fwmark > 0 { |
| 38 | + rawConn, err := udpConn.(*net.UDPConn).SyscallConn() |
| 39 | + if err != nil { |
| 40 | + udpConn.Close() |
| 41 | + return nil, onet.NewConnectionError("ERR_CREATE_SOCKET", "Failed to get UDP raw connection", err) |
| 42 | + } |
| 43 | + err = rawConn.Control(func(fd uintptr) { |
| 44 | + err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, int(fwmark)) |
| 45 | + if err != nil { |
| 46 | + slog.Error("Set fwmark failed.", "err", os.NewSyscallError("failed to set fwmark for UDP socket", err)) |
| 47 | + } |
| 48 | + }) |
| 49 | + if err != nil { |
| 50 | + udpConn.Close() |
| 51 | + return nil, onet.NewConnectionError("ERR_CREATE_SOCKET", "Set UDPDialer Control func failed.", err) |
| 52 | + } |
| 53 | + } |
| 54 | + return udpConn, nil |
| 55 | + } |
| 56 | +} |
0 commit comments