forked from cloudwego/netpoll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net_netfd.go
194 lines (182 loc) · 6.04 KB
/
net_netfd.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
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
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// This file may have been modified by CloudWeGo authors. (“CloudWeGo Modifications”).
// All CloudWeGo Modifications are Copyright 2022 CloudWeGo authors.
//go:build aix || darwin || dragonfly || freebsd || linux || nacl || netbsd || openbsd || solaris
// +build aix darwin dragonfly freebsd linux nacl netbsd openbsd solaris
package netpoll
import (
"context"
"errors"
"net"
"os"
"runtime"
"syscall"
"time"
)
var (
// aLongTimeAgo is a non-zero time, far in the past, used for
// immediate cancelation of dials.
aLongTimeAgo = time.Unix(1, 0)
// nonDeadline and noCancel are just zero values for
// readability with functions taking too many parameters.
noDeadline = time.Time{}
)
type netFD struct {
// file descriptor
fd int
// When calling netFD.dial(), fd will be registered into poll in some scenarios, such as dialing tcp socket,
// but not in other scenarios, such as dialing unix socket.
// This leads to a different behavior in register poller at after, so use this field to mark it.
pd *pollDesc
// closed marks whether fd has expired
closed uint32
// Whether this is a streaming descriptor, as opposed to a
// packet-based descriptor like a UDP socket. Immutable.
isStream bool
// Whether a zero byte read indicates EOF. This is false for a
// message based socket connection.
zeroReadIsEOF bool
family int // AF_INET, AF_INET6, syscall.AF_UNIX
sotype int // syscall.SOCK_STREAM, syscall.SOCK_DGRAM, syscall.SOCK_RAW
isConnected bool // handshake completed or use of association with peer
network string // tcp tcp4 tcp6, udp, udp4, udp6, ip, ip4, ip6, unix, unixgram, unixpacket
localAddr net.Addr
remoteAddr net.Addr
// for detaching conn from poller
detaching bool
}
func newNetFD(fd, family, sotype int, net string) *netFD {
var ret = &netFD{}
ret.fd = fd
ret.network = net
ret.family = family
ret.sotype = sotype
ret.isStream = sotype == syscall.SOCK_STREAM
ret.zeroReadIsEOF = sotype != syscall.SOCK_DGRAM && sotype != syscall.SOCK_RAW
return ret
}
// if dial connection error, you need exec netFD.Close actively
func (c *netFD) dial(ctx context.Context, laddr, raddr sockaddr) (err error) {
var lsa syscall.Sockaddr
if laddr != nil {
if lsa, err = laddr.sockaddr(c.family); err != nil {
return err
} else if lsa != nil {
// bind local address
if err = syscall.Bind(c.fd, lsa); err != nil {
return os.NewSyscallError("bind", err)
}
}
}
var rsa syscall.Sockaddr // remote address from the user
var crsa syscall.Sockaddr // remote address we actually connected to
if raddr != nil {
if rsa, err = raddr.sockaddr(c.family); err != nil {
return err
}
}
// remote address we actually connected to
if crsa, err = c.connect(ctx, lsa, rsa); err != nil {
return err
}
c.isConnected = true
// Record the local and remote addresses from the actual socket.
// Get the local address by calling Getsockname.
// For the remote address, use
// 1) the one returned by the connect method, if any; or
// 2) the one from Getpeername, if it succeeds; or
// 3) the one passed to us as the raddr parameter.
lsa, _ = syscall.Getsockname(c.fd)
c.localAddr = sockaddrToAddr(lsa)
if crsa != nil {
c.remoteAddr = sockaddrToAddr(crsa)
} else if crsa, _ = syscall.Getpeername(c.fd); crsa != nil {
c.remoteAddr = sockaddrToAddr(crsa)
} else {
c.remoteAddr = sockaddrToAddr(rsa)
}
return nil
}
func (c *netFD) connect(ctx context.Context, la, ra syscall.Sockaddr) (rsa syscall.Sockaddr, retErr error) {
// Do not need to call c.writing here,
// because c is not yet accessible to user,
// so no concurrent operations are possible.
switch err := syscall.Connect(c.fd, ra); err {
case syscall.EINPROGRESS, syscall.EALREADY, syscall.EINTR:
case nil, syscall.EISCONN:
select {
case <-ctx.Done():
return nil, mapErr(ctx.Err())
default:
}
return nil, nil
case syscall.EINVAL:
// On Solaris we can see EINVAL if the socket has
// already been accepted and closed by the server.
// Treat this as a successful connection--writes to
// the socket will see EOF. For details and a test
// case in C see https://golang.org/issue/6828.
if runtime.GOOS == "solaris" {
return nil, nil
}
fallthrough
default:
return nil, os.NewSyscallError("connect", err)
}
c.pd = newPollDesc(c.fd)
for {
// Performing multiple connect system calls on a
// non-blocking socket under Unix variants does not
// necessarily result in earlier errors being
// returned. Instead, once runtime-integrated network
// poller tells us that the socket is ready, get the
// SO_ERROR socket option to see if the connection
// succeeded or failed. See issue 7474 for further
// details.
if err := c.pd.WaitWrite(ctx); err != nil {
return nil, err
}
nerr, err := syscall.GetsockoptInt(c.fd, syscall.SOL_SOCKET, syscall.SO_ERROR)
if err != nil {
return nil, os.NewSyscallError("getsockopt", err)
}
switch err := syscall.Errno(nerr); err {
case syscall.EINPROGRESS, syscall.EALREADY, syscall.EINTR:
case syscall.EISCONN:
return nil, nil
case syscall.Errno(0):
// The runtime poller can wake us up spuriously;
// see issues 14548 and 19289. Check that we are
// really connected; if not, wait again.
if rsa, err := syscall.Getpeername(c.fd); err == nil {
return rsa, nil
}
default:
return nil, os.NewSyscallError("connect", err)
}
}
}
// Various errors contained in OpError.
var (
errMissingAddress = errors.New("missing address")
errCanceled = errors.New("operation was canceled")
errIOTimeout = errors.New("i/o timeout")
)
// mapErr maps from the context errors to the historical internal net
// error values.
//
// TODO(bradfitz): get rid of this after adjusting tests and making
// context.DeadlineExceeded implement net.Error?
func mapErr(err error) error {
switch err {
case context.Canceled:
return errCanceled
case context.DeadlineExceeded:
return errIOTimeout
default:
return err
}
}