Adding pcap file contents to Hash Table dynamically in lua - networking

I am trying to read .pcap file, and aggregate number of data packets for each client(client ip here is destination address). For example, if 5 data packets have been sent to xxx.ccc.vvv.bbb, i am outputting into a file in this format:
xxx.ccc.vvv.bbb 5
This is the program i have written below:
#!/usr/bin/lua
do
numberofpkts = 0
stat = {client1 = {numberofpkts = {}}}
local file = io.open("luawrite","w")
local function init_listener()
local tap = Listener.new("wlan")
local dest_addr = Field.new("wlan.da")
local pkt_type = Field.new("wlan.fc.type")
function tap.reset()
numberofpkts = 0;
end
function tap.packet(pinfo, tvb)
client = dest_addr()
client1 = tostring(client)
type = pkt_type()
if(tostring(type) == '2') then
stat.client1.numberofpkts = stat.client1.numberofpkts+1
file:write(tostring(client1),"\t", tostring(stat.client1.numberofpkts),"\n")
end
end
end
init_listener()
end
Here, wlan.da gives the destination address. wlan.fc.type indicates that it is data packet(type = 2). I am running this using a tshark on wireless traffic.
I am getting an error:
tshark: Lua: on packet 3 Error During execution of Listener Packet Callback:
/root/statistics.lua:21: attempt to call field 'tostring' (a nil value)
tshark: Lua: on packet 12 Error During execution of Listener Packet Callback happened 2 times:
/root/statistics.lua:21: attempt to call field 'tostring' (a nil value)
Please help me how i should solve this problem. Thanks in advance!

Seems that you're trying to make the stat table a dict of statistics; if so, make sure to initialize its members correctly (by the client, whatever its value is). Maybe this helps?
do
stat = {}
local file = io.open("luawrite","w")
local function init_listener()
local tap = Listener.new("wlan")
local dest_addr = Field.new("wlan.da")
local pkt_type = Field.new("wlan.fc.type")
function tap.reset()
local client = dest_addr()
stat[client] = stat[client] or {numberofpkts = 0}
stat[client].numberofpkts = 0
end
function tap.packet(pinfo, tvb)
local client, type = dest_addr(), pkt_type()
if(tostring(type) == '2') then
stat[client] = stat[client] or {numberofpkts = 0}
stat[client].numberofpkts = stat[client].numberofpkts + 1
file:write(tostring(client),"\t", tostring(stat.client1.numberofpkts),"\n")
end
end
end
init_listener()
end

Related

Android: Why is Room so slow?

I am working on a simple database procedure in Kotlin using Room, and I can't explain why the process is so slow, mostly on the Android Studio emulator.
The table I am working on is this:
#Entity(tableName = "folders_items_table", indices = arrayOf(Index(value = ["folder_name"]), Index(value = ["item_id"])))
data class FoldersItems(
#PrimaryKey(autoGenerate = true)
var uid: Long = 0L,
#ColumnInfo(name = "folder_name")
var folder_name: String = "",
#ColumnInfo(name = "item_id")
var item_id: String = ""
)
And what I am just trying to do is this: checking if a combination folder/item is already present, insert a new record. If not, ignore it. on the emulator, it takes up to 7-8 seconds to insert 100 records. On a real device, it is much faster, but still, it takes around 3-4 seconds which is not acceptable for just 100 records. It looks like the "insert" query is particularly slow.
Here is the procedure that makes what I have just described (inside a coroutine):
val vsmFoldersItems = FoldersItems()
items.forEach{
val itmCk = database.checkFolderItem(item.folder_name, it)
if (itmCk == 0L) {
val newFolderItemHere = vsmFoldersItems.copy(
folder_name = item.folder_name,
item_id = it
)
database.insertFolderItems(newFolderItemHere)
}
}
the variable "items" is an array of Strings.
Here is the DAO definitions of the above-called functions:
#Query("SELECT uid FROM folders_items_table WHERE folder_name = :folder AND item_id = :item")
fun checkFolderItem(folder: String, item: String): Long
#Insert
suspend fun insertFolderItems(item: FoldersItems)
Placing the loop inside a single transaction should significantly reduce the time taken.
The reason is that each transaction (by default each SQL statement that makes a change to the database) will result in a disk write. So that's 100 disk writes for your loop.
If you begin a transaction before the loop and then set the transaction successful when the loop is completed and then end the transaction a single disk write is required.
What I am unsure of is exactly how to do this when using a suspended function (not that familiar with Kotlin).
As such I'd suggest either dropping the suspend or having another Dao for use within loops.
Then have something like :-
val vsmFoldersItems = FoldersItems()
your_RoomDatabase.beginTransaction()
items.forEach{
val itmCk = database.checkFolderItem(item.folder_name, it)
if (itmCk == 0L) {
val newFolderItemHere = vsmFoldersItems.copy(
folder_name = item.folder_name,
item_id = it
)
database.insertFolderItems(newFolderItemHere)
}
}
your_RoomDatabase.setTransactionSuccessful() //<<<<<<< IF NOT set then ALL updates will be rolled back
your_RoomDatabase.endTransaction()
You may wish to refer to:-
https://developer.android.com/reference/androidx/room/RoomDatabase
You may wish to especially refer to runInTransaction

