Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
lima-vm
GitHub Repository: lima-vm/lima
Path: blob/master/pkg/bicopy/bicopy.go
2601 views
1
// SPDX-FileCopyrightText: Copyright The Lima Authors
2
// SPDX-License-Identifier: Apache-2.0
3
4
// From https://raw.githubusercontent.com/norouter/norouter/v0.6.5/pkg/agent/bicopy/bicopy.go
5
/*
6
Copyright (C) NoRouter authors.
7
8
Copyright (C) libnetwork authors.
9
10
Licensed under the Apache License, Version 2.0 (the "License");
11
you may not use this file except in compliance with the License.
12
You may obtain a copy of the License at
13
14
http://www.apache.org/licenses/LICENSE-2.0
15
16
Unless required by applicable law or agreed to in writing, software
17
distributed under the License is distributed on an "AS IS" BASIS,
18
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
See the License for the specific language governing permissions and
20
limitations under the License.
21
*/
22
23
package bicopy
24
25
import (
26
"io"
27
"sync"
28
29
"github.com/sirupsen/logrus"
30
)
31
32
// Bicopy is from https://github.com/rootless-containers/rootlesskit/blob/v0.10.1/pkg/port/builtin/parent/tcp/tcp.go#L73-L104
33
// (originally from libnetwork, Apache License 2.0).
34
func Bicopy(x, y io.ReadWriter, quit <-chan struct{}) {
35
type closeReader interface {
36
CloseRead() error
37
}
38
type closeWriter interface {
39
CloseWrite() error
40
}
41
var wg sync.WaitGroup
42
broker := func(to, from io.ReadWriter) {
43
if _, err := io.Copy(to, from); err != nil {
44
logrus.WithError(err).Debug("failed to call io.Copy")
45
}
46
if fromCR, ok := from.(closeReader); ok {
47
if err := fromCR.CloseRead(); err != nil {
48
logrus.WithError(err).Debug("failed to call CloseRead")
49
}
50
}
51
if toCW, ok := to.(closeWriter); ok {
52
if err := toCW.CloseWrite(); err != nil {
53
logrus.WithError(err).Debug("failed to call CloseWrite")
54
}
55
}
56
wg.Done()
57
}
58
59
wg.Add(2)
60
go broker(x, y)
61
go broker(y, x)
62
finish := make(chan struct{})
63
go func() {
64
wg.Wait()
65
close(finish)
66
}()
67
68
select {
69
case <-quit:
70
case <-finish:
71
}
72
if xCloser, ok := x.(io.Closer); ok {
73
if err := xCloser.Close(); err != nil {
74
logrus.WithError(err).Debug("failed to call xCloser.Close")
75
}
76
}
77
if yCloser, ok := y.(io.Closer); ok {
78
if err := yCloser.Close(); err != nil {
79
logrus.WithError(err).Debug("failed to call yCloser.Close")
80
}
81
}
82
<-finish
83
// TODO: return copied bytes
84
}
85
86