chunked_reader_v4.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. package s3api
  2. // the related code is copied and modified from minio source code
  3. /*
  4. * Minio Cloud Storage, (C) 2016 Minio, Inc.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. import (
  19. "bufio"
  20. "bytes"
  21. "crypto/sha1"
  22. "crypto/sha256"
  23. "encoding/base64"
  24. "encoding/hex"
  25. "errors"
  26. "fmt"
  27. "hash"
  28. "hash/crc32"
  29. "hash/crc64"
  30. "io"
  31. "net/http"
  32. "time"
  33. "github.com/seaweedfs/seaweedfs/weed/glog"
  34. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  35. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  36. "github.com/dustin/go-humanize"
  37. )
  38. // calculateSeedSignature - Calculate seed signature in accordance with
  39. // - http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html
  40. //
  41. // returns signature, error otherwise if the signature mismatches or any other
  42. // error while parsing and validating.
  43. func (iam *IdentityAccessManagement) calculateSeedSignature(r *http.Request) (cred *Credential, signature string, region string, date time.Time, errCode s3err.ErrorCode) {
  44. // Copy request.
  45. req := *r
  46. // Save authorization header.
  47. v4Auth := req.Header.Get("Authorization")
  48. // Parse signature version '4' header.
  49. signV4Values, errCode := parseSignV4(v4Auth)
  50. if errCode != s3err.ErrNone {
  51. return nil, "", "", time.Time{}, errCode
  52. }
  53. contentSha256Header := req.Header.Get("X-Amz-Content-Sha256")
  54. switch contentSha256Header {
  55. // Payload for STREAMING signature should be 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD'
  56. case streamingContentSHA256:
  57. glog.V(3).Infof("streaming content sha256")
  58. case streamingUnsignedPayload:
  59. glog.V(3).Infof("streaming unsigned payload")
  60. default:
  61. return nil, "", "", time.Time{}, s3err.ErrContentSHA256Mismatch
  62. }
  63. // Payload streaming.
  64. payload := contentSha256Header
  65. // Extract all the signed headers along with its values.
  66. extractedSignedHeaders, errCode := extractSignedHeaders(signV4Values.SignedHeaders, r)
  67. if errCode != s3err.ErrNone {
  68. return nil, "", "", time.Time{}, errCode
  69. }
  70. // Verify if the access key id matches.
  71. identity, cred, found := iam.lookupByAccessKey(signV4Values.Credential.accessKey)
  72. if !found {
  73. return nil, "", "", time.Time{}, s3err.ErrInvalidAccessKeyID
  74. }
  75. bucket, object := s3_constants.GetBucketAndObject(r)
  76. if !identity.canDo(s3_constants.ACTION_WRITE, bucket, object) {
  77. errCode = s3err.ErrAccessDenied
  78. return
  79. }
  80. // Verify if region is valid.
  81. region = signV4Values.Credential.scope.region
  82. // Extract date, if not present throw error.
  83. var dateStr string
  84. if dateStr = req.Header.Get(http.CanonicalHeaderKey("x-amz-date")); dateStr == "" {
  85. if dateStr = r.Header.Get("Date"); dateStr == "" {
  86. return nil, "", "", time.Time{}, s3err.ErrMissingDateHeader
  87. }
  88. }
  89. // Parse date header.
  90. var err error
  91. date, err = time.Parse(iso8601Format, dateStr)
  92. if err != nil {
  93. return nil, "", "", time.Time{}, s3err.ErrMalformedDate
  94. }
  95. // Query string.
  96. queryStr := req.URL.Query().Encode()
  97. // Get canonical request.
  98. canonicalRequest := getCanonicalRequest(extractedSignedHeaders, payload, queryStr, req.URL.Path, req.Method)
  99. // Get string to sign from canonical request.
  100. stringToSign := getStringToSign(canonicalRequest, date, signV4Values.Credential.getScope())
  101. // Calculate signature.
  102. newSignature := iam.getSignature(
  103. cred.SecretKey,
  104. signV4Values.Credential.scope.date,
  105. region,
  106. "s3",
  107. stringToSign,
  108. )
  109. // Verify if signature match.
  110. if !compareSignatureV4(newSignature, signV4Values.Signature) {
  111. return nil, "", "", time.Time{}, s3err.ErrSignatureDoesNotMatch
  112. }
  113. // Return calculated signature.
  114. return cred, newSignature, region, date, s3err.ErrNone
  115. }
  116. const maxLineLength = 4 * humanize.KiByte // assumed <= bufio.defaultBufSize 4KiB
  117. // lineTooLong is generated as chunk header is bigger than 4KiB.
  118. var errLineTooLong = errors.New("header line too long")
  119. // Malformed encoding is generated when chunk header is wrongly formed.
  120. var errMalformedEncoding = errors.New("malformed chunked encoding")
  121. // newChunkedReader returns a new s3ChunkedReader that translates the data read from r
  122. // out of HTTP "chunked" format before returning it.
  123. // The s3ChunkedReader returns io.EOF when the final 0-length chunk is read.
  124. func (iam *IdentityAccessManagement) newChunkedReader(req *http.Request) (io.ReadCloser, s3err.ErrorCode) {
  125. glog.V(3).Infof("creating a new newSignV4ChunkedReader")
  126. contentSha256Header := req.Header.Get("X-Amz-Content-Sha256")
  127. authorizationHeader := req.Header.Get("Authorization")
  128. var ident *Credential
  129. var seedSignature, region string
  130. var seedDate time.Time
  131. var errCode s3err.ErrorCode
  132. switch contentSha256Header {
  133. // Payload for STREAMING signature should be 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD'
  134. case streamingContentSHA256:
  135. glog.V(3).Infof("streaming content sha256")
  136. ident, seedSignature, region, seedDate, errCode = iam.calculateSeedSignature(req)
  137. if errCode != s3err.ErrNone {
  138. return nil, errCode
  139. }
  140. case streamingUnsignedPayload:
  141. glog.V(3).Infof("streaming unsigned payload")
  142. if authorizationHeader != "" {
  143. // We do not need to pass the seed signature to the Reader as each chunk is not signed,
  144. // but we do compute it to verify the caller has the correct permissions.
  145. _, _, _, _, errCode = iam.calculateSeedSignature(req)
  146. if errCode != s3err.ErrNone {
  147. return nil, errCode
  148. }
  149. }
  150. }
  151. // Get the checksum algorithm from the x-amz-trailer Header.
  152. amzTrailerHeader := req.Header.Get("x-amz-trailer")
  153. checksumAlgorithm, err := extractChecksumAlgorithm(amzTrailerHeader)
  154. if err != nil {
  155. glog.V(3).Infof("error extracting checksum algorithm: %v", err)
  156. return nil, s3err.ErrInvalidRequest
  157. }
  158. checkSumWriter := getCheckSumWriter(checksumAlgorithm)
  159. return &s3ChunkedReader{
  160. cred: ident,
  161. reader: bufio.NewReader(req.Body),
  162. seedSignature: seedSignature,
  163. seedDate: seedDate,
  164. region: region,
  165. chunkSHA256Writer: sha256.New(),
  166. checkSumAlgorithm: checksumAlgorithm.String(),
  167. checkSumWriter: checkSumWriter,
  168. state: readChunkHeader,
  169. iam: iam,
  170. }, s3err.ErrNone
  171. }
  172. func extractChecksumAlgorithm(amzTrailerHeader string) (ChecksumAlgorithm, error) {
  173. // Extract checksum algorithm from the x-amz-trailer header.
  174. switch amzTrailerHeader {
  175. case "x-amz-checksum-crc32":
  176. return ChecksumAlgorithmCRC32, nil
  177. case "x-amz-checksum-crc32c":
  178. return ChecksumAlgorithmCRC32C, nil
  179. case "x-amz-checksum-crc64nvme":
  180. return ChecksumAlgorithmCRC64NVMe, nil
  181. case "x-amz-checksum-sha1":
  182. return ChecksumAlgorithmSHA1, nil
  183. case "x-amz-checksum-sha256":
  184. return ChecksumAlgorithmSHA256, nil
  185. case "":
  186. return ChecksumAlgorithmNone, nil
  187. default:
  188. return ChecksumAlgorithmNone, errors.New("unsupported checksum algorithm '" + amzTrailerHeader + "'")
  189. }
  190. }
  191. // Represents the overall state that is required for decoding a
  192. // AWS Signature V4 chunked reader.
  193. type s3ChunkedReader struct {
  194. cred *Credential
  195. reader *bufio.Reader
  196. seedSignature string
  197. seedDate time.Time
  198. region string
  199. state chunkState
  200. lastChunk bool
  201. chunkSignature string // Empty string if unsigned streaming upload.
  202. checkSumAlgorithm string // Empty string if no checksum algorithm is specified.
  203. checkSumWriter hash.Hash
  204. chunkSHA256Writer hash.Hash // Calculates sha256 of chunk data.
  205. n uint64 // Unread bytes in chunk
  206. err error
  207. iam *IdentityAccessManagement
  208. }
  209. // Read chunk reads the chunk token signature portion.
  210. func (cr *s3ChunkedReader) readS3ChunkHeader() {
  211. // Read the first chunk line until CRLF.
  212. var bytesRead, hexChunkSize, hexChunkSignature []byte
  213. bytesRead, cr.err = readChunkLine(cr.reader)
  214. // Parse s3 specific chunk extension and fetch the values.
  215. hexChunkSize, hexChunkSignature = parseS3ChunkExtension(bytesRead)
  216. if cr.err != nil {
  217. return
  218. }
  219. // <hex>;token=value - converts the hex into its uint64 form.
  220. cr.n, cr.err = parseHexUint(hexChunkSize)
  221. if cr.err != nil {
  222. return
  223. }
  224. if cr.n == 0 {
  225. cr.err = io.EOF
  226. }
  227. // Save the incoming chunk signature.
  228. if hexChunkSignature == nil {
  229. // We are using unsigned streaming upload.
  230. cr.chunkSignature = ""
  231. } else {
  232. cr.chunkSignature = string(hexChunkSignature)
  233. }
  234. }
  235. type chunkState int
  236. const (
  237. readChunkHeader chunkState = iota
  238. readChunkTrailer
  239. readChunk
  240. readTrailerChunk
  241. verifyChunk
  242. verifyChecksum
  243. eofChunk
  244. )
  245. func (cs chunkState) String() string {
  246. stateString := ""
  247. switch cs {
  248. case readChunkHeader:
  249. stateString = "readChunkHeader"
  250. case readChunkTrailer:
  251. stateString = "readChunkTrailer"
  252. case readChunk:
  253. stateString = "readChunk"
  254. case readTrailerChunk:
  255. stateString = "readTrailerChunk"
  256. case verifyChunk:
  257. stateString = "verifyChunk"
  258. case verifyChecksum:
  259. stateString = "verifyChecksum"
  260. case eofChunk:
  261. stateString = "eofChunk"
  262. }
  263. return stateString
  264. }
  265. func (cr *s3ChunkedReader) Close() (err error) {
  266. return nil
  267. }
  268. // Read - implements `io.Reader`, which transparently decodes
  269. // the incoming AWS Signature V4 streaming signature.
  270. func (cr *s3ChunkedReader) Read(buf []byte) (n int, err error) {
  271. for {
  272. switch cr.state {
  273. case readChunkHeader:
  274. cr.readS3ChunkHeader()
  275. // If we're at the end of a chunk.
  276. if cr.n == 0 && cr.err == io.EOF {
  277. cr.state = readChunkTrailer
  278. cr.lastChunk = true
  279. continue
  280. }
  281. if cr.err != nil {
  282. return 0, cr.err
  283. }
  284. cr.state = readChunk
  285. case readChunkTrailer:
  286. err = peekCRLF(cr.reader)
  287. isTrailingChunk := cr.n == 0 && cr.lastChunk
  288. if !isTrailingChunk {
  289. // If we're not in the trailing chunk, we should consume the bytes no matter what.
  290. // The error returned by peekCRLF is the same as the one by readCRLF.
  291. readCRLF(cr.reader)
  292. cr.err = err
  293. } else if err != nil && err != errMalformedEncoding {
  294. cr.err = err
  295. return 0, errMalformedEncoding
  296. } else { // equivalent to isTrailingChunk && err == errMalformedEncoding
  297. // FIXME: The "right" structure of the last chunk as provided by the examples in the
  298. // AWS documentation is "0\r\n\r\n" instead of "0\r\n", but some s3 clients when calling with
  299. // streaming-unsigned-payload-trailer omit the last CRLF. To avoid returning an error that, we need to accept both.
  300. // We arrive here when we're at the end of the 0-byte chunk, depending on the client implementation
  301. // the client may or may not send the optional CRLF after the 0-byte chunk.
  302. // If the client sends the optional CRLF, we should consume it.
  303. if err == nil {
  304. readCRLF(cr.reader)
  305. }
  306. }
  307. // If we're using unsigned streaming upload, there is no signature to verify at each chunk.
  308. if cr.chunkSignature != "" {
  309. cr.state = verifyChunk
  310. } else if cr.lastChunk {
  311. cr.state = readTrailerChunk
  312. } else {
  313. cr.state = readChunkHeader
  314. }
  315. case readTrailerChunk:
  316. // When using unsigned upload, this would be the raw contents of the trailer chunk:
  317. //
  318. // x-amz-checksum-crc32:YABb/g==\n\r\n\r\n // Trailer chunk (note optional \n character)
  319. // \r\n // CRLF
  320. //
  321. // When using signed upload with an additional checksum algorithm, this would be the raw contents of the trailer chunk:
  322. //
  323. // x-amz-checksum-crc32:YABb/g==\n\r\n // Trailer chunk (note optional \n character)
  324. // trailer-signature\r\n
  325. // \r\n // CRLF
  326. //
  327. // This implementation currently only supports the first case.
  328. // TODO: Implement the second case (signed upload with additional checksum computation for each chunk)
  329. extractedCheckSumAlgorithm, extractedChecksum := parseChunkChecksum(cr.reader)
  330. if extractedCheckSumAlgorithm.String() != cr.checkSumAlgorithm {
  331. errorMessage := fmt.Sprintf("checksum algorithm in trailer '%s' does not match the one advertised in the header '%s'", extractedCheckSumAlgorithm.String(), cr.checkSumAlgorithm)
  332. glog.V(3).Infof(errorMessage)
  333. cr.err = errors.New(errorMessage)
  334. return 0, cr.err
  335. }
  336. computedChecksum := cr.checkSumWriter.Sum(nil)
  337. base64Checksum := base64.StdEncoding.EncodeToString(computedChecksum)
  338. if string(extractedChecksum) != base64Checksum {
  339. // TODO: Return BadDigest
  340. glog.V(3).Infof("payload checksum '%s' does not match provided checksum '%s'", base64Checksum, string(extractedChecksum))
  341. cr.err = errors.New("payload checksum does not match")
  342. return 0, cr.err
  343. }
  344. // TODO: Extract signature from trailer chunk and verify it.
  345. // For now, we just read the trailer chunk and discard it.
  346. // Reading remaining CRLF.
  347. for i := 0; i < 2; i++ {
  348. cr.err = readCRLF(cr.reader)
  349. }
  350. cr.state = eofChunk
  351. case readChunk:
  352. // There is no more space left in the request buffer.
  353. if len(buf) == 0 {
  354. return n, nil
  355. }
  356. rbuf := buf
  357. // The request buffer is larger than the current chunk size.
  358. // Read only the current chunk from the underlying reader.
  359. if uint64(len(rbuf)) > cr.n {
  360. rbuf = rbuf[:cr.n]
  361. }
  362. var n0 int
  363. n0, cr.err = cr.reader.Read(rbuf)
  364. if cr.err != nil {
  365. // We have lesser than chunk size advertised in chunkHeader, this is 'unexpected'.
  366. if cr.err == io.EOF {
  367. cr.err = io.ErrUnexpectedEOF
  368. }
  369. return 0, cr.err
  370. }
  371. // Calculate sha256.
  372. cr.chunkSHA256Writer.Write(rbuf[:n0])
  373. // Compute checksum
  374. if cr.checkSumWriter != nil {
  375. cr.checkSumWriter.Write(rbuf[:n0])
  376. }
  377. // Update the bytes read into request buffer so far.
  378. n += n0
  379. buf = buf[n0:]
  380. // Update bytes to be read of the current chunk before verifying chunk's signature.
  381. cr.n -= uint64(n0)
  382. // If we're at the end of a chunk.
  383. if cr.n == 0 {
  384. cr.state = readChunkTrailer
  385. continue
  386. }
  387. case verifyChunk:
  388. // Calculate the hashed chunk.
  389. hashedChunk := hex.EncodeToString(cr.chunkSHA256Writer.Sum(nil))
  390. // Calculate the chunk signature.
  391. newSignature := cr.getChunkSignature(hashedChunk)
  392. if !compareSignatureV4(cr.chunkSignature, newSignature) {
  393. // Chunk signature doesn't match we return signature does not match.
  394. cr.err = errors.New("chunk signature does not match")
  395. return 0, cr.err
  396. }
  397. // Newly calculated signature becomes the seed for the next chunk
  398. // this follows the chaining.
  399. cr.seedSignature = newSignature
  400. cr.chunkSHA256Writer.Reset()
  401. if cr.lastChunk {
  402. cr.state = eofChunk
  403. } else {
  404. cr.state = readChunkHeader
  405. }
  406. case eofChunk:
  407. return n, io.EOF
  408. }
  409. }
  410. }
  411. // getChunkSignature - get chunk signature.
  412. func (cr *s3ChunkedReader) getChunkSignature(hashedChunk string) string {
  413. // Calculate string to sign.
  414. stringToSign := signV4ChunkedAlgorithm + "\n" +
  415. cr.seedDate.Format(iso8601Format) + "\n" +
  416. getScope(cr.seedDate, cr.region) + "\n" +
  417. cr.seedSignature + "\n" +
  418. emptySHA256 + "\n" +
  419. hashedChunk
  420. // Calculate signature.
  421. return cr.iam.getSignature(
  422. cr.cred.SecretKey,
  423. cr.seedDate,
  424. cr.region,
  425. "s3",
  426. stringToSign,
  427. )
  428. }
  429. // readCRLF - check if reader only has '\r\n' CRLF character.
  430. // returns malformed encoding if it doesn't.
  431. func readCRLF(reader *bufio.Reader) error {
  432. buf := make([]byte, 2)
  433. _, err := reader.Read(buf)
  434. if err != nil {
  435. return err
  436. }
  437. return checkCRLF(buf)
  438. }
  439. // peekCRLF - peeks at the next two bytes to check for CRLF without consuming them.
  440. func peekCRLF(reader *bufio.Reader) error {
  441. peeked, err := reader.Peek(2)
  442. if err != nil {
  443. return err
  444. }
  445. if err := checkCRLF(peeked); err != nil {
  446. return err
  447. }
  448. return nil
  449. }
  450. // checkCRLF - checks if the buffer contains '\r\n' CRLF character.
  451. func checkCRLF(buf []byte) error {
  452. if buf[0] != '\r' || buf[1] != '\n' {
  453. return errMalformedEncoding
  454. }
  455. return nil
  456. }
  457. // Read a line of bytes (up to \n) from b.
  458. // Give up if the line exceeds maxLineLength.
  459. // The returned bytes are owned by the bufio.Reader
  460. // so they are only valid until the next bufio read.
  461. func readChunkLine(b *bufio.Reader) ([]byte, error) {
  462. buf, err := b.ReadSlice('\n')
  463. if err != nil {
  464. // We always know when EOF is coming.
  465. // If the caller asked for a line, there should be a line.
  466. if err == io.EOF {
  467. err = io.ErrUnexpectedEOF
  468. } else if err == bufio.ErrBufferFull {
  469. err = errLineTooLong
  470. }
  471. return nil, err
  472. }
  473. if len(buf) >= maxLineLength {
  474. return nil, errLineTooLong
  475. }
  476. return buf, nil
  477. }
  478. // trimTrailingWhitespace - trim trailing white space.
  479. func trimTrailingWhitespace(b []byte) []byte {
  480. for len(b) > 0 && isASCIISpace(b[len(b)-1]) {
  481. b = b[:len(b)-1]
  482. }
  483. return b
  484. }
  485. // isASCIISpace - is ascii space?
  486. func isASCIISpace(b byte) bool {
  487. return b == ' ' || b == '\t' || b == '\n' || b == '\r'
  488. }
  489. // Constant s3 chunk encoding signature.
  490. const s3ChunkSignatureStr = ";chunk-signature="
  491. // parses3ChunkExtension removes any s3 specific chunk-extension from buf.
  492. // For example,
  493. //
  494. // "10000;chunk-signature=..." => "10000", "chunk-signature=..."
  495. func parseS3ChunkExtension(buf []byte) ([]byte, []byte) {
  496. buf = trimTrailingWhitespace(buf)
  497. semi := bytes.Index(buf, []byte(s3ChunkSignatureStr))
  498. // Chunk signature not found, return the whole buffer.
  499. // This means we're using unsigned streaming upload.
  500. if semi == -1 {
  501. return buf, nil
  502. }
  503. return buf[:semi], parseChunkSignature(buf[semi:])
  504. }
  505. func parseChunkChecksum(b *bufio.Reader) (ChecksumAlgorithm, []byte) {
  506. // When using unsigned upload, this would be the raw contents of the trailer chunk:
  507. //
  508. // x-amz-checksum-crc32:YABb/g==\n\r\n\r\n // Trailer chunk (note optional \n character)
  509. // \r\n // CRLF
  510. //
  511. // When using signed upload with an additional checksum algorithm, this would be the raw contents of the trailer chunk:
  512. //
  513. // x-amz-checksum-crc32:YABb/g==\n\r\n // Trailer chunk (note optional \n character)
  514. // trailer-signature\r\n
  515. // \r\n // CRLF
  516. //
  517. // x-amz-checksum-crc32:YABb/g==\n
  518. bytesRead, err := readChunkLine(b)
  519. if err != nil {
  520. return ChecksumAlgorithmNone, nil
  521. }
  522. // Split on ':'
  523. parts := bytes.SplitN(bytesRead, []byte(":"), 2)
  524. checksumKey := string(parts[0])
  525. checksumValue := parts[1]
  526. // Discard all trailing whitespace characters
  527. checksumValue = trimTrailingWhitespace(checksumValue)
  528. // If the checksum key is not a supported checksum algorithm, return an error.
  529. // TODO: Bubble that error up to the caller
  530. extractedAlgorithm, err := extractChecksumAlgorithm(checksumKey)
  531. if err != nil {
  532. return ChecksumAlgorithmNone, nil
  533. }
  534. return extractedAlgorithm, checksumValue
  535. }
  536. // parseChunkSignature - parse chunk signature.
  537. func parseChunkSignature(chunk []byte) []byte {
  538. chunkSplits := bytes.SplitN(chunk, []byte(s3ChunkSignatureStr), 2)
  539. return chunkSplits[1]
  540. }
  541. // parse hex to uint64.
  542. func parseHexUint(v []byte) (n uint64, err error) {
  543. for i, b := range v {
  544. switch {
  545. case '0' <= b && b <= '9':
  546. b = b - '0'
  547. case 'a' <= b && b <= 'f':
  548. b = b - 'a' + 10
  549. case 'A' <= b && b <= 'F':
  550. b = b - 'A' + 10
  551. default:
  552. return 0, errors.New("invalid byte in chunk length")
  553. }
  554. if i == 16 {
  555. return 0, errors.New("http chunk length too large")
  556. }
  557. n <<= 4
  558. n |= uint64(b)
  559. }
  560. return
  561. }
  562. type ChecksumAlgorithm int
  563. const (
  564. ChecksumAlgorithmNone ChecksumAlgorithm = iota
  565. ChecksumAlgorithmCRC32
  566. ChecksumAlgorithmCRC32C
  567. ChecksumAlgorithmCRC64NVMe
  568. ChecksumAlgorithmSHA1
  569. ChecksumAlgorithmSHA256
  570. )
  571. func (ca ChecksumAlgorithm) String() string {
  572. switch ca {
  573. case ChecksumAlgorithmCRC32:
  574. return "CRC32"
  575. case ChecksumAlgorithmCRC32C:
  576. return "CRC32C"
  577. case ChecksumAlgorithmCRC64NVMe:
  578. return "CRC64NVMe"
  579. case ChecksumAlgorithmSHA1:
  580. return "SHA1"
  581. case ChecksumAlgorithmSHA256:
  582. return "SHA256"
  583. case ChecksumAlgorithmNone:
  584. return ""
  585. }
  586. return ""
  587. }
  588. // getCheckSumWriter - get checksum writer.
  589. func getCheckSumWriter(checksumAlgorithm ChecksumAlgorithm) hash.Hash {
  590. switch checksumAlgorithm {
  591. case ChecksumAlgorithmCRC32:
  592. return crc32.NewIEEE()
  593. case ChecksumAlgorithmCRC32C:
  594. return crc32.New(crc32.MakeTable(crc32.Castagnoli))
  595. case ChecksumAlgorithmCRC64NVMe:
  596. return crc64.New(crc64.MakeTable(crc64.ISO))
  597. case ChecksumAlgorithmSHA1:
  598. return sha1.New()
  599. case ChecksumAlgorithmSHA256:
  600. return sha256.New()
  601. }
  602. return nil
  603. }