gzip.odin 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. package gzip
  2. /*
  3. Copyright 2021 Jeroen van Rijn <[email protected]>.
  4. Made available under Odin's BSD-3 license.
  5. List of contributors:
  6. Jeroen van Rijn: Initial implementation.
  7. This package implements support for the GZIP file format v4.3,
  8. as specified in RFC 1952.
  9. It is implemented in such a way that it lends itself naturally
  10. to be the input to a complementary TAR implementation.
  11. */
  12. import "core:compress/zlib"
  13. import "core:compress"
  14. import "core:os"
  15. import "core:io"
  16. import "core:bytes"
  17. import "core:hash"
  18. Magic :: enum u16le {
  19. GZIP = 0x8b << 8 | 0x1f,
  20. }
  21. Header :: struct #packed {
  22. magic: Magic,
  23. compression_method: Compression,
  24. flags: Header_Flags,
  25. modification_time: u32le,
  26. xfl: Compression_Flags,
  27. os: OS,
  28. }
  29. #assert(size_of(Header) == 10)
  30. Header_Flag :: enum u8 {
  31. // Order is important
  32. text = 0,
  33. header_crc = 1,
  34. extra = 2,
  35. name = 3,
  36. comment = 4,
  37. reserved_1 = 5,
  38. reserved_2 = 6,
  39. reserved_3 = 7,
  40. }
  41. Header_Flags :: distinct bit_set[Header_Flag; u8]
  42. OS :: enum u8 {
  43. FAT = 0,
  44. Amiga = 1,
  45. VMS = 2,
  46. Unix = 3,
  47. VM_CMS = 4,
  48. Atari_TOS = 5,
  49. HPFS = 6,
  50. Macintosh = 7,
  51. Z_System = 8,
  52. CP_M = 9,
  53. TOPS_20 = 10,
  54. NTFS = 11,
  55. QDOS = 12,
  56. Acorn_RISCOS = 13,
  57. _Unknown = 14,
  58. Unknown = 255,
  59. }
  60. OS_Name :: #partial [OS]string{
  61. .FAT = "FAT",
  62. .Amiga = "Amiga",
  63. .VMS = "VMS/OpenVMS",
  64. .Unix = "Unix",
  65. .VM_CMS = "VM/CMS",
  66. .Atari_TOS = "Atari TOS",
  67. .HPFS = "HPFS",
  68. .Macintosh = "Macintosh",
  69. .Z_System = "Z-System",
  70. .CP_M = "CP/M",
  71. .TOPS_20 = "TOPS-20",
  72. .NTFS = "NTFS",
  73. .QDOS = "QDOS",
  74. .Acorn_RISCOS = "Acorn RISCOS",
  75. .Unknown = "Unknown",
  76. }
  77. Compression :: enum u8 {
  78. DEFLATE = 8,
  79. }
  80. Compression_Flags :: enum u8 {
  81. Maximum_Compression = 2,
  82. Fastest_Compression = 4,
  83. }
  84. Error :: compress.Error
  85. E_General :: compress.General_Error
  86. E_GZIP :: compress.GZIP_Error
  87. E_ZLIB :: compress.ZLIB_Error
  88. E_Deflate :: compress.Deflate_Error
  89. GZIP_MAX_PAYLOAD_SIZE :: int(max(u32le))
  90. load :: proc{load_from_slice, load_from_file, load_from_context}
  91. load_from_file :: proc(filename: string, buf: ^bytes.Buffer, expected_output_size := -1, allocator := context.allocator) -> (err: Error) {
  92. context.allocator = allocator
  93. data, ok := os.read_entire_file(filename)
  94. defer delete(data)
  95. err = E_General.File_Not_Found
  96. if ok {
  97. err = load_from_slice(data, buf, len(data), expected_output_size)
  98. }
  99. return
  100. }
  101. load_from_slice :: proc(slice: []u8, buf: ^bytes.Buffer, known_gzip_size := -1, expected_output_size := -1, allocator := context.allocator) -> (err: Error) {
  102. buf := buf
  103. z := &compress.Context_Memory_Input{
  104. input_data = slice,
  105. output = buf,
  106. }
  107. return load_from_context(z, buf, known_gzip_size, expected_output_size, allocator)
  108. }
  109. load_from_context :: proc(z: ^$C, buf: ^bytes.Buffer, known_gzip_size := -1, expected_output_size := -1, allocator := context.allocator) -> (err: Error) {
  110. context.allocator = allocator
  111. buf := buf
  112. expected_output_size := expected_output_size
  113. input_data_consumed := 0
  114. z.output = buf
  115. if expected_output_size > GZIP_MAX_PAYLOAD_SIZE {
  116. return E_GZIP.Payload_Size_Exceeds_Max_Payload
  117. }
  118. if expected_output_size > compress.COMPRESS_OUTPUT_ALLOCATE_MAX {
  119. return E_GZIP.Output_Exceeds_COMPRESS_OUTPUT_ALLOCATE_MAX
  120. }
  121. b: []u8
  122. header, e := compress.read_data(z, Header)
  123. if e != .None {
  124. return E_General.File_Too_Short
  125. }
  126. input_data_consumed += size_of(Header)
  127. if header.magic != .GZIP {
  128. return E_GZIP.Invalid_GZIP_Signature
  129. }
  130. if header.compression_method != .DEFLATE {
  131. return E_General.Unknown_Compression_Method
  132. }
  133. if header.os >= ._Unknown {
  134. header.os = .Unknown
  135. }
  136. if .reserved_1 in header.flags || .reserved_2 in header.flags || .reserved_3 in header.flags {
  137. return E_GZIP.Reserved_Flag_Set
  138. }
  139. // printf("signature: %v\n", header.magic);
  140. // printf("compression: %v\n", header.compression_method);
  141. // printf("flags: %v\n", header.flags);
  142. // printf("modification time: %v\n", time.unix(i64(header.modification_time), 0));
  143. // printf("xfl: %v (%v)\n", header.xfl, int(header.xfl));
  144. // printf("os: %v\n", OS_Name[header.os]);
  145. if .extra in header.flags {
  146. xlen, e_extra := compress.read_data(z, u16le)
  147. input_data_consumed += 2
  148. if e_extra != .None {
  149. return E_General.Stream_Too_Short
  150. }
  151. // printf("Extra data present (%v bytes)\n", xlen);
  152. if xlen < 4 {
  153. // Minimum length is 2 for ID + 2 for a field length, if set to zero.
  154. return E_GZIP.Invalid_Extra_Data
  155. }
  156. field_id: [2]u8
  157. field_length: u16le
  158. field_error: io.Error
  159. for xlen >= 4 {
  160. // println("Parsing Extra field(s).");
  161. field_id, field_error = compress.read_data(z, [2]u8)
  162. if field_error != .None {
  163. // printf("Parsing Extra returned: %v\n", field_error);
  164. return E_General.Stream_Too_Short
  165. }
  166. xlen -= 2
  167. input_data_consumed += 2
  168. field_length, field_error = compress.read_data(z, u16le)
  169. if field_error != .None {
  170. // printf("Parsing Extra returned: %v\n", field_error);
  171. return E_General.Stream_Too_Short
  172. }
  173. xlen -= 2
  174. input_data_consumed += 2
  175. if xlen <= 0 {
  176. // We're not going to try and recover by scanning for a ZLIB header.
  177. // Who knows what else is wrong with this file.
  178. return E_GZIP.Invalid_Extra_Data
  179. }
  180. // printf(" Field \"%v\" of length %v found: ", string(field_id[:]), field_length);
  181. if field_length > 0 {
  182. b, field_error = compress.read_slice(z, int(field_length))
  183. if field_error != .None {
  184. // printf("Parsing Extra returned: %v\n", field_error);
  185. return E_General.Stream_Too_Short
  186. }
  187. xlen -= field_length
  188. input_data_consumed += int(field_length)
  189. // printf("%v\n", string(field_data));
  190. }
  191. if xlen != 0 {
  192. return E_GZIP.Invalid_Extra_Data
  193. }
  194. }
  195. }
  196. if .name in header.flags {
  197. // Should be enough.
  198. name: [1024]u8
  199. i := 0
  200. name_error: io.Error
  201. for i < len(name) {
  202. b, name_error = compress.read_slice(z, 1)
  203. if name_error != .None {
  204. return E_General.Stream_Too_Short
  205. }
  206. input_data_consumed += 1
  207. if b[0] == 0 {
  208. break
  209. }
  210. name[i] = b[0]
  211. i += 1
  212. if i >= len(name) {
  213. return E_GZIP.Original_Name_Too_Long
  214. }
  215. }
  216. // printf("Original filename: %v\n", string(name[:i]));
  217. }
  218. if .comment in header.flags {
  219. // Should be enough.
  220. comment: [1024]u8
  221. i := 0
  222. comment_error: io.Error
  223. for i < len(comment) {
  224. b, comment_error = compress.read_slice(z, 1)
  225. if comment_error != .None {
  226. return E_General.Stream_Too_Short
  227. }
  228. input_data_consumed += 1
  229. if b[0] == 0 {
  230. break
  231. }
  232. comment[i] = b[0]
  233. i += 1
  234. if i >= len(comment) {
  235. return E_GZIP.Comment_Too_Long
  236. }
  237. }
  238. // printf("Comment: %v\n", string(comment[:i]));
  239. }
  240. if .header_crc in header.flags {
  241. crc_error: io.Error
  242. _, crc_error = compress.read_slice(z, 2)
  243. input_data_consumed += 2
  244. if crc_error != .None {
  245. return E_General.Stream_Too_Short
  246. }
  247. /*
  248. We don't actually check the CRC16 (lower 2 bytes of CRC32 of header data until the CRC field).
  249. If we find a gzip file in the wild that sets this field, we can add proper support for it.
  250. */
  251. }
  252. /*
  253. We should have arrived at the ZLIB payload.
  254. */
  255. payload_u32le: u32le
  256. // fmt.printf("known_gzip_size: %v | expected_output_size: %v\n", known_gzip_size, expected_output_size);
  257. if expected_output_size > -1 {
  258. /*
  259. We already checked that it's not larger than the output buffer max,
  260. or GZIP length field's max.
  261. We'll just pass it on to `zlib.inflate_raw`;
  262. */
  263. } else {
  264. /*
  265. If we know the size of the GZIP file *and* it is fully in memory,
  266. then we can peek at the unpacked size at the end.
  267. We'll still want to ensure there's capacity left in the output buffer when we write, of course.
  268. */
  269. if known_gzip_size > -1 {
  270. offset := i64(known_gzip_size - input_data_consumed - 4)
  271. size, _ := compress.input_size(z)
  272. if size >= offset + 4 {
  273. length_bytes := z.input_data[offset:][:4]
  274. payload_u32le = (^u32le)(&length_bytes[0])^
  275. expected_output_size = int(payload_u32le)
  276. }
  277. } else {
  278. /*
  279. TODO(Jeroen): When reading a GZIP from a stream, check if impl_seek is present.
  280. If so, we can seek to the end, grab the size from the footer, and seek back to payload start.
  281. */
  282. }
  283. }
  284. // fmt.printf("GZIP: Expected Payload Size: %v\n", expected_output_size);
  285. zlib_error := zlib.inflate_raw(z=z, expected_output_size=expected_output_size)
  286. if zlib_error != nil {
  287. return zlib_error
  288. }
  289. /*
  290. Read CRC32 using the ctx bit reader because zlib may leave bytes in there.
  291. */
  292. compress.discard_to_next_byte_lsb(z)
  293. footer_error: io.Error
  294. payload_crc_b: [4]u8
  295. for _, i in payload_crc_b {
  296. payload_crc_b[i], footer_error = compress.read_u8_prefer_code_buffer_lsb(z)
  297. }
  298. payload_crc := transmute(u32le)payload_crc_b
  299. payload := bytes.buffer_to_bytes(buf)
  300. crc32 := u32le(hash.crc32(payload))
  301. if crc32 != payload_crc {
  302. return E_GZIP.Payload_CRC_Invalid
  303. }
  304. payload_len_b: [4]u8
  305. for _, i in payload_len_b {
  306. payload_len_b[i], footer_error = compress.read_u8_prefer_code_buffer_lsb(z)
  307. }
  308. payload_len := transmute(u32le)payload_len_b
  309. if len(payload) != int(payload_len) {
  310. return E_GZIP.Payload_Length_Invalid
  311. }
  312. return nil
  313. }