dae/component/sniffing/http.go

68 lines
1.6 KiB
Go
Raw Normal View History

/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) 2022-2024, daeuniverse Organization <dae@v2raya.org>
*/
package sniffing
2023-02-15 11:54:25 +07:00
import (
"bufio"
2023-02-15 11:54:25 +07:00
"bytes"
"strings"
2023-02-15 11:54:25 +07:00
"unicode"
"github.com/daeuniverse/dae/common"
2023-02-15 11:54:25 +07:00
)
func (s *Sniffer) SniffHttp() (d string, err error) {
2023-02-15 11:54:25 +07:00
// First byte should be printable.
if s.buf.Len() == 0 || !unicode.IsPrint(rune(s.buf.Bytes()[0])) {
return "", ErrNotApplicable
2023-02-15 11:54:25 +07:00
}
// Search method.
search := s.buf.Bytes()
2023-02-15 11:54:25 +07:00
if len(search) > 12 {
search = search[:12]
}
method, _, found := bytes.Cut(search, []byte(" "))
if !found {
return "", ErrNotApplicable
}
if !common.IsValidHttpMethod(string(method)) {
return "", ErrNotApplicable
}
2023-02-15 11:54:25 +07:00
// Now we assume it is an HTTP packet. We should not return NotApplicableError after here.
// Search Host.
scanner := bufio.NewScanner(bytes.NewReader(s.buf.Bytes()))
// \r\n
scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.Index(data, []byte("\r\n")); i >= 0 {
// We have a full newline-terminated line.
return i + 2, data[0:i], nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
})
for scanner.Scan() && len(scanner.Bytes()) > 0 {
key, value, found := bytes.Cut(scanner.Bytes(), []byte{':'})
if !found {
// Bad key value.
continue
}
if strings.EqualFold(string(key), "host") {
return string(value), nil
}
}
return "", ErrNotFound
}