wireguard-go/rwcancel/rwcancel.go

116 lines
2 KiB
Go
Raw Normal View History

2019-01-02 00:55:51 +00:00
/* SPDX-License-Identifier: MIT
2018-05-13 22:28:30 +00:00
*
2019-01-02 00:55:51 +00:00
* Copyright (C) 2017-2019 WireGuard LLC. All Rights Reserved.
2018-05-13 22:28:30 +00:00
*/
package rwcancel
import (
"errors"
"os"
"syscall"
2019-05-14 07:09:52 +00:00
"golang.org/x/sys/unix"
2018-05-13 22:28:30 +00:00
)
func max(a, b int) int {
if a > b {
return a
}
return b
}
type RWCancel struct {
fd int
closingReader *os.File
closingWriter *os.File
}
2018-05-13 22:28:30 +00:00
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
}
2018-05-24 13:29:16 +00:00
func RetryAfterError(err error) bool {
2018-05-13 22:28:30 +00:00
if pe, ok := err.(*os.PathError); ok {
2018-05-24 13:29:16 +00:00
err = pe.Err
}
if errno, ok := err.(syscall.Errno); ok {
switch errno {
case syscall.EAGAIN, syscall.EINTR:
2018-05-13 22:28:30 +00:00
return true
}
2018-05-24 13:29:16 +00:00
2018-05-13 22:28:30 +00:00
}
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)
2018-05-13 22:28:30 +00:00
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)
2018-05-13 22:28:30 +00:00
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)
2018-05-24 13:29:16 +00:00
if err == nil || !RetryAfterError(err) {
2018-05-13 22:28:30 +00:00
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)
2018-05-24 13:29:16 +00:00
if err == nil || !RetryAfterError(err) {
2018-05-13 22:28:30 +00:00
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
}