SpoofDPI/proxy/io.go

80 lines
1.2 KiB
Go
Raw Normal View History

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
)
const BUF_SIZE = 1024
2024-07-22 10:59:11 +00:00
func WriteChunks(conn *net.TCPConn, c [][]byte) (n int, err error) {
total := 0
for i := 0; i < len(c); i++ {
b, err := conn.Write(c[i])
if err != nil {
return 0, nil
}
total += b
}
return total, nil
}
2024-07-22 10:59:11 +00:00
func ReadBytes(conn *net.TCPConn) ([]byte, error) {
2022-11-29 07:54:28 +00:00
ret := make([]byte, 0)
buf := make([]byte, BUF_SIZE)
2022-05-12 12:21:54 +00:00
2022-11-29 07:54:28 +00:00
for {
n, err := conn.Read(buf)
if err != nil {
switch err.(type) {
case *net.OpError:
return nil, errors.New("timed out")
default:
return nil, err
}
}
ret = append(ret, buf[:n]...)
2022-01-04 16:47:18 +00:00
2022-11-29 07:54:28 +00:00
if n < BUF_SIZE {
break
}
}
2022-01-04 16:47:18 +00:00
2022-11-29 07:54:28 +00:00
if len(ret) == 0 {
return nil, io.EOF
}
2022-06-05 05:50:55 +00:00
2022-11-29 07:54:28 +00:00
return ret, nil
2022-01-04 16:47:18 +00:00
}
2024-07-22 10:59:11 +00:00
func Serve(from *net.TCPConn, to *net.TCPConn, proto string, fd string, td string, timeout int) {
proto += " "
2022-11-29 07:54:28 +00:00
for {
2024-07-22 10:59:11 +00:00
from.SetReadDeadline(
time.Now().Add(time.Millisecond * time.Duration(timeout)),
)
2023-09-08 08:35:41 +00:00
2024-07-22 10:59:11 +00:00
buf, err := ReadBytes(from)
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
}
if _, err := to.Write(buf); err != nil {
log.Debug(proto, "Error Writing to ", td)
return
}
}
2022-01-04 16:47:18 +00:00
}