1 // Copyright 2015 go-swagger maintainers 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 package swag 16 17 import ( 18 "fmt" 19 "io" 20 "log" 21 "net/http" 22 "net/url" 23 "os" 24 "path" 25 "path/filepath" 26 "runtime" 27 "strings" 28 "time" 29 ) 30 31 // LoadHTTPTimeout the default timeout for load requests 32 var LoadHTTPTimeout = 30 * time.Second 33 34 // LoadHTTPBasicAuthUsername the username to use when load requests require basic auth 35 var LoadHTTPBasicAuthUsername = "" 36 37 // LoadHTTPBasicAuthPassword the password to use when load requests require basic auth 38 var LoadHTTPBasicAuthPassword = "" 39 40 // LoadHTTPCustomHeaders an optional collection of custom HTTP headers for load requests 41 var LoadHTTPCustomHeaders = map[string]string{} 42 43 // LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in 44 func LoadFromFileOrHTTP(pth string) ([]byte, error) { 45 return LoadStrategy(pth, os.ReadFile, loadHTTPBytes(LoadHTTPTimeout))(pth) 46 } 47 48 // LoadFromFileOrHTTPWithTimeout loads the bytes from a file or a remote http server based on the path passed in 49 // timeout arg allows for per request overriding of the request timeout 50 func LoadFromFileOrHTTPWithTimeout(pth string, timeout time.Duration) ([]byte, error) { 51 return LoadStrategy(pth, os.ReadFile, loadHTTPBytes(timeout))(pth) 52 } 53 54 // LoadStrategy returns a loader function for a given path or URI. 55 // 56 // The load strategy returns the remote load for any path starting with `http`. 57 // So this works for any URI with a scheme `http` or `https`. 58 // 59 // The fallback strategy is to call the local loader. 60 // 61 // The local loader takes a local file system path (absolute or relative) as argument, 62 // or alternatively a `file://...` URI, **without host** (see also below for windows). 63 // 64 // There are a few liberalities, initially intended to be tolerant regarding the URI syntax, 65 // especially on windows. 66 // 67 // Before the local loader is called, the given path is transformed: 68 // - percent-encoded characters are unescaped 69 // - simple paths (e.g. `./folder/file`) are passed as-is 70 // - on windows, occurrences of `/` are replaced by `\`, so providing a relative path such a `folder/file` works too. 71 // 72 // For paths provided as URIs with the "file" scheme, please note that: 73 // - `file://` is simply stripped. 74 // This means that the host part of the URI is not parsed at all. 75 // For example, `file:///folder/file" becomes "/folder/file`, 76 // but `file://localhost/folder/file` becomes `localhost/folder/file` on unix systems. 77 // Similarly, `file://./folder/file` yields `./folder/file`. 78 // - on windows, `file://...` can take a host so as to specify an UNC share location. 79 // 80 // Reminder about windows-specifics: 81 // - `file://host/folder/file` becomes an UNC path like `\\host\folder\file` (no port specification is supported) 82 // - `file:///c:/folder/file` becomes `C:\folder\file` 83 // - `file://c:/folder/file` is tolerated (without leading `/`) and becomes `c:\folder\file` 84 func LoadStrategy(pth string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) { 85 if strings.HasPrefix(pth, "http") { 86 return remote 87 } 88 89 return func(p string) ([]byte, error) { 90 upth, err := url.PathUnescape(p) 91 if err != nil { 92 return nil, err 93 } 94 95 if !strings.HasPrefix(p, `file://`) { 96 // regular file path provided: just normalize slashes 97 return local(filepath.FromSlash(upth)) 98 } 99 100 if runtime.GOOS != "windows" { 101 // crude processing: this leaves full URIs with a host with a (mostly) unexpected result 102 upth = strings.TrimPrefix(upth, `file://`) 103 104 return local(filepath.FromSlash(upth)) 105 } 106 107 // windows-only pre-processing of file://... URIs 108 109 // support for canonical file URIs on windows. 110 u, err := url.Parse(filepath.ToSlash(upth)) 111 if err != nil { 112 return nil, err 113 } 114 115 if u.Host != "" { 116 // assume UNC name (volume share) 117 // NOTE: UNC port not yet supported 118 119 // when the "host" segment is a drive letter: 120 // file://C:/folder/... => C:\folder 121 upth = path.Clean(strings.Join([]string{u.Host, u.Path}, `/`)) 122 if !strings.HasSuffix(u.Host, ":") && u.Host[0] != '.' { 123 // tolerance: if we have a leading dot, this can't be a host 124 // file://host/share/folder\... ==> \\host\share\path\folder 125 upth = "//" + upth 126 } 127 } else { 128 // no host, let's figure out if this is a drive letter 129 upth = strings.TrimPrefix(upth, `file://`) 130 first, _, _ := strings.Cut(strings.TrimPrefix(u.Path, "/"), "/") 131 if strings.HasSuffix(first, ":") { 132 // drive letter in the first segment: 133 // file:///c:/folder/... ==> strip the leading slash 134 upth = strings.TrimPrefix(upth, `/`) 135 } 136 } 137 138 return local(filepath.FromSlash(upth)) 139 } 140 } 141 142 func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) { 143 return func(path string) ([]byte, error) { 144 client := &http.Client{Timeout: timeout} 145 req, err := http.NewRequest(http.MethodGet, path, nil) //nolint:noctx 146 if err != nil { 147 return nil, err 148 } 149 150 if LoadHTTPBasicAuthUsername != "" && LoadHTTPBasicAuthPassword != "" { 151 req.SetBasicAuth(LoadHTTPBasicAuthUsername, LoadHTTPBasicAuthPassword) 152 } 153 154 for key, val := range LoadHTTPCustomHeaders { 155 req.Header.Set(key, val) 156 } 157 158 resp, err := client.Do(req) 159 defer func() { 160 if resp != nil { 161 if e := resp.Body.Close(); e != nil { 162 log.Println(e) 163 } 164 } 165 }() 166 if err != nil { 167 return nil, err 168 } 169 170 if resp.StatusCode != http.StatusOK { 171 return nil, fmt.Errorf("could not access document at %q [%s] ", path, resp.Status) 172 } 173 174 return io.ReadAll(resp.Body) 175 } 176 } 177