| 1 | --[[ |
| 2 | Handle Proxmark USB Commands |
| 3 | --]] |
| 4 | |
| 5 | local _commands = require('usb_cmd') |
| 6 | |
| 7 | local _reverse_lookup,k,v = {} |
| 8 | for k, v in pairs(_commands) do |
| 9 | _reverse_lookup[v] = k |
| 10 | end |
| 11 | _commands.tostring = function(command) |
| 12 | if(type(command) == 'number') then |
| 13 | return ("%s (%d)"):format(_reverse_lookup[command]or "ERROR UNDEFINED!", command) |
| 14 | end |
| 15 | return ("Error, numeric argument expected, got : %s"):format(tostring(command)) |
| 16 | end |
| 17 | |
| 18 | Command = { |
| 19 | |
| 20 | new = function(self, o) |
| 21 | |
| 22 | local o = o or {} -- create object if user does not provide one |
| 23 | setmetatable(o, self) -- DIY inheritance a'la javascript |
| 24 | self.__index = self |
| 25 | |
| 26 | o.cmd = o.cmd or _commands.CMD_UNKNOWN |
| 27 | --o.arg1 = "test" |
| 28 | o.arg1 = o.arg1 or 0 |
| 29 | o.arg2 = o.arg2 or 0 |
| 30 | o.arg3 = o.arg3 or 0 |
| 31 | local data = o.data or "0" |
| 32 | |
| 33 | if(type(data) == 'string') then |
| 34 | -- We need to check if it is correct length, otherwise pad it |
| 35 | local len = string.len(data) |
| 36 | if(len < 1024) then |
| 37 | --Should be 1024 hex characters to represent 512 bytes of data |
| 38 | data = data .. string.rep("0",1024 - len ) |
| 39 | end |
| 40 | if(len > 1024) then |
| 41 | -- OOps, a bit too much data here |
| 42 | print( ( "WARNING: data size too large, was %s chars, will be truncated "):format(len) ) |
| 43 | -- |
| 44 | data = data:sub(1,1024) |
| 45 | end |
| 46 | else |
| 47 | print(("WARNING; data was NOT a (hex-) string, but was %s"):format(type(data))) |
| 48 | end |
| 49 | o.data = data |
| 50 | |
| 51 | return o |
| 52 | end, |
| 53 | parse = function (packet) |
| 54 | local count,cmd,arg1,arg2,arg3,data = bin.unpack('LLLLH512',packet) |
| 55 | return Command:new{cmd = cmd, arg1 = arg1, arg2 = arg2, arg3 = arg3, data = data} |
| 56 | end, |
| 57 | } |
| 58 | function Command:__tostring() |
| 59 | local output = ("%s\r\nargs : (%s, %s, %s)\r\ndata:\r\n%s\r\n"):format( |
| 60 | _commands.tostring(self.cmd), |
| 61 | tostring(self.arg1), |
| 62 | tostring(self.arg2), |
| 63 | tostring(self.arg3), |
| 64 | tostring(self.data)) |
| 65 | return output |
| 66 | end |
| 67 | function Command:getBytes() |
| 68 | --If a hex-string has been used |
| 69 | local data = self.data |
| 70 | local cmd = self.cmd |
| 71 | local arg1, arg2, arg3 = self.arg1, self.arg2, self.arg3 |
| 72 | return bin.pack("LLLLH",cmd, arg1, arg2, arg3, data); |
| 73 | end |
| 74 | return _commands |