SpoofDPI/util/util.go

132 lines
2.6 KiB
Go
Raw Normal View History

2021-12-29 17:08:30 +00:00
package util
import (
2022-01-03 07:24:39 +00:00
"log"
"net"
"strings"
2022-01-03 08:12:51 +00:00
"errors"
2022-01-03 07:24:39 +00:00
"github.com/babolivier/go-doh-client"
"github.com/xvzc/SpoofDPI/config"
2021-12-29 17:08:30 +00:00
)
2022-01-03 07:24:39 +00:00
const BUF_SIZE = 1024
2022-01-02 12:56:24 +00:00
func WriteAndRead(conn net.Conn, message []byte) ([]byte, error){
_, err := conn.Write(message)
if err != nil {
log.Fatal("Error writing to client:", err)
return nil, err
}
// defer conn.(*net.TCPConn).CloseWrite()
buf, err := ReadMessage(conn)
if err != nil {
log.Fatal("failed:", err)
return nil, err
}
return buf, nil
}
2021-12-29 17:08:30 +00:00
func ReadMessage(conn net.Conn)([]byte, error) {
2022-01-03 07:24:39 +00:00
buf := make([]byte, 0) // big buffer
tmp := make([]byte, BUF_SIZE) // using small tmo buffer for demonstrating
2021-12-29 17:08:30 +00:00
for {
n, err := conn.Read(tmp)
if err != nil {
2022-01-02 15:24:59 +00:00
return nil, err
2021-12-29 17:08:30 +00:00
}
buf = append(buf, tmp[:n]...)
2022-01-03 07:24:39 +00:00
if n < BUF_SIZE {
2021-12-29 17:08:30 +00:00
break
}
}
return buf, nil
}
func ExtractDomain(message *[]byte) (string) {
i := 0
for ; i < len(*message); i++ {
if (*message)[i] == '\n' {
i++
break;
}
}
for ; i < len(*message); i++ {
if (*message)[i] == ' ' {
i++
break;
}
}
j := i
for ; j < len(*message); j++ {
if (*message)[j] == '\n' {
break;
}
}
domain := strings.Split(string((*message)[i:j]), ":")[0]
return strings.TrimSpace(domain)
}
func DnsLookupOverHttps(dns string, domain string)(string, error) {
// Perform a A lookup on example.com
resolver := doh.Resolver{
Host: dns, // Change this with your favourite DoH-compliant resolver.
Class: doh.IN,
}
log.Println(domain)
a, _, err := resolver.LookupA(domain)
if err != nil {
2022-01-02 15:24:59 +00:00
log.Println("Error looking up dns. ", err)
2021-12-29 17:08:30 +00:00
return "", err
}
ip := a[0].IP4
return ip, nil
}
func ExtractMethod(message *[]byte) (string) {
i := 0
for ; i < len(*message); i++ {
if (*message)[i] == ' ' {
break;
}
}
method := strings.TrimSpace(string((*message)[:i]))
log.Println(method)
return strings.ToUpper(method)
}
2022-01-03 07:24:39 +00:00
2022-01-03 08:12:51 +00:00
func SplitSliceInChunks(a []byte, size int) ([][]byte, error) {
if size < 1 {
return nil, errors.New("chuckSize must be greater than zero")
}
chunks := make([][]byte, 0, (len(a)+size-1)/size)
for size < len(a) {
a, chunks = a[size:], append(chunks, a[0:size:size])
}
chunks = append(chunks, a)
return chunks, nil
}
2022-01-03 07:24:39 +00:00
func Debug(v ...interface{}) {
if config.GetConfig().Debug == false {
return
}
log.Println(v...)
}