| 1 | // Copyright 2026 The frp Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | //go:build !frps |
| 16 | |
| 17 | package httpsserver |
| 18 | |
| 19 | import ( |
| 20 | "crypto/tls" |
| 21 | "fmt" |
| 22 | "net/http" |
| 23 | "time" |
| 24 | |
| 25 | "github.com/samber/lo" |
| 26 | |
| 27 | "github.com/fatedier/frp/pkg/transport" |
| 28 | httppkg "github.com/fatedier/frp/pkg/util/http" |
| 29 | ) |
| 30 | |
| 31 | func New(handler http.Handler, crtPath, keyPath string, enableHTTP2 *bool) (*http.Server, error) { |
| 32 | tlsConfig, err := transport.NewServerTLSConfig(crtPath, keyPath, "") |
| 33 | if err != nil { |
| 34 | return nil, fmt.Errorf("gen TLS config error: %v", err) |
| 35 | } |
| 36 | |
| 37 | server := &http.Server{ |
| 38 | Handler: withMisdirectedRequestCheck(handler), |
| 39 | ReadHeaderTimeout: 60 * time.Second, |
| 40 | TLSConfig: tlsConfig, |
| 41 | } |
| 42 | if !lo.FromPtr(enableHTTP2) { |
| 43 | server.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler)) |
| 44 | } |
| 45 | return server, nil |
| 46 | } |
| 47 | |
| 48 | func withMisdirectedRequestCheck(handler http.Handler) http.Handler { |
| 49 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 50 | if r.TLS != nil { |
| 51 | tlsServerName, _ := httppkg.CanonicalHost(r.TLS.ServerName) |
| 52 | host, _ := httppkg.CanonicalHost(r.Host) |
| 53 | if tlsServerName != "" && tlsServerName != host { |
| 54 | w.WriteHeader(http.StatusMisdirectedRequest) |
| 55 | return |
| 56 | } |
| 57 | } |
| 58 | handler.ServeHTTP(w, r) |
| 59 | }) |
| 60 | } |