github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/hud/server/gorilla/origin.go (about)

     1  // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  //
     5  // Used from github.com/gorilla/websocket
     6  
     7  package gorilla
     8  
     9  import (
    10  	"net/http"
    11  	"net/url"
    12  	"unicode/utf8"
    13  )
    14  
    15  // checkSameOrigin returns true if the origin is not set or is equal to the request host.
    16  func CheckSameOrigin(r *http.Request) bool {
    17  	origin := r.Header["Origin"]
    18  	if len(origin) == 0 {
    19  		return true
    20  	}
    21  	u, err := url.Parse(origin[0])
    22  	if err != nil {
    23  		return false
    24  	}
    25  	return equalASCIIFold(u.Host, r.Host)
    26  }
    27  
    28  // equalASCIIFold returns true if s is equal to t with ASCII case folding as
    29  // defined in RFC 4790.
    30  func equalASCIIFold(s, t string) bool {
    31  	for s != "" && t != "" {
    32  		sr, size := utf8.DecodeRuneInString(s)
    33  		s = s[size:]
    34  		tr, size := utf8.DecodeRuneInString(t)
    35  		t = t[size:]
    36  		if sr == tr {
    37  			continue
    38  		}
    39  		if 'A' <= sr && sr <= 'Z' {
    40  			sr = sr + 'a' - 'A'
    41  		}
    42  		if 'A' <= tr && tr <= 'Z' {
    43  			tr = tr + 'a' - 'A'
    44  		}
    45  		if sr != tr {
    46  			return false
    47  		}
    48  	}
    49  	return s == t
    50  }