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-07-22 10:59:11 +00:00
|
|
|
func WriteChunks(conn *net.TCPConn, c [][]byte) (n int, err error) {
|
2022-01-10 17:11:30 +00:00
|
|
|
total := 0
|
|
|
|
for i := 0; i < len(c); i++ {
|
|
|
|
b, err := conn.Write(c[i])
|
|
|
|
if err != nil {
|
|
|
|
return 0, nil
|
|
|
|
}
|
|
|
|
|
2023-09-03 02:24:16 +00:00
|
|
|
total += b
|
2022-01-10 17:11:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return total, nil
|
|
|
|
}
|
|
|
|
|
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-08 18:47:34 +00:00
|
|
|
func Serve(from *net.TCPConn, to *net.TCPConn, proto string, fd string, td string, timeout int, bufferSize int) {
|
2022-01-14 08:23:41 +00:00
|
|
|
proto += " "
|
2024-08-08 18:47:34 +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 {
|
|
|
|
log.Debug(proto, "Finished ", fd)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
log.Debug(proto, "Error reading from ", fd, " ", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-08 18:47:34 +00:00
|
|
|
if _, err := to.Write(bytesRead); err != nil {
|
2022-11-29 07:54:28 +00:00
|
|
|
log.Debug(proto, "Error Writing to ", td)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2022-01-04 16:47:18 +00:00
|
|
|
}
|