Debian Codegraph @

internal/openvpn/handler.go

raw
1 package openvpn
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "log/slog"
10 "regexp"
11 "strings"
12 "sync"
13 "time"
14
15 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/openvpn/connection"
16 )
17
18 var reMaskClientPassword = regexp.MustCompile(`CLIENT:ENV,password=(.*)\r?\n`)
19
20 const (
21 clientWorkerCount = 10
22 clientWorkerQueueSize = 32
23 )
24
25 // handlePassword enters the password on the OpenVPN management interface connection.
26 func (c *Client) handlePassword(ctx context.Context) error {
27 buf := make([]byte, 15)
28
29 err := c.conn.SetReadDeadline(time.Now().Add(1 * time.Second))
30 if err != nil {
31 return fmt.Errorf("set read deadline: %w", err)
32 }
33
34 _, err = io.ReadFull(c.conn, buf)
35 if err != nil {
36 return fmt.Errorf("error probe password: %w", err)
37 }
38
39 err = c.conn.SetReadDeadline(time.Time{})
40 if err != nil {
41 return fmt.Errorf("set read deadline: %w", err)
42 }
43
44 c.logger.LogAttrs(ctx, slog.LevelDebug, "password probe: "+string(buf))
45
46 switch {
47 case string(buf) == "ENTER PASSWORD:":
48 if c.conf.OpenVPN.Password == "" {
49 return errors.New("management password required")
50 }
51
52 if err = c.sendPassword(ctx); err != nil {
53 return err
54 }
55 case c.conf.OpenVPN.Password != "":
56 return errors.New("management password expected, but server does not ask for me")
57 default:
58 // In case there is no password, read the whole line
59 c.scanner.Scan()
60 }
61
62 return nil
63 }
64
65 // sendPassword enters the password on the OpenVPN management interface connection.
66 func (c *Client) sendPassword(ctx context.Context) error {
67 if err := c.rawCommand(ctx, c.conf.OpenVPN.Password.String(), "management-password"); err != nil {
68 return fmt.Errorf("error from password command: %w", err)
69 }
70
71 buf := make([]byte, 15)
72 if _, err := io.ReadFull(c.conn, buf); err != nil {
73 return fmt.Errorf("unable to read answer after sending password: %w", err)
74 }
75
76 if !strings.Contains("SUCCESS: password is correct", string(buf)) { //nolint:gocritic
77 return ErrInvalidPassword
78 }
79
80 // read the whole line
81 c.scanner.Scan()
82
83 return nil
84 }
85
86 // handleMessages handles all incoming messages and route messages to different channels.
87 func (c *Client) handleMessages(ctx context.Context, errCh chan<- error) {
88 // This handler is the sole producer and owns closing both channels.
89 defer close(c.commandResponseCh)
90 defer close(c.clientsCh)
91
92 var (
93 err error
94 buf bytes.Buffer
95 )
96
97 buf.Grow(4096)
98
99 for {
100 if err = c.readMessage(&buf); err != nil {
101 if errors.Is(err, io.EOF) {
102 c.logger.LogAttrs(ctx, slog.LevelWarn, "OpenVPN management interface connection terminated")
103
104 errCh <- nil
105
106 return
107 }
108
109 errCh <- fmt.Errorf("error reading message: %w", err)
110
111 return
112 }
113
114 if err = c.handleMessage(ctx, buf.String()); err != nil {
115 if ctxErr := ctx.Err(); ctxErr != nil && errors.Is(err, ctxErr) {
116 errCh <- nil
117
118 return
119 }
120
121 if c.closed.Load() == 1 && errors.Is(err, ErrConnectionTerminated) {
122 errCh <- nil
123
124 return
125 }
126
127 errCh <- err
128
129 return
130 }
131 }
132 }
133
134 //nolint:cyclop
135 func (c *Client) handleMessage(ctx context.Context, message string) error {
136 switch {
137 case strings.HasPrefix(message, ">"):
138 switch {
139 case strings.HasPrefix(message, ">CLIEN"):
140 return c.handleClientMessage(ctx, message)
141 case strings.HasPrefix(message, ">HOLD:"):
142 select {
143 case c.commandsCh <- "hold release":
144 case <-ctx.Done():
145 return fmt.Errorf("enqueue hold release: %w", ctx.Err())
146 case <-c.shutdownCh:
147 return ErrConnectionTerminated
148 }
149 case strings.HasPrefix(message, ">INFO:"):
150 // welcome message
151 if strings.HasPrefix(message, ">INFO:OpenVPN Management Interface Version") {
152 return nil
153 }
154
155 select {
156 case c.commandResponseCh <- message:
157 case <-ctx.Done():
158 return fmt.Errorf("dispatch info response: %w", ctx.Err())
159 case <-c.shutdownCh:
160 return ErrConnectionTerminated
161 }
162 default:
163 c.writeToPassThroughClient(message)
164 }
165
166 // SUCCESS: hold release succeeded
167 case len(message) >= 13 && message[9:13] == "hold":
168 c.logger.LogAttrs(ctx, slog.LevelInfo, "hold release succeeded")
169 default:
170 select {
171 case c.commandResponseCh <- message:
172 case <-ctx.Done():
173 return fmt.Errorf("dispatch command response: %w", ctx.Err())
174 case <-c.shutdownCh:
175 return ErrConnectionTerminated
176 case <-time.After(2 * time.Second):
177 c.logger.LogAttrs(ctx, slog.LevelWarn, "command response not accepted. Was there a timeout before? Dropping message", slog.String("message", message))
178 }
179 }
180
181 return nil
182 }
183
184 func (c *Client) handleClientMessage(ctx context.Context, message string) error {
185 if c.logger.Enabled(ctx, slog.LevelDebug) {
186 c.logger.LogAttrs(ctx, slog.LevelDebug, reMaskClientPassword.ReplaceAllLiteralString(message, "CLIENT:ENV,password=***\r\n"))
187 }
188
189 client, err := connection.NewClient(c.conf, message)
190 if err != nil {
191 return fmt.Errorf("error parsing client message: %w", err)
192 }
193
194 select {
195 case c.clientsCh <- client:
196 case <-ctx.Done():
197 return fmt.Errorf("enqueue client event: %w", ctx.Err())
198 case <-c.shutdownCh:
199 return ErrConnectionTerminated
200 }
201
202 return nil
203 }
204
205 // handleClients receives new messages from clientsCh and processes them.
206 func (c *Client) handleClients(ctx context.Context, errCh chan<- error) {
207 clientJobs := make([]chan connection.Client, clientWorkerCount)
208
209 var (
210 wg sync.WaitGroup
211 errOnce sync.Once
212 )
213
214 reportErr := func(err error) {
215 errOnce.Do(func() {
216 errCh <- err
217 })
218 }
219
220 for i := range clientJobs {
221 clientJobs[i] = make(chan connection.Client, clientWorkerQueueSize)
222
223 wg.Go(func() {
224 c.handleClientWorker(ctx, clientJobs[i], reportErr)
225 })
226 }
227
228 defer func() {
229 for _, clientJob := range clientJobs {
230 close(clientJob)
231 }
232
233 wg.Wait()
234 }()
235
236 for {
237 select {
238 case <-ctx.Done():
239 return // Error somewhere, terminate
240 case client, ok := <-c.clientsCh:
241 if !ok {
242 return
243 }
244
245 workerIndex := client.CID % uint64(len(clientJobs))
246
247 select {
248 case clientJobs[workerIndex] <- client:
249 case <-ctx.Done():
250 return
251 }
252 }
253 }
254 }
255
256 func (c *Client) handleClientWorker(ctx context.Context, clients <-chan connection.Client, reportErr func(error)) {
257 for {
258 select {
259 case <-ctx.Done():
260 return
261 case client, ok := <-clients:
262 if !ok {
263 return
264 }
265
266 if err := c.processClient(ctx, client); err != nil {
267 reportErr(err)
268
269 return
270 }
271 }
272 }
273 }
274
275 // handleCommands receive new command from commandsCh and send them to OpenVPN management interface.
276 func (c *Client) handleCommands(ctx context.Context, errCh chan<- error) {
277 var (
278 command string
279 ok bool
280 )
281
282 for {
283 select {
284 case <-ctx.Done():
285 return // Error somewhere, terminate
286 case <-c.shutdownCh:
287 return
288 case command, ok = <-c.commandsCh:
289 if !ok {
290 return
291 }
292
293 if err := c.rawCommand(ctx, command, managementCommandName(command)); err != nil {
294 if c.closed.Load() == 1 {
295 return
296 }
297
298 errCh <- err
299
300 return
301 }
302 }
303 }
304 }