File: network_util.go

package info (click to toggle)
incus 6.0.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 24,428 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (63 lines) | stat: -rw-r--r-- 1,381 bytes parent folder | download | duplicates (5)
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
package endpoints

import (
	"bytes"
	"net"
	"regexp"

	"github.com/lxc/incus/v6/shared/logger"
)

type networkServerErrorLogWriter struct {
	proxies []net.IP
}

// Regex for the log we want to ignore.
var unwantedLogRegex = regexp.MustCompile(`^http: TLS handshake error from ([^\[:]+?|\[([^\]]+?)\]):[0-9]+: .+: connection reset by peer$`)

func (d networkServerErrorLogWriter) Write(p []byte) (int, error) {
	strippedLog := d.stripLog(p)
	if strippedLog == "" {
		return 0, nil
	}

	logger.Info(strippedLog)
	return len(p), nil
}

func (d networkServerErrorLogWriter) stripLog(p []byte) string {
	// Strip the beginning of the log until we reach "http:".
	for len(p) > 5 && string(p[0:5]) != "http:" {
		p = bytes.TrimLeftFunc(p, func(r rune) bool {
			return r != 'h'
		})
	}

	// Strip the newline from the end.
	p = bytes.TrimRightFunc(p, func(r rune) bool {
		return r == '\n'
	})

	// Get the source IP address.
	match := unwantedLogRegex.FindSubmatch(p)
	var sourceIP string
	if match != nil {
		if match[2] != nil {
			// Inner match omits parentheses of ipv6 address.
			sourceIP = string(match[2])
		} else if match[1] != nil {
			sourceIP = string(match[1])
		}
	}

	// Discard the log if the source is in our list of trusted proxies.
	if sourceIP != "" {
		for _, ip := range d.proxies {
			if ip.String() == sourceIP {
				return ""
			}
		}
	}

	return string(p)
}