2021-05-14 15:19:02 +00:00
|
|
|
package upgrade
|
2018-04-25 16:58:48 +00:00
|
|
|
|
|
|
|
import (
|
2018-09-29 12:39:12 +00:00
|
|
|
"crypto/sha1"
|
|
|
|
"encoding/base64"
|
2018-04-25 16:58:48 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
2021-06-15 22:04:09 +00:00
|
|
|
// constants
|
|
|
|
const (
|
|
|
|
httpVersion = "1.1"
|
|
|
|
wsVersion = 13
|
|
|
|
keySalt = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
|
|
|
)
|
2021-05-14 15:19:02 +00:00
|
|
|
|
2021-06-15 22:04:09 +00:00
|
|
|
// Response is an HTTP Upgrade Response
|
2021-05-14 15:19:02 +00:00
|
|
|
type Response struct {
|
2021-06-15 22:04:09 +00:00
|
|
|
StatusCode StatusCode
|
|
|
|
// Sec-WebSocket-Protocol or nil if missing
|
|
|
|
Protocol []byte
|
|
|
|
// processed from Sec-WebSocket-Key
|
|
|
|
key []byte
|
2018-04-25 16:58:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ProcessKey processes the accept token according
|
|
|
|
// to the rfc from the Sec-WebSocket-Key
|
2021-05-14 15:19:02 +00:00
|
|
|
func (r *Response) ProcessKey(k []byte) {
|
2021-06-15 22:04:09 +00:00
|
|
|
// ignore empty key
|
|
|
|
if k == nil || len(k) < 1 {
|
2018-04-28 14:23:07 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-06-15 22:04:09 +00:00
|
|
|
// concat with constant salt
|
|
|
|
salted := append(k, []byte(keySalt)...)
|
|
|
|
// hash with sha1
|
|
|
|
digest := sha1.Sum(salted)
|
|
|
|
// base64 encode
|
|
|
|
r.key = []byte(base64.StdEncoding.EncodeToString(digest[:sha1.Size]))
|
2018-04-25 16:58:48 +00:00
|
|
|
}
|
|
|
|
|
2021-06-15 22:04:09 +00:00
|
|
|
// WriteTo writes the response; typically in a socket
|
|
|
|
//
|
|
|
|
// implements io.WriterTo
|
|
|
|
func (r Response) WriteTo(w io.Writer) (int64, error) {
|
|
|
|
responseLine := fmt.Sprintf("HTTP/%s %d %s\r\n", httpVersion, r.StatusCode, r.StatusCode)
|
2018-04-25 16:58:48 +00:00
|
|
|
|
|
|
|
optionalProtocol := ""
|
2021-06-15 22:04:09 +00:00
|
|
|
if len(r.Protocol) > 0 {
|
|
|
|
optionalProtocol = fmt.Sprintf("Sec-WebSocket-Protocol: %s\r\n", r.Protocol)
|
2018-04-25 16:58:48 +00:00
|
|
|
}
|
|
|
|
|
2021-06-15 22:04:09 +00:00
|
|
|
headers := fmt.Sprintf("Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: %d\r\n%s", wsVersion, optionalProtocol)
|
|
|
|
if r.key != nil {
|
|
|
|
headers = fmt.Sprintf("%sSec-WebSocket-Accept: %s\r\n", headers, r.key)
|
2018-04-28 14:23:07 +00:00
|
|
|
}
|
|
|
|
headers = fmt.Sprintf("%s\r\n", headers)
|
2018-04-25 16:58:48 +00:00
|
|
|
|
2021-06-15 22:04:09 +00:00
|
|
|
combined := []byte(fmt.Sprintf("%s%s", responseLine, headers))
|
2018-04-25 16:58:48 +00:00
|
|
|
|
2021-06-15 22:04:09 +00:00
|
|
|
written, err := w.Write(combined)
|
|
|
|
return int64(written), err
|
2018-04-28 14:23:07 +00:00
|
|
|
|
2018-09-29 12:39:12 +00:00
|
|
|
}
|