github.com/inazumav/sing-box@v0.0.0-20230926072359-ab51429a14f1/transport/hysteria2/internal/protocol/http.go (about)

     1  package protocol
     2  
     3  import (
     4  	"net/http"
     5  	"strconv"
     6  )
     7  
     8  const (
     9  	URLHost = "hysteria"
    10  	URLPath = "/auth"
    11  
    12  	RequestHeaderAuth        = "Hysteria-Auth"
    13  	ResponseHeaderUDPEnabled = "Hysteria-UDP"
    14  	CommonHeaderCCRX         = "Hysteria-CC-RX"
    15  	CommonHeaderPadding      = "Hysteria-Padding"
    16  
    17  	StatusAuthOK = 233
    18  )
    19  
    20  // AuthRequest is what client sends to server for authentication.
    21  type AuthRequest struct {
    22  	Auth string
    23  	Rx   uint64 // 0 = unknown, client asks server to use bandwidth detection
    24  }
    25  
    26  // AuthResponse is what server sends to client when authentication is passed.
    27  type AuthResponse struct {
    28  	UDPEnabled bool
    29  	Rx         uint64 // 0 = unlimited
    30  	RxAuto     bool   // true = server asks client to use bandwidth detection
    31  }
    32  
    33  func AuthRequestFromHeader(h http.Header) AuthRequest {
    34  	rx, _ := strconv.ParseUint(h.Get(CommonHeaderCCRX), 10, 64)
    35  	return AuthRequest{
    36  		Auth: h.Get(RequestHeaderAuth),
    37  		Rx:   rx,
    38  	}
    39  }
    40  
    41  func AuthRequestToHeader(h http.Header, req AuthRequest) {
    42  	h.Set(RequestHeaderAuth, req.Auth)
    43  	h.Set(CommonHeaderCCRX, strconv.FormatUint(req.Rx, 10))
    44  	h.Set(CommonHeaderPadding, authRequestPadding.String())
    45  }
    46  
    47  func AuthResponseFromHeader(h http.Header) AuthResponse {
    48  	resp := AuthResponse{}
    49  	resp.UDPEnabled, _ = strconv.ParseBool(h.Get(ResponseHeaderUDPEnabled))
    50  	rxStr := h.Get(CommonHeaderCCRX)
    51  	if rxStr == "auto" {
    52  		// Special case for server requesting client to use bandwidth detection
    53  		resp.RxAuto = true
    54  	} else {
    55  		resp.Rx, _ = strconv.ParseUint(rxStr, 10, 64)
    56  	}
    57  	return resp
    58  }
    59  
    60  func AuthResponseToHeader(h http.Header, resp AuthResponse) {
    61  	h.Set(ResponseHeaderUDPEnabled, strconv.FormatBool(resp.UDPEnabled))
    62  	if resp.RxAuto {
    63  		h.Set(CommonHeaderCCRX, "auto")
    64  	} else {
    65  		h.Set(CommonHeaderCCRX, strconv.FormatUint(resp.Rx, 10))
    66  	}
    67  	h.Set(CommonHeaderPadding, authResponsePadding.String())
    68  }