-
Notifications
You must be signed in to change notification settings - Fork 43
/
server.go
111 lines (96 loc) · 2.24 KB
/
server.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
package dap
import (
"io"
"net"
"strings"
"github.com/google/go-dap"
"github.com/yaklang/yaklang/common/log"
"github.com/yaklang/yaklang/common/utils"
)
type DAPServer struct {
listener net.Listener
session *DebugSession
config *DAPServerConfig
}
func (s *DAPServer) Start() {
go func() {
for {
conn, err := s.listener.Accept()
if err != nil {
select {
case <-s.config.stopped:
default:
if !strings.Contains(err.Error(), "use of closed network connection") {
log.Errorf("Error accepting client connection: %v", err)
}
s.config.triggerServerStop()
}
return
}
log.Infof("Accept connection from %v", conn.RemoteAddr())
go s.handleConnection(conn)
}
}()
}
func (s *DAPServer) Stop() {
if s.listener != nil {
s.listener.Close()
}
if s.session == nil {
return
}
s.session.Close()
}
func NewDAPServer(config *DAPServerConfig) *DAPServer {
log.Infof("Start DAP server at %s", config.listener.Addr())
if config.stopped == nil {
config.stopped = make(chan struct{})
}
server := &DAPServer{
listener: config.listener,
config: config,
}
return server
}
func StartDAPServer(ip string, port any) (*DAPServer, chan struct{}, error) {
host := utils.HostPort(ip, port)
listener, err := net.Listen("tcp", host)
if err != nil {
return nil, nil, err
}
stopChan := make(chan struct{})
config := &DAPServerConfig{
listener: listener,
stopped: stopChan,
}
server := NewDAPServer(config)
server.Start()
return server, stopChan, nil
}
func (s *DAPServer) handleConnection(conn net.Conn) {
defer conn.Close()
session := NewDebugSession(conn, s.config)
s.session = session
for {
request, err := dap.ReadProtocolMessage(session.rw.Reader)
if err != nil {
defer s.config.triggerServerStop()
if err == io.EOF {
log.Infof("No more data to read: %v", err)
break
}
if decodeErr, ok := err.(*dap.DecodeProtocolMessageFieldError); ok {
// Send an error response to the users if we were unable to process the message.
session.sendInternalErrorResponse(decodeErr.Seq, err.Error())
continue
} else {
log.Errorf("DAP error: %v", err)
break
}
}
session.handleRequest(request)
if _, ok := request.(*dap.DisconnectRequest); ok {
return
}
}
}