2024-07-22 10:59:11 +00:00
|
|
|
package proxy
|
2022-01-04 16:47:18 +00:00
|
|
|
|
|
|
|
import (
|
2022-05-12 12:21:54 +00:00
|
|
|
"errors"
|
2022-06-05 05:50:55 +00:00
|
|
|
"io"
|
2022-01-04 16:47:18 +00:00
|
|
|
"net"
|
2022-03-04 23:46:47 +00:00
|
|
|
"time"
|
2022-01-11 15:05:16 +00:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
2022-01-04 16:47:18 +00:00
|
|
|
)
|
|
|
|
|
2024-08-15 07:50:03 +00:00
|
|
|
const (
|
|
|
|
BufferSize = 1024
|
|
|
|
TLSHeaderLen = 5
|
|
|
|
)
|
2022-01-10 17:11:30 +00:00
|
|
|
|
2024-08-08 18:47:34 +00:00
|
|
|
func ReadBytes(conn *net.TCPConn, dest []byte) ([]byte, error) {
|
|
|
|
n, err := readBytesInternal(conn, dest)
|
|
|
|
return dest[:n], err
|
|
|
|
}
|
2022-05-12 12:21:54 +00:00
|
|
|
|
2024-08-08 20:52:59 +00:00
|
|
|
func readBytesInternal(conn *net.TCPConn, dest []byte) (int, error) {
|
|
|
|
totalRead, err := conn.Read(dest)
|
|
|
|
if err != nil {
|
|
|
|
switch err.(type) {
|
|
|
|
case *net.OpError:
|
|
|
|
return totalRead, errors.New("timed out")
|
|
|
|
default:
|
|
|
|
return totalRead, err
|
2022-11-29 07:54:28 +00:00
|
|
|
}
|
|
|
|
}
|
2024-08-08 20:52:59 +00:00
|
|
|
return totalRead, nil
|
2022-01-04 16:47:18 +00:00
|
|
|
}
|
|
|
|
|
2024-08-15 07:50:03 +00:00
|
|
|
func Serve(from *net.TCPConn, to *net.TCPConn, proto string, fd string, td string, timeout int) {
|
2024-08-15 06:19:45 +00:00
|
|
|
defer func() {
|
|
|
|
from.Close()
|
|
|
|
to.Close()
|
|
|
|
|
2024-08-18 07:33:02 +00:00
|
|
|
log.Debugf("%s closing proxy connection: %s -> %s", proto, fd, td)
|
2024-08-15 06:19:45 +00:00
|
|
|
}()
|
|
|
|
|
2024-08-15 07:50:03 +00:00
|
|
|
buf := make([]byte, BufferSize)
|
2022-11-29 07:54:28 +00:00
|
|
|
for {
|
2024-08-08 18:47:34 +00:00
|
|
|
if timeout > 0 {
|
|
|
|
from.SetReadDeadline(
|
|
|
|
time.Now().Add(time.Millisecond * time.Duration(timeout)),
|
|
|
|
)
|
|
|
|
}
|
2023-09-08 08:35:41 +00:00
|
|
|
|
2024-08-08 18:47:34 +00:00
|
|
|
bytesRead, err := ReadBytes(from, buf)
|
2022-11-29 07:54:28 +00:00
|
|
|
if err != nil {
|
|
|
|
if err == io.EOF {
|
2024-08-18 07:33:02 +00:00
|
|
|
log.Debugf("%s finished reading from %s", proto, fd)
|
2022-11-29 07:54:28 +00:00
|
|
|
return
|
|
|
|
}
|
2024-08-18 07:33:02 +00:00
|
|
|
log.Debugf("%s error reading from %s: %s", proto, fd, err)
|
2022-11-29 07:54:28 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-08 18:47:34 +00:00
|
|
|
if _, err := to.Write(bytesRead); err != nil {
|
2024-08-18 07:33:02 +00:00
|
|
|
log.Debugf("%s error Writing to %s", proto, td)
|
2022-11-29 07:54:28 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2022-01-04 16:47:18 +00:00
|
|
|
}
|