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
import (
"bytes"
"context"
"net/http"
"time"
"github.com/xtls/xray-core/common"
@@ -21,6 +23,16 @@ type Handler struct {
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.
func New(ctx context.Context, config *Config) (*Handler, error) {
response := []byte{}
@@ -28,7 +40,9 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
switch config.Response.Type {
case "", "none":
case "http":
response = http403response
var data bytes.Buffer
common.Must(http403response.Write(&data))
response = data.Bytes()
case "custom":
response = config.Response.CustomResponseData
default:
+12 -9
View File
@@ -1,8 +1,11 @@
package blackhole_test
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"net/http"
"testing"
"github.com/xtls/xray-core/common"
@@ -22,22 +25,22 @@ func TestBlackholeHTTPResponse(t *testing.T) {
reader, writer := pipe.New(pipe.WithoutSizeLimit())
var mb buf.MultiBuffer
var rerr error
dataCh := make(chan buf.MultiBuffer, 1)
go func() {
b, e := reader.ReadMultiBuffer()
mb = b
rerr = e
mb := common.Must2(reader.ReadMultiBuffer())
dataCh <- mb
}()
link := transport.Link{
Reader: reader,
Writer: writer,
}
common.Must(handler.Process(ctx, &link, nil))
common.Must(rerr)
if mb.IsEmpty() {
t.Error("expect http response, but nothing")
mb := <-dataCh
data := make([]byte, mb.Len())
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
`)