Skip to content

Commit

Permalink
feat: add a timeout option for tcp detector
Browse files Browse the repository at this point in the history
  • Loading branch information
mrhaoxx committed Aug 13, 2024
1 parent f704425 commit f59461d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
14 changes: 13 additions & 1 deletion tcp/detect.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"net/http"
"reflect"
"time"

utils "github.com/mrhaoxx/OpenNG/utils"
)
Expand Down Expand Up @@ -40,6 +41,9 @@ type Detector func(io.Reader, *Conn) string

type Detect struct {
Dets []Detector

Timeout time.Duration
TimeoutProtocol string
}

// var detectors = []detector{
Expand All @@ -65,11 +69,19 @@ func (det *Detect) Handle(c *Conn) SerRet {
Writer: raw,
Rawconn: raw,
})
if det.Timeout > 0 {
raw.SetReadDeadline(time.Now().Add(det.Timeout))
defer raw.SetReadDeadline(time.Time{})
}
var proto string
for _, f := range det.Dets {
for i, f := range det.Dets {
if proto = f(buf, c); proto != "" {
break
}
if i == 0 && buf.buffer.Len() == 0 {
proto = det.TimeoutProtocol
break
}
buf.Reset(true)
}
if proto == "" {
Expand Down
16 changes: 14 additions & 2 deletions ui/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,14 @@ var _builtin_refs_assertions = map[string]Assert{
},
},
},
"timeout": {
Type: "int",
Default: 0,
},
"timeoutprotocol": {
Type: "string",
Default: "UNKNOWN",
},
},
},
"builtin::tcp::controller": {
Expand Down Expand Up @@ -879,6 +887,10 @@ var _builtin_refs = map[string]Inst{
},
"builtin::tcp::det": func(spec *ArgNode) (any, error) {
protocols := spec.MustGet("protocols").ToStringList()
timeout := spec.MustGet("timeout").ToInt()
_t := time.Duration(timeout)

timeoutprotocol := spec.MustGet("timeoutprotocol").ToString()

var dets []tcp.Detector
for _, p := range protocols {
Expand All @@ -898,9 +910,9 @@ var _builtin_refs = map[string]Inst{
}
}

log.Verboseln(fmt.Sprintf("new tcp detector: protocols=%#v", protocols))
log.Verboseln(fmt.Sprintf("new tcp detector: protocols=%#v timeout=%d(%s) timeoutprotocol=%s", protocols, timeout, _t.String(), timeoutprotocol))

return &tcp.Detect{Dets: dets}, nil
return &tcp.Detect{Dets: dets, Timeout: _t, TimeoutProtocol: timeoutprotocol}, nil
},
"builtin::tcp::controller": func(spec *ArgNode) (any, error) {
services := spec.MustGet("services").ToMap()
Expand Down

0 comments on commit f59461d

Please sign in to comment.