Debian Codegraph @

pkg/hvsock/hvsock_windows.go

raw
1 package hvsock
2
3 import (
4 "fmt"
5 "io"
6 "log"
7 "net"
8 "runtime"
9 "sync"
10 "sync/atomic"
11 "syscall"
12 "time"
13 "unsafe"
14
15 "github.com/pkg/errors"
16 )
17
18 // Make sure Winsock2 is initialised
19 func init() {
20 e := syscall.WSAStartup(uint32(0x202), &wsaData)
21 if e != nil {
22 log.Fatal("WSAStartup", e)
23 }
24 }
25
26 const (
27 hvsockAF = 34 // AF_HYPERV
28 hvsockRaw = 1 // SHV_PROTO_RAW
29 )
30
31 var (
32 // ErrTimeout is an error returned on timeout
33 ErrTimeout = &timeoutError{}
34
35 wsaData syscall.WSAData
36 )
37
38 // Supported returns if hvsocks are supported on your platform
39 func Supported() bool {
40 return true
41 }
42
43 // Dial a Hyper-V socket address
44 func Dial(raddr Addr) (Conn, error) {
45 fd, err := syscall.Socket(hvsockAF, syscall.SOCK_STREAM, hvsockRaw)
46 if err != nil {
47 return nil, err
48 }
49
50 var sa rawSockaddrHyperv
51 ptr, n, err := raddr.sockaddr(&sa)
52 if err != nil {
53 return nil, err
54 }
55
56 if err := sys_connect(fd, ptr, n); err != nil {
57 return nil, errors.Wrapf(err, "connect(%s) failed", raddr)
58 }
59
60 return newHVsockConn(fd, Addr{VMID: GUIDZero, ServiceID: GUIDZero}, raddr)
61 }
62
63 // Listen returns a net.Listener which can accept connections on the given port
64 func Listen(addr Addr) (net.Listener, error) {
65 fd, err := syscall.Socket(hvsockAF, syscall.SOCK_STREAM, hvsockRaw)
66 if err != nil {
67 return nil, err
68 }
69
70 var sa rawSockaddrHyperv
71 ptr, n, err := addr.sockaddr(&sa)
72 if err != nil {
73 return nil, err
74 }
75 if err := sys_bind(fd, ptr, n); err != nil {
76 return nil, fmt.Errorf("bind(%s) failed with %v", addr, err)
77 }
78
79 err = syscall.Listen(fd, syscall.SOMAXCONN)
80 if err != nil {
81 return nil, errors.Wrapf(err, "listen(%s) failed", addr)
82 }
83
84 return &hvsockListener{fd, addr}, nil
85 }
86
87 //
88 // Hyper-v sockets Listener implementation
89 //
90
91 type hvsockListener struct {
92 fd syscall.Handle
93 local Addr
94 }
95
96 // Accept accepts an incoming call and returns the new connection
97 func (v *hvsockListener) Accept() (net.Conn, error) {
98 var sa rawSockaddrHyperv
99 var n = int32(unsafe.Sizeof(sa))
100 fd, err := sys_accept(v.fd, &sa, &n)
101 if err != nil {
102 return nil, err
103 }
104
105 // Extract an Addr from sa
106 raddr := Addr{}
107 for i := 0; i < len(raddr.VMID); i++ {
108 raddr.VMID[i] = sa.VMID[i]
109 }
110 for i := 0; i < len(raddr.ServiceID); i++ {
111 raddr.ServiceID[i] = sa.ServiceID[i]
112 }
113 return newHVsockConn(fd, v.local, raddr)
114 }
115
116 // Close closes the listening connection
117 func (v *hvsockListener) Close() error {
118 return syscall.Close(v.fd)
119 }
120
121 // Addr returns the address the Listener is listening on
122 func (v *hvsockListener) Addr() net.Addr {
123 return v.local
124 }
125
126 //
127 // Hyper-V socket connection implementation
128 //
129
130 // hvsockConn represent a Hyper-V connection. Complex mostly due to asynch send()/recv() syscalls.
131 type hvsockConn struct {
132 fd syscall.Handle
133 local Addr
134 remote Addr
135
136 wg sync.WaitGroup
137 wgLock sync.RWMutex
138 closing atomicBool
139
140 readDeadline deadlineHandler
141 writeDeadline deadlineHandler
142 }
143
144 func newHVsockConn(h syscall.Handle, local Addr, remote Addr) (*hvsockConn, error) {
145 ioInitOnce.Do(initIo)
146 v := &hvsockConn{fd: h, local: local, remote: remote}
147
148 _, err := createIoCompletionPort(h, ioCompletionPort, 0, 0xffffffff)
149 if err != nil {
150 return nil, err
151 }
152 err = setFileCompletionNotificationModes(h,
153 cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS|cFILE_SKIP_SET_EVENT_ON_HANDLE)
154 if err != nil {
155 return nil, err
156 }
157 v.readDeadline.channel = make(timeoutChan)
158 v.writeDeadline.channel = make(timeoutChan)
159
160 return v, nil
161 }
162
163 // LocalAddr returns the local address of a connection
164 func (v *hvsockConn) LocalAddr() net.Addr {
165 return v.local
166 }
167
168 // RemoteAddr returns the remote address of a connection
169 func (v *hvsockConn) RemoteAddr() net.Addr {
170 return v.remote
171 }
172
173 // Close closes the connection
174 func (v *hvsockConn) Close() error {
175 v.close()
176 return nil
177 }
178
179 // CloseRead shuts down the reading side of a hvsock connection
180 func (v *hvsockConn) CloseRead() error {
181 return syscall.Shutdown(v.fd, syscall.SHUT_RD)
182 }
183
184 // CloseWrite shuts down the writing side of a hvsock connection
185 func (v *hvsockConn) CloseWrite() error {
186 return syscall.Shutdown(v.fd, syscall.SHUT_WR)
187 }
188
189 // Read reads data from the connection
190 func (v *hvsockConn) Read(buf []byte) (int, error) {
191 var b syscall.WSABuf
192 var f uint32
193
194 b.Len = uint32(len(buf))
195 b.Buf = &buf[0]
196
197 c, err := v.prepareIo()
198 if err != nil {
199 return 0, err
200 }
201 defer v.wg.Done()
202
203 if v.readDeadline.timedout.isSet() {
204 return 0, ErrTimeout
205 }
206
207 var bytes uint32
208 err = syscall.WSARecv(v.fd, &b, 1, &bytes, &f, &c.o, nil)
209 n, err := v.asyncIo(c, &v.readDeadline, bytes, err)
210 runtime.KeepAlive(buf)
211
212 // Handle EOF conditions.
213 if err == nil && n == 0 && len(buf) != 0 {
214 return 0, io.EOF
215 } else if err == syscall.ERROR_BROKEN_PIPE {
216 return 0, io.EOF
217 } else {
218 return n, err
219 }
220 }
221
222 // Write writes data over the connection
223 // TODO(rn): Remove once 4.9.x support is deprecated
224 func (v *hvsockConn) Write(buf []byte) (int, error) {
225 written := 0
226 toWrite := len(buf)
227 for toWrite > 0 {
228 thisBatch := min(toWrite, maxMsgSize)
229 n, err := v.write(buf[written : written+thisBatch])
230 if err != nil {
231 return written, err
232 }
233 if n != thisBatch {
234 return written, fmt.Errorf("short write %d != %d", n, thisBatch)
235 }
236 toWrite -= n
237 written += n
238 }
239
240 return written, nil
241 }
242
243 func (v *hvsockConn) write(buf []byte) (int, error) {
244 var b syscall.WSABuf
245 var f uint32
246
247 if len(buf) == 0 {
248 return 0, nil
249 }
250
251 f = 0
252 b.Len = uint32(len(buf))
253 b.Buf = &buf[0]
254
255 c, err := v.prepareIo()
256 if err != nil {
257 return 0, err
258 }
259 defer v.wg.Done()
260
261 if v.writeDeadline.timedout.isSet() {
262 return 0, ErrTimeout
263 }
264
265 var bytes uint32
266 err = syscall.WSASend(v.fd, &b, 1, &bytes, f, &c.o, nil)
267 n, err := v.asyncIo(c, &v.writeDeadline, bytes, err)
268 runtime.KeepAlive(buf)
269 return n, err
270 }
271
272 // SetReadDeadline implementation for Hyper-V sockets
273 func (v *hvsockConn) SetReadDeadline(deadline time.Time) error {
274 return v.readDeadline.set(deadline)
275 }
276
277 // SetWriteDeadline implementation for Hyper-V sockets
278 func (v *hvsockConn) SetWriteDeadline(deadline time.Time) error {
279 return v.writeDeadline.set(deadline)
280 }
281
282 // SetDeadline implementation for Hyper-V sockets
283 func (v *hvsockConn) SetDeadline(deadline time.Time) error {
284 if err := v.SetReadDeadline(deadline); err != nil {
285 return err
286 }
287 return v.SetWriteDeadline(deadline)
288 }
289
290 // Helper functions for conversion to sockaddr
291
292 // struck sockaddr equivalent
293 type rawSockaddrHyperv struct {
294 Family uint16
295 Reserved uint16
296 VMID GUID
297 ServiceID GUID
298 }
299
300 // Utility function to build a struct sockaddr for syscalls.
301 func (a Addr) sockaddr(sa *rawSockaddrHyperv) (unsafe.Pointer, int32, error) {
302 sa.Family = hvsockAF
303 sa.Reserved = 0
304 for i := 0; i < len(sa.VMID); i++ {
305 sa.VMID[i] = a.VMID[i]
306 }
307 for i := 0; i < len(sa.ServiceID); i++ {
308 sa.ServiceID[i] = a.ServiceID[i]
309 }
310
311 return unsafe.Pointer(sa), int32(unsafe.Sizeof(*sa)), nil
312 }
313
314 // Help for read/write timeouts
315 type deadlineHandler struct {
316 setLock sync.Mutex
317 channel timeoutChan
318 channelLock sync.RWMutex
319 timer *time.Timer
320 timedout atomicBool
321 }
322
323 // The code below here is adjusted from:
324 // https://github.com/Microsoft/go-winio/blob/master/file.go
325 type atomicBool int32
326
327 func (b *atomicBool) isSet() bool { return atomic.LoadInt32((*int32)(b)) != 0 }
328 func (b *atomicBool) setFalse() { atomic.StoreInt32((*int32)(b), 0) }
329 func (b *atomicBool) setTrue() { atomic.StoreInt32((*int32)(b), 1) }
330 func (b *atomicBool) swap(new bool) bool {
331 var newInt int32
332 if new {
333 newInt = 1
334 }
335 return atomic.SwapInt32((*int32)(b), newInt) == 1
336 }
337
338 type timeoutError struct{}
339
340 func (e *timeoutError) Error() string { return "i/o timeout" }
341 func (e *timeoutError) Timeout() bool { return true }
342 func (e *timeoutError) Temporary() bool { return true }
343
344 type timeoutChan chan struct{}
345
346 var ioInitOnce sync.Once
347 var ioCompletionPort syscall.Handle
348
349 // ioResult contains the result of an asynchronous IO operation
350 type ioResult struct {
351 bytes uint32
352 err error
353 }
354
355 type ioOperation struct {
356 o syscall.Overlapped
357 ch chan ioResult
358 }
359
360 func initIo() {
361 h, err := createIoCompletionPort(syscall.InvalidHandle, 0, 0, 0xffffffff)
362 if err != nil {
363 panic(err)
364 }
365 ioCompletionPort = h
366 go ioCompletionProcessor(h)
367 }
368
369 func (v *hvsockConn) close() {
370 v.wgLock.Lock()
371 if !v.closing.swap(true) {
372 v.wgLock.Unlock()
373 // cancel all IO and wait for it to complete
374 cancelIoEx(v.fd, nil)
375 v.wg.Wait()
376 // at this point, no new IO can start
377 syscall.Close(v.fd)
378 v.fd = 0
379 } else {
380 v.wgLock.Unlock()
381 }
382 }
383
384 // prepareIo prepares for a new IO operation
385 func (v *hvsockConn) prepareIo() (*ioOperation, error) {
386 v.wgLock.RLock()
387 if v.closing.isSet() {
388 v.wgLock.RUnlock()
389 return nil, fmt.Errorf("HvSocket has already been closed")
390 }
391 v.wg.Add(1)
392 v.wgLock.RUnlock()
393 c := &ioOperation{}
394 c.ch = make(chan ioResult)
395 return c, nil
396 }
397
398 // ioCompletionProcessor processes completed async IOs forever
399 func ioCompletionProcessor(h syscall.Handle) {
400 // Set the timer resolution to 1. This fixes a performance regression in golang 1.6.
401 timeBeginPeriod(1)
402 for {
403 var bytes uint32
404 var key uintptr
405 var op *ioOperation
406 err := getQueuedCompletionStatus(h, &bytes, &key, &op, syscall.INFINITE)
407 if op == nil {
408 panic(err)
409 }
410 op.ch <- ioResult{bytes, err}
411 }
412 }
413
414 // asyncIo processes the return value from Recv or Send, blocking until
415 // the operation has actually completed.
416 func (v *hvsockConn) asyncIo(c *ioOperation, d *deadlineHandler, bytes uint32, err error) (int, error) {
417 if err != syscall.ERROR_IO_PENDING {
418 return int(bytes), err
419 }
420
421 if v.closing.isSet() {
422 cancelIoEx(v.fd, &c.o)
423 }
424
425 var timeout timeoutChan
426 if d != nil {
427 d.channelLock.Lock()
428 timeout = d.channel
429 d.channelLock.Unlock()
430 }
431
432 var r ioResult
433 select {
434 case r = <-c.ch:
435 err = r.err
436 if err == syscall.ERROR_OPERATION_ABORTED {
437 if v.closing.isSet() {
438 err = fmt.Errorf("HvSocket has already been closed")
439 }
440 }
441 case <-timeout:
442 cancelIoEx(v.fd, &c.o)
443 r = <-c.ch
444 err = r.err
445 if err == syscall.ERROR_OPERATION_ABORTED {
446 err = ErrTimeout
447 }
448 }
449
450 // runtime.KeepAlive is needed, as c is passed via native
451 // code to ioCompletionProcessor, c must remain alive
452 // until the channel read is complete.
453 runtime.KeepAlive(c)
454 return int(r.bytes), err
455 }
456
457 func (d *deadlineHandler) set(deadline time.Time) error {
458 d.setLock.Lock()
459 defer d.setLock.Unlock()
460
461 if d.timer != nil {
462 if !d.timer.Stop() {
463 <-d.channel
464 }
465 d.timer = nil
466 }
467 d.timedout.setFalse()
468
469 select {
470 case <-d.channel:
471 d.channelLock.Lock()
472 d.channel = make(chan struct{})
473 d.channelLock.Unlock()
474 default:
475 }
476
477 if deadline.IsZero() {
478 return nil
479 }
480
481 timeoutIO := func() {
482 d.timedout.setTrue()
483 close(d.channel)
484 }
485
486 now := time.Now()
487 duration := deadline.Sub(now)
488 if deadline.After(now) {
489 // Deadline is in the future, set a timer to wait
490 d.timer = time.AfterFunc(duration, timeoutIO)
491 } else {
492 // Deadline is in the past. Cancel all pending IO now.
493 timeoutIO()
494 }
495 return nil
496 }