forked from lesismal/nbio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net_unix.go
100 lines (84 loc) · 1.83 KB
/
net_unix.go
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
// Copyright 2020 lesismal. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
//go:build linux || darwin || netbsd || freebsd || openbsd || dragonfly
// +build linux darwin netbsd freebsd openbsd dragonfly
package nbio
import (
"errors"
"net"
"syscall"
)
func init() {
var limit syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err == nil {
if n := int(limit.Max); n > 0 && n < MaxOpenFiles {
MaxOpenFiles = n
}
}
}
func dupStdConn(conn net.Conn) (*Conn, error) {
sc, ok := conn.(interface {
SyscallConn() (syscall.RawConn, error)
})
if !ok {
return nil, errors.New("RawConn Unsupported")
}
rc, err := sc.SyscallConn()
if err != nil {
return nil, errors.New("RawConn Unsupported")
}
var newFd int
errCtrl := rc.Control(func(fd uintptr) {
newFd, err = syscall.Dup(int(fd))
})
if errCtrl != nil {
return nil, errCtrl
}
if err != nil {
return nil, err
}
lAddr := conn.LocalAddr()
rAddr := conn.RemoteAddr()
conn.Close()
// err = syscall.SetNonblock(newFd, true)
// if err != nil {
// syscall.Close(newFd)
// return nil, err
// }
c := &Conn{
fd: newFd,
lAddr: lAddr,
rAddr: rAddr,
}
switch conn.(type) {
case *net.TCPConn:
c.typ = ConnTypeTCP
case *net.UnixConn:
c.typ = ConnTypeUnix
case *net.UDPConn:
lAddrUDP := lAddr.(*net.UDPAddr)
newLAddr := net.UDPAddr{
IP: make([]byte, len(lAddrUDP.IP)),
Port: lAddrUDP.Port,
Zone: lAddrUDP.Zone,
}
copy(newLAddr.IP, lAddrUDP.IP)
c.lAddr = &newLAddr
// c.lAddr = lAddrUDP
if rAddr == nil {
c.typ = ConnTypeUDPServer
c.connUDP = &udpConn{
parent: c,
conns: map[string]*Conn{},
}
} else {
c.typ = ConnTypeUDPClientFromDial
c.connUDP = &udpConn{
parent: c,
}
}
default:
}
return c, nil
}