http.go 1.8 KB

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