i try to write dissector on lua for wireshark. i need to parse header field version = 4 bytes (0x00000000)
my code:
do
local asc_sccp =Proto("asc_sccp", "ASC Skinny Client Control Protocol")
local f =asc_sccp.fields
f.length = ProtoField.bytes("asc_sccp.length", "length")
f.version =ProtoField.uint8("asc_sccp.version", "version", base.HEX, 0xC)
function asc_sccp.init()
end
function asc_sccp.dissector(buffer,pinfo,tree)
local subtree = tree:add (asc_sccp, buffer())
local offset = 0
pinfo.cols.protocol = asc_sccp.name
local length = buffer (offset, 4)
subtree:add (f.length, length)
subtree:append_text ("Data length: " .. length)
offset = offset + 4
local version = buffer (offset, 4)
subtree:add (f.version, version)
subtree:append_text (" Version: " .. version)
end
local tcp_table = DissectorTable.get("tcp.port")
tcp_table:add(2000, asc_sccp)
end
Why i am getting error 'attempt to index global 'base' (a nil value)' ?
Could you please help, i looked through a lot of dissector example but i can't find solution
This may be happening because init.lua isn't installed. This can happen in Redhat-based distributions (Fedora, Centos, RHEL etc.) if the development packages aren't installed. See answer here: https://stackoverflow.com/a/40489742/409638
In this line of code:
f.version =ProtoField.uint8("asc_sccp.version", "version", base.HEX, 0xC)
you are accessing the variable 'base'. Specifically, you are indexing it by telling Lua it is a table containing the key "HEX" and trying to retrieve the value at that key. Unless you define the variable 'base' somewhere to be a table (or userdata) and add a value at the key "HEX", lua will complain that you are attempting to index a global variable called 'base', when it is actually nil (i.e. non-existent).
Related
I have a lua script with code block as below:
local call_data = cjson.decode(ARGV[1])
local other_data = cjson.decode(ARGV[2])
local data = {}
local next = next
local populate_data = function(source)
if next(source) == nil then
return
end
for property,value in pairs(source) do
redis.call('HSET', KEYS[2], property, value)
end
end
populate_data(call_data)
populate_data(other_data)
When I try to run the script with the following command KEYS and ARGV as:-
redis-cli --eval dialed.lua "inflight_stats:18" "calls:AC443d7a8111a96ba8074f54a71f0521ce:CA1ec49703eee1959471c71506f43bb42e:dialed" , "{\"from\":\"+18035224181\",\"to\":\"+919943413333\",\"sid\":\"CA1ec49703eee1959471c71506f43bb42e\",\"status\":\"queued\",\"direction\":\"outbound-api\",\"date_created\":null,\"account_sid\":\"AC443d8a8111a96ba8074f54a71f0521ce\"}" "{\"phone\":\"919943413333\",\"campaign_id\":18,\"caller_session_sid\":\"CA828b163153bf5cc301ef5285e38925f9\"}" 0
Error :-
(error) ERR Error running script (call to f_08dcc69ee8baa0200e0cf552948ab4bc338c9978): #user_script:11: #user_script: 11: Lua redis() command arguments must be strings or integers
TL;DR for values returned by cjson.decode(), use cjson.null to compare to JSON's null value.
Explanation: Lua uses nil in tables to mark deleted entries. If JSONinc nulls were converted to Lunatic nils, the decoded objects would be corrupt. Therefore, the cjson lib uses a lightweight userdata type to represent null/nil.
Your 'call_data' has a 'date_created' field that is null - that causes the error.
The funny thing is that Redis, like Lua, will not store a nil/null value, so you'll have to either ignore null values or use a special value in Redis to flag them.
Assuming you'll be ignoring them, here's one way around it:
local call_data = cjson.decode(ARGV[1])
local other_data = cjson.decode(ARGV[2])
local data = {}
local next = next
local null = cjson.null
local populate_data = function(source)
if next(source) == nil then
return
end
for property,value in pairs(source) do
if value ~= null then
redis.call('HSET', KEYS[2], property, value)
end
end
end
populate_data(call_data)
populate_data(other_data)
Also, a small optimization would be to batch the updates, like so:
local payload = {}
for property,value in pairs(source) do
if value ~= null then
table.insert(payload, property)
table.insert(payload, value)
end
end
redis.call('HSET', KEYS[2], unpack(payload))
P.S. if you want, look at ReJSON that I wrote - it is designed to help with what it appears that you're trying to do.
I'm using this (old) Lua module to save and access tables from local files (if there is a better way, please shout I'm not invested) -- https://github.com/gideros/table.save/blob/master/table.save-0.94.lua
It's been working great, but now I'm trying to save key value pairs I'm getting the error:
attempt to call global exportstring (a nil value)
I'm new to Lua. The error is on line 108 on that file I linked to. Any ideas?
I've tried creating blank tables, or basic tables without key value pairs, this works fine. It's when I come to insert strings the issues arise.
This will work:
local myTable = {}
myTable[0] = 2
inputOutputTable.save(myTable, "testytesty")
local testy = inputOutputTable.load("testytesty")
print("Testing 123... " .. testy[0])
However this wont:
local myTable = {}
myTable["welcome"] = "1"
I get : attempt to call global 'exportstring' (a nil value)
Expected results - it saves the table.
What happens - it throws the error.
I am getting an error when i compile this lua script. The LUA editor and ptokaX Server seem to think so. I am unable to figure out the error.
The LUA Editor says the error is in dofile( path.."files/mcunsubs.txt" ).
The PtokaX Editor says that the error is in this part of the code :
data = data:gsub( "[\|]", "" )
data = data:gsub( "\&\#124\;", "\|" )
data = data:gsub( "\&\#036\;", "\$" )
Here is the code.
--[[
This file is part of HiT Hi FiT Hai's PtokaX scripts
Copyright: © 2014 HiT Hi FiT Hai group
Licence: GNU General Public Licence v3 https://www.gnu.org/licenses/gpl-3.0.html
--]]
unsubbed={}
subbed={}
dofile( path.."files/mcunsubs.txt" )
tabUsers = Core.GetOnlineUsers()
for k,v in ipairs(tabUsers) do
if not isthere_key(v.sNick,unsubbed) then
table.insert(subbed,v.sNick)
end
end
ircout = function(data)
data = data:gsub( "[\|]", "" ) -- Removing the terminating '|' character only.
data = data:gsub( "\&\#124\;", "\|" )
data = data:gsub( "\&\#036\;", "\$" )
local file= io.open("/root/DCout.txt","a+")
file:write(data.."\n")
file:flush()
file:close()
end
dcmcout = function(data)
for k,v in ipairs(subbed) do
Core.SendToNick(v,data)
end
end
UserConnected= function (tUser)
if not isthere_key(tUser.sNick,unsubbed) then
if not isthere_key(tUser.sNick,subbed) then
table.insert(subbed,tUser.sNick)
end
end
end
RegConnected = UserConnected
OpConnected = UserConnected
UserDisConnected= function (tUser)
key = isthere_key(tUser.sNick,subbed)
while key do
table.remove( subbed, key)
key = isthere_key(user.sNick,subbed)
end
end
RegDisConnected = UserDisConnected
OpDisConnected = UserDisConnected
The Lua editor (which I assume is SciTE) is giving you the error in line #12 because SciTE doesn't recognise the Core table in the next line:
tabUsers = Core.GetOnlineUsers()
When you execute the same script in PtokaX, the Core table is defined and no error is encountered there. Since you are using a newer Lua version than the one in which this file was originally written (written for Lua 5.1, you've Lua 5.2) you are getting the error. Lua 5.1 was more permissive with wrong patterns for string matching, whereas the latter isn't.
For a solution, you can use the following:
data = data:gsub( "|", "" ):gsub( "|", "|" ):gsub( "$", "$" )
When call a lua function like
PrintMe(MyVariableName)
I would like to be able to actually print "MyVariableName" and not it's value(well, for demo purposes).
Obviously I could just pass the string but that requires extra quotes and I also would like to print it's value.
e.g.,
MyVariable = 4
PrintVariable(MyVariable)
Would print "MyVariable is 4" or whatever
I do not want to have to duplicate the name and variable like
PrintVariable(MyVariable, "MyVariable")
as this is unnecessary duplication.
Can lua handle it?
What I'm doing now is passing the variable name in quotes and using loadstring to get the value but I would like to just pass the variable directly without the extra unnecessary quotes(which I thought debug.getlocal did but it ends up returning the value instead of the name).
Here is mock example
function printme1(var, val)
print(var.." = "..val)
end
function printme2(v)
local r
loadstring("r = "..v)() -- equivalent to r = a but must be used since v is a string representing a and not the object a
print(v.." = "..tostring(r))
end
function printme3(v)
-- unknown
end
a = 3
printme1("a", a)
printme2("a")
printme3(a)
In this case all 3 should print the same thing. printme3 obviously is the most convenient.
You can't say PrintVariable(MyVariable), because Lua gives you no way of determining which variable (if any; a constant could have been used) was used to pass an argument to your function. However, you can say PrintVariable('MyVariable') then used the debug API to look for a local variable in the caller's scope which has that name:
function PrintVariable(name)
-- default to showing the global with that name, if any
local value = _G[name]
-- see if we can find a local in the caller's scope with that name
for i=1,math.huge do
local localname, localvalue = debug.getlocal(2,i,1)
if not localname then
break -- no more locals to check
elseif localname == name then
value = localvalue
end
end
if value then
print(string.format("%s = %s", name, tostring(value)))
else
print(string.format("No variable named '%s' found.", name))
end
end
Now you can say:
PrintVariable('MyVariable')
While in this case will print "MyVariable = 4".
Not, if you really want to do this without the quotes, you could check the caller's locals for variables that have a supplied value, but that's occasionally going to give you the wrong variable name if there is more than one variable in the caller's scope with a given value. With that said, here's how you'd do that:
function PrintVariable(value)
local name
-- see if we can find a local in the caller's scope with the given value
for i=1,math.huge do
local localname, localvalue = debug.getlocal(2,i,1)
if not localname then
break
elseif localvalue == value then
name = localname
end
end
-- if we couldn't find a local, check globals
if not name then
for globalname, globalvalue in pairs(_G) do
if globalvalue == value then
name = globalname
end
end
end
if name then
print(string.format("%s = %s", name, tostring(value)))
else
print(string.format("No variable found for the value '%s'.", tostring(value)))
end
end
Now you can say PrintVariable(MyVariable), but if there happened to be another variable in the caller's scope with the value 4, and it occurred before MyVariable, it's that variable name that will be printed.
you can do stuff like this with the debug library... something like this does what you seem to be looking for:
function a_func(arg1, asdf)
-- if this function doesn't use an argument... it shows up as (*temporary) in
-- calls to debug.getlocal() because they aren't used...
if arg1 == "10" then end
if asdf == 99 then end
-- does stuff with arg1 and asdf?
end
-- just a function to dump variables in a user-readable format
function myUnpack(tbl)
if type(tbl) ~= "table" then
return ""
end
local ret = ""
for k,v in pairs(tbl) do
if tostring(v) ~= "" then
ret = ret.. tostring(k).. "=".. tostring(v).. ", "
end
end
return string.gsub(ret, ", $", "")
end
function hook()
-- passing 2 to to debug.getinfo means 'give me info on the function that spawned
-- this call to this function'. level 1 is the C function that called the hook.
local info = debug.getinfo(2)
if info ~= nil and info.what == "Lua" then
local i, variables = 1, {""}
-- now run through all the local variables at this level of the lua stack
while true do
local name, value = debug.getlocal(2, i)
if name == nil then
break
end
-- this just skips unused variables
if name ~= "(*temporary)" then
variables[tostring(name)] = value
end
i = i + 1
end
-- this is what dumps info about a function thats been called
print((info.name or "unknown").. "(".. myUnpack(variables).. ")")
end
end
-- tell the debug library to call lua function 'hook 'every time a function call
-- is made...
debug.sethook(hook, "c")
-- call a function to try it out...
a_func("some string", 2012)
this results in the output:
a_func(asdf=2012, arg1=some string)
you can do fancier stuff to pretty this up, but this basically covers how to do what you're asking.
I have bad news, my friend. You can access function parameter names as they appear at the top of the function, but the data to access exactly what they were named in the calling function does not exist. See the following:
function PrintVariable(VariableToPrint)
--we can use debug.getinfo() to determine the name 'VariableToPrint'
--we cannot determine the name 'MyVariable' without some really convoluted stuff (see comment by VBRonPaulFan on his own answer)
print(VariableToPrint);
end
MyVariable = 4
PrintVariable(MyVariable)
To illustrate this, imagine if we had done:
x = 4
MyVariable = x
MyOtherVariable = x
x = nil
PrintVariable(MyVariable)
Now if you were Lua, what name would you attach in the metadata to the variable that ends up getting passed to the function? Yes, you could walk up the stack with debug.getint() looking for the variable that was passed in, but you may find several references.
Also consider:
PrintVariable("StringLiteral")
What would you call that variable? It has a value but no name.
You could just use this form:
local parms = { "MyVariable" }
local function PrintVariable(vars)
print(parms[1]..": "..vars[1])
end
local MyVariable = "bar"
PrintVariable{MyVariable}
Which gives:
MyVariable: bar
It isn't generic, but it is simple. You avoid the debug library and loadstring by doing it this way. If your editor is any good, you could write a macro to do it.
Another possible solution is add this facility your self.
The Lua C API and source is pretty simple and extendable.
I/we don't know the context of your project/work but if you ARE making/embedding your own Lua build you could extend the debug library with something to do this.
Lua passes it's values by reference, but unknown offhand if these contain a string name in them and if so if easily accessible.
In your example the value declaration is the same as:
_G["MyVariable"] = 4
Since it's global. If it were declared local then like others stated here you can enumerate those via debug.getlocal(). But again in the C context of the actual reference context it might not matter.
Implement a debug.getargumentinfo(...) that extends the argument table with name key, value pairs.
This is quite an old topic and I apologize for bringing it back to life.
In my experience with lua, the closest I know to what the OP asked for is something like this:
PrintVariable = {}
setmetatable(PrintVariable, {__index = function (self, k, v) return string.format('%s = %s', k, _G[k]) end})
VAR = 0
VAR2 = "Hello World"
print(PrintVariable.VAR, PrintVariable.VAR2)
-- Result: VAR = 0 VAR2 = Hello World
I do not give more explanation, because the code is quite readable, however:
What happens here is simple, you only set a metatable to the PrintVariable variable and add the __index metamethod that is called when the table is forced to search for a value in its index, thanks to this functionality you can achieve what you see in the example.
Reference: https://www.lua.org/manual/5.1/manual.html
I hope that future and new visitors will find this helpful.
First of all, I'm new to Lua altogether, and this is my first attempt at writing a wireshark dissector.
My protocol is straightforward - a 2 byte length field, followed by a string of that length.
When I run the code through the Lua console, everything works as expected.
When the code is added to the Wireshark plugins directory, I get the error
Lua Error: [string "C:\Users...\AppData\Roaming\Wireshark..."]:15: calling 'add' on bad self (number expected, got string)
Line 15 corresponds is the t:add(f_text... line.
Can anyone explain the discrepancy between the execution methods?
do
local p_multi = Proto("aggregator","Aggregator");
local f_len = ProtoField.int16("aggregator.length","Length",base.DEC)
local f_text = ProtoField.string("aggregator.text","Text")
p_multi.fields = { f_len, f_text }
local data_dis = Dissector.get("data")
function p_multi.dissector(buf,pkt,root)
pkt.cols.protocol = "Aggregator"
local len = buf(0,2):int()
local t = root:add(p_multi,buf(0,len+2))
t:add(f_len,buf(0,2),"Length: " .. buf(0,2):int())
t:add(f_text,buf(2,len),"Text: " .. buf(2,len):string())
end
local tcp_encap_table = DissectorTable.get("tcp.port")
tcp_encap_table:add(4321,p_multi)
end
Your dissector code is very close to correct, but you're doing extra work that the interface won't accept. If you change your dissector function like so,
function p_multi.dissector(buf,pkt,root)
pkt.cols.protocol = "Aggregator"
local len = buf(0,2):int()
local t = root:add(p_multi,buf(0,len+2))
t:add(f_len,buf(0,2)) --let Wireshark do the hard work
t:add(f_text,buf(2,len)) --you've already defined their labels etc.
end
you'll get the desired behavior. The labels "Text" and "Length" are already defined for your fields, so there is no need to provide them again on lines 15 and 16.