Fix all lint errors

This commit is contained in:
9seconds
2018-05-31 09:54:20 +03:00
parent 42e5be36bf
commit 4ad913add2
12 changed files with 101 additions and 47 deletions
+11 -6
View File
@@ -5,39 +5,44 @@ import (
"io"
)
// Cipher is an interface to anything which can encrypt and decrypt
type Cipher interface {
Encrypt([]byte) []byte
Decrypt([]byte) []byte
}
// CipherReadWriteCloser wraps connection for transparent encryption
type CipherReadWriteCloser struct {
crypt Cipher
conn io.ReadWriteCloser
rest *bytes.Buffer
}
// Read reads from connection
func (c *CipherReadWriteCloser) Read(p []byte) (n int, err error) {
n, err = c.conn.Read(p)
copy(p, c.crypt.Decrypt(p[:n]))
return
}
func (c *CipherReadWriteCloser) Write(p []byte) (n int, err error) {
// Write writes into connection.
func (c *CipherReadWriteCloser) Write(p []byte) (int, error) {
encrypted := c.crypt.Encrypt(p)
allWritten := 0
curN := 0
for len(encrypted) > 0 {
curN, err = c.conn.Write(encrypted)
n += curN
n, err := c.conn.Write(encrypted)
allWritten += n
if err != nil {
return
return allWritten, err
}
encrypted = encrypted[n:]
}
return
return allWritten, nil
}
// Close closes underlying connection.
func (c *CipherReadWriteCloser) Close() error {
return c.conn.Close()
}
+6 -1
View File
@@ -7,12 +7,15 @@ import (
"github.com/juju/errors"
)
// CtxReadWriteCloser wraps underlying connection and does management of the
// context and its cancel function.
type CtxReadWriteCloser struct {
ctx context.Context
conn io.ReadWriteCloser
cancel context.CancelFunc
}
// Read reads from connection
func (c *CtxReadWriteCloser) Read(p []byte) (int, error) {
select {
case <-c.ctx.Done():
@@ -26,6 +29,7 @@ func (c *CtxReadWriteCloser) Read(p []byte) (int, error) {
}
}
// Write writes into connection.
func (c *CtxReadWriteCloser) Write(p []byte) (int, error) {
select {
case <-c.ctx.Done():
@@ -39,11 +43,12 @@ func (c *CtxReadWriteCloser) Write(p []byte) (int, error) {
}
}
// Close closes underlying connection.
func (c *CtxReadWriteCloser) Close() error {
return c.conn.Close()
}
func newCtxReadWriteCloser(conn io.ReadWriteCloser, ctx context.Context, cancel context.CancelFunc) io.ReadWriteCloser {
func newCtxReadWriteCloser(ctx context.Context, cancel context.CancelFunc, conn io.ReadWriteCloser) io.ReadWriteCloser {
return &CtxReadWriteCloser{
conn: conn,
ctx: ctx,
+5
View File
@@ -6,6 +6,8 @@ import (
"go.uber.org/zap"
)
// LogReadWriteCloser adds additional logging for reading/writing. All
// logging is performed for debug mode only.
type LogReadWriteCloser struct {
conn io.ReadWriteCloser
logger *zap.SugaredLogger
@@ -13,18 +15,21 @@ type LogReadWriteCloser struct {
name string
}
// Read reads from connection
func (l *LogReadWriteCloser) Read(p []byte) (n int, err error) {
n, err = l.conn.Read(p)
l.logger.Debugw("Finish reading", "name", l.name, "socketid", l.sockid, "nbytes", n, "error", err)
return
}
// Write writes into connection.
func (l *LogReadWriteCloser) Write(p []byte) (n int, err error) {
n, err = l.conn.Write(p)
l.logger.Debugw("Finish writing", "name", l.name, "socketid", l.sockid, "nbytes", n, "error", err)
return
}
// Close closes underlying connection.
func (l *LogReadWriteCloser) Close() error {
err := l.conn.Close()
l.logger.Debugw("Finish closing socket", "name", l.name, "socketid", l.sockid, "error", err)
+22 -26
View File
@@ -14,14 +14,12 @@ import (
"go.uber.org/zap"
)
const bufferSize = 4096
// Server is an insgtance of MTPROTO proxy.
type Server struct {
ip net.IP
port int
secret []byte
logger *zap.SugaredLogger
lsock net.Listener
ctx context.Context
readTimeout time.Duration
writeTimeout time.Duration
@@ -29,8 +27,10 @@ type Server struct {
ipv6 bool
}
// Serve does MTPROTO proxying.
func (s *Server) Serve() error {
lsock, err := net.Listen("tcp", s.Addr())
addr := net.JoinHostPort(s.ip.String(), strconv.Itoa(s.port))
lsock, err := net.Listen("tcp", addr)
if err != nil {
return errors.Annotate(err, "Cannot create listen socket")
}
@@ -42,18 +42,12 @@ func (s *Server) Serve() error {
go s.accept(conn)
}
}
return nil
}
func (s *Server) Addr() string {
return net.JoinHostPort(s.ip.String(), strconv.Itoa(s.port))
}
func (s *Server) accept(conn net.Conn) {
defer func() {
s.stats.closeConnection()
conn.Close()
conn.Close() // nolint: errcheck
if r := recover(); r != nil {
s.logger.Errorw("Crash of accept handler", "error", r)
@@ -70,7 +64,7 @@ func (s *Server) accept(conn net.Conn) {
"socketid", socketID,
)
clientConn, dc, err := s.getClientStream(conn, ctx, cancel, socketID)
clientConn, dc, err := s.getClientStream(ctx, cancel, conn, socketID)
if err != nil {
s.logger.Warnw("Cannot initialize client connection",
"secret", s.secret,
@@ -80,9 +74,9 @@ func (s *Server) accept(conn net.Conn) {
)
return
}
defer clientConn.Close()
defer clientConn.Close() // nolint: errcheck
tgConn, err := s.getTelegramStream(dc, ctx, cancel, socketID)
tgConn, err := s.getTelegramStream(ctx, cancel, dc, socketID)
if err != nil {
s.logger.Warnw("Cannot initialize Telegram connection",
"socketid", socketID,
@@ -90,12 +84,18 @@ func (s *Server) accept(conn net.Conn) {
)
return
}
defer tgConn.Close()
defer tgConn.Close() // nolint: errcheck
wait := &sync.WaitGroup{}
wait.Add(2)
go s.pipe(wait, clientConn, tgConn)
go s.pipe(wait, tgConn, clientConn)
go func() {
defer wait.Done()
io.Copy(clientConn, tgConn) // nolint: errcheck
}()
go func() {
defer wait.Done()
io.Copy(tgConn, clientConn) // nolint: errcheck
}()
<-ctx.Done()
wait.Wait()
@@ -110,7 +110,7 @@ func (s *Server) makeSocketID() string {
return uuid.NewV4().String()
}
func (s *Server) getClientStream(conn net.Conn, ctx context.Context, cancel context.CancelFunc, socketID string) (io.ReadWriteCloser, int16, error) {
func (s *Server) getClientStream(ctx context.Context, cancel context.CancelFunc, conn net.Conn, socketID string) (io.ReadWriteCloser, int16, error) {
wConn := newTimeoutReadWriteCloser(conn, s.readTimeout, s.writeTimeout)
wConn = newTrafficReadWriteCloser(wConn, s.stats.addIncomingTraffic, s.stats.addOutgoingTraffic)
frame, err := obfuscated2.ExtractFrame(wConn)
@@ -125,12 +125,12 @@ func (s *Server) getClientStream(conn net.Conn, ctx context.Context, cancel cont
wConn = newLogReadWriteCloser(wConn, s.logger, socketID, "client")
wConn = newCipherReadWriteCloser(wConn, obfs2)
wConn = newCtxReadWriteCloser(wConn, ctx, cancel)
wConn = newCtxReadWriteCloser(ctx, cancel, wConn)
return wConn, dc, nil
}
func (s *Server) getTelegramStream(dc int16, ctx context.Context, cancel context.CancelFunc, socketID string) (io.ReadWriteCloser, error) {
func (s *Server) getTelegramStream(ctx context.Context, cancel context.CancelFunc, dc int16, socketID string) (io.ReadWriteCloser, error) {
socket, err := dialToTelegram(s.ipv6, dc, s.readTimeout)
if err != nil {
return nil, errors.Annotate(err, "Cannot dial")
@@ -145,16 +145,12 @@ func (s *Server) getTelegramStream(dc int16, ctx context.Context, cancel context
wConn = newLogReadWriteCloser(wConn, s.logger, socketID, "telegram")
wConn = newCipherReadWriteCloser(wConn, obfs2)
wConn = newCtxReadWriteCloser(wConn, ctx, cancel)
wConn = newCtxReadWriteCloser(ctx, cancel, wConn)
return wConn, nil
}
func (s *Server) pipe(wait *sync.WaitGroup, reader io.Reader, writer io.Writer) {
defer wait.Done()
io.Copy(writer, reader)
}
// NewServer creates new instance of MTPROTO proxy.
func NewServer(ip net.IP, port int, secret []byte, logger *zap.SugaredLogger,
readTimeout, writeTimeout time.Duration, ipv6 bool, stat *Stats) *Server {
return &Server{
+7 -3
View File
@@ -2,6 +2,7 @@ package proxy
import (
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
@@ -17,6 +18,7 @@ func (s statsUptime) MarshalJSON() ([]byte, error) {
return []byte(strconv.Itoa(uptime)), nil
}
// Stats is a datastructure for statistics on work of this proxy.
type Stats struct {
AllConnections uint64 `json:"all_connections"`
ActiveConnections uint32 `json:"active_connections"`
@@ -50,20 +52,22 @@ func (s *Stats) addOutgoingTraffic(n int) {
atomic.AddUint64(&s.Traffic.Outgoing, uint64(n))
}
func (s *Stats) Serve(host net.IP, port uint16) {
// Serve runs statistics HTTP server.
func (s *Stats) Serve(host fmt.Stringer, port uint16) {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
encoder := json.NewEncoder(w)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
encoder.Encode(s)
encoder.Encode(s) // nolint: errcheck, gas
})
addr := net.JoinHostPort(host.String(), strconv.Itoa(int(port)))
http.ListenAndServe(addr, nil)
http.ListenAndServe(addr, nil) // nolint: errcheck, gas
}
// NewStats returns new instance of statistics datastructure.
func NewStats(serverName string, port uint16, secret string) *Stats {
urlQuery := makeURLQuery(serverName, port, secret)
+5
View File
@@ -7,19 +7,24 @@ import (
"github.com/juju/errors"
)
// TelegramAddress presents a pair of v4 and v6 addresses. This pairization
// is required because we want to use DC indexes.
type TelegramAddress struct {
v4 string
v6 string
}
// IPv4 returns v4 address.
func (t *TelegramAddress) IPv4() string {
return net.JoinHostPort(t.v4, telegramPort)
}
// IPv6 returns v4 address.
func (t *TelegramAddress) IPv6() string {
return net.JoinHostPort(t.v6, telegramPort)
}
// TelegramAddresses is a list of all known Telegram addresses for DC indexes.
var TelegramAddresses = []TelegramAddress{
TelegramAddress{v4: "149.154.175.50", v6: "2001:b28:f23d:f001::a"},
TelegramAddress{v4: "149.154.167.51", v6: "2001:67c:04e8:f002::a"},
+7 -2
View File
@@ -6,22 +6,27 @@ import (
"time"
)
// TimeoutReadWriteCloser sets timeouts for read/write into underlying
// network connection.
type TimeoutReadWriteCloser struct {
conn net.Conn
readTimeout time.Duration
writeTimeout time.Duration
}
// Read reads from connection
func (t *TimeoutReadWriteCloser) Read(p []byte) (int, error) {
t.conn.SetReadDeadline(time.Now().Add(t.readTimeout))
t.conn.SetReadDeadline(time.Now().Add(t.readTimeout)) // nolint: errcheck, gas
return t.conn.Read(p)
}
// Write writes into connection.
func (t *TimeoutReadWriteCloser) Write(p []byte) (int, error) {
t.conn.SetWriteDeadline(time.Now().Add(t.writeTimeout))
t.conn.SetWriteDeadline(time.Now().Add(t.writeTimeout)) // nolint: errcheck, gas
return t.conn.Write(p)
}
// Close closes underlying connection.
func (t *TimeoutReadWriteCloser) Close() error {
return t.conn.Close()
}
+5
View File
@@ -2,24 +2,29 @@ package proxy
import "io"
// TrafficReadWriteCloser counts an amount of ingress/egress traffic by
// calling given callbacks.
type TrafficReadWriteCloser struct {
conn io.ReadWriteCloser
readCallback func(int)
writeCallback func(int)
}
// Read reads from connection
func (t *TrafficReadWriteCloser) Read(p []byte) (n int, err error) {
n, err = t.conn.Read(p)
t.readCallback(n)
return
}
// Write writes into connection.
func (t *TrafficReadWriteCloser) Write(p []byte) (n int, err error) {
n, err = t.conn.Write(p)
t.writeCallback(n)
return
}
// Close closes underlying connection.
func (t *TrafficReadWriteCloser) Close() error {
return t.conn.Close()
}