This commit is contained in:
Fangliding
2026-09-03 02:21:01 +08:00
parent f49d8b89c8
commit bd60b01576
3 changed files with 27 additions and 19 deletions
+15 -1
View File
@@ -2,7 +2,9 @@
package blackhole package blackhole
import ( import (
"bytes"
"context" "context"
"net/http"
"time" "time"
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
@@ -21,6 +23,16 @@ type Handler struct {
response []byte response []byte
} }
var http403response = http.Response{
StatusCode: 403,
ProtoMajor: 1,
ProtoMinor: 1,
Header: http.Header{
"Connection": {"close"},
"Cache-Control": {"max-age=3600, public"},
},
}
// New creates a new blackhole handler. // New creates a new blackhole handler.
func New(ctx context.Context, config *Config) (*Handler, error) { func New(ctx context.Context, config *Config) (*Handler, error) {
response := []byte{} response := []byte{}
@@ -28,7 +40,9 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
switch config.Response.Type { switch config.Response.Type {
case "", "none": case "", "none":
case "http": case "http":
response = http403response var data bytes.Buffer
common.Must(http403response.Write(&data))
response = data.Bytes()
case "custom": case "custom":
response = config.Response.CustomResponseData response = config.Response.CustomResponseData
default: default:
+12 -9
View File
@@ -1,8 +1,11 @@
package blackhole_test package blackhole_test
import ( import (
"bufio"
"bytes"
"context" "context"
"crypto/rand" "crypto/rand"
"net/http"
"testing" "testing"
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
@@ -22,22 +25,22 @@ func TestBlackholeHTTPResponse(t *testing.T) {
reader, writer := pipe.New(pipe.WithoutSizeLimit()) reader, writer := pipe.New(pipe.WithoutSizeLimit())
var mb buf.MultiBuffer dataCh := make(chan buf.MultiBuffer, 1)
var rerr error
go func() { go func() {
b, e := reader.ReadMultiBuffer() mb := common.Must2(reader.ReadMultiBuffer())
mb = b dataCh <- mb
rerr = e
}() }()
link := transport.Link{ link := transport.Link{
Reader: reader, Reader: reader,
Writer: writer, Writer: writer,
} }
common.Must(handler.Process(ctx, &link, nil)) common.Must(handler.Process(ctx, &link, nil))
common.Must(rerr) mb := <-dataCh
if mb.IsEmpty() { data := make([]byte, mb.Len())
t.Error("expect http response, but nothing") mb.Copy(data)
resp := common.Must2(http.ReadResponse(bufio.NewReader(bytes.NewBuffer(data)), nil))
if resp.StatusCode != 403 {
t.Errorf("expected 403 response, got %d", resp.StatusCode)
} }
} }
-9
View File
@@ -1,9 +0,0 @@
package blackhole
var http403response = []byte(`HTTP/1.1 403 Forbidden
Connection: close
Cache-Control: max-age=3600, public
Content-Length: 0
`)