Skip to content

Commit

Permalink
featuer: device add support unixsocket use fd
Browse files Browse the repository at this point in the history
  • Loading branch information
huangxiangyu committed Aug 18, 2023
1 parent f588b4c commit 9cfd77e
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
6 changes: 6 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"flag"
"fmt"
"github.com/xjasonlyu/tun2socks/v2/sock2fd"

Check failure on line 6 in main.go

View workflow job for this annotation

GitHub Actions / lint

File is not `gci`-ed with --skip-generated -s standard -s default -s prefix(github.com/xjasonlyu/tun2socks) --custom-order (gci)
"os"
"os/signal"
"syscall"

Check failure on line 9 in main.go

View workflow job for this annotation

GitHub Actions / lint

File is not `gofumpt`-ed (gofumpt)
Expand Down Expand Up @@ -61,6 +62,11 @@ func main() {
}
}

fd, err := sock2fd.Sock2Fd(key.Device)
if err == nil {
key.Device = fmt.Sprintf("fd://%d", fd)
}

engine.Insert(key)

engine.Start()
Expand Down
41 changes: 41 additions & 0 deletions sock2fd/unix2fd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package sock2fd

import (
"errors"
"net"
"strings"
)

func Sock2Fd(s string) (int, error) {

Check failure on line 10 in sock2fd/unix2fd.go

View workflow job for this annotation

GitHub Actions / lint

File is not `gofumpt`-ed (gofumpt)
strSplit := strings.Split(s, "://")

if strSplit[0] == "unix" || strSplit[0] == "Unix" || strSplit[0] == "UNIX" {
return Unix2Fd(strSplit[1])
}
return 0, errors.New("unsupported socket")
}

/*
for example:
device: unix:///tmp/unix_socket
*/

func Unix2Fd(path string) (int, error) {
conn, err := net.Dial("unix", path)
if err != nil {
return 0, err
}

unixConn, ok := conn.(*net.UnixConn)
if !ok {
return 0, errors.New("unexpected")
}

fd, err := unixConn.File()
if err != nil {
return 0, errors.New("unexpected")
}

return int(fd.Fd()), nil
}

0 comments on commit 9cfd77e

Please sign in to comment.