citizen:/scripting/lua/scheduler.lua:61: attempt to call a nil value (upvalue 'fn')

So the code error is this:
Also, the lua code is used for FiveM-coding, using vRP as main framework.
The error appeals a function that is on vRP, and the caller is a base-function from the artifacts.
Even so, this is the code of the artifact that triggers the error
Code
How the error looks like
local GetGameTimer = GetGameTimer
local _sbs = Citizen.SubmitBoundaryStart
local coresume, costatus = coroutine.resume, coroutine.status
local debug = debug
local coroutine_close = coroutine.close or (function(c) end) -- 5.3 compatibility
local hadThread = false
local curTime = 0
-- setup msgpack compat
msgpack.set_string('string_compat')
msgpack.set_integer('unsigned')
msgpack.set_array('without_hole')
msgpack.setoption('empty_table_as_array', true)
-- setup json compat
json.version = json._VERSION -- Version compatibility
json.setoption("empty_table_as_array", true)
json.setoption('with_hole', true)
-- temp
local _in = Citizen.InvokeNative
local function FormatStackTrace()
return _in(`FORMAT_STACK_TRACE` & 0xFFFFFFFF, nil, 0, Citizen.ResultAsString())
end
local function ProfilerEnterScope(scopeName)
return _in(`PROFILER_ENTER_SCOPE` & 0xFFFFFFFF, scopeName)
end
local function ProfilerExitScope()
return _in(`PROFILER_EXIT_SCOPE` & 0xFFFFFFFF)
end
local newThreads = {}
local threads = setmetatable({}, {
-- This circumvents undefined behaviour in "next" (and therefore "pairs")
__newindex = newThreads,
-- This is needed for CreateThreadNow to work correctly
__index = newThreads
})
local boundaryIdx = 1
local runningThread
local function dummyUseBoundary(idx)
return nil
end
local function getBoundaryFunc(bfn, bid)
return function(fn, ...)
local boundary = bid or (boundaryIdx + 1)
boundaryIdx = boundaryIdx + 1
bfn(boundary, coroutine.running())
local wrap = function(...)
dummyUseBoundary(boundary)
local v = table.pack(fn(...))
return table.unpack(v)
end
local v = table.pack(wrap(...))
bfn(boundary, nil)
return table.unpack(v)
end
end
The screenshot of your code shows two calls to getBoundaryFunc
runWithBoundaryStart = getBoundaryFunc(Citizen.SubmitBoundaryStart)
runWithBoundaryEnd = getBoundaryFunc(Citizen.SubmitBoundaryEnd)
In order for fn to become nil either of this funcions must be called without proving the first parameter.
find out wether there are more calls to getBoundaryFunc
find out if its return values are called with nil instead of the expected function value as first parameter
fix that

Adjust TCP/UDP Server Runtime

I am using Embarcadero RAD Studio 10. I am trying to use Indy client/server components in my application.
I want to adjust the TCP/UDP server IP address and port at runtime.
I can see the default settings at design-time:
I can add entries to the Bindings and set the DefaultPort.
But, I want to do this while the program is running. I want to set the bindings and port in my UI and push a button to make the server use what I entered.
How do I do this?
The Bindings is a collection of TIdSocketHandle objects. Adding a new entry to the collection at design-time is the same as calling the Bindings.Add() method at runtime.
TIdSocketHandle has IP and Port properties. When a TIdSocketHandle object is created, its Port is initialized with the current value of the DefaultPort.
To do what you are asking, simply call Bindings.Add() and set the new object's IP and Port properties. For example:
Delphi:
procedure TMyForm.ConnectButtonClick(Sender: TObject);
var
LIP: string;
LPort: TIdPort;
LBinding: TIdSocketHandle;
begin
LIP := ServerIPEdit.Text;
LPort := IntToStr(ServerPortEdit.Text);
IdTCPServer1.Active := False;
IdTCPServer1.Bindings.Clear;
LBinding := IdTCPServer1.Bindings.Add;
LBinding.IP := LIP;
LBinding.Port := LPort;
IdTCPServer1.Active := True;
end;
C++:
void __fastcall TMyForm::ConnectButtonClick(TObject *Sender);
{
String LIP = ServerIPEdit->Text;
TIdPort LPort = IntToStr(ServerPortEdit->Text);
IdTCPServer1->Active = false;
IdTCPServer1->Bindings->Clear();
TIdSocketHandle *LBinding = IdTCPServer1->Bindings->Add();
LBinding->IP = LIP;
LBinding->Port = LPort;
IdTCPServer1->Active = true;
}
Same thing with TIdUDPServer.

