t8rt0t

zipAPI.lua

Apr 2nd, 2024 (edited)
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 15.21 KB | None | 0 0
  1. if not docs then os.loadAPI("apis/docs.lua") end
  2. --Type registry
  3. local types = {
  4.     ["Bits"]={colors.lightBlue,"A series of bits from 0-7. A byte would be represented by 76543210"},
  5.     ["Byte"]={colors.yellow,"A single byte, number 0-255"},
  6.     ["DecodedBlock"]={colors.lightBlue,"A list of decoded bytes"},
  7.     ["HuffmanCode"]={colors.purple,"A code for decompressing values"},
  8.     ["Bitstream"]={colors.lightBlue,"A stream of bits from the file"}
  9. }
  10. for k,v in pairs(types) do
  11.     docs.registerType(k,v[1],v[2])
  12. end
  13.  
  14. --Gets the bits from a byte, starting from least significant
  15. --@Arg Byte byte: The byte to unpack
  16. --@Returns Bits b: The bits from the byte
  17. local function unpackByte(byte)
  18.     local b = {}
  19.     for i=0,7 do
  20.         b[i] = byte%2
  21.         byte = math.floor(byte/2)
  22.     end
  23.     return b
  24. end
  25.  
  26. --Takes a byte and turns it into a series of bits
  27. --@Arg Byte byte: A byte 0-255 to be converted
  28. --@OptionalArg boolean bool: If true, converts the bits to false/true instead of 0/1
  29. --@Returns Bits bits: A table of the bits from 0-7
  30. local function byteToBits(byte,bool)
  31.     local bits = {}
  32.     for i=0,7 do
  33.         bits[i] = byte%2
  34.         if bool then bits[i] = bits[i] == 1 end
  35.         byte = math.floor(byte/2)
  36.     end
  37.     return bits
  38. end
  39.  
  40. local function unpackBits(bytes)
  41.     local bits = {}
  42.     for k,v in ipairs(bytes) do
  43.         local b = unpackByte(v)
  44.         for i=0,7 do
  45.             table.insert(bits,b[i])
  46.         end
  47.     end
  48.     return bits
  49. end
  50. --Starting with least significant bit
  51. --@Arg Bits bits: The series of bits to convert to a number, with the least significant bit first and the most significant last
  52. --@Arg boolean littleEndian: Whether to start with least significant, or most significant
  53. --@Returns number num: The resultant number
  54. local function bitsToNum(bits,littleEndian)
  55.     if not littleEndian then
  56.         local num = 0
  57.         for k,v in ipairs(bits) do
  58.             num = num*2+v
  59.         end
  60.         return num
  61.     end
  62.     local num = 0
  63.     local i = #bits
  64.     while i >= 1 do
  65.         num = num*2+bits[i]
  66.         i = i - 1
  67.     end
  68.     return num
  69. end
  70.        
  71. --Instantiates a new bitstream
  72. --@Arg table bytes: A table of the bytes to be decoded
  73. --@Returns Bitstream bs: The bitstream and functions to access it
  74. function bitStream(bytes)
  75.     local bs = {
  76.         pos=0
  77.     }
  78.     if bytes.type == "bits" then bs.bits = bytes
  79.     else bs.bits = unpackBits(bytes) end
  80.     --Peeks a certain amount, without incrementing position
  81.     function bs:peekb(amount,pos)
  82.         pos = tonumber(pos) or self.pos
  83.         local b = {}
  84.         amount = tonumber(amount) or 1
  85.         for i=1,amount do
  86.             table.insert(b,self.bits[pos+i])
  87.         end
  88.         return b
  89.     end
  90.     --Gets a series of the next few bits
  91.     function bs:getb(amount)
  92.         amount = tonumber(amount) or 1
  93.         self.pos = self.pos
  94.         return self:peekb(amount)
  95.     end
  96.     --Gets the next byte, discarding the remaining bits in the current byte
  97.     --If you want to get the next byte starting at the current position, use bitsToNum(bs:getb(8))
  98.     function bs:nextByte(bigEndian)
  99.         local _ = self:getb((8-self.pos%8))
  100.         return bitsToNum(self:getb(8),bigEndian)
  101.     end
  102.     function bs:shiftl(amount)
  103.         amount = amount or 1
  104.         self.pos = self.pos - amount
  105.     end
  106.     function bs:shiftr(amount)
  107.         amount = amount or 1
  108.         self.pos = self.pos + amount
  109.     end
  110.     --Gets the next huff code
  111.     --@Arg HuffmanCode hufftable: The table to get the code from
  112.     --@OptionalArg number maxLen: The maximum length to read
  113.     --@Returns number code: The huffman code read from the bitstream
  114.     --@Returns None nil: If there was no code found
  115.     function bs:getHuffV(hufftable,maxLen)
  116.         -- local num = hufftable[bitsToNum(self:peekb(maxLen),true)]
  117.         -- local len = bit.band(num,15)
  118.         -- self:shiftr(len)
  119.         -- return math.floor(num/(2^4))
  120.         for i=1,(tonumber(maxLen) or 16) do
  121.             local num = bitsToNum(self:peekb(i),true)
  122.             term.write(num .. " ")
  123.             if hufftable[num] then
  124.                 self:shiftr(i)
  125.                 print()
  126.                 return hufftable[num]
  127.             end
  128.         end
  129.     end
  130.     --Gets a bitstream starting from a position in this bitstream with a predefined length
  131.     --@Arg number len: The length of the bitstream
  132.     --@OptionalArg number startPos: The position within the bitstream to use
  133.     --@Returns Bitstream bs2: The new bitstream
  134.     function bs:subBits(len,startPos)
  135.         local bits = self:peekb(len,startPos)
  136.         bits.type = "bits"
  137.         return bitStream(bits)
  138.     end
  139.     --Gets a number from a bitstream
  140.     --@OptionalArg number amount: The number of bits to read
  141.     --@Returns number num: The number read from the bits, with least significant bit read first
  142.     function bs:getn(amount,bigEndian)
  143.         return bitsToNum(self:getb(amount),bigEndian)
  144.     end
  145.     return bs
  146. end
  147.  
  148. --TODO: Test out, came from https://www.ietf.org/rfc/rfc1951.txt
  149. --@Arg table lengths: {{n=v1,len=length}...}
  150. --@Returns HuffmanCode h: The huffman code
  151. function createHuffman(lengths)
  152.     local bl_count = {}
  153.     local next_code = {}
  154.     local max_bits = 0
  155.     for k,v in ipairs(lengths) do
  156.         bl_count[v.len] = (bl_count[v.len] or 0) + 1
  157.         max_bits = math.max(max_bits,v.len)
  158.     end
  159.     local code = 0
  160.     bl_count[0] = 0
  161.     for i=1,max_bits do
  162.         code = (code+(bl_count[i-1] or 0))*2 --doing a << 1; in general a<<b (a leftshifted by b) is equal to a*(2^b)
  163.         next_code[i] = code
  164.     end
  165.     local h = {}
  166.     for i,v in ipairs(lengths) do
  167.         if v.len ~= 0 then
  168.            h[next_code[v.len]] = v.n
  169.            next_code[v.len] = next_code[v.len]+1
  170.         end
  171.         -- v = v or 0
  172.         -- if v > 0 then
  173.         --     local e = (i-1)*16 + v
  174.         --     local code = next_code[v]
  175.         --     local rcode = 0
  176.         --     for j=1,v do
  177.         --         rcode = rcode + bit.band(1,math.floor(code/(2^(j-1))))*(2^(v-j))
  178.         --     end
  179.         --     for j=0,2^max_bits-1,2^v do
  180.         --         table[j+rcode] = e
  181.         --     end
  182.         --     next_code[v] = next_code[v] + 1
  183.         -- end
  184.     end
  185.     return h
  186. end
  187. --Creates a huffman code from a bitstream
  188. --@Arg Bitstream bs: The bitstream to read from, if the table is dynamic
  189. --@Arg boolean isStatic: Whether the table should be static or not
  190. --@Returns HuffmanCode lit, HuffmanCode dist, HuffmanCode clen: The huffman codes for the literal/lengths, the distances, and the code lengths
  191. --@Returns HuffmanCode lit, HuffmanCode dist: If is static, no codelength table is needed
  192. function huffman(bs,isStatic)
  193.     if not isStatic then
  194.         local hlit = bs:getn(5) + 257 --Length of literal and length codes
  195.         local hdist = bs:getn(5) + 1
  196.         local hclen = bs:getn(4) + 4
  197.         local order = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}
  198.         local clen = {} --code length lengths table
  199.         for i=1,hclen do
  200.             local key = bs:getn(3)
  201.             table.insert(clen,{n=order[i],len=key})
  202.             --clen[order[i]] = key
  203.         end
  204.         for i=hclen+1,#order do
  205.             --clen[order[i]] = 0
  206.             table.insert(clen,{n=order[i],len=0})
  207.         end
  208.         clen = createHuffman(clen) --converting into huffman
  209.         local prevCode = 0
  210.         local lit = {} --literal lengths table
  211.         local index = 0
  212.         while index < hlit do
  213.             local code = bs:getHuffV(clen) or 0
  214.             if code <= 15 then --literal lengths
  215.                 table.insert(lit,{n=index,len=code})
  216.                 index = index+1
  217.                 prevCode = code
  218.             elseif code == 16 then
  219.                 local len = bs:getn(2) + 3
  220.                 for i=1,len do
  221.                     table.insert(lit,{n=index,len=prevCode})
  222.                     index = index+1
  223.                 end
  224.             elseif code == 17 or code == 18 then
  225.                 local len
  226.                 if code == 17 then len = 3+bs:getn(3) else len = 11+bs:getn(7) end
  227.                 for i=1,len do
  228.                     table.insert(lit,{n=index,len=0})
  229.                     index = index+1
  230.                 end
  231.             end
  232.         end
  233.         lit = createHuffman(lit)
  234.         local index = 0
  235.         local dist = {}
  236.         while index < hdist do
  237.             local code = bs:getHuffV(clen) or 0
  238.             if code <= 15 then --literal lengths
  239.                 table.insert(dist,{n=index,len=code})
  240.                 index = index+1
  241.                 prevCode = code
  242.             elseif code == 16 then
  243.                 local len = bs:getn(2) + 3
  244.                 for i=1,len do
  245.                     table.insert(dist,{n=index,len=prevCode})
  246.                     index = index+1
  247.                 end
  248.             elseif code == 17 or code == 18 then
  249.                 local len
  250.                 if code == 17 then len = 3+bs:getn(3) else len = 11+bs:getn(7) end
  251.                 for i=1,len do
  252.                     table.insert(dist,{n=index,len=0})
  253.                     index = index+1
  254.                 end
  255.             end
  256.         end
  257.         dist = createHuffman(dist)
  258.         return lit,dist,clen
  259.     else
  260.         local lengths = {}
  261.         local counts = {144,112,24,8}
  262.         local blens = {8,9,7,8}
  263.         local n = 0
  264.         for i=1,#counts do
  265.             local blen = blens[i]
  266.             for j=1,counts[i] do
  267.                 table.insert(lengths,{n=n,len=blen})
  268.                 n = n+1
  269.             end
  270.         end
  271.         local lit = createHuffman(lengths)
  272.         lengths = {}
  273.         for i=0,31 do
  274.             table.insert(lengths,{n=i,len=5})
  275.             --lengths[i] = 5
  276.         end
  277.         local dist = createHuffman(lengths)
  278.         return lit,dist
  279.     end
  280. end
  281.  
  282. --Reads a block within a bitstream
  283. --@Arg Bitstream bs: The bitstream to read from
  284. --@Returns boolean bfinal, DecodedBlock bytes: If the block is the last one, and the decoded information
  285. function readBlock(bs)
  286.     local bfinal = bs:getn() == 1
  287.     local btype = bs:getn(2)
  288.     print(bfinal, btype)
  289.     if btype == 3 then error("Invalid type") end
  290.     if btype == 0 then
  291.         local len = bs:nextByte()
  292.         len = len + bs:nextByte()*256
  293.         local nlen = bs:nextByte()
  294.         nlen = nlen + bs:nextByte()*256
  295.         local bytes = {}
  296.         for i=1,len do
  297.             local b = bs:nextByte()
  298.             print(b)
  299.             table.insert(bytes,b)
  300.         end
  301.         return bfinal,bytes
  302.     end
  303.     local bytes = {}
  304.     local littable,disttable = huffman(bs,btype == 1)
  305.     local code = bs:getHuffV(littable) or 0
  306.     while code ~= 256 do
  307.         print("code:", code)
  308.         if code <= 255 then
  309.             print(code)
  310.             table.insert(bytes,code)
  311.         else
  312.             local nbits = 0
  313.             local size = 3
  314.             local dist = 1
  315.             if code < 265 then
  316.                 size = size + code - 257
  317.             elseif code < 285 then
  318.                 nbits = math.floor((lit-261)/4) -- lit-261 >> 2, rightshifted 2
  319.                 size = size + (bit.band(code-261,3)+4)*(2^nbits) --no clue how this formula works
  320.             else
  321.                 size = 258
  322.             end
  323.             if nbits > 0 then
  324.                 size = size + bs:getn(nbits)
  325.             end
  326.             local v = bs:getHuffV(disttable) or 0
  327.             if v < 4 then dist = dist + v
  328.             else
  329.                 nbits = math.floor((v-2)/2)
  330.                 dist = dist + (bit.band(v,1)+2)*(2^nbits)
  331.                 dist = dist + bs:getb(nbits)
  332.             end
  333.             print("len:",size,"dist:",dist)
  334.             local p = #bytes - dist + 1 --copying repeat sequences
  335.             while size > 0 do
  336.                 print("prev code at p:",bytes[p])
  337.                 table.insert(bytes,bytes[p])
  338.                 p = p+1
  339.                 size = size - 1
  340.             end
  341.         end
  342.         code = bs:getHuffV(littable) or 0
  343.     end
  344.     return bfinal,bytes
  345. end
  346. --Gets the stupid member thingie
  347. --@Arg File file: The file opened in rb mode to read
  348. --@Returns boolean false: If sussy stuff happens
  349. --@Returns Byte id1, Byte id2, Byte cm, number mtime, Byte xfl, byte opSys, table extra, string name, string comment, number fhcrc, table data, number crc32, number iSize
  350. function readMember(file)
  351.     local name, comment = "",""
  352.     local fhcrc
  353.     local extra  = {}
  354.     local id1,id2 = file.read(), file.read() --bytes 1 and 2 are for the ids
  355.     local cm = file.read() --byte 3 is for the compression method, usually 0x08
  356.     local flgs = byteToBits(file.read(),true)
  357.     --Ignore flgs[0] because we dont care about text/nontext. Dealing with flgs[1] FHCRC later
  358.     local mtime = 0
  359.     for i=0,3 do
  360.         mtime = file.read()*(256^i)+mtime --changed to little endian
  361.     end
  362.     local xfl = file.read()
  363.     local opSys = file.read()
  364.     if flgs[2] then --FEXTRA
  365.         local len = file.read()
  366.         len = len+256*file.read() --changed to little endian
  367.         while len > 0 do
  368.             local si1 = file.read()
  369.             local si2 = file.read()
  370.             local sLen = file.read()
  371.             sLen = sLen+256*file.read() --changed to little endian
  372.             len = len - 4
  373.             local sData = {}
  374.             while sLen > 0 and len > 0 do
  375.                 table.insert(sData,file.read())
  376.                 sLen = sLen-1
  377.                 len = len-1
  378.             end
  379.             extra[si1+si2*256] = sData --little endian as well for index
  380.         end  
  381.     end
  382.     if flgs[3] then --FNAME
  383.         name = ""
  384.         local byte = file.read()
  385.         while byte > 0 do
  386.             name = name .. string.char(byte)
  387.             byte = file.read()
  388.         end
  389.     end
  390.     if flgs[4] then --FCOMMENT
  391.         comment = ""
  392.         local byte = file.read()
  393.         while byte > 0 do
  394.             name = name .. string.char(byte)
  395.             byte = file.read()
  396.         end
  397.     end
  398.     if flgs[1] then --dealing with FHCRC
  399.         fhcrc = file.read()
  400.         fhcrc = fhcrc+256*file.read() --made little endian
  401.     end
  402.     --Reading the data
  403.     local data = {}
  404.     while file.read(0) do
  405.         table.insert(data,file.read())
  406.     end
  407.     local crc32 = 0
  408.     for i=#data-7,#data-4 do
  409.         crc32 = crc32+data[i]*256 --little endian
  410.     end
  411.     local iSize = 0
  412.     for i=#data-3,#data do
  413.         iSize = iSize+256*data[i] --little endian
  414.     end
  415.     return id1,id2,cm,mtime,xfl,opSys,extra,name,comment,fhcrc,data,crc32,iSize
  416. end
  417.  
  418. --Gets the decoded bytes from a zipped file
  419. --@Arg string path: The absolute path to the gzip file
  420. --@Returns boolean false: If stuff went wrong or something
  421. --@Returns table info: A table of DecodedBytes
  422. function getUnzippedBytes(path)
  423.     if not fs.exists(path) then return false end
  424.     file = fs.open(path,"rb")
  425.     local id1,id2,cm,mtime,xfl,opSys,extra,name,comment,fhcrc,data,crc32,iSize = readMember(file)
  426.     file.close()
  427.     if id1 ~= 0x1f or id2 ~= 0x8b then
  428.         return false
  429.     end
  430.     if cm ~= 8 then
  431.         return false
  432.     end
  433.     local bs = bitStream(data)
  434.     local info = {}
  435.     local isFinal,bytes = readBlock(bs)
  436.     table.insert(info,bytes)
  437.     while not isFinal do
  438.         table.insert(info,bytes)
  439.         isFinal,bytes = readBlock(bs)
  440.     end
  441.     return info
  442. end
Advertisement
Add Comment
Please, Sign In to add comment