reader.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright 2010 The Go 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. package zip
  5. import (
  6. "encoding/binary"
  7. "errors"
  8. "io"
  9. )
  10. var (
  11. ErrFormat = errors.New("zip: not a valid zip file")
  12. ErrAlgorithm = errors.New("zip: unsupported compression algorithm")
  13. ErrChecksum = errors.New("zip: checksum error")
  14. ErrInsecurePath = errors.New("zip: insecure file path")
  15. )
  16. type FileContent struct {
  17. Filename []byte
  18. Content []byte
  19. }
  20. func ReadFile(r io.ReadSeeker) (*FileContent, error) {
  21. var buf [fileHeaderLen]byte
  22. if _, err := io.ReadFull(r, buf[:]); err != nil {
  23. return nil, err
  24. }
  25. b := readBuf(buf[:])
  26. if sig := b.uint32(); sig != fileHeaderSignature {
  27. return nil, ErrFormat
  28. }
  29. b = b[18:] // skip over most of the header
  30. fileContentLen := int(b.uint32())
  31. filenameLen := int(b.uint16())
  32. extraLen := int64(b.uint16())
  33. filename := make([]byte, filenameLen)
  34. if _, err := io.ReadFull(r, filename[:]); err != nil {
  35. return nil, err
  36. }
  37. if _, err := r.Seek(extraLen, io.SeekCurrent); err != nil {
  38. return nil, err
  39. }
  40. // pos, err := r.Seek(0, io.SeekCurrent)
  41. // if err != nil {
  42. // return nil, err
  43. // }
  44. // fmt.Printf("pso: %d", pos)
  45. content := make([]byte, fileContentLen)
  46. if _, err := io.ReadFull(r, content[:]); err != nil {
  47. return nil, err
  48. }
  49. // pos, err = r.Seek(0, io.SeekCurrent)
  50. // if err != nil {
  51. // return nil, err
  52. // }
  53. // fmt.Printf("pso: %d", pos)
  54. return &FileContent{
  55. Filename: filename,
  56. Content: content,
  57. }, nil
  58. }
  59. type readBuf []byte
  60. func (b *readBuf) uint8() uint8 {
  61. v := (*b)[0]
  62. *b = (*b)[1:]
  63. return v
  64. }
  65. func (b *readBuf) uint16() uint16 {
  66. v := binary.LittleEndian.Uint16(*b)
  67. *b = (*b)[2:]
  68. return v
  69. }
  70. func (b *readBuf) uint32() uint32 {
  71. v := binary.LittleEndian.Uint32(*b)
  72. *b = (*b)[4:]
  73. return v
  74. }
  75. func (b *readBuf) uint64() uint64 {
  76. v := binary.LittleEndian.Uint64(*b)
  77. *b = (*b)[8:]
  78. return v
  79. }
  80. func (b *readBuf) sub(n int) readBuf {
  81. b2 := (*b)[:n]
  82. *b = (*b)[n:]
  83. return b2
  84. }