How to set focus on a client under mouse cursor when a tag is changed?

When I switch to another tag, a new client gets selected, but it is sometimes not a client that I have my mouse cursor over. To get a client under my mouse pointer focused, I have to either click somewhere on it, or switch to it with Mod4+j / k, or move mouse cursor out and back on that client.
I want awesome to give focus to a client that is under the mouse cursor whenever a tag is changed. How do I do that?
I found a function mouse.object_under_pointer() that finds the client I need, but I don't know when to call that function. Should I connect a handler to some particular signal? I tried connecting to various signals from Signals page on the wiki and checking with naughty.notify() if that is the right signal, but none of them were triggered when I was switching between tags.
This code did the trick, however there should be a better way to do this than setting up a huge 200 ms timer (smaller timeouts didn't properly focus some clients for me, but you can try setting a smaller one).
tag.connect_signal(
"property::selected",
function (t)
local selected = tostring(t.selected) == "false"
if selected then
local focus_timer = timer({ timeout = 0.2 })
focus_timer:connect_signal("timeout", function()
local c = awful.mouse.client_under_pointer()
if not (c == nil) then
client.focus = c
c:raise()
end
focus_timer:stop()
end)
focus_timer:start()
end
end
)
tag is this global object, so you should just place this code anywhere in your rc.lua.
Two things should be done:
First, you should remove require("awful.autofocus") from your config, so that this module no longer tries to focus some client via the focus history when you switch tags.
Then, this code works for me:
do
local pending = false
local glib = require("lgi").GLib
tag.connect_signal("property::selected", function()
if not pending then
pending = true
glib.idle_add(glib.PRIORITY_DEFAULT_IDLE, function()
pending = false
local c = mouse.current_client
if c then
client.focus = c
end
return false
end)
end
end)
end
This uses GLib directly to get a callback for when no other events are pending. This should mean that "everything else" was handled.
I know this is pretty old, but it helped me to come up with this
function focus_client_under_mouse()
gears.timer( { timeout = 0.1,
autostart = true,
single_shot = true,
callback = function()
local n = mouse.object_under_pointer()
if n ~= nil and n ~= client.focus then
client.focus = n end
end
} )
end
screen.connect_signal( "tag::history::update", focus_client_under_mouse )

connecting to two different sqlite databases in lua using luasql

Goal
I'm trying to connect to two different databases, one after the other.
I know the first connection is working because I attempt to create a new record, and it works. When I try to connect to the second database and query a table, the logic fails with an error saying that the table I'm querying doesn't exist. But i know it does.
Here's the test code that creates the connection objects:
local database1con
local database2con
local database1env
local database2env
local firstdatabase_connect = function()
if not database1con then
database1env = assert (luasql.sqlite3())
database1con = assert (database1env:connect("database1.sqlite"))
return true
else
return false
end
end
local seconddatabase_connect = function()
if not database2con then
database2env = assert (luasql.sqlite3())
database2con = assert (database2env:connect("database2.sqlite"))
return true
else
return false
end
end
local firstdatabase_disconnect = function()
if database1env then
database1env:close()
database1env = nil
end
if database1con then
database1con:close()
database1con = nil
end
end
local seconddatabase_disconnect = function()
if database2env then
database2env:close()
database2env = nil
end
if database2con then
database2con:close()
database2con = nil
end
end
And here's the logic that tries to actually connect to the databases:
local connected = firstdatabase_connect()
-- run some select & insert commands
firstdatabase_disconnect()
-- now connect to second database
sql = "INSERT INTO users VALUES("..user_id..", "..username.value..", 'test',"..os.date("%Y%m%d%H%M%S")..", Null,Null)"
local db2connected = seconddatabase_connect()
if db2connected then
local res, err = database2con:execute(sql)
if not res and err then
success = false
end
seconddatabase_disconnect()
end
Problem
The insert fails with the following message: LuaSQL: no such table: users
The users tables doesn't exist in database1, but does exist in database2.
What i've tested so far
I thought that perhaps even though I'm disconnecting from the first database, it was somehow checking the wrong db. So after I make the call to firstdatabase_disconnect(), I added another select statement that attempted to select from the first database.
The system failed with a message that the connection object for database1 is nil.
which is good.
I'm not sure what else to test.
If you have any suggestions, I'd appreciate it.

Resources