/
flisten.go
90 lines (72 loc) · 2 KB
/
flisten.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
// Package flisten provides a type that manages a file-based unix domain socket.
// The construction funcs enable flexible usage, so abstraction of this type
// will likely require some redesign of how it is interacted with.
package flisten
import (
"context"
"errors"
"net"
"os"
"path/filepath"
"github.com/ActiveState/cli/internal/errs"
"github.com/ActiveState/cli/internal/ipc/sockpath"
)
type FListen struct {
spath *sockpath.SockPath
net.Listener
}
func New(ctx context.Context, spath *sockpath.SockPath, network string) (*FListen, error) {
sockpath := spath.String()
sockpathDir := filepath.Dir(sockpath)
_, err := os.Stat(sockpathDir)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
return nil, errs.Wrap(err, "Cannot verify ipc dir %q", sockpathDir)
}
if err = os.MkdirAll(sockpathDir, 0755); err != nil {
return nil, errs.Wrap(err, "Cannot make ipc dir %q", sockpathDir)
}
}
l, err := (&net.ListenConfig{}).Listen(ctx, network, sockpath)
if err != nil {
err = asInUseError(err)
return nil, errs.Wrap(err, "Cannot get listener for %q", sockpath)
}
f := FListen{
spath: spath,
Listener: l,
}
if os.Getenv("FLISTEN_SLOW") == "true" {
f.Listener = newListenSlow(l)
}
if err := os.Chmod(sockpath, 0700); err != nil {
_ = f.Close()
return nil, errs.Wrap(err, "Cannot set file mode for %q", sockpath)
}
return &f, nil
}
func NewWithCleanup(ctx context.Context, spath *sockpath.SockPath, network string) (*FListen, error) {
sockpath := spath.String()
if err := os.Remove(sockpath); err != nil {
return nil, errs.Wrap(err, "Cannot remove file %q", sockpath)
}
return New(ctx, spath, network)
}
type listenSlow struct {
net.Listener
debug bool
}
func newListenSlow(listener net.Listener) *listenSlow {
return &listenSlow{
Listener: listener,
debug: os.Getenv("FLISTEN_DEBUG") == "true",
}
}
func (l *listenSlow) Accept() (net.Conn, error) {
c, err := l.Listener.Accept()
if err != nil {
return nil, err
}
c = newSlowConn(c, l.debug)
return c, nil
}