gzip.odin 9.1 KB

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