Update golangci-lint

This commit is contained in:
9seconds
2022-08-08 15:54:38 +03:00
parent 6a19ded78e
commit 36dad5a2f6
70 changed files with 227 additions and 214 deletions
+11 -1
View File
@@ -9,4 +9,14 @@ format = "colored-line-number"
[linters]
enable-all = true
disable = ["thelper", "ireturn", "varnamelen", "gochecknoglobals", "gas", "goerr113", "exhaustivestruct", "containedctx"]
disable = [
"containedctx",
"exhaustivestruct",
"exhaustruct",
"gas",
"gochecknoglobals",
"goerr113",
"ireturn",
"thelper",
"varnamelen",
]
+1 -1
View File
@@ -2,7 +2,7 @@ ROOT_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
IMAGE_NAME := mtg
APP_NAME := $(IMAGE_NAME)
GOLANGCI_LINT_VERSION := v1.47.3
GOLANGCI_LINT_VERSION := v1.48.0
VERSION := $(shell git describe --exact-match HEAD 2>/dev/null || git describe --tags --always)
COMMON_BUILD_FLAGS := -trimpath -mod=readonly -ldflags="-extldflags '-static' -s -w -X 'main.version=$(VERSION)'"
+1 -1
View File
@@ -42,7 +42,7 @@ func NewStableBloomFilter(byteSize uint, errorRate float64) mtglib.AntiReplayCac
errorRate = DefaultStableBloomFilterErrorRate
}
sf := boom.NewDefaultStableBloomFilter(byteSize*8, errorRate) // nolint: gomnd
sf := boom.NewDefaultStableBloomFilter(byteSize*8, errorRate) //nolint: gomnd
sf.SetHash(xxhash.New64())
return &stableBloomFilter{
+22 -30
View File
@@ -21,31 +21,15 @@ const (
)
func getVersion() string {
goVersion, date, commit, modulesChecksum, dirty := getVersionData()
dirtySuffix := ""
if dirty {
dirtySuffix = " [dirty]"
}
return fmt.Sprintf("%s (%s: %s on %s%s, modules checksum %s)",
version,
goVersion,
date.Format(time.RFC3339),
commit,
dirtySuffix,
modulesChecksum)
}
func getVersionData() (goVersion string, date time.Time, commit string, modulesChecksum string, dirty bool) {
date = time.Now()
buildInfo, ok := debug.ReadBuildInfo()
if !ok {
return
return version
}
goVersion = buildInfo.GoVersion
date := time.Now()
commit := ""
goVersion := buildInfo.GoVersion
dirtySuffix := ""
for _, setting := range buildInfo.Settings {
switch setting.Key {
@@ -54,7 +38,9 @@ func getVersionData() (goVersion string, date time.Time, commit string, modulesC
case "vcs.revision":
commit = setting.Value
case "vcs.modified":
dirty, _ = strconv.ParseBool(setting.Value)
if dirty, _ := strconv.ParseBool(setting.Value); dirty {
dirtySuffix = " [dirty]"
}
}
}
@@ -62,40 +48,46 @@ func getVersionData() (goVersion string, date time.Time, commit string, modulesC
if _, err := io.WriteString(hasher, buildInfo.Path); err != nil {
panic(err)
}
binary.Write(hasher, binary.LittleEndian, uint64(1+len(buildInfo.Deps)))
binary.Write(hasher, binary.LittleEndian, uint64(1+len(buildInfo.Deps))) //nolint: errcheck
sort.Slice(buildInfo.Deps, func(i, j int) bool {
return buildInfo.Deps[i].Path > buildInfo.Deps[j].Path
})
buildInfoCheckSumModule(hasher, &buildInfo.Main)
for _, module := range buildInfo.Deps {
buildInfoCheckSumModule(hasher, module)
}
modulesChecksum = base64.StdEncoding.EncodeToString(hasher.Sum(nil))
return
return fmt.Sprintf("%s (%s: %s on %s%s, modules checksum %s)",
version,
goVersion,
date.Format(time.RFC3339),
commit,
dirtySuffix,
base64.StdEncoding.EncodeToString(hasher.Sum(nil)))
}
func buildInfoCheckSumModule(w io.Writer, module *debug.Module) {
w.Write([]byte{buildInfoModuleStart})
w.Write([]byte{buildInfoModuleStart}) //nolint: errcheck
if _, err := io.WriteString(w, module.Path); err != nil {
panic(err)
}
w.Write([]byte{buildInfoModuleDelimeter})
w.Write([]byte{buildInfoModuleDelimeter}) //nolint: errcheck
if _, err := io.WriteString(w, module.Version); err != nil {
panic(err)
}
w.Write([]byte{buildInfoModuleDelimeter})
w.Write([]byte{buildInfoModuleDelimeter}) //nolint: errcheck
if _, err := io.WriteString(w, module.Sum); err != nil {
panic(err)
}
w.Write([]byte{buildInfoModuleFinish})
w.Write([]byte{buildInfoModuleFinish}) //nolint: errcheck
}
+1 -1
View File
@@ -77,7 +77,7 @@ func NewEventStream(observerFactories []ObserverFactory) EventStream {
return rv
}
func eventStreamProcessor(ctx context.Context, eventChan <-chan mtglib.Event, observer Observer) { // nolint: cyclop
func eventStreamProcessor(ctx context.Context, eventChan <-chan mtglib.Event, observer Observer) { //nolint: cyclop
defer observer.Shutdown()
for {
+12 -12
View File
@@ -31,17 +31,17 @@ type accessResponse struct {
type accessResponseURLs struct {
IP net.IP `json:"ip"`
Port uint `json:"port"`
TgURL string `json:"tg_url"` // nolint: tagliatelle
TgQrCode string `json:"tg_qrcode"` // nolint: tagliatelle
TmeURL string `json:"tme_url"` // nolint: tagliatelle
TmeQrCode string `json:"tme_qrcode"` // nolint: tagliatelle
TgURL string `json:"tg_url"` //nolint: tagliatelle
TgQrCode string `json:"tg_qrcode"` //nolint: tagliatelle
TmeURL string `json:"tme_url"` //nolint: tagliatelle
TmeQrCode string `json:"tme_qrcode"` //nolint: tagliatelle
}
type Access struct {
ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"` // nolint: lll
PublicIPv4 net.IP `kong:"help='Public IPv4 address for proxy. By default it is resolved via remote website',name='ipv4',short='i'"` // nolint: lll
PublicIPv6 net.IP `kong:"help='Public IPv6 address for proxy. By default it is resolved via remote website',name='ipv6',short='I'"` // nolint: lll
Port uint `kong:"help='Port number. Default port is taken from configuration file, bind-to parameter',type:'uint',short='p'"` // nolint: lll
ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"` //nolint: lll
PublicIPv4 net.IP `kong:"help='Public IPv4 address for proxy. By default it is resolved via remote website',name='ipv4',short='i'"` //nolint: lll
PublicIPv6 net.IP `kong:"help='Public IPv6 address for proxy. By default it is resolved via remote website',name='ipv6',short='I'"` //nolint: lll
Port uint `kong:"help='Port number. Default port is taken from configuration file, bind-to parameter',type:'uint',short='p'"` //nolint: lll
Hex bool `kong:"help='Print secret in hex encoding.',short='x'"`
}
@@ -61,7 +61,7 @@ func (a *Access) Run(cli *CLI, version string) error {
}
wg := &sync.WaitGroup{}
wg.Add(2) // nolint: gomnd
wg.Add(2) //nolint: gomnd
go func() {
defer wg.Done()
@@ -108,10 +108,10 @@ func (a *Access) Run(cli *CLI, version string) error {
func (a *Access) getIP(ntw mtglib.Network, protocol string) net.IP {
client := ntw.MakeHTTPClient(func(ctx context.Context, network, address string) (essentials.Conn, error) {
return ntw.DialContext(ctx, protocol, address) // nolint: wrapcheck
return ntw.DialContext(ctx, protocol, address) //nolint: wrapcheck
})
req, err := http.NewRequest(http.MethodGet, "https://ifconfig.co", nil) // nolint: noctx
req, err := http.NewRequest(http.MethodGet, "https://ifconfig.co", nil) //nolint: noctx
if err != nil {
panic(err)
}
@@ -128,7 +128,7 @@ func (a *Access) getIP(ntw mtglib.Network, protocol string) net.IP {
}
defer func() {
io.Copy(io.Discard, resp.Body) // nolint: errcheck
io.Copy(io.Discard, resp.Body) //nolint: errcheck
resp.Body.Close()
}()
+2 -2
View File
@@ -15,9 +15,9 @@ func (g *GenerateSecret) Run(cli *CLI, _ string) error {
secret := mtglib.GenerateSecret(cli.GenerateSecret.HostName)
if g.Hex {
fmt.Println(secret.Hex()) // nolint: forbidigo
fmt.Println(secret.Hex()) //nolint: forbidigo
} else {
fmt.Println(secret.Base64()) // nolint: forbidigo
fmt.Println(secret.Base64()) //nolint: forbidigo
}
return nil
+1 -1
View File
@@ -7,7 +7,7 @@ import (
)
type Run struct {
ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"` // nolint: lll
ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"` //nolint: lll
}
func (r *Run) Run(cli *CLI, version string) error {
+13 -8
View File
@@ -49,7 +49,7 @@ func makeNetwork(conf *config.Config, version string) (mtglib.Network, error) {
}
if len(conf.Network.Proxies) == 0 {
return network.NewNetwork(baseDialer, userAgent, dohIP, httpTimeout) // nolint: wrapcheck
return network.NewNetwork(baseDialer, userAgent, dohIP, httpTimeout) //nolint: wrapcheck
}
proxyURLs := make([]*url.URL, 0, len(conf.Network.Proxies))
@@ -66,7 +66,7 @@ func makeNetwork(conf *config.Config, version string) (mtglib.Network, error) {
return nil, fmt.Errorf("cannot build socks5 dialer: %w", err)
}
return network.NewNetwork(socksDialer, userAgent, dohIP, httpTimeout) // nolint: wrapcheck
return network.NewNetwork(socksDialer, userAgent, dohIP, httpTimeout) //nolint: wrapcheck
}
socksDialer, err := network.NewLoadBalancedSocks5Dialer(baseDialer, proxyURLs)
@@ -74,7 +74,7 @@ func makeNetwork(conf *config.Config, version string) (mtglib.Network, error) {
return nil, fmt.Errorf("cannot build socks5 dialer: %w", err)
}
return network.NewNetwork(socksDialer, userAgent, dohIP, httpTimeout) // nolint: wrapcheck
return network.NewNetwork(socksDialer, userAgent, dohIP, httpTimeout) //nolint: wrapcheck
}
func makeAntiReplayCache(conf *config.Config) mtglib.AntiReplayCache {
@@ -127,7 +127,12 @@ func makeIPAllowlist(conf config.ListConfig,
logger mtglib.Logger,
ntw mtglib.Network,
updateCallback ipblocklist.FireholUpdateCallback,
) (allowlist mtglib.IPBlocklist, err error) {
) (mtglib.IPBlocklist, error) {
var (
allowlist mtglib.IPBlocklist
err error
)
if !conf.Enabled.Get(false) {
allowlist, err = ipblocklist.NewFireholFromFiles(
logger.Named("ipblocklist"),
@@ -159,7 +164,7 @@ func makeIPAllowlist(conf config.ListConfig,
}
func makeEventStream(conf *config.Config, logger mtglib.Logger) (mtglib.EventStream, error) {
factories := make([]events.ObserverFactory, 0, 2) // nolint: gomnd
factories := make([]events.ObserverFactory, 0, 2) //nolint: gomnd
if conf.Stats.StatsD.Enabled.Get(false) {
statsdFactory, err := stats.NewStatsd(
@@ -185,7 +190,7 @@ func makeEventStream(conf *config.Config, logger mtglib.Logger) (mtglib.EventStr
return nil, fmt.Errorf("cannot start a listener for prometheus: %w", err)
}
go prometheus.Serve(listener) // nolint: errcheck
go prometheus.Serve(listener) //nolint: errcheck
factories = append(factories, prometheus.Make)
}
@@ -197,7 +202,7 @@ func makeEventStream(conf *config.Config, logger mtglib.Logger) (mtglib.EventStr
return events.NewNoopStream(), nil
}
func runProxy(conf *config.Config, version string) error { // nolint: funlen
func runProxy(conf *config.Config, version string) error { //nolint: funlen
logger := makeLogger(conf)
logger.BindJSON("configuration", conf.String()).Debug("configuration")
@@ -263,7 +268,7 @@ func runProxy(conf *config.Config, version string) error { // nolint: funlen
ctx := utils.RootContext()
go proxy.Serve(listener) // nolint: errcheck
go proxy.Serve(listener) //nolint: errcheck
<-ctx.Done()
listener.Close()
+11 -11
View File
@@ -13,17 +13,17 @@ type SimpleRun struct {
BindTo string `kong:"arg,required,name='bind-to',help='A host:port to bind proxy to.'"`
Secret string `kong:"arg,required,name='secret',help='Proxy secret.'"`
Debug bool `kong:"name='debug',short='d',help='Run in debug mode.'"` // nolint: lll
Concurrency uint64 `kong:"name='concurrency',short='c',default='8192',help='Max number of concurrent connection to proxy.'"` // nolint: lll
TCPBuffer string `kong:"name='tcp-buffer',short='b',default='4KB',help='Deprecated and ignored'"` // nolint: lll
PreferIP string `kong:"name='prefer-ip',short='i',default='prefer-ipv6',help='IP preference. By default we prefer IPv6 with fallback to IPv4.'"` // nolint: lll
DomainFrontingPort uint64 `kong:"name='domain-fronting-port',short='p',default='443',help='A port to access for domain fronting.'"` // nolint: lll
DOHIP net.IP `kong:"name='doh-ip',short='n',default='9.9.9.9',help='IP address of DNS-over-HTTP to use.'"` // nolint: lll
Timeout time.Duration `kong:"name='timeout',short='t',default='10s',help='Network timeout to use'"` // nolint: lll
AntiReplayCacheSize string `kong:"name='antireplay-cache-size',short='a',default='1MB',help='A size of anti-replay cache to use.'"` // nolint: lll
Debug bool `kong:"name='debug',short='d',help='Run in debug mode.'"` //nolint: lll
Concurrency uint64 `kong:"name='concurrency',short='c',default='8192',help='Max number of concurrent connection to proxy.'"` //nolint: lll
TCPBuffer string `kong:"name='tcp-buffer',short='b',default='4KB',help='Deprecated and ignored'"` //nolint: lll
PreferIP string `kong:"name='prefer-ip',short='i',default='prefer-ipv6',help='IP preference. By default we prefer IPv6 with fallback to IPv4.'"` //nolint: lll
DomainFrontingPort uint64 `kong:"name='domain-fronting-port',short='p',default='443',help='A port to access for domain fronting.'"` //nolint: lll
DOHIP net.IP `kong:"name='doh-ip',short='n',default='9.9.9.9',help='IP address of DNS-over-HTTP to use.'"` //nolint: lll
Timeout time.Duration `kong:"name='timeout',short='t',default='10s',help='Network timeout to use'"` //nolint: lll
AntiReplayCacheSize string `kong:"name='antireplay-cache-size',short='a',default='1MB',help='A size of anti-replay cache to use.'"` //nolint: lll
}
func (s *SimpleRun) Run(cli *CLI, version string) error { // nolint: cyclop
func (s *SimpleRun) Run(cli *CLI, version string) error { //nolint: cyclop
conf := &config.Config{}
if err := conf.BindTo.Set(s.BindTo); err != nil {
@@ -34,7 +34,7 @@ func (s *SimpleRun) Run(cli *CLI, version string) error { // nolint: cyclop
return fmt.Errorf("incorrect secret: %w", err)
}
if err := conf.Concurrency.Set(strconv.FormatUint(s.Concurrency, 10)); err != nil { // nolint: gomnd
if err := conf.Concurrency.Set(strconv.FormatUint(s.Concurrency, 10)); err != nil { //nolint: gomnd
return fmt.Errorf("incorrect concurrency: %w", err)
}
@@ -42,7 +42,7 @@ func (s *SimpleRun) Run(cli *CLI, version string) error { // nolint: cyclop
return fmt.Errorf("incorrect prefer-ip: %w", err)
}
if err := conf.DomainFrontingPort.Set(strconv.FormatUint(s.DomainFrontingPort, 10)); err != nil { // nolint: gomnd
if err := conf.DomainFrontingPort.Set(strconv.FormatUint(s.DomainFrontingPort, 10)); err != nil { //nolint: gomnd
return fmt.Errorf("incorrect domain-fronting-port: %w", err)
}
+2 -2
View File
@@ -10,7 +10,7 @@ type TypeConcurrency struct {
}
func (t *TypeConcurrency) Set(value string) error {
concurrencyValue, err := strconv.ParseUint(value, 10, 16) // nolint: gomnd
concurrencyValue, err := strconv.ParseUint(value, 10, 16) //nolint: gomnd
if err != nil {
return fmt.Errorf("value is not uint (%s): %w", value, err)
}
@@ -41,5 +41,5 @@ func (t TypeConcurrency) MarshalJSON() ([]byte, error) {
}
func (t TypeConcurrency) String() string {
return strconv.FormatUint(uint64(t.Value), 10) // nolint: gomnd
return strconv.FormatUint(uint64(t.Value), 10) //nolint: gomnd
}
+2 -2
View File
@@ -12,7 +12,7 @@ type TypeErrorRate struct {
}
func (t *TypeErrorRate) Set(value string) error {
parsedValue, err := strconv.ParseFloat(value, 64) // nolint: gomnd
parsedValue, err := strconv.ParseFloat(value, 64) //nolint: gomnd
if err != nil {
return fmt.Errorf("value is not a float (%s): %w", value, err)
}
@@ -43,5 +43,5 @@ func (t TypeErrorRate) MarshalJSON() ([]byte, error) {
}
func (t TypeErrorRate) String() string {
return strconv.FormatFloat(t.Value, 'f', -1, 64) // nolint: gomnd
return strconv.FormatFloat(t.Value, 'f', -1, 64) //nolint: gomnd
}
+1 -1
View File
@@ -18,7 +18,7 @@ func (t *TypeHostPort) Set(value string) error {
return fmt.Errorf("incorrect host:port value (%v): %w", value, err)
}
portValue, err := strconv.ParseUint(port, 10, 16) // nolint: gomnd
portValue, err := strconv.ParseUint(port, 10, 16) //nolint: gomnd
if err != nil {
return fmt.Errorf("incorrect port number (%v): %w", value, err)
}
+1 -1
View File
@@ -10,7 +10,7 @@ type TypePort struct {
}
func (t *TypePort) Set(value string) error {
portValue, err := strconv.ParseUint(value, 10, 16) // nolint: gomnd
portValue, err := strconv.ParseUint(value, 10, 16) //nolint: gomnd
if err != nil {
return fmt.Errorf("incorrect port number (%v): %w", value, err)
}
+1 -1
View File
@@ -27,7 +27,7 @@ func captureOutput(filefp **os.File, callback func()) string {
closeChan := make(chan bool)
go func() {
io.Copy(buf, reader) // nolint: errcheck
io.Copy(buf, reader) //nolint: errcheck
close(closeChan)
}()
+3 -3
View File
@@ -15,17 +15,17 @@ type MtglibNetworkMock struct {
func (m *MtglibNetworkMock) Dial(network, address string) (essentials.Conn, error) {
args := m.Called(network, address)
return args.Get(0).(essentials.Conn), args.Error(1) // nolint: wrapcheck, forcetypeassert
return args.Get(0).(essentials.Conn), args.Error(1) //nolint: wrapcheck, forcetypeassert
}
func (m *MtglibNetworkMock) DialContext(ctx context.Context, network, address string) (essentials.Conn, error) {
args := m.Called(ctx, network, address)
return args.Get(0).(essentials.Conn), args.Error(1) // nolint: wrapcheck, forcetypeassert
return args.Get(0).(essentials.Conn), args.Error(1) //nolint: wrapcheck, forcetypeassert
}
func (m *MtglibNetworkMock) MakeHTTPClient(dialFunc func(ctx context.Context,
network, address string) (essentials.Conn, error),
) *http.Client {
return m.Called(dialFunc).Get(0).(*http.Client) // nolint: forcetypeassert
return m.Called(dialFunc).Get(0).(*http.Client) //nolint: forcetypeassert
}
+8 -8
View File
@@ -24,33 +24,33 @@ func (n *EssentialsConnMock) Write(b []byte) (int, error) {
}
func (n *EssentialsConnMock) Close() error {
return n.Called().Error(0) // nolint: wrapcheck
return n.Called().Error(0) //nolint: wrapcheck
}
func (n *EssentialsConnMock) CloseRead() error {
return n.Called().Error(0) // nolint: wrapcheck
return n.Called().Error(0) //nolint: wrapcheck
}
func (n *EssentialsConnMock) CloseWrite() error {
return n.Called().Error(0) // nolint: wrapcheck
return n.Called().Error(0) //nolint: wrapcheck
}
func (n *EssentialsConnMock) LocalAddr() net.Addr {
return n.Called().Get(0).(net.Addr) // nolint: forcetypeassert
return n.Called().Get(0).(net.Addr) //nolint: forcetypeassert
}
func (n *EssentialsConnMock) RemoteAddr() net.Addr {
return n.Called().Get(0).(net.Addr) // nolint: forcetypeassert
return n.Called().Get(0).(net.Addr) //nolint: forcetypeassert
}
func (n *EssentialsConnMock) SetDeadline(t time.Time) error {
return n.Called(t).Error(0) // nolint: wrapcheck
return n.Called(t).Error(0) //nolint: wrapcheck
}
func (n *EssentialsConnMock) SetReadDeadline(t time.Time) error {
return n.Called(t).Error(0) // nolint: wrapcheck
return n.Called(t).Error(0) //nolint: wrapcheck
}
func (n *EssentialsConnMock) SetWriteDeadline(t time.Time) error {
return n.Called(t).Error(0) // nolint: wrapcheck
return n.Called(t).Error(0) //nolint: wrapcheck
}
+1 -1
View File
@@ -14,7 +14,7 @@ type Listener struct {
func (l Listener) Accept() (net.Conn, error) {
conn, err := l.Listener.Accept()
if err != nil {
return nil, err // nolint: wrapcheck
return nil, err //nolint: wrapcheck
}
if err := network.SetClientSocketOptions(conn, 0); err != nil {
+8
View File
@@ -0,0 +1,8 @@
// files defines a set of abstraction for 'files': an openable entities that
// could be read after.
//
// This is not a file on a filesystem of your local machine, it also can
// include "in memory" files or even remote ones, like HTTP endpoints. If you
// make a GET request to HTTP endpoint, then a body is readable and you can
// consider it as an openable file.
package files
+1 -1
View File
@@ -22,7 +22,7 @@ func (h httpFile) Open(ctx context.Context) (io.ReadCloser, error) {
response, err := h.http.Do(request)
if err != nil {
if response != nil {
io.Copy(io.Discard, response.Body) // nolint: errcheck
io.Copy(io.Discard, response.Body) //nolint: errcheck
response.Body.Close()
}
+1 -1
View File
@@ -22,7 +22,7 @@ type HTTPTestSuite struct {
}
func (suite *HTTPTestSuite) makeFile(path string) (files.File, error) {
return files.NewHTTP(suite.httpClient, suite.httpServer.URL+"/"+path) // nolint: wrapcheck
return files.NewHTTP(suite.httpClient, suite.httpServer.URL+"/"+path) //nolint: wrapcheck
}
func (suite *HTTPTestSuite) SetupSuite() {
+1 -1
View File
@@ -12,7 +12,7 @@ type localFile struct {
}
func (l localFile) Open(ctx context.Context) (io.ReadCloser, error) {
return os.Open(l.path) // nolint: wrapcheck
return os.Open(l.path) //nolint: wrapcheck
}
func (l localFile) String() string {
+2 -2
View File
@@ -19,8 +19,8 @@ import (
var (
fireholRegexpComment = regexp.MustCompile(`\s*#.*?$`)
fireholIPv4DefaultCIDR = net.CIDRMask(32, 32) // nolint: gomnd
fireholIPv6DefaultCIDR = net.CIDRMask(128, 128) // nolint: gomnd
fireholIPv4DefaultCIDR = net.CIDRMask(32, 32) //nolint: gomnd
fireholIPv6DefaultCIDR = net.CIDRMask(128, 128) //nolint: gomnd
)
// FireholUpdateCallback defines a signature of the callback that has to be
+1 -1
View File
@@ -37,7 +37,7 @@ func (suite *FireholTestSuite) SetupSuite() {
defer filefp.Close()
io.Copy(w, filefp) // nolint: errcheck
io.Copy(w, filefp) //nolint: errcheck
})
suite.httpServer = httptest.NewServer(mux)
+1 -1
View File
@@ -116,6 +116,6 @@ func (suite *ZeroLoggerTestSuite) TestIndependence() {
suite.NotContains("lalala", log12Output)
}
func TestZeroLogger(t *testing.T) { // nolint: paralleltest
func TestZeroLogger(t *testing.T) { //nolint: paralleltest
suite.Run(t, &ZeroLoggerTestSuite{})
}
+3 -3
View File
@@ -24,7 +24,7 @@ func (c connTraffic) Read(b []byte) (int, error) {
c.stream.Send(c.ctx, NewEventTraffic(c.streamID, uint(n), true))
}
return n, err // nolint: wrapcheck
return n, err //nolint: wrapcheck
}
func (c connTraffic) Write(b []byte) (int, error) {
@@ -34,7 +34,7 @@ func (c connTraffic) Write(b []byte) (int, error) {
c.stream.Send(c.ctx, NewEventTraffic(c.streamID, uint(n), false))
}
return n, err // nolint: wrapcheck
return n, err //nolint: wrapcheck
}
type connRewind struct {
@@ -49,7 +49,7 @@ func (c *connRewind) Read(p []byte) (int, error) {
c.mutex.RLock()
defer c.mutex.RUnlock()
return c.active.Read(p) // nolint: wrapcheck
return c.active.Read(p) //nolint: wrapcheck
}
func (c *connRewind) Rewind() {
+3 -3
View File
@@ -22,7 +22,7 @@ type ConnRewindBaseConn struct {
func (c *ConnRewindBaseConn) Read(p []byte) (int, error) {
c.Called(p)
return c.readBuffer.Read(p) // nolint: wrapcheck
return c.readBuffer.Read(p) //nolint: wrapcheck
}
type ConnTrafficTestSuite struct {
@@ -69,7 +69,7 @@ func (suite *ConnTrafficTestSuite) TestReadOk() {
suite.Equal(10, n)
}
func (suite *ConnTrafficTestSuite) TestReadErr() { // nolint: dupl
func (suite *ConnTrafficTestSuite) TestReadErr() { //nolint: dupl
suite.eventStreamMock.
On("Send", mock.Anything, mock.Anything).
Once().
@@ -125,7 +125,7 @@ func (suite *ConnTrafficTestSuite) TestWriteOk() {
suite.Equal(10, n)
}
func (suite *ConnTrafficTestSuite) TestWriteErr() { // nolint: dupl
func (suite *ConnTrafficTestSuite) TestWriteErr() { //nolint: dupl
suite.eventStreamMock.
On("Send", mock.Anything, mock.Anything).
Once().
+3 -3
View File
@@ -110,9 +110,9 @@ const (
// This knowledge is encapsulated into instances of such interface.
//
// mtglib uses Network for:
// 1. Dialing to Telegram
// 2. Dialing to front domain
// 3. Doing HTTP requests (for example, for FireHOL ipblocklist).
// 1. Dialing to Telegram
// 2. Dialing to front domain
// 3. Doing HTTP requests (for example, for FireHOL ipblocklist).
type Network interface {
// Dial establishes context-free TCP connections.
Dial(network, address string) (essentials.Conn, error)
+3 -3
View File
@@ -56,7 +56,7 @@ func ParseClientHello(secret, handshake []byte) (ClientHello, error) {
if len(handshake)-4 != int(handshakeLength) {
return hello,
fmt.Errorf("incorrect handshake size. manifested=%d, real=%d",
handshakeLength, len(handshake)-4) // nolint: gomnd
handshakeLength, len(handshake)-4) //nolint: gomnd
}
copy(hello.Random[:], handshake[ClientHelloRandomOffset:])
@@ -72,7 +72,7 @@ func ParseClientHello(secret, handshake []byte) (ClientHello, error) {
// mac is calculated for the whole record, not only
// for the payload part
mac := hmac.New(sha256.New, secret)
rec.Dump(mac) // nolint: errcheck
rec.Dump(mac) //nolint: errcheck
computedRandom := mac.Sum(nil)
@@ -100,7 +100,7 @@ func parseSessionID(hello *ClientHello, handshake []byte) {
}
func parseCipherSuite(hello *ClientHello, handshake []byte) {
cipherSuiteOffset := ClientHelloSessionIDOffset + len(hello.SessionID) + 3 // nolint: gomnd
cipherSuiteOffset := ClientHelloSessionIDOffset + len(hello.SessionID) + 3 //nolint: gomnd
hello.CipherSuite = binary.BigEndian.Uint16(handshake[cipherSuiteOffset : cipherSuiteOffset+2])
}
+6 -6
View File
@@ -25,14 +25,14 @@ func (c *Conn) Read(p []byte) (int, error) {
for {
if err := rec.Read(c.Conn); err != nil {
return 0, err // nolint: wrapcheck
return 0, err //nolint: wrapcheck
}
switch rec.Type { // nolint: exhaustive
switch rec.Type { //nolint: exhaustive
case record.TypeApplicationData:
rec.Payload.WriteTo(&c.readBuffer) // nolint: errcheck
rec.Payload.WriteTo(&c.readBuffer) //nolint: errcheck
return c.readBuffer.Read(p) // nolint: wrapcheck
return c.readBuffer.Read(p) //nolint: wrapcheck
case record.TypeChangeCipherSpec:
default:
return 0, fmt.Errorf("unsupported record type %v", rec.Type)
@@ -60,13 +60,13 @@ func (c *Conn) Write(p []byte) (int, error) {
rec.Payload.Reset()
rec.Payload.Write(p[:chunkSize])
rec.Dump(sendBuffer) // nolint: errcheck
rec.Dump(sendBuffer) //nolint: errcheck
p = p[chunkSize:]
}
if _, err := c.Conn.Write(sendBuffer.Bytes()); err != nil {
return 0, err // nolint: wrapcheck
return 0, err //nolint: wrapcheck
}
return lenP, nil
+7 -7
View File
@@ -24,13 +24,13 @@ type ConnMock struct {
func (m *ConnMock) Read(p []byte) (int, error) {
m.Called(p)
return m.readBuffer.Read(p) // nolint: wrapcheck
return m.readBuffer.Read(p) //nolint: wrapcheck
}
func (m *ConnMock) Write(p []byte) (int, error) {
m.Called(p)
return m.writeBuffer.Write(p) // nolint: wrapcheck
return m.writeBuffer.Write(p) //nolint: wrapcheck
}
type ConnTestSuite struct {
@@ -61,14 +61,14 @@ func (suite *ConnTestSuite) TestRead() {
rec.Version = record.Version12
rec.Payload.WriteByte(0x01)
rec.Dump(&suite.connMock.readBuffer) // nolint: errcheck
rec.Dump(&suite.connMock.readBuffer) //nolint: errcheck
rec.Reset()
rec.Type = record.TypeApplicationData
rec.Version = record.Version12
rec.Payload.Write([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
rec.Dump(&suite.connMock.readBuffer) // nolint: errcheck
rec.Dump(&suite.connMock.readBuffer) //nolint: errcheck
resultBuffer := &bytes.Buffer{}
buf := make([]byte, 2)
@@ -95,14 +95,14 @@ func (suite *ConnTestSuite) TestReadUnexpected() {
rec.Version = record.Version12
rec.Payload.WriteByte(0x01)
rec.Dump(&suite.connMock.readBuffer) // nolint: errcheck
rec.Dump(&suite.connMock.readBuffer) //nolint: errcheck
rec.Reset()
rec.Type = record.TypeHandshake
rec.Version = record.Version12
rec.Payload.Write([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
rec.Dump(&suite.connMock.readBuffer) // nolint: errcheck
rec.Dump(&suite.connMock.readBuffer) //nolint: errcheck
buf := make([]byte, 2)
@@ -141,7 +141,7 @@ func (suite *ConnTestSuite) TestWrite() {
suite.Equal(record.TypeApplicationData, rec.Type)
suite.Equal(record.Version12, rec.Version)
rec.Payload.WriteTo(buf) // nolint: errcheck
rec.Payload.WriteTo(buf) //nolint: errcheck
}
suite.Equal(dataToRec, buf.Bytes())
+1 -1
View File
@@ -12,7 +12,7 @@ var bytesBufferPool = sync.Pool{
}
func acquireBytesBuffer() *bytes.Buffer {
return bytesBufferPool.Get().(*bytes.Buffer) // nolint: forcetypeassert
return bytesBufferPool.Get().(*bytes.Buffer) //nolint: forcetypeassert
}
func releaseBytesBuffer(b *bytes.Buffer) {
+1 -1
View File
@@ -11,7 +11,7 @@ var recordPool = sync.Pool{
}
func AcquireRecord() *Record {
return recordPool.Get().(*Record) // nolint: forcetypeassert
return recordPool.Get().(*Record) //nolint: forcetypeassert
}
func ReleaseRecord(r *Record) {
+7 -7
View File
@@ -23,24 +23,24 @@ func SendWelcomePacket(writer io.Writer, secret []byte, clientHello ClientHello)
rec.Version = record.Version12
generateServerHello(&rec.Payload, clientHello)
rec.Dump(buf) // nolint: errcheck
rec.Dump(buf) //nolint: errcheck
rec.Reset()
rec.Type = record.TypeChangeCipherSpec
rec.Version = record.Version12
rec.Payload.WriteByte(ChangeCipherValue)
rec.Dump(buf) // nolint: errcheck
rec.Dump(buf) //nolint: errcheck
rec.Reset()
rec.Type = record.TypeApplicationData
rec.Version = record.Version12
if _, err := io.CopyN(&rec.Payload, rand.Reader, int64(1024+mrand.Intn(3092))); err != nil { // nolint: gomnd
if _, err := io.CopyN(&rec.Payload, rand.Reader, int64(1024+mrand.Intn(3092))); err != nil { //nolint: gomnd
panic(err)
}
rec.Dump(buf) // nolint: errcheck
rec.Dump(buf) //nolint: errcheck
packet := buf.Bytes()
mac := hmac.New(sha256.New, secret)
@@ -51,7 +51,7 @@ func SendWelcomePacket(writer io.Writer, secret []byte, clientHello ClientHello)
copy(packet[WelcomePacketRandomOffset:], mac.Sum(nil))
if _, err := writer.Write(packet); err != nil {
return err // nolint: wrapcheck
return err //nolint: wrapcheck
}
return nil
@@ -87,6 +87,6 @@ func generateServerHello(writer io.Writer, clientHello ClientHello) {
binary.BigEndian.PutUint32(header[:], uint32(bodyBuf.Len()))
header[0] = HandshakeTypeServer
writer.Write(header[:]) // nolint: errcheck
bodyBuf.WriteTo(writer) // nolint: errcheck
writer.Write(header[:]) //nolint: errcheck
bodyBuf.WriteTo(writer) //nolint: errcheck
}
@@ -22,7 +22,7 @@ func (suite *ClientHandshakeTestSuite) SetupSuite() {
func (suite *ClientHandshakeTestSuite) TestCannotRead() {
buf := bytes.NewBuffer([]byte{1, 2, 3})
_, _, _, err := obfuscated2.ClientHandshake([]byte{1, 2, 3}, buf) // nolint: dogsled
_, _, _, err := obfuscated2.ClientHandshake([]byte{1, 2, 3}, buf) //nolint: dogsled
suite.Error(err)
}
+2 -2
View File
@@ -16,7 +16,7 @@ type Conn struct {
func (c Conn) Read(p []byte) (int, error) {
n, err := c.Conn.Read(p)
if err != nil {
return n, err // nolint: wrapcheck
return n, err //nolint: wrapcheck
}
c.Decryptor.XORKeyStream(p, p[:n])
@@ -33,5 +33,5 @@ func (c Conn) Write(p []byte) (int, error) {
payload := buf.Bytes()
c.Encryptor.XORKeyStream(payload, payload)
return c.Conn.Write(payload) // nolint: wrapcheck
return c.Conn.Write(payload) //nolint: wrapcheck
}
@@ -23,20 +23,20 @@ var handshakeConnectionType = []byte{0xdd, 0xdd, 0xdd, 0xdd}
// A structure of obfuscated2 handshake frame is following:
//
// [frameOffsetFirst:frameOffsetKey:frameOffsetIV:frameOffsetMagic:frameOffsetDC:frameOffsetEnd].
// [frameOffsetFirst:frameOffsetKey:frameOffsetIV:frameOffsetMagic:frameOffsetDC:frameOffsetEnd].
//
// - 8 bytes of noise
// - 32 bytes of AES Key
// - 16 bytes of AES IV
// - 4 bytes of 'connection type' - this has some setting like a connection type
// - 2 bytes of 'DC'. DC is little endian int16
// - 2 bytes of noise
// - 8 bytes of noise
// - 32 bytes of AES Key
// - 16 bytes of AES IV
// - 4 bytes of 'connection type' - this has some setting like a connection type
// - 2 bytes of 'DC'. DC is little endian int16
// - 2 bytes of noise
type handshakeFrame struct {
data [handshakeFrameLen]byte
}
func (h *handshakeFrame) dc() int {
idx := int16(h.data[handshakeFrameOffsetDC]) | int16(h.data[handshakeFrameOffsetDC+1])<<8 // nolint: gomnd, lll // little endian for int16 is here
idx := int16(h.data[handshakeFrameOffsetDC]) | int16(h.data[handshakeFrameOffsetDC+1])<<8 //nolint: gomnd, lll // little endian for int16 is here
switch {
case idx > 0:
@@ -57,7 +57,7 @@ func (suite *HandshakeFrameTestSuite) TestDC() {
suite.T().Run(strconv.Itoa(int(incoming)), func(t *testing.T) {
frame := handshakeFrame{}
rand.Read(frame.data[:]) // nolint: errcheck
rand.Read(frame.data[:]) //nolint: errcheck
frame.data[handshakeFrameOffsetDC] = byte(incoming)
frame.data[handshakeFrameOffsetDC+1] = byte(incoming >> 8)
+2 -2
View File
@@ -21,7 +21,7 @@ var (
)
func acquireSha256Hasher() hash.Hash {
return sha256HasherPool.Get().(hash.Hash) // nolint: forcetypeassert
return sha256HasherPool.Get().(hash.Hash) //nolint: forcetypeassert
}
func releaseSha256Hasher(h hash.Hash) {
@@ -30,7 +30,7 @@ func releaseSha256Hasher(h hash.Hash) {
}
func acquireBytesBuffer() *bytes.Buffer {
return bytesBufferPool.Get().(*bytes.Buffer) // nolint: forcetypeassert
return bytesBufferPool.Get().(*bytes.Buffer) //nolint: forcetypeassert
}
func releaseBytesBuffer(buf *bytes.Buffer) {
@@ -47,12 +47,12 @@ func generateServerHanshakeFrame() serverHandshakeFrame {
panic(err)
}
if frame.data[0] == 0xef { // nolint: gomnd // taken from tg sources
if frame.data[0] == 0xef { //nolint: gomnd // taken from tg sources
continue
}
switch binary.LittleEndian.Uint32(frame.data[:4]) {
case 0x44414548, 0x54534f50, 0x20544547, 0x4954504f, 0xeeeeeeee: // nolint: gomnd // taken from tg sources
case 0x44414548, 0x54534f50, 0x20544547, 0x4954504f, 0xeeeeeeee: //nolint: gomnd // taken from tg sources
continue
}
@@ -19,7 +19,7 @@ func FuzzServerSend(f *testing.F) {
Once().
Run(func(args mock.Arguments) {
message := make([]byte, len(data))
handshakeData.decryptor.XORKeyStream(message, args.Get(0).([]byte)) // nolint: forcetypeassert
handshakeData.decryptor.XORKeyStream(message, args.Get(0).([]byte)) //nolint: forcetypeassert
assert.Equal(t, message, data)
})
@@ -45,7 +45,7 @@ func FuzzServerReceive(f *testing.F) {
Run(func(args mock.Arguments) {
message := make([]byte, len(data))
handshakeData.encryptor.XORKeyStream(message, data)
copy(args.Get(0).([]byte), message) // nolint: forcetypeassert
copy(args.Get(0).([]byte), message) //nolint: forcetypeassert
})
n, err := handshakeData.proxyConn.Read(buffer)
@@ -30,7 +30,7 @@ func (suite *ServerHandshakeTestSuite) TestSendToTelegram() {
Once().
Run(func(args mock.Arguments) {
message := make([]byte, len(messageToTelegram))
suite.data.decryptor.XORKeyStream(message, args.Get(0).([]byte)) // nolint: forcetypeassert
suite.data.decryptor.XORKeyStream(message, args.Get(0).([]byte)) //nolint: forcetypeassert
suite.Equal(messageToTelegram, message)
})
@@ -50,7 +50,7 @@ func (suite *ServerHandshakeTestSuite) TestRecieveFromTelegram() {
Run(func(args mock.Arguments) {
message := make([]byte, len(messageFromTelegram))
suite.data.encryptor.XORKeyStream(message, messageFromTelegram)
copy(args.Get(0).([]byte), message) // nolint: forcetypeassert
copy(args.Get(0).([]byte), message) //nolint: forcetypeassert
})
n, err := suite.data.proxyConn.Read(buffer)
+1 -1
View File
@@ -11,7 +11,7 @@ var copyBufferPool = sync.Pool{
}
func acquireCopyBuffer() *[]byte {
return copyBufferPool.Get().(*[]byte) // nolint: forcetypeassert
return copyBufferPool.Get().(*[]byte) //nolint: forcetypeassert
}
func releaseCopyBuffer(buf *[]byte) {
+2 -2
View File
@@ -35,8 +35,8 @@ func Relay(ctx context.Context, log Logger, telegramConn, clientConn essentials.
}
func pump(log Logger, src, dst essentials.Conn, direction string) {
defer src.CloseRead() // nolint: errcheck
defer dst.CloseWrite() // nolint: errcheck
defer src.CloseRead() //nolint: errcheck
defer dst.CloseWrite() //nolint: errcheck
copyBuffer := acquireCopyBuffer()
defer releaseCopyBuffer(copyBuffer)
+3 -3
View File
@@ -106,7 +106,7 @@ func (p *Proxy) Serve(listener net.Listener) error {
}
}
ipAddr := conn.RemoteAddr().(*net.TCPAddr).IP // nolint: forcetypeassert
ipAddr := conn.RemoteAddr().(*net.TCPAddr).IP //nolint: forcetypeassert
logger := p.logger.BindStr("ip", ipAddr.String())
if !p.allowlist.Contains(ipAddr) {
@@ -253,7 +253,7 @@ func (p *Proxy) doTelegramCall(ctx *streamContext) error {
p.eventStream.Send(ctx,
NewEventConnectedToDC(ctx.streamID,
conn.RemoteAddr().(*net.TCPAddr).IP, // nolint: forcetypeassert
conn.RemoteAddr().(*net.TCPAddr).IP, //nolint: forcetypeassert
ctx.dc),
)
@@ -316,7 +316,7 @@ func NewProxy(opts ProxyOpts) (*Proxy, error) {
pool, err := ants.NewPoolWithFunc(opts.getConcurrency(),
func(arg interface{}) {
proxy.ServeConn(arg.(essentials.Conn)) // nolint: forcetypeassert
proxy.ServeConn(arg.(essentials.Conn)) //nolint: forcetypeassert
},
ants.WithLogger(opts.getLogger("ants")),
ants.WithNonblocking(true))
+4 -4
View File
@@ -86,7 +86,7 @@ func (suite *ProxyTestSuite) SetupSuite() {
suite.listener = listener
go suite.p.Serve(suite.listener) // nolint: errcheck
go suite.p.Serve(suite.listener) //nolint: errcheck
}
func (suite *ProxyTestSuite) TearDownSuite() {
@@ -179,7 +179,7 @@ func (suite *ProxyTestSuite) TestHTTPSRequest() {
addr := fmt.Sprintf("https://%s/headers", suite.ProxyAddress())
resp, err := client.Get(addr) // nolint: noctx
resp, err := client.Get(addr) //nolint: noctx
suite.NoError(err)
defer resp.Body.Close()
@@ -191,7 +191,7 @@ func (suite *ProxyTestSuite) TestHTTPSRequest() {
jsonStruct := struct {
Headers struct {
TraceID string `json:"X-Amzn-Trace-Id"` // nolint: tagliatelle
TraceID string `json:"X-Amzn-Trace-Id"` //nolint: tagliatelle
} `json:"headers"`
}{}
@@ -221,7 +221,7 @@ func (suite *ProxyTestSuite) TestMakeRealRequest() {
_, err := tg.NewClient(tgClient).HelpGetConfig(ctx)
suite.NoError(err)
return err // nolint: wrapcheck
return err //nolint: wrapcheck
}))
}
+1 -1
View File
@@ -74,7 +74,7 @@ func (s *Secret) Set(text string) error {
return fmt.Errorf("incorrect secret format: %w", err)
}
if len(decoded) < 2 { // nolint: gomnd // we need at least 1 byte here
if len(decoded) < 2 { //nolint: gomnd // we need at least 1 byte here
return fmt.Errorf("secret is truncated, length=%d", len(decoded))
}
+2 -2
View File
@@ -29,7 +29,7 @@ func (s *streamContext) Done() <-chan struct{} {
}
func (s *streamContext) Err() error {
return s.ctx.Err() // nolint: wrapcheck
return s.ctx.Err() //nolint: wrapcheck
}
func (s *streamContext) Value(key interface{}) interface{} {
@@ -49,7 +49,7 @@ func (s *streamContext) Close() {
}
func (s *streamContext) ClientIP() net.IP {
return s.clientConn.RemoteAddr().(*net.TCPAddr).IP // nolint: forcetypeassert
return s.clientConn.RemoteAddr().(*net.TCPAddr).IP //nolint: forcetypeassert
}
func newStreamContext(ctx context.Context, logger Logger, clientConn essentials.Conn) *streamContext {
+1 -1
View File
@@ -24,7 +24,7 @@ func (suite *StreamContextTestSuite) SetupSuite() {
func (suite *StreamContextTestSuite) SetupTest() {
ctx, cancel := context.WithCancel(context.Background())
ctx = context.WithValue(ctx, "key", "value") // nolint: golint, revive, staticcheck
ctx = context.WithValue(ctx, "key", "value") //nolint: golint, staticcheck
suite.ctxCancel = cancel
suite.connMock = &testlib.EssentialsConnMock{}
+5 -5
View File
@@ -59,7 +59,7 @@ func (c *circuitBreakerDialer) doClosed(ctx context.Context,
conn.Close()
}
return nil, ctx.Err() // nolint: wrapcheck
return nil, ctx.Err() //nolint: wrapcheck
case c.stateMutexChan <- true:
defer func() {
<-c.stateMutexChan
@@ -78,7 +78,7 @@ func (c *circuitBreakerDialer) doClosed(ctx context.Context,
c.switchState(circuitBreakerStateOpened)
}
return conn, err // nolint: wrapcheck
return conn, err //nolint: wrapcheck
}
func (c *circuitBreakerDialer) doHalfOpened(ctx context.Context,
@@ -96,7 +96,7 @@ func (c *circuitBreakerDialer) doHalfOpened(ctx context.Context,
conn.Close()
}
return nil, ctx.Err() // nolint: wrapcheck
return nil, ctx.Err() //nolint: wrapcheck
case c.stateMutexChan <- true:
defer func() {
<-c.stateMutexChan
@@ -104,7 +104,7 @@ func (c *circuitBreakerDialer) doHalfOpened(ctx context.Context,
}
if c.state != circuitBreakerStateHalfOpened {
return conn, err // nolint: wrapcheck
return conn, err //nolint: wrapcheck
}
if err == nil {
@@ -113,7 +113,7 @@ func (c *circuitBreakerDialer) doHalfOpened(ctx context.Context,
c.switchState(circuitBreakerStateOpened)
}
return conn, err // nolint: wrapcheck
return conn, err //nolint: wrapcheck
}
func (c *circuitBreakerDialer) switchState(state uint32) {
+4 -4
View File
@@ -110,10 +110,10 @@ func (suite *CircuitBreakerTestSuite) TestHalfOpen() {
Port: 80,
})
suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") // nolint: errcheck
suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") // nolint: errcheck
suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") // nolint: errcheck
suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") // nolint: errcheck
suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") //nolint: errcheck
suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") //nolint: errcheck
suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") //nolint: errcheck
suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") //nolint: errcheck
time.Sleep(500 * time.Millisecond)
+2 -2
View File
@@ -19,7 +19,7 @@ func (d *defaultDialer) Dial(network, address string) (essentials.Conn, error) {
func (d *defaultDialer) DialContext(ctx context.Context, network, address string) (essentials.Conn, error) {
switch network {
case "tcp", "tcp4", "tcp6": // nolint: goconst
case "tcp", "tcp4", "tcp6": //nolint: goconst
default:
return nil, fmt.Errorf("unsupported network %s", network)
}
@@ -36,7 +36,7 @@ func (d *defaultDialer) DialContext(ctx context.Context, network, address string
return nil, fmt.Errorf("cannot set socket options: %w", err)
}
return conn.(essentials.Conn), nil // nolint: forcetypeassert
return conn.(essentials.Conn), nil //nolint: forcetypeassert
}
// NewDefaultDialer build a new dialer which dials bypassing proxies
+1 -1
View File
@@ -57,7 +57,7 @@ func (suite *DefaultDialerTestSuite) TestConnectOk() {
func (suite *DefaultDialerTestSuite) TestHTTPRequest() {
httpClient := suite.MakeHTTPClient(suite.d)
resp, err := httpClient.Get(suite.MakeURL("/get")) // nolint: noctx
resp, err := httpClient.Get(suite.MakeURL("/get")) //nolint: noctx
if err == nil {
defer resp.Body.Close()
}
+2 -4
View File
@@ -85,13 +85,13 @@ func (d *dnsResolver) LookupAAAA(hostname string) []string {
return ips
}
func newDNSResolver(hostname string, httpClient *http.Client) (ret *dnsResolver) {
func newDNSResolver(hostname string, httpClient *http.Client) *dnsResolver {
if net.ParseIP(hostname).To4() == nil {
// the hostname is an IPv6 address
hostname = fmt.Sprintf("[%s]", hostname)
}
ret = &dnsResolver{
return &dnsResolver{
resolver: doh.Resolver{
Host: hostname,
Class: doh.IN,
@@ -99,6 +99,4 @@ func newDNSResolver(hostname string, httpClient *http.Client) (ret *dnsResolver)
},
cache: map[string]dnsResolverCacheEntry{},
}
return
}
+2 -2
View File
@@ -14,11 +14,11 @@ type DialerMock struct {
func (d *DialerMock) Dial(network, address string) (essentials.Conn, error) {
args := d.Called(network, address)
return args.Get(0).(essentials.Conn), args.Error(1) // nolint: wrapcheck, forcetypeassert
return args.Get(0).(essentials.Conn), args.Error(1) //nolint: wrapcheck, forcetypeassert
}
func (d *DialerMock) DialContext(ctx context.Context, network, address string) (essentials.Conn, error) {
args := d.Called(ctx, network, address)
return args.Get(0).(essentials.Conn), args.Error(1) // nolint: wrapcheck, forcetypeassert
return args.Get(0).(essentials.Conn), args.Error(1) //nolint: wrapcheck, forcetypeassert
}
+4 -4
View File
@@ -22,13 +22,13 @@ type DialerMock struct {
func (d *DialerMock) Dial(network, address string) (essentials.Conn, error) {
args := d.Called(network, address)
return args.Get(0).(essentials.Conn), args.Error(1) // nolint: wrapcheck, forcetypeassert
return args.Get(0).(essentials.Conn), args.Error(1) //nolint: wrapcheck, forcetypeassert
}
func (d *DialerMock) DialContext(ctx context.Context, network, address string) (essentials.Conn, error) {
args := d.Called(ctx, network, address)
return args.Get(0).(essentials.Conn), args.Error(1) // nolint: wrapcheck, forcetypeassert
return args.Get(0).(essentials.Conn), args.Error(1) //nolint: wrapcheck, forcetypeassert
}
type HTTPServerTestSuite struct {
@@ -55,7 +55,7 @@ func (suite *HTTPServerTestSuite) MakeHTTPClient(dialer network.Dialer) *http.Cl
return &http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
return dialer.DialContext(ctx, network, address) // nolint: wrapcheck
return dialer.DialContext(ctx, network, address) //nolint: wrapcheck
},
},
}
@@ -74,7 +74,7 @@ func (suite *Socks5ServerTestSuite) SetupSuite() {
},
})
go suite.socks5Server.Serve(suite.socks5Listener) // nolint: errcheck
go suite.socks5Server.Serve(suite.socks5Listener) //nolint: errcheck
}
func (suite *Socks5ServerTestSuite) TearDownSuite() {
+1 -1
View File
@@ -73,7 +73,7 @@ func (suite *LoadBalancedSocks5TestSuite) TestCannotDial() {
}
func (suite *LoadBalancedSocks5TestSuite) TestDialOk() {
resp, err := suite.httpClient.Get(suite.MakeURL("/get")) // nolint: noctx
resp, err := suite.httpClient.Get(suite.MakeURL("/get")) //nolint: noctx
if err == nil {
defer resp.Body.Close()
}
+1 -1
View File
@@ -21,7 +21,7 @@ type networkHTTPTransport struct {
func (n networkHTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("User-Agent", n.userAgent)
return n.next.RoundTrip(req) // nolint: wrapcheck
return n.next.RoundTrip(req) //nolint: wrapcheck
}
type network struct {
+4 -4
View File
@@ -31,7 +31,7 @@ func (suite *NetworkTestSuite) TestLocalHTTPRequest() {
client := ntw.MakeHTTPClient(nil)
resp, err := client.Get(suite.httpServer.URL + "/headers") // nolint: noctx
resp, err := client.Get(suite.httpServer.URL + "/headers") //nolint: noctx
suite.NoError(err)
defer resp.Body.Close()
@@ -42,7 +42,7 @@ func (suite *NetworkTestSuite) TestLocalHTTPRequest() {
jsonStruct := struct {
Headers struct {
UserAgent []string `json:"User-Agent"` // nolint: tagliatelle
UserAgent []string `json:"User-Agent"` //nolint: tagliatelle
} `json:"headers"`
}{}
@@ -56,7 +56,7 @@ func (suite *NetworkTestSuite) TestRealHTTPRequest() {
client := ntw.MakeHTTPClient(nil)
resp, err := client.Get("https://httpbin.org/headers") // nolint: noctx
resp, err := client.Get("https://httpbin.org/headers") //nolint: noctx
suite.NoError(err)
defer resp.Body.Close()
@@ -67,7 +67,7 @@ func (suite *NetworkTestSuite) TestRealHTTPRequest() {
jsonStruct := struct {
Headers struct {
UserAgent string `json:"User-Agent"` // nolint: tagliatelle
UserAgent string `json:"User-Agent"` //nolint: tagliatelle
} `json:"headers"`
}{}
+1 -1
View File
@@ -16,7 +16,7 @@ func newProxyDialer(baseDialer Dialer, proxyURL *url.URL) Dialer {
)
if param := params.Get("open_threshold"); param != "" {
if intNum, err := strconv.ParseUint(param, 10, 32); err == nil { // nolint: gomnd
if intNum, err := strconv.ParseUint(param, 10, 32); err == nil { //nolint: gomnd
openThreshold = uint32(intNum)
}
}
+5 -5
View File
@@ -21,7 +21,7 @@ func (suite *ProxyDialerTestSuite) SetupSuite() {
}
func (suite *ProxyDialerTestSuite) TestSetupDefaults() {
d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) // nolint: forcetypeassert
d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) //nolint: forcetypeassert
suite.EqualValues(ProxyDialerOpenThreshold, d.openThreshold)
suite.EqualValues(ProxyDialerHalfOpenTimeout, d.halfOpenTimeout)
suite.EqualValues(ProxyDialerResetFailuresTimeout, d.resetFailuresTimeout)
@@ -34,7 +34,7 @@ func (suite *ProxyDialerTestSuite) TestSetupValuesAllOk() {
query.Set("half_open_timeout", "2s")
suite.u.RawQuery = query.Encode()
d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) // nolint: forcetypeassert
d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) //nolint: forcetypeassert
suite.EqualValues(30, d.openThreshold)
suite.EqualValues(2*time.Second, d.halfOpenTimeout)
suite.EqualValues(time.Second, d.resetFailuresTimeout)
@@ -50,7 +50,7 @@ func (suite *ProxyDialerTestSuite) TestOpenThreshold() {
query.Set("open_threshold", param)
suite.u.RawQuery = query.Encode()
d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) // nolint: forcetypeassert
d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) //nolint: forcetypeassert
assert.EqualValues(t, ProxyDialerOpenThreshold, d.openThreshold)
})
}
@@ -66,7 +66,7 @@ func (suite *ProxyDialerTestSuite) TestHalfOpenTimeout() {
query.Set("half_open_timeout", param)
suite.u.RawQuery = query.Encode()
d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) // nolint: forcetypeassert
d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) //nolint: forcetypeassert
assert.EqualValues(t, ProxyDialerHalfOpenTimeout, d.halfOpenTimeout)
})
}
@@ -82,7 +82,7 @@ func (suite *ProxyDialerTestSuite) TestResetFailuresTimeout() {
query.Set("reset_failures_timeout", param)
suite.u.RawQuery = query.Encode()
d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) // nolint: forcetypeassert
d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) //nolint: forcetypeassert
assert.EqualValues(t, ProxyDialerHalfOpenTimeout, d.halfOpenTimeout)
})
}
+2 -2
View File
@@ -10,13 +10,13 @@ import (
//
// bufferSize setting is deprecated and ignored.
func SetClientSocketOptions(conn net.Conn, bufferSize int) error {
return setCommonSocketOptions(conn.(*net.TCPConn)) // nolint: forcetypeassert
return setCommonSocketOptions(conn.(*net.TCPConn)) //nolint: forcetypeassert
}
// SetServerSocketOptions tunes a TCP socket that represents a connection to
// remote server like Telegram or fronting domain (but not end user).
func SetServerSocketOptions(conn net.Conn, bufferSize int) error {
return setCommonSocketOptions(conn.(*net.TCPConn)) // nolint: forcetypeassert
return setCommonSocketOptions(conn.(*net.TCPConn)) //nolint: forcetypeassert
}
func setCommonSocketOptions(conn *net.TCPConn) error {
+3 -3
View File
@@ -13,15 +13,15 @@ import (
func setSocketReuseAddrPort(conn syscall.RawConn) error {
var err error
conn.Control(func(fd uintptr) { // nolint: errcheck
err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
conn.Control(func(fd uintptr) { //nolint: errcheck
err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1) //nolint: nosnakecase
if err != nil {
err = fmt.Errorf("cannot set SO_REUSEADDR: %w", err)
return
}
err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1) //nolint: nosnakecase
if err != nil {
err = fmt.Errorf("cannot set SO_REUSEPORT: %w", err)
}
+1 -1
View File
@@ -139,7 +139,7 @@ func (s socks5Dialer) connect(conn io.ReadWriter, address string) error {
// NewSocks5Dialer build a new dialer from a given one (so, in theory you can
// chain here). Proxy parameters are passed with URI in a form of:
//
// socks5://[user:[password]]@host:port
// socks5://[user:[password]]@host:port
func NewSocks5Dialer(baseDialer Dialer, proxyURL *url.URL) (Dialer, error) {
if _, _, err := net.SplitHostPort(proxyURL.Host); err != nil {
return nil, fmt.Errorf("incorrect url %s", proxyURL.Redacted())
+2 -2
View File
@@ -33,7 +33,7 @@ func (suite *Socks5TestSuite) TestRequestFailed() {
dialer, _ := network.NewSocks5Dialer(suite.d, proxyURL)
httpClient := suite.MakeHTTPClient(dialer)
resp, err := httpClient.Get(suite.MakeURL("/get")) // nolint: noctx
resp, err := httpClient.Get(suite.MakeURL("/get")) //nolint: noctx
if err == nil {
defer resp.Body.Close()
}
@@ -46,7 +46,7 @@ func (suite *Socks5TestSuite) TestRequestOk() {
dialer, _ := network.NewSocks5Dialer(suite.d, proxyURL)
httpClient := suite.MakeHTTPClient(dialer)
resp, err := httpClient.Get(suite.MakeURL("/get")) // nolint: noctx
resp, err := httpClient.Get(suite.MakeURL("/get")) //nolint: noctx
if err == nil {
defer resp.Body.Close()
}
+1 -1
View File
@@ -11,7 +11,7 @@ var streamInfoPool = sync.Pool{
}
func acquireStreamInfo() *streamInfo {
return streamInfoPool.Get().(*streamInfo) // nolint: forcetypeassert
return streamInfoPool.Get().(*streamInfo) //nolint: forcetypeassert
}
func releaseStreamInfo(info *streamInfo) {
+3 -3
View File
@@ -171,18 +171,18 @@ func (p *PrometheusFactory) Make() events.Observer {
// Serve starts an HTTP server on a given listener.
func (p *PrometheusFactory) Serve(listener net.Listener) error {
return p.httpServer.Serve(listener) // nolint: wrapcheck
return p.httpServer.Serve(listener) //nolint: wrapcheck
}
// Close stops a factory. Please pay attention that underlying listener
// is not closed.
func (p *PrometheusFactory) Close() error {
return p.httpServer.Shutdown(context.Background()) // nolint: wrapcheck
return p.httpServer.Shutdown(context.Background()) //nolint: wrapcheck
}
// NewPrometheus builds an events.ObserverFactory which can serve HTTP
// endpoint with Prometheus scrape data.
func NewPrometheus(metricPrefix, httpPath string) *PrometheusFactory { // nolint: funlen
func NewPrometheus(metricPrefix, httpPath string) *PrometheusFactory { //nolint: funlen
registry := prometheus.NewPedanticRegistry()
httpHandler := promhttp.HandlerFor(registry, promhttp.HandlerOpts{
EnableOpenMetrics: true,
+4 -4
View File
@@ -25,16 +25,16 @@ type PrometheusTestSuite struct {
func (suite *PrometheusTestSuite) Get() (string, error) {
addr := fmt.Sprintf("http://%s/", suite.httpListener.Addr().String())
resp, err := http.Get(addr) // nolint: noctx
resp, err := http.Get(addr) //nolint: noctx
if err != nil {
return "", err // nolint: wrapcheck
return "", err //nolint: wrapcheck
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return "", err // nolint: wrapcheck
return "", err //nolint: wrapcheck
}
return string(data), nil
@@ -45,7 +45,7 @@ func (suite *PrometheusTestSuite) SetupTest() {
suite.factory = stats.NewPrometheus("mtg", "/")
suite.prometheus = suite.factory.Make()
go suite.factory.Serve(suite.httpListener) // nolint: errcheck
go suite.factory.Serve(suite.httpListener) //nolint: errcheck
}
func (suite *PrometheusTestSuite) TearDownTest() {
+1 -1
View File
@@ -160,7 +160,7 @@ type StatsdFactory struct {
// Close stops sending requests to statsd.
func (s StatsdFactory) Close() error {
return s.client.Close() // nolint: wrapcheck
return s.client.Close() //nolint: wrapcheck
}
// Make build a new observer.
+1 -1
View File
@@ -30,7 +30,7 @@ func (s *statsdFakeServer) Addr() string {
func (s *statsdFakeServer) Close() error {
if s.conn != nil {
return s.conn.Close() // nolint: wrapcheck
return s.conn.Close() //nolint: wrapcheck
}
return nil