-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathdatagram.go
213 lines (196 loc) · 4.82 KB
/
datagram.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
package main
import (
"bufio"
"crypto/tls"
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"github.com/goburrow/quic"
"github.com/goburrow/quic/transport"
)
type datagramCommand struct{}
func (datagramCommand) Name() string {
return "datagram"
}
func (datagramCommand) Desc() string {
return "send or receive datagram over QUIC."
}
func (datagramCommand) Run(args []string) error {
cmd := flag.NewFlagSet("datagram", flag.ExitOnError)
listenAddr := cmd.String("listen", "0.0.0.0:0", "listen on the given IP:port")
insecure := cmd.Bool("insecure", false, "skip verifying server certificate (client only)")
certFile := cmd.String("cert", "cert.pem", "TLS certificate path (server only)")
keyFile := cmd.String("key", "key.pem", "TLS certificate key path (server only)")
logLevel := cmd.Int("v", 2, "log verbose: 0=off 1=error 2=info 3=debug 4=trace")
data := cmd.String("data", "", "Datagram for sending (or from stdin if empty)")
cmd.Usage = func() {
fmt.Fprintln(cmd.Output(), "Usage: quiwi datagram [arguments] [url]")
cmd.PrintDefaults()
}
cmd.Parse(args)
addr := cmd.Arg(0)
config := newConfig()
config.Params.MaxIdleTimeout = 30 * time.Second
config.Params.MaxDatagramFramePayloadSize = 1024
// Disable streams
config.Params.InitialMaxStreamDataBidiLocal = 0
config.Params.InitialMaxStreamDataBidiRemote = 0
config.Params.InitialMaxStreamDataUni = 0
config.Params.InitialMaxStreamsBidi = 0
config.Params.InitialMaxStreamsUni = 0
sigCh := make(chan os.Signal, 2)
signal.Notify(sigCh, os.Interrupt, syscall.SIGQUIT)
if addr == "" {
// Server mode
if *certFile != "" {
cert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
if err != nil {
return err
}
config.TLS.Certificates = []tls.Certificate{cert}
}
server := quic.NewServer(config)
server.SetLogger(*logLevel, os.Stderr)
server.SetHandler(&datagramServerHandler{})
go func() {
<-sigCh
server.Close()
}()
return server.ListenAndServe(*listenAddr)
}
// Client mode
addrURL, err := parseURL(addr)
if err != nil {
return err
}
config.TLS.ServerName = addrURL.Hostname()
config.TLS.InsecureSkipVerify = *insecure
client := quic.NewClient(config)
client.SetLogger(*logLevel, os.Stderr)
clientHandler := &datagramClientHandler{
data: *data,
close: make(chan struct{}),
}
client.SetHandler(clientHandler)
if err := client.ListenAndServe(*listenAddr); err != nil {
return err
}
if err := client.Connect(canonicalAddr(addrURL)); err != nil {
return err
}
select {
case <-sigCh:
case <-clientHandler.close:
}
return client.Close()
}
type datagramClientHandler struct {
data string
close chan struct{}
}
func (s *datagramClientHandler) Serve(c *quic.Conn, events []transport.Event) {
for _, e := range events {
switch e.Type {
case transport.EventDatagramOpen:
s.handleDatagramOpen(c)
case transport.EventDatagramWritable:
err := s.handleDatagramWritable(c)
if err != nil {
c.CloseWithError(transport.ApplicationError, err.Error())
return
}
case transport.EventDatagramReadable:
err := s.handleDatagramReadable(c)
if err != nil {
c.CloseWithError(transport.ApplicationError, err.Error())
return
}
case transport.EventConnClosed:
close(s.close)
return
}
}
}
func (s *datagramClientHandler) handleDatagramOpen(c *quic.Conn) {
if len(s.data) == 0 {
return
}
// Read from stdin and send each line in a datagram.
go func(dgram *quic.Datagram) {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
b := scanner.Bytes()
if len(b) > 0 {
_, err := dgram.Write(b)
if err != nil {
return
}
}
}
}(c.Datagram())
}
func (s *datagramClientHandler) handleDatagramWritable(c *quic.Conn) error {
if len(s.data) > 0 {
_, err := c.DatagramWrite([]byte(s.data))
s.data = ""
if err != nil {
return err
}
}
return nil
}
func (s *datagramClientHandler) handleDatagramReadable(c *quic.Conn) error {
b := buffers.pop()
defer buffers.push(b)
for {
n, err := c.DatagramRead(b)
if err != nil {
return err
}
if n > 0 {
_, err := fmt.Fprintln(os.Stdout, "recv:", b[:n])
if err != nil {
return err
}
} else {
return nil
}
}
}
type datagramServerHandler struct{}
func (s *datagramServerHandler) Serve(c *quic.Conn, events []transport.Event) {
for _, e := range events {
switch e.Type {
case transport.EventDatagramReadable:
err := s.handleDatagramReadable(c)
if err != nil {
c.CloseWithError(transport.ApplicationError, err.Error())
return
}
case transport.EventConnClosed:
return
}
}
}
func (s *datagramServerHandler) handleDatagramReadable(c *quic.Conn) error {
// Echo back
b := buffers.pop()
defer buffers.push(b)
for {
n, err := c.DatagramRead(b)
if err != nil {
return err
}
if n > 0 {
n, err = c.DatagramWrite(b[:n])
if err != nil {
return err
}
} else {
return nil
}
}
}