-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathrcvr_namedpipe.go
335 lines (287 loc) · 8.9 KB
/
rcvr_namedpipe.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
//go:build windows
// +build windows
package trace2receiver
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"net"
"os"
"sync"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/component/componentstatus"
"golang.org/x/sys/windows"
"github.com/git-ecosystem/trace2receiver/internal/go-winio"
)
type Rcvr_NamedPipe struct {
// These fields should be set in ctor()
Base *Rcvr_Base
NamedPipePath string
// Windows named pipe properties
listener net.Listener
}
// Start receiving connections from Trace2 clients.
//
// This is part of the `component.Component` interface.
func (rcvr *Rcvr_NamedPipe) Start(unused_ctx context.Context, host component.Host) error {
var err error
var listenQueueSize int = 5
var acceptPoolSize int = listenQueueSize * 2
err = rcvr.Base.Start(unused_ctx, host)
if err != nil {
return err
}
err = rcvr.openNamedPipeServer(listenQueueSize)
if err != nil {
componentstatus.ReportStatus(host, componentstatus.NewFatalErrorEvent(err))
return err
}
go rcvr.listenLoop(acceptPoolSize)
return nil
}
// Stop accepting new connections from Trace2 clients.
//
// This is part of the `component.Component` interface.
func (rcvr *Rcvr_NamedPipe) Shutdown(context.Context) error {
rcvr.listener.Close()
os.Remove(rcvr.NamedPipePath)
rcvr.Base.cancel()
return nil
}
func (rcvr *Rcvr_NamedPipe) makeSDDL() (sddl string, err error) {
adminSid, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid)
if err != nil {
rcvr.Base.Logger.Error(fmt.Sprintf("could not create adminSid: %v", err))
return "", err
}
systemSid, err := windows.CreateWellKnownSid(windows.WinLocalSystemSid)
if err != nil {
rcvr.Base.Logger.Error(fmt.Sprintf("could not create LocalSystemSid: %v", err))
return "", err
}
ownerSid, err := windows.CreateWellKnownSid(windows.WinCreatorOwnerSid)
if err != nil {
rcvr.Base.Logger.Error(fmt.Sprintf("could not create CreatorSid: %v", err))
return "", err
}
everyoneSid, err := windows.CreateWellKnownSid(windows.WinWorldSid)
if err != nil {
rcvr.Base.Logger.Error(fmt.Sprintf("could not create WorldSid: %v", err))
return "", err
}
access := []windows.EXPLICIT_ACCESS{
{
AccessPermissions: windows.GENERIC_ALL,
AccessMode: windows.GRANT_ACCESS,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_GROUP,
TrusteeValue: windows.TrusteeValueFromSID(adminSid),
},
},
{
AccessPermissions: windows.GENERIC_ALL,
AccessMode: windows.GRANT_ACCESS,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_GROUP,
TrusteeValue: windows.TrusteeValueFromSID(systemSid),
},
},
{
AccessPermissions: windows.GENERIC_ALL,
AccessMode: windows.GRANT_ACCESS,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_USER,
TrusteeValue: windows.TrusteeValueFromSID(ownerSid),
},
},
{
AccessPermissions: windows.GENERIC_WRITE | windows.GENERIC_READ,
AccessMode: windows.GRANT_ACCESS,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_GROUP,
TrusteeValue: windows.TrusteeValueFromSID(everyoneSid),
},
},
}
sd, err := windows.NewSecurityDescriptor()
if err != nil {
rcvr.Base.Logger.Error(fmt.Sprintf("could not create SD: %v", err))
return "", err
}
acl, err := windows.ACLFromEntries(access, nil)
if err != nil {
rcvr.Base.Logger.Error(fmt.Sprintf("could not create ACL: %v", err))
return "", err
}
err = sd.SetDACL(acl, true, false)
if err != nil {
rcvr.Base.Logger.Error(fmt.Sprintf("could not set ACL: %v", err))
return "", err
}
sddl = sd.String()
rcvr.Base.Logger.Debug(fmt.Sprintf("SDDL is: %v", sddl))
return sddl, nil
}
// Open the server-side of a named pipe.
func (rcvr *Rcvr_NamedPipe) openNamedPipeServer(listenQueueSize int) (err error) {
_ = os.Remove(rcvr.NamedPipePath)
sddl, err := rcvr.makeSDDL()
if err != nil {
rcvr.Base.Logger.Error(fmt.Sprintf("could not create security descriptor for named pipe: %v", err))
return err
}
c := winio.PipeConfig{
SDDL: sddl,
MessageMode: false,
InputBufferSize: 65536,
OutputBufferSize: 65536,
QueueSize: int32(listenQueueSize),
}
rcvr.listener, err = winio.ListenPipe(rcvr.NamedPipePath, &c)
if err != nil || rcvr.listener == nil {
rcvr.Base.Logger.Error(fmt.Sprintf("could not create named pipe: %v", err))
return err
}
rcvr.Base.Logger.Info(fmt.Sprintf("listening on '%s'", rcvr.NamedPipePath))
return nil
}
var workerIdMux sync.Mutex
var workerId uint64
func makeWorkerId() uint64 {
workerIdMux.Lock()
id := workerId
workerId++
workerIdMux.Unlock()
return id
}
// Listen for incoming connections from Trace2 clients.
// Dispatch each to a worker thread.
func (rcvr *Rcvr_NamedPipe) listenLoop(acceptPoolSize int) {
acceptWorkerDoneCh := make(chan bool, acceptPoolSize)
var nrFinished int
for acceptId := 0; acceptId < acceptPoolSize; acceptId++ {
go rcvr.acceptWorker(acceptId, acceptWorkerDoneCh)
}
// Watch for `context.cancelFunc` being called by another thread
// while we wait for our accept workers to finish.
for_loop:
for {
select {
case <-rcvr.Base.ctx.Done():
// Force close the socket so that current and
// future calls to `Accept()` will fail.
rcvr.listener.Close()
case <-acceptWorkerDoneCh:
nrFinished++
if nrFinished == acceptPoolSize {
break for_loop
}
}
}
//rcvr.Base.Logger.Debug(fmt.Sprintf("listenLoop: finished[%d]", nrFinished))
}
func (rcvr *Rcvr_NamedPipe) acceptWorker(acceptId int, doneCh chan bool) {
//rcvr.Base.Logger.Debug(fmt.Sprintf("acceptWorker[%d] starting", acceptId))
for {
//rcvr.Base.Logger.Debug(fmt.Sprintf("acceptWorker[%d] calling Accept()", acceptId))
conn, err := rcvr.listener.Accept()
//rcvr.Base.Logger.Debug(fmt.Sprintf("acceptWorker[%d] result '%v'", acceptId, err))
if errors.Is(err, net.ErrClosed) {
break
}
if err != nil {
// Perhaps the client hung up before
// we could service this connection.
rcvr.Base.Logger.Error(err.Error())
} else {
go rcvr.worker(conn, acceptId, makeWorkerId())
}
}
doneCh <- true
//rcvr.Base.Logger.Debug(fmt.Sprintf("acceptWorker[%d] finished", acceptId))
}
func (rcvr *Rcvr_NamedPipe) worker(conn net.Conn, acceptId int, workerId uint64) {
var haveError = false
var wg sync.WaitGroup
defer conn.Close()
//rcvr.Base.Logger.Debug(fmt.Sprintf("worker[%d,%d] starting", acceptId, workerId))
doneReading := make(chan bool, 1)
// Create a subordinate thread to watch for `context.cancelFunc`
// being called by another thread. We need to interrupt our
// (blocking) call to `ReadBytes()` in this worker and (maybe)
// let it emit partial results (if it can do so quickly).
//
// However, we don't want to leak this subordinate thread if this
// worker normally finishes reading all the data from the client
// Git command.
wg.Add(1)
go func() {
defer wg.Done()
select {
case <-rcvr.Base.ctx.Done():
// Force close the connection from the client to
// help keep the Git command from getting stuck.
// That is, let it get a clean write-error rather
// than blocking on a buffer that we'll never
// read. (It might not actually matter, but it
// doesn't hurt.)
//
// This will also cause the worker's `ReadBytes()`
// to return an error, so that the worker can
// terminate the loop.
conn.Close()
case <-doneReading:
}
}()
// We assume that a `worker` represents the server side of a connection
// from a single Git client. That is, all events that we receive over
// this connection are from the same process (and will therefore have
// the same Trace2 SID). That is, we don't have to maintain a SID to
// Dataset mapping.
tr2 := NewTrace2Dataset(rcvr.Base)
tr2.pii_gather(rcvr.Base.RcvrConfig)
var nrBytesRead int = 0
r := bufio.NewReader(conn)
for {
rawLine, err := r.ReadBytes('\n')
if err == io.EOF {
//if nrBytesRead == 0 {
// rcvr.Base.Logger.Debug(fmt.Sprintf("worker[%d,%d][dsid %06d] EOF after %d bytes",
// acceptId, workerId, tr2.datasetId, nrBytesRead))
//}
break
}
if errors.Is(err, net.ErrClosed) {
break
}
if err != nil {
rcvr.Base.Logger.Error(err.Error())
haveError = true
break
}
nrBytesRead += len(rawLine)
if processRawLine(rawLine, tr2, rcvr.Base.Logger,
rcvr.Base.RcvrConfig.AllowCommandControlVerbs) != nil {
haveError = true
break
}
}
// Tell the subordinate thread that we are finished reading from
// the client so it can go away now. This must not block (because
// the subordinate may already be gone (which is the case if the
// `context.cancelFunc` was called)).
doneReading <- true
conn.Close()
if !haveError {
tr2.exportTraces()
}
// Wait for our subordinate thread to exit
wg.Wait()
//rcvr.Base.Logger.Debug(fmt.Sprintf("worker[%d,%d] finished", acceptId, workerId))
}