You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1168 lines
34 KiB

directio: Check if buffers are set. (#13440) Check if directio buffers have actually been fetched and prevent errors on double Close. Return error on Read after Close. Fixes ``` panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0xf8582f] goroutine 210 [running]: github.com/minio/minio/internal/ioutil.(*ODirectReader).Read(0xc0054f8320, {0xc0014560b0, 0xa8, 0x44d012}) github.com/minio/minio/internal/ioutil/odirect_reader.go:88 +0x10f io.ReadAtLeast({0x428c5c0, 0xc0054f8320}, {0xc0014560b0, 0xa8, 0xa8}, 0xa8) io/io.go:328 +0x9a io.ReadFull(...) io/io.go:347 github.com/minio/minio/internal/ioutil.ReadFile({0xc001bf60e0, 0x6}) github.com/minio/minio/internal/ioutil/read_file.go:48 +0x19b github.com/minio/minio/cmd.(*FSObjects).scanBucket.func1({{0xc00444e1e0, 0x4d}, 0x0, {0xc0040cf240, 0xe}, {0xc0040cf24f, 0x18}, {0xc0040cf268, 0x18}, 0x0, ...}) github.com/minio/minio/cmd/fs-v1.go:366 +0x1ea github.com/minio/minio/cmd.(*folderScanner).scanFolder.func1({0xc00474a6a8, 0xc0065d6793}, 0x0) github.com/minio/minio/cmd/data-scanner.go:494 +0xb15 github.com/minio/minio/cmd.readDirFn({0xc002803e80, 0x34}, 0xc000670270) github.com/minio/minio/cmd/os-readdir_unix.go:172 +0x638 github.com/minio/minio/cmd.(*folderScanner).scanFolder(0xc002deeb40, {0x42dc9d0, 0xc00068cbc0}, {{0xc001c6e2d0, 0x27}, 0xc0023db8e0, 0x1}, 0xc0001c7ab0) github.com/minio/minio/cmd/data-scanner.go:427 +0xa8f github.com/minio/minio/cmd.(*folderScanner).scanFolder.func2({{0xc001c6e2d0, 0x27}, 0xc0023db8e0, 0x27}) github.com/minio/minio/cmd/data-scanner.go:549 +0xd0 github.com/minio/minio/cmd.(*folderScanner).scanFolder(0xc002deeb40, {0x42dc9d0, 0xc00068cbc0}, {{0xc0013fa9e0, 0xe}, 0x0, 0x1}, 0xc000670dd8) github.com/minio/minio/cmd/data-scanner.go:623 +0x205d github.com/minio/minio/cmd.scanDataFolder({_, _}, {_, _}, {{{0xc0013fa9e0, 0xe}, 0x802, {0x210f15d2, 0xed8f903b8, 0x5bc0e80}, ...}, ...}, ...) github.com/minio/minio/cmd/data-scanner.go:333 +0xc51 github.com/minio/minio/cmd.(*FSObjects).scanBucket(_, {_, _}, {_, _}, {{{0xc0013fa9e0, 0xe}, 0x802, {0x210f15d2, 0xed8f903b8, ...}, ...}, ...}) github.com/minio/minio/cmd/fs-v1.go:364 +0x305 github.com/minio/minio/cmd.(*FSObjects).NSScanner(0x42dc9d0, {0x42dc9d0, 0xc00068cbc0}, 0x0, 0xc003bcfda0, 0x802) github.com/minio/minio/cmd/fs-v1.go:307 +0xa16 github.com/minio/minio/cmd.runDataScanner({0x42dc9d0, 0xc00068cbc0}, {0x436a6c0, 0xc000bfcf50}) github.com/minio/minio/cmd/data-scanner.go:150 +0x749 created by github.com/minio/minio/cmd.initDataScanner github.com/minio/minio/cmd/data-scanner.go:73 +0xb0 ```
4 years ago
  1. // Copyright (c) 2015-2021 MinIO, Inc.
  2. //
  3. // This file is part of MinIO Object Storage stack
  4. //
  5. // This program is free software: you can redistribute it and/or modify
  6. // it under the terms of the GNU Affero General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // This program is distributed in the hope that it will be useful
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU Affero General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Affero General Public License
  16. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. package cmd
  18. import (
  19. "bytes"
  20. "context"
  21. "crypto/tls"
  22. "encoding/json"
  23. "encoding/xml"
  24. "errors"
  25. "fmt"
  26. "io"
  27. "io/ioutil"
  28. "net"
  29. "net/http"
  30. "net/url"
  31. "os"
  32. "path"
  33. "path/filepath"
  34. "reflect"
  35. "runtime"
  36. "runtime/pprof"
  37. "runtime/trace"
  38. "strings"
  39. "sync"
  40. "syscall"
  41. "time"
  42. "github.com/coreos/go-oidc"
  43. "github.com/dustin/go-humanize"
  44. "github.com/gorilla/mux"
  45. "github.com/minio/madmin-go"
  46. miniogopolicy "github.com/minio/minio-go/v7/pkg/policy"
  47. "github.com/minio/minio/internal/config"
  48. "github.com/minio/minio/internal/config/api"
  49. xtls "github.com/minio/minio/internal/config/identity/tls"
  50. "github.com/minio/minio/internal/fips"
  51. "github.com/minio/minio/internal/handlers"
  52. xhttp "github.com/minio/minio/internal/http"
  53. "github.com/minio/minio/internal/logger"
  54. "github.com/minio/minio/internal/logger/message/audit"
  55. "github.com/minio/minio/internal/rest"
  56. "github.com/minio/pkg/certs"
  57. "github.com/minio/pkg/env"
  58. "golang.org/x/oauth2"
  59. )
  60. const (
  61. slashSeparator = "/"
  62. )
  63. // BucketAccessPolicy - Collection of canned bucket policy at a given prefix.
  64. type BucketAccessPolicy struct {
  65. Bucket string `json:"bucket"`
  66. Prefix string `json:"prefix"`
  67. Policy miniogopolicy.BucketPolicy `json:"policy"`
  68. }
  69. // IsErrIgnored returns whether given error is ignored or not.
  70. func IsErrIgnored(err error, ignoredErrs ...error) bool {
  71. return IsErr(err, ignoredErrs...)
  72. }
  73. // IsErr returns whether given error is exact error.
  74. func IsErr(err error, errs ...error) bool {
  75. for _, exactErr := range errs {
  76. if errors.Is(err, exactErr) {
  77. return true
  78. }
  79. }
  80. return false
  81. }
  82. func request2BucketObjectName(r *http.Request) (bucketName, objectName string) {
  83. path, err := getResource(r.URL.Path, r.Host, globalDomainNames)
  84. if err != nil {
  85. logger.CriticalIf(GlobalContext, err)
  86. }
  87. return path2BucketObject(path)
  88. }
  89. // path2BucketObjectWithBasePath returns bucket and prefix, if any,
  90. // of a 'path'. basePath is trimmed from the front of the 'path'.
  91. func path2BucketObjectWithBasePath(basePath, path string) (bucket, prefix string) {
  92. path = strings.TrimPrefix(path, basePath)
  93. path = strings.TrimPrefix(path, SlashSeparator)
  94. m := strings.Index(path, SlashSeparator)
  95. if m < 0 {
  96. return path, ""
  97. }
  98. return path[:m], path[m+len(SlashSeparator):]
  99. }
  100. func path2BucketObject(s string) (bucket, prefix string) {
  101. return path2BucketObjectWithBasePath("", s)
  102. }
  103. func getWriteQuorum(drive int) int {
  104. parity := getDefaultParityBlocks(drive)
  105. quorum := drive - parity
  106. if quorum == parity {
  107. quorum++
  108. }
  109. return quorum
  110. }
  111. // cloneMSS will clone a map[string]string.
  112. // If input is nil an empty map is returned, not nil.
  113. func cloneMSS(v map[string]string) map[string]string {
  114. r := make(map[string]string, len(v))
  115. for k, v := range v {
  116. r[k] = v
  117. }
  118. return r
  119. }
  120. // URI scheme constants.
  121. const (
  122. httpScheme = "http"
  123. httpsScheme = "https"
  124. )
  125. // nopCharsetConverter is a dummy charset convert which just copies input to output,
  126. // it is used to ignore custom encoding charset in S3 XML body.
  127. func nopCharsetConverter(label string, input io.Reader) (io.Reader, error) {
  128. return input, nil
  129. }
  130. // xmlDecoder provide decoded value in xml.
  131. func xmlDecoder(body io.Reader, v interface{}, size int64) error {
  132. var lbody io.Reader
  133. if size > 0 {
  134. lbody = io.LimitReader(body, size)
  135. } else {
  136. lbody = body
  137. }
  138. d := xml.NewDecoder(lbody)
  139. // Ignore any encoding set in the XML body
  140. d.CharsetReader = nopCharsetConverter
  141. return d.Decode(v)
  142. }
  143. // hasContentMD5 returns true if Content-MD5 header is set.
  144. func hasContentMD5(h http.Header) bool {
  145. _, ok := h[xhttp.ContentMD5]
  146. return ok
  147. }
  148. // http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html
  149. const (
  150. // Maximum object size per PUT request is 5TB.
  151. // This is a divergence from S3 limit on purpose to support
  152. // use cases where users are going to upload large files
  153. // using 'curl' and presigned URL.
  154. globalMaxObjectSize = 5 * humanize.TiByte
  155. // Minimum Part size for multipart upload is 5MiB
  156. globalMinPartSize = 5 * humanize.MiByte
  157. // Maximum Part size for multipart upload is 5GiB
  158. globalMaxPartSize = 5 * humanize.GiByte
  159. // Maximum Part ID for multipart upload is 10000
  160. // (Acceptable values range from 1 to 10000 inclusive)
  161. globalMaxPartID = 10000
  162. // Default values used while communicating for gateway communication
  163. defaultDialTimeout = 5 * time.Second
  164. )
  165. // isMaxObjectSize - verify if max object size
  166. func isMaxObjectSize(size int64) bool {
  167. return size > globalMaxObjectSize
  168. }
  169. // // Check if part size is more than maximum allowed size.
  170. func isMaxAllowedPartSize(size int64) bool {
  171. return size > globalMaxPartSize
  172. }
  173. // Check if part size is more than or equal to minimum allowed size.
  174. func isMinAllowedPartSize(size int64) bool {
  175. return size >= globalMinPartSize
  176. }
  177. // isMaxPartNumber - Check if part ID is greater than the maximum allowed ID.
  178. func isMaxPartID(partID int) bool {
  179. return partID > globalMaxPartID
  180. }
  181. func contains(slice interface{}, elem interface{}) bool {
  182. v := reflect.ValueOf(slice)
  183. if v.Kind() == reflect.Slice {
  184. for i := 0; i < v.Len(); i++ {
  185. if v.Index(i).Interface() == elem {
  186. return true
  187. }
  188. }
  189. }
  190. return false
  191. }
  192. // profilerWrapper is created becauses pkg/profiler doesn't
  193. // provide any API to calculate the profiler file path in the
  194. // disk since the name of this latter is randomly generated.
  195. type profilerWrapper struct {
  196. // Profile recorded at start of benchmark.
  197. records map[string][]byte
  198. stopFn func() ([]byte, error)
  199. ext string
  200. }
  201. // record will record the profile and store it as the base.
  202. func (p *profilerWrapper) record(profileType string, debug int, recordName string) {
  203. var buf bytes.Buffer
  204. if p.records == nil {
  205. p.records = make(map[string][]byte)
  206. }
  207. err := pprof.Lookup(profileType).WriteTo(&buf, debug)
  208. if err != nil {
  209. return
  210. }
  211. p.records[recordName] = buf.Bytes()
  212. }
  213. // Records returns the recorded profiling if any.
  214. func (p profilerWrapper) Records() map[string][]byte {
  215. return p.records
  216. }
  217. // Stop the currently running benchmark.
  218. func (p profilerWrapper) Stop() ([]byte, error) {
  219. return p.stopFn()
  220. }
  221. // Extension returns the extension without dot prefix.
  222. func (p profilerWrapper) Extension() string {
  223. return p.ext
  224. }
  225. // Returns current profile data, returns error if there is no active
  226. // profiling in progress. Stops an active profile.
  227. func getProfileData() (map[string][]byte, error) {
  228. globalProfilerMu.Lock()
  229. defer globalProfilerMu.Unlock()
  230. if len(globalProfiler) == 0 {
  231. return nil, errors.New("profiler not enabled")
  232. }
  233. dst := make(map[string][]byte, len(globalProfiler))
  234. for typ, prof := range globalProfiler {
  235. // Stop the profiler
  236. var err error
  237. buf, err := prof.Stop()
  238. delete(globalProfiler, typ)
  239. if err == nil {
  240. dst[typ+"."+prof.Extension()] = buf
  241. }
  242. for name, buf := range prof.Records() {
  243. if len(buf) > 0 {
  244. dst[typ+"-"+name+"."+prof.Extension()] = buf
  245. }
  246. }
  247. }
  248. return dst, nil
  249. }
  250. func setDefaultProfilerRates() {
  251. runtime.MemProfileRate = 4096 // 512K -> 4K - Must be constant throughout application lifetime.
  252. runtime.SetMutexProfileFraction(0) // Disable until needed
  253. runtime.SetBlockProfileRate(0) // Disable until needed
  254. }
  255. // Starts a profiler returns nil if profiler is not enabled, caller needs to handle this.
  256. func startProfiler(profilerType string) (minioProfiler, error) {
  257. var prof profilerWrapper
  258. prof.ext = "pprof"
  259. // Enable profiler and set the name of the file that pkg/pprof
  260. // library creates to store profiling data.
  261. switch madmin.ProfilerType(profilerType) {
  262. case madmin.ProfilerCPU:
  263. dirPath, err := ioutil.TempDir("", "profile")
  264. if err != nil {
  265. return nil, err
  266. }
  267. fn := filepath.Join(dirPath, "cpu.out")
  268. f, err := os.Create(fn)
  269. if err != nil {
  270. return nil, err
  271. }
  272. err = pprof.StartCPUProfile(f)
  273. if err != nil {
  274. return nil, err
  275. }
  276. prof.stopFn = func() ([]byte, error) {
  277. pprof.StopCPUProfile()
  278. err := f.Close()
  279. if err != nil {
  280. return nil, err
  281. }
  282. defer os.RemoveAll(dirPath)
  283. return ioutil.ReadFile(fn)
  284. }
  285. case madmin.ProfilerMEM:
  286. runtime.GC()
  287. prof.record("heap", 0, "before")
  288. prof.stopFn = func() ([]byte, error) {
  289. runtime.GC()
  290. var buf bytes.Buffer
  291. err := pprof.Lookup("heap").WriteTo(&buf, 0)
  292. return buf.Bytes(), err
  293. }
  294. case madmin.ProfilerBlock:
  295. runtime.SetBlockProfileRate(100)
  296. prof.stopFn = func() ([]byte, error) {
  297. var buf bytes.Buffer
  298. err := pprof.Lookup("block").WriteTo(&buf, 0)
  299. runtime.SetBlockProfileRate(0)
  300. return buf.Bytes(), err
  301. }
  302. case madmin.ProfilerMutex:
  303. prof.record("mutex", 0, "before")
  304. runtime.SetMutexProfileFraction(1)
  305. prof.stopFn = func() ([]byte, error) {
  306. var buf bytes.Buffer
  307. err := pprof.Lookup("mutex").WriteTo(&buf, 0)
  308. runtime.SetMutexProfileFraction(0)
  309. return buf.Bytes(), err
  310. }
  311. case madmin.ProfilerThreads:
  312. prof.record("threadcreate", 0, "before")
  313. prof.stopFn = func() ([]byte, error) {
  314. var buf bytes.Buffer
  315. err := pprof.Lookup("threadcreate").WriteTo(&buf, 0)
  316. return buf.Bytes(), err
  317. }
  318. case madmin.ProfilerGoroutines:
  319. prof.ext = "txt"
  320. prof.record("goroutine", 1, "before")
  321. prof.record("goroutine", 2, "before,debug=2")
  322. prof.stopFn = func() ([]byte, error) {
  323. var buf bytes.Buffer
  324. err := pprof.Lookup("goroutine").WriteTo(&buf, 1)
  325. return buf.Bytes(), err
  326. }
  327. case madmin.ProfilerTrace:
  328. dirPath, err := ioutil.TempDir("", "profile")
  329. if err != nil {
  330. return nil, err
  331. }
  332. fn := filepath.Join(dirPath, "trace.out")
  333. f, err := os.Create(fn)
  334. if err != nil {
  335. return nil, err
  336. }
  337. err = trace.Start(f)
  338. if err != nil {
  339. return nil, err
  340. }
  341. prof.ext = "trace"
  342. prof.stopFn = func() ([]byte, error) {
  343. trace.Stop()
  344. err := f.Close()
  345. if err != nil {
  346. return nil, err
  347. }
  348. defer os.RemoveAll(dirPath)
  349. return ioutil.ReadFile(fn)
  350. }
  351. default:
  352. return nil, errors.New("profiler type unknown")
  353. }
  354. return prof, nil
  355. }
  356. // minioProfiler - minio profiler interface.
  357. type minioProfiler interface {
  358. // Return recorded profiles, each profile associated with a distinct generic name.
  359. Records() map[string][]byte
  360. // Stop the profiler
  361. Stop() ([]byte, error)
  362. // Return extension of profile
  363. Extension() string
  364. }
  365. // Global profiler to be used by service go-routine.
  366. var (
  367. globalProfiler map[string]minioProfiler
  368. globalProfilerMu sync.Mutex
  369. )
  370. // dump the request into a string in JSON format.
  371. func dumpRequest(r *http.Request) string {
  372. header := r.Header.Clone()
  373. header.Set("Host", r.Host)
  374. // Replace all '%' to '%%' so that printer format parser
  375. // to ignore URL encoded values.
  376. rawURI := strings.ReplaceAll(r.RequestURI, "%", "%%")
  377. req := struct {
  378. Method string `json:"method"`
  379. RequestURI string `json:"reqURI"`
  380. Header http.Header `json:"header"`
  381. }{r.Method, rawURI, header}
  382. var buffer bytes.Buffer
  383. enc := json.NewEncoder(&buffer)
  384. enc.SetEscapeHTML(false)
  385. if err := enc.Encode(&req); err != nil {
  386. // Upon error just return Go-syntax representation of the value
  387. return fmt.Sprintf("%#v", req)
  388. }
  389. // Formatted string.
  390. return strings.TrimSpace(buffer.String())
  391. }
  392. // isFile - returns whether given path is a file or not.
  393. func isFile(path string) bool {
  394. if fi, err := os.Stat(path); err == nil {
  395. return fi.Mode().IsRegular()
  396. }
  397. return false
  398. }
  399. // UTCNow - returns current UTC time.
  400. func UTCNow() time.Time {
  401. return time.Now().UTC()
  402. }
  403. // GenETag - generate UUID based ETag
  404. func GenETag() string {
  405. return ToS3ETag(getMD5Hash([]byte(mustGetUUID())))
  406. }
  407. // ToS3ETag - return checksum to ETag
  408. func ToS3ETag(etag string) string {
  409. etag = canonicalizeETag(etag)
  410. if !strings.HasSuffix(etag, "-1") {
  411. // Tools like s3cmd uses ETag as checksum of data to validate.
  412. // Append "-1" to indicate ETag is not a checksum.
  413. etag += "-1"
  414. }
  415. return etag
  416. }
  417. func newInternodeHTTPTransport(tlsConfig *tls.Config, dialTimeout time.Duration) func() http.RoundTripper {
  418. // For more details about various values used here refer
  419. // https://golang.org/pkg/net/http/#Transport documentation
  420. tr := &http.Transport{
  421. Proxy: http.ProxyFromEnvironment,
  422. DialContext: xhttp.DialContextWithDNSCache(globalDNSCache, xhttp.NewInternodeDialContext(dialTimeout)),
  423. MaxIdleConnsPerHost: 1024,
  424. WriteBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
  425. ReadBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
  426. IdleConnTimeout: 15 * time.Second,
  427. ResponseHeaderTimeout: 15 * time.Minute, // Set conservative timeouts for MinIO internode.
  428. TLSHandshakeTimeout: 15 * time.Second,
  429. ExpectContinueTimeout: 15 * time.Second,
  430. TLSClientConfig: tlsConfig,
  431. // Go net/http automatically unzip if content-type is
  432. // gzip disable this feature, as we are always interested
  433. // in raw stream.
  434. DisableCompression: true,
  435. }
  436. // https://github.com/golang/go/issues/23559
  437. // https://github.com/golang/go/issues/42534
  438. // https://github.com/golang/go/issues/43989
  439. // https://github.com/golang/go/issues/33425
  440. // https://github.com/golang/go/issues/29246
  441. // if tlsConfig != nil {
  442. // trhttp2, _ := http2.ConfigureTransports(tr)
  443. // if trhttp2 != nil {
  444. // // ReadIdleTimeout is the timeout after which a health check using ping
  445. // // frame will be carried out if no frame is received on the
  446. // // connection. 5 minutes is sufficient time for any idle connection.
  447. // trhttp2.ReadIdleTimeout = 5 * time.Minute
  448. // // PingTimeout is the timeout after which the connection will be closed
  449. // // if a response to Ping is not received.
  450. // trhttp2.PingTimeout = dialTimeout
  451. // // DisableCompression, if true, prevents the Transport from
  452. // // requesting compression with an "Accept-Encoding: gzip"
  453. // trhttp2.DisableCompression = true
  454. // }
  455. // }
  456. return func() http.RoundTripper {
  457. return tr
  458. }
  459. }
  460. // Used by only proxied requests, specifically only supports HTTP/1.1
  461. func newCustomHTTPProxyTransport(tlsConfig *tls.Config, dialTimeout time.Duration) func() *http.Transport {
  462. // For more details about various values used here refer
  463. // https://golang.org/pkg/net/http/#Transport documentation
  464. tr := &http.Transport{
  465. Proxy: http.ProxyFromEnvironment,
  466. DialContext: xhttp.DialContextWithDNSCache(globalDNSCache, xhttp.NewInternodeDialContext(dialTimeout)),
  467. MaxIdleConnsPerHost: 1024,
  468. MaxConnsPerHost: 1024,
  469. WriteBufferSize: 16 << 10, // 16KiB moving up from 4KiB default
  470. ReadBufferSize: 16 << 10, // 16KiB moving up from 4KiB default
  471. IdleConnTimeout: 15 * time.Second,
  472. ResponseHeaderTimeout: 30 * time.Minute, // Set larger timeouts for proxied requests.
  473. TLSHandshakeTimeout: 10 * time.Second,
  474. ExpectContinueTimeout: 10 * time.Second,
  475. TLSClientConfig: tlsConfig,
  476. // Go net/http automatically unzip if content-type is
  477. // gzip disable this feature, as we are always interested
  478. // in raw stream.
  479. DisableCompression: true,
  480. }
  481. return func() *http.Transport {
  482. return tr
  483. }
  484. }
  485. func newCustomHTTPTransport(tlsConfig *tls.Config, dialTimeout time.Duration) func() *http.Transport {
  486. // For more details about various values used here refer
  487. // https://golang.org/pkg/net/http/#Transport documentation
  488. tr := &http.Transport{
  489. Proxy: http.ProxyFromEnvironment,
  490. DialContext: xhttp.DialContextWithDNSCache(globalDNSCache, xhttp.NewInternodeDialContext(dialTimeout)),
  491. MaxIdleConnsPerHost: 1024,
  492. WriteBufferSize: 16 << 10, // 16KiB moving up from 4KiB default
  493. ReadBufferSize: 16 << 10, // 16KiB moving up from 4KiB default
  494. IdleConnTimeout: 15 * time.Second,
  495. ResponseHeaderTimeout: 3 * time.Minute, // Set conservative timeouts for MinIO internode.
  496. TLSHandshakeTimeout: 10 * time.Second,
  497. ExpectContinueTimeout: 10 * time.Second,
  498. TLSClientConfig: tlsConfig,
  499. // Go net/http automatically unzip if content-type is
  500. // gzip disable this feature, as we are always interested
  501. // in raw stream.
  502. DisableCompression: true,
  503. }
  504. // https://github.com/golang/go/issues/23559
  505. // https://github.com/golang/go/issues/42534
  506. // https://github.com/golang/go/issues/43989
  507. // https://github.com/golang/go/issues/33425
  508. // https://github.com/golang/go/issues/29246
  509. // if tlsConfig != nil {
  510. // trhttp2, _ := http2.ConfigureTransports(tr)
  511. // if trhttp2 != nil {
  512. // // ReadIdleTimeout is the timeout after which a health check using ping
  513. // // frame will be carried out if no frame is received on the
  514. // // connection. 5 minutes is sufficient time for any idle connection.
  515. // trhttp2.ReadIdleTimeout = 5 * time.Minute
  516. // // PingTimeout is the timeout after which the connection will be closed
  517. // // if a response to Ping is not received.
  518. // trhttp2.PingTimeout = dialTimeout
  519. // // DisableCompression, if true, prevents the Transport from
  520. // // requesting compression with an "Accept-Encoding: gzip"
  521. // trhttp2.DisableCompression = true
  522. // }
  523. // }
  524. return func() *http.Transport {
  525. return tr
  526. }
  527. }
  528. // NewGatewayHTTPTransportWithClientCerts returns a new http configuration
  529. // used while communicating with the cloud backends.
  530. func NewGatewayHTTPTransportWithClientCerts(clientCert, clientKey string) *http.Transport {
  531. transport := newGatewayHTTPTransport(1 * time.Minute)
  532. if clientCert != "" && clientKey != "" {
  533. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  534. defer cancel()
  535. c, err := certs.NewManager(ctx, clientCert, clientKey, tls.LoadX509KeyPair)
  536. if err != nil {
  537. logger.LogIf(ctx, fmt.Errorf("failed to load client key and cert, please check your endpoint configuration: %s",
  538. err.Error()))
  539. }
  540. if c != nil {
  541. c.ReloadOnSignal(syscall.SIGHUP) // allow reloads upon SIGHUP
  542. transport.TLSClientConfig.GetClientCertificate = c.GetClientCertificate
  543. }
  544. }
  545. return transport
  546. }
  547. // NewGatewayHTTPTransport returns a new http configuration
  548. // used while communicating with the cloud backends.
  549. func NewGatewayHTTPTransport() *http.Transport {
  550. return newGatewayHTTPTransport(1 * time.Minute)
  551. }
  552. func newGatewayHTTPTransport(timeout time.Duration) *http.Transport {
  553. tr := newCustomHTTPTransport(&tls.Config{
  554. RootCAs: globalRootCAs,
  555. ClientSessionCache: tls.NewLRUClientSessionCache(tlsClientSessionCacheSize),
  556. }, defaultDialTimeout)()
  557. // Customize response header timeout for gateway transport.
  558. tr.ResponseHeaderTimeout = timeout
  559. return tr
  560. }
  561. // NewRemoteTargetHTTPTransport returns a new http configuration
  562. // used while communicating with the remote replication targets.
  563. func NewRemoteTargetHTTPTransport() *http.Transport {
  564. // For more details about various values used here refer
  565. // https://golang.org/pkg/net/http/#Transport documentation
  566. tr := &http.Transport{
  567. Proxy: http.ProxyFromEnvironment,
  568. DialContext: (&net.Dialer{
  569. Timeout: 15 * time.Second,
  570. KeepAlive: 30 * time.Second,
  571. }).DialContext,
  572. MaxIdleConnsPerHost: 1024,
  573. WriteBufferSize: 16 << 10, // 16KiB moving up from 4KiB default
  574. ReadBufferSize: 16 << 10, // 16KiB moving up from 4KiB default
  575. IdleConnTimeout: 15 * time.Second,
  576. TLSHandshakeTimeout: 5 * time.Second,
  577. ExpectContinueTimeout: 5 * time.Second,
  578. TLSClientConfig: &tls.Config{
  579. RootCAs: globalRootCAs,
  580. ClientSessionCache: tls.NewLRUClientSessionCache(tlsClientSessionCacheSize),
  581. },
  582. // Go net/http automatically unzip if content-type is
  583. // gzip disable this feature, as we are always interested
  584. // in raw stream.
  585. DisableCompression: true,
  586. }
  587. return tr
  588. }
  589. // Load the json (typically from disk file).
  590. func jsonLoad(r io.ReadSeeker, data interface{}) error {
  591. if _, err := r.Seek(0, io.SeekStart); err != nil {
  592. return err
  593. }
  594. return json.NewDecoder(r).Decode(data)
  595. }
  596. // Save to disk file in json format.
  597. func jsonSave(f interface {
  598. io.WriteSeeker
  599. Truncate(int64) error
  600. }, data interface{}) error {
  601. b, err := json.Marshal(data)
  602. if err != nil {
  603. return err
  604. }
  605. if err = f.Truncate(0); err != nil {
  606. return err
  607. }
  608. if _, err = f.Seek(0, io.SeekStart); err != nil {
  609. return err
  610. }
  611. _, err = f.Write(b)
  612. if err != nil {
  613. return err
  614. }
  615. return nil
  616. }
  617. // ceilFrac takes a numerator and denominator representing a fraction
  618. // and returns its ceiling. If denominator is 0, it returns 0 instead
  619. // of crashing.
  620. func ceilFrac(numerator, denominator int64) (ceil int64) {
  621. if denominator == 0 {
  622. // do nothing on invalid input
  623. return
  624. }
  625. // Make denominator positive
  626. if denominator < 0 {
  627. numerator = -numerator
  628. denominator = -denominator
  629. }
  630. ceil = numerator / denominator
  631. if numerator > 0 && numerator%denominator != 0 {
  632. ceil++
  633. }
  634. return
  635. }
  636. // pathClean is like path.Clean but does not return "." for
  637. // empty inputs, instead returns "empty" as is.
  638. func pathClean(p string) string {
  639. cp := path.Clean(p)
  640. if cp == "." {
  641. return ""
  642. }
  643. return cp
  644. }
  645. func trimLeadingSlash(ep string) string {
  646. if len(ep) > 0 && ep[0] == '/' {
  647. // Path ends with '/' preserve it
  648. if ep[len(ep)-1] == '/' && len(ep) > 1 {
  649. ep = path.Clean(ep)
  650. ep += slashSeparator
  651. } else {
  652. ep = path.Clean(ep)
  653. }
  654. ep = ep[1:]
  655. }
  656. return ep
  657. }
  658. // unescapeGeneric is similar to url.PathUnescape or url.QueryUnescape
  659. // depending on input, additionally also handles situations such as
  660. // `//` are normalized as `/`, also removes any `/` prefix before
  661. // returning.
  662. func unescapeGeneric(p string, escapeFn func(string) (string, error)) (string, error) {
  663. ep, err := escapeFn(p)
  664. if err != nil {
  665. return "", err
  666. }
  667. return trimLeadingSlash(ep), nil
  668. }
  669. // unescapePath is similar to unescapeGeneric but for specifically
  670. // path unescaping.
  671. func unescapePath(p string) (string, error) {
  672. return unescapeGeneric(p, url.PathUnescape)
  673. }
  674. // similar to unescapeGeneric but never returns any error if the unescaping
  675. // fails, returns the input as is in such occasion, not meant to be
  676. // used where strict validation is expected.
  677. func likelyUnescapeGeneric(p string, escapeFn func(string) (string, error)) string {
  678. ep, err := unescapeGeneric(p, escapeFn)
  679. if err != nil {
  680. return p
  681. }
  682. return ep
  683. }
  684. func updateReqContext(ctx context.Context, objects ...ObjectV) context.Context {
  685. req := logger.GetReqInfo(ctx)
  686. if req != nil {
  687. req.Objects = make([]logger.ObjectVersion, 0, len(objects))
  688. for _, ov := range objects {
  689. req.Objects = append(req.Objects, logger.ObjectVersion{
  690. ObjectName: ov.ObjectName,
  691. VersionID: ov.VersionID,
  692. })
  693. }
  694. return logger.SetReqInfo(ctx, req)
  695. }
  696. return ctx
  697. }
  698. // Returns context with ReqInfo details set in the context.
  699. func newContext(r *http.Request, w http.ResponseWriter, api string) context.Context {
  700. vars := mux.Vars(r)
  701. bucket := vars["bucket"]
  702. object := likelyUnescapeGeneric(vars["object"], url.PathUnescape)
  703. prefix := likelyUnescapeGeneric(vars["prefix"], url.QueryUnescape)
  704. if prefix != "" {
  705. object = prefix
  706. }
  707. reqInfo := &logger.ReqInfo{
  708. DeploymentID: globalDeploymentID,
  709. RequestID: w.Header().Get(xhttp.AmzRequestID),
  710. RemoteHost: handlers.GetSourceIP(r),
  711. Host: getHostName(r),
  712. UserAgent: r.UserAgent(),
  713. API: api,
  714. BucketName: bucket,
  715. ObjectName: object,
  716. VersionID: strings.TrimSpace(r.Form.Get(xhttp.VersionID)),
  717. }
  718. return logger.SetReqInfo(r.Context(), reqInfo)
  719. }
  720. // Used for registering with rest handlers (have a look at registerStorageRESTHandlers for usage example)
  721. // If it is passed ["aaaa", "bbbb"], it returns ["aaaa", "{aaaa:.*}", "bbbb", "{bbbb:.*}"]
  722. func restQueries(keys ...string) []string {
  723. var accumulator []string
  724. for _, key := range keys {
  725. accumulator = append(accumulator, key, "{"+key+":.*}")
  726. }
  727. return accumulator
  728. }
  729. // Suffix returns the longest common suffix of the provided strings
  730. func lcpSuffix(strs []string) string {
  731. return lcp(strs, false)
  732. }
  733. func lcp(strs []string, pre bool) string {
  734. // short-circuit empty list
  735. if len(strs) == 0 {
  736. return ""
  737. }
  738. xfix := strs[0]
  739. // short-circuit single-element list
  740. if len(strs) == 1 {
  741. return xfix
  742. }
  743. // compare first to rest
  744. for _, str := range strs[1:] {
  745. xfixl := len(xfix)
  746. strl := len(str)
  747. // short-circuit empty strings
  748. if xfixl == 0 || strl == 0 {
  749. return ""
  750. }
  751. // maximum possible length
  752. maxl := xfixl
  753. if strl < maxl {
  754. maxl = strl
  755. }
  756. // compare letters
  757. if pre {
  758. // prefix, iterate left to right
  759. for i := 0; i < maxl; i++ {
  760. if xfix[i] != str[i] {
  761. xfix = xfix[:i]
  762. break
  763. }
  764. }
  765. } else {
  766. // suffix, iterate right to left
  767. for i := 0; i < maxl; i++ {
  768. xi := xfixl - i - 1
  769. si := strl - i - 1
  770. if xfix[xi] != str[si] {
  771. xfix = xfix[xi+1:]
  772. break
  773. }
  774. }
  775. }
  776. }
  777. return xfix
  778. }
  779. // Returns the mode in which MinIO is running
  780. func getMinioMode() string {
  781. mode := globalMinioModeFS
  782. if globalIsDistErasure {
  783. mode = globalMinioModeDistErasure
  784. } else if globalIsErasure {
  785. mode = globalMinioModeErasure
  786. } else if globalIsGateway {
  787. mode = globalMinioModeGatewayPrefix + globalGatewayName
  788. }
  789. return mode
  790. }
  791. func iamPolicyClaimNameOpenID() string {
  792. return globalOpenIDConfig.ClaimPrefix + globalOpenIDConfig.ClaimName
  793. }
  794. func iamPolicyClaimNameSA() string {
  795. return "sa-policy"
  796. }
  797. // timedValue contains a synchronized value that is considered valid
  798. // for a specific amount of time.
  799. // An Update function must be set to provide an updated value when needed.
  800. type timedValue struct {
  801. // Update must return an updated value.
  802. // If an error is returned the cached value is not set.
  803. // Only one caller will call this function at any time, others will be blocking.
  804. // The returned value can no longer be modified once returned.
  805. // Should be set before calling Get().
  806. Update func() (interface{}, error)
  807. // TTL for a cached value.
  808. // If not set 1 second TTL is assumed.
  809. // Should be set before calling Get().
  810. TTL time.Duration
  811. // Once can be used to initialize values for lazy initialization.
  812. // Should be set before calling Get().
  813. Once sync.Once
  814. // Managed values.
  815. value interface{}
  816. lastUpdate time.Time
  817. mu sync.RWMutex
  818. }
  819. // Get will return a cached value or fetch a new one.
  820. // If the Update function returns an error the value is forwarded as is and not cached.
  821. func (t *timedValue) Get() (interface{}, error) {
  822. v := t.get()
  823. if v != nil {
  824. return v, nil
  825. }
  826. v, err := t.Update()
  827. if err != nil {
  828. return v, err
  829. }
  830. t.update(v)
  831. return v, nil
  832. }
  833. func (t *timedValue) get() (v interface{}) {
  834. ttl := t.TTL
  835. if ttl <= 0 {
  836. ttl = time.Second
  837. }
  838. t.mu.RLock()
  839. defer t.mu.RUnlock()
  840. v = t.value
  841. if time.Since(t.lastUpdate) < ttl {
  842. return v
  843. }
  844. return nil
  845. }
  846. func (t *timedValue) update(v interface{}) {
  847. t.mu.Lock()
  848. defer t.mu.Unlock()
  849. t.value = v
  850. t.lastUpdate = time.Now()
  851. }
  852. // On MinIO a directory object is stored as a regular object with "__XLDIR__" suffix.
  853. // For ex. "prefix/" is stored as "prefix__XLDIR__"
  854. func encodeDirObject(object string) string {
  855. if HasSuffix(object, slashSeparator) {
  856. return strings.TrimSuffix(object, slashSeparator) + globalDirSuffix
  857. }
  858. return object
  859. }
  860. // Reverse process of encodeDirObject()
  861. func decodeDirObject(object string) string {
  862. if HasSuffix(object, globalDirSuffix) {
  863. return strings.TrimSuffix(object, globalDirSuffix) + slashSeparator
  864. }
  865. return object
  866. }
  867. // This is used by metrics to show the number of failed RPC calls
  868. // between internodes
  869. func loadAndResetRPCNetworkErrsCounter() uint64 {
  870. defer rest.ResetNetworkErrsCounter()
  871. return rest.GetNetworkErrsCounter()
  872. }
  873. // Helper method to return total number of nodes in cluster
  874. func totalNodeCount() uint64 {
  875. peers, _ := globalEndpoints.peers()
  876. totalNodesCount := uint64(len(peers))
  877. if totalNodesCount == 0 {
  878. totalNodesCount = 1 // For standalone erasure coding
  879. }
  880. return totalNodesCount
  881. }
  882. // AuditLogOptions takes options for audit logging subsystem activity
  883. type AuditLogOptions struct {
  884. Trigger string
  885. APIName string
  886. Status string
  887. VersionID string
  888. }
  889. // sends audit logs for internal subsystem activity
  890. func auditLogInternal(ctx context.Context, bucket, object string, opts AuditLogOptions) {
  891. entry := audit.NewEntry(globalDeploymentID)
  892. entry.Trigger = opts.Trigger
  893. entry.API.Name = opts.APIName
  894. entry.API.Bucket = bucket
  895. entry.API.Object = object
  896. if opts.VersionID != "" {
  897. entry.ReqQuery = make(map[string]string)
  898. entry.ReqQuery[xhttp.VersionID] = opts.VersionID
  899. }
  900. entry.API.Status = opts.Status
  901. ctx = logger.SetAuditEntry(ctx, &entry)
  902. logger.AuditLog(ctx, nil, nil, nil)
  903. }
  904. func newTLSConfig(getCert certs.GetCertificateFunc) *tls.Config {
  905. if getCert == nil {
  906. return nil
  907. }
  908. tlsConfig := &tls.Config{
  909. PreferServerCipherSuites: true,
  910. MinVersion: tls.VersionTLS12,
  911. NextProtos: []string{"http/1.1", "h2"},
  912. GetCertificate: getCert,
  913. ClientSessionCache: tls.NewLRUClientSessionCache(tlsClientSessionCacheSize),
  914. }
  915. tlsClientIdentity := env.Get(xtls.EnvIdentityTLSEnabled, "") == config.EnableOn
  916. if tlsClientIdentity {
  917. tlsConfig.ClientAuth = tls.RequestClientCert
  918. }
  919. secureCiphers := env.Get(api.EnvAPISecureCiphers, config.EnableOn) == config.EnableOn
  920. if secureCiphers || fips.Enabled {
  921. // Hardened ciphers
  922. tlsConfig.CipherSuites = fips.CipherSuitesTLS()
  923. tlsConfig.CurvePreferences = fips.EllipticCurvesTLS()
  924. } else {
  925. // Default ciphers while excluding those with security issues
  926. for _, cipher := range tls.CipherSuites() {
  927. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, cipher.ID)
  928. }
  929. }
  930. return tlsConfig
  931. }
  932. /////////// Types and functions for OpenID IAM testing
  933. // OpenIDClientAppParams - contains openID client application params, used in
  934. // testing.
  935. type OpenIDClientAppParams struct {
  936. ClientID, ClientSecret, ProviderURL, RedirectURL string
  937. }
  938. // MockOpenIDTestUserInteraction - tries to login to dex using provided credentials.
  939. // It performs the user's browser interaction to login and retrieves the auth
  940. // code from dex and exchanges it for a JWT.
  941. func MockOpenIDTestUserInteraction(ctx context.Context, pro OpenIDClientAppParams, username, password string) (string, error) {
  942. ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
  943. defer cancel()
  944. provider, err := oidc.NewProvider(ctx, pro.ProviderURL)
  945. if err != nil {
  946. return "", fmt.Errorf("unable to create provider: %v", err)
  947. }
  948. // Configure an OpenID Connect aware OAuth2 client.
  949. oauth2Config := oauth2.Config{
  950. ClientID: pro.ClientID,
  951. ClientSecret: pro.ClientSecret,
  952. RedirectURL: pro.RedirectURL,
  953. // Discovery returns the OAuth2 endpoints.
  954. Endpoint: provider.Endpoint(),
  955. // "openid" is a required scope for OpenID Connect flows.
  956. Scopes: []string{oidc.ScopeOpenID, "groups"},
  957. }
  958. state := fmt.Sprintf("x%dx", time.Now().Unix())
  959. authCodeURL := oauth2Config.AuthCodeURL(state)
  960. // fmt.Printf("authcodeurl: %s\n", authCodeURL)
  961. var lastReq *http.Request
  962. checkRedirect := func(req *http.Request, via []*http.Request) error {
  963. // fmt.Printf("CheckRedirect:\n")
  964. // fmt.Printf("Upcoming: %s %s\n", req.Method, req.URL.String())
  965. // for i, c := range via {
  966. // fmt.Printf("Sofar %d: %s %s\n", i, c.Method, c.URL.String())
  967. // }
  968. // Save the last request in a redirect chain.
  969. lastReq = req
  970. // We do not follow redirect back to client application.
  971. if req.URL.Path == "/oauth_callback" {
  972. return http.ErrUseLastResponse
  973. }
  974. return nil
  975. }
  976. dexClient := http.Client{
  977. CheckRedirect: checkRedirect,
  978. }
  979. u, err := url.Parse(authCodeURL)
  980. if err != nil {
  981. return "", fmt.Errorf("url parse err: %v", err)
  982. }
  983. // Start the user auth flow. This page would present the login with
  984. // email or LDAP option.
  985. req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
  986. if err != nil {
  987. return "", fmt.Errorf("new request err: %v", err)
  988. }
  989. _, err = dexClient.Do(req)
  990. // fmt.Printf("Do: %#v %#v\n", resp, err)
  991. if err != nil {
  992. return "", fmt.Errorf("auth url request err: %v", err)
  993. }
  994. // Modify u to choose the ldap option
  995. u.Path += "/ldap"
  996. // fmt.Println(u)
  997. // Pick the LDAP login option. This would return a form page after
  998. // following some redirects. `lastReq` would be the URL of the form
  999. // page, where we need to POST (submit) the form.
  1000. req, err = http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
  1001. if err != nil {
  1002. return "", fmt.Errorf("new request err (/ldap): %v", err)
  1003. }
  1004. _, err = dexClient.Do(req)
  1005. // fmt.Printf("Fetch LDAP login page: %#v %#v\n", resp, err)
  1006. if err != nil {
  1007. return "", fmt.Errorf("request err: %v", err)
  1008. }
  1009. // {
  1010. // bodyBuf, err := ioutil.ReadAll(resp.Body)
  1011. // if err != nil {
  1012. // return "", fmt.Errorf("Error reading body: %v", err)
  1013. // }
  1014. // fmt.Printf("bodyBuf (for LDAP login page): %s\n", string(bodyBuf))
  1015. // }
  1016. // Fill the login form with our test creds:
  1017. // fmt.Printf("login form url: %s\n", lastReq.URL.String())
  1018. formData := url.Values{}
  1019. formData.Set("login", username)
  1020. formData.Set("password", password)
  1021. req, err = http.NewRequestWithContext(ctx, http.MethodPost, lastReq.URL.String(), strings.NewReader(formData.Encode()))
  1022. if err != nil {
  1023. return "", fmt.Errorf("new request err (/login): %v", err)
  1024. }
  1025. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1026. _, err = dexClient.Do(req)
  1027. if err != nil {
  1028. return "", fmt.Errorf("post form err: %v", err)
  1029. }
  1030. // fmt.Printf("resp: %#v %#v\n", resp.StatusCode, resp.Header)
  1031. // bodyBuf, err := ioutil.ReadAll(resp.Body)
  1032. // if err != nil {
  1033. // return "", fmt.Errorf("Error reading body: %v", err)
  1034. // }
  1035. // fmt.Printf("resp body: %s\n", string(bodyBuf))
  1036. // fmt.Printf("lastReq: %#v\n", lastReq.URL.String())
  1037. // On form submission, the last redirect response contains the auth
  1038. // code, which we now have in `lastReq`. Exchange it for a JWT id_token.
  1039. q := lastReq.URL.Query()
  1040. // fmt.Printf("lastReq.URL: %#v q: %#v\n", lastReq.URL, q)
  1041. code := q.Get("code")
  1042. oauth2Token, err := oauth2Config.Exchange(ctx, code)
  1043. if err != nil {
  1044. return "", fmt.Errorf("unable to exchange code for id token: %v", err)
  1045. }
  1046. rawIDToken, ok := oauth2Token.Extra("id_token").(string)
  1047. if !ok {
  1048. return "", fmt.Errorf("id_token not found!")
  1049. }
  1050. // fmt.Printf("TOKEN: %s\n", rawIDToken)
  1051. return rawIDToken, nil
  1052. }