summaryrefslogtreecommitdiffhomepage
path: root/rwcancel/rwcancel.go
blob: 1e3572a03dc3573be6528e0c926ff263a496ed72 (plain)
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
/* SPDX-License-Identifier: GPL-2.0
 *
 * Copyright (C) 2017-2018 WireGuard LLC. All Rights Reserved.
 */

package rwcancel

import (
	"errors"
	"golang.org/x/sys/unix"
	"os"
	"syscall"
)

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

type RWCancel struct {
	fd            int
	closingReader *os.File
	closingWriter *os.File
}

func NewRWCancel(fd int) (*RWCancel, error) {
	err := unix.SetNonblock(fd, true)
	if err != nil {
		return nil, err
	}
	rwcancel := RWCancel{fd: fd}

	rwcancel.closingReader, rwcancel.closingWriter, err = os.Pipe()
	if err != nil {
		return nil, err
	}

	return &rwcancel, nil
}

func RetryAfterError(err error) bool {
	if pe, ok := err.(*os.PathError); ok {
		err = pe.Err
	}
	if errno, ok := err.(syscall.Errno); ok {
		switch errno {
		case syscall.EAGAIN, syscall.EINTR:
			return true
		}

	}
	return false
}

func (rw *RWCancel) ReadyRead() bool {
	closeFd := int(rw.closingReader.Fd())
	fdset := fdSet{}
	fdset.set(rw.fd)
	fdset.set(closeFd)
	err := unixSelect(max(rw.fd, closeFd)+1, &fdset.fdset, nil, nil, nil)
	if err != nil {
		return false
	}
	if fdset.check(closeFd) {
		return false
	}
	return fdset.check(rw.fd)
}

func (rw *RWCancel) ReadyWrite() bool {
	closeFd := int(rw.closingReader.Fd())
	fdset := fdSet{}
	fdset.set(rw.fd)
	fdset.set(closeFd)
	err := unixSelect(max(rw.fd, closeFd)+1, nil, &fdset.fdset, nil, nil)
	if err != nil {
		return false
	}
	if fdset.check(closeFd) {
		return false
	}
	return fdset.check(rw.fd)
}

func (rw *RWCancel) Read(p []byte) (n int, err error) {
	for {
		n, err := unix.Read(rw.fd, p)
		if err == nil || !RetryAfterError(err) {
			return n, err
		}
		if !rw.ReadyRead() {
			return 0, errors.New("fd closed")
		}
	}
}

func (rw *RWCancel) Write(p []byte) (n int, err error) {
	for {
		n, err := unix.Write(rw.fd, p)
		if err == nil || !RetryAfterError(err) {
			return n, err
		}
		if !rw.ReadyWrite() {
			return 0, errors.New("fd closed")
		}
	}
}

func (rw *RWCancel) Cancel() (err error) {
	_, err = rw.closingWriter.Write([]byte{0})
	return
}