oremanj/python-netfilterqueue

How to work with async loop and file descriptor

tessanix opened this issue · 4 comments

I'm working with asyncio loop and I would like to await a nfqueue.run(block=False) function.
I read that I could do that with the nfqueue.get_fd() method but this method seems to only return a integer.
I really don't understand the concept of file descriptor and how to use them.
Could someone help me please ?

I'm not an asyncio expert but I think something like this will work (once you're already inside an asyncio.run() context):

loop = asyncio.get_event_loop()

def on_readable():
    nfqueue.run(block=False)

loop.add_reader(nfqueue.get_fd(), on_readable)

The file descriptor is indeed a plain old integer, but one that has special meaning to the operating system: it represents an open file, socket, or other thing you can do I/O on. The netfilter queue is implemented using a special kind of socket, so you can wait for it to have data available to read, in the same way you would for any other socket. And then when there is data available to read, you call run(block=False) to tell the netfilterqueue library to read everything that's currently available, but not wait for more things after that.

I have a better understanding of file descriptors and I can progress in my work with this little piece of code now.
Thank you very much!
I have another question if you don't mind. Does the netfilterqueue library work with nftables instead of iptables?

Yes, nftables should work too, but the syntax for setting up a firewall rule to route to the queue is different. https://wiki.nftables.org/wiki-nftables/index.php/Queueing_to_userspace -- it's the same mechanism inside the kernel, so the netfilterqueue library doesn't care whether you're using nftables or iptables as long as you give it the same queue number listed in your firewall rule.

Ok! Thank you again!