asyncio: setting file permissions of a Unix socket?
Martin
martin at libtec.org
Sat Oct 25 08:42:12 EDT 2014
Hi! :)
I'm using the asyncio.Protocol interface to build a server which binds
to a unix socket file. I want other system users to connect to the
unix socket, so to communicate with the server.
Where should I set the permissions of the file?
The problem is that the socket file is created when the programs
starts listening for the connections. Because of this, I can't change
the file permission before a connection is made. At the same time, a
connection can't happen because of the file permissions.
Currently, I workaround this with os.umask(0o000). But I also want to
make other files later with default permissions. So I have to revert
the umask, but where? I can only do this in the client connection
code, which is out of place.
Bellow is what I've done. Can you suggest a better way? I wish to
avoid permission fixing code like os.umask() for every connection.
Maybe I shouldn't use asyncio.Protocol in the first place?
Thank you! :)
Example code:
#! /usr/bin/env python3
import os
import asyncio
class ExampleServer(asyncio.Protocol):
def __init__(self):
os.umask(0o002) # This is my workaround. Can I avoid this?
# if not umask_restored: # An alternative workaround.
# os.umask(0o002)
def connection_made(self, transport):
self.transport = transport
def data_received(self, data):
print("Data: ", data)
self.transport.write(b"OK, bye!\n")
self.transport.close()
def main():
socket_filepath = "/tmp/example-server.socket"
loop = asyncio.get_event_loop()
server_coroutine = loop.create_unix_server(ExampleServer, socket_filepath)
server = loop.run_until_complete(server_coroutine)
os.umask(0o000) # This is my workaround.
try:
loop.run_forever()
except KeyboardInterrupt:
print("exit")
finally:
server.close()
loop.close()
os.remove(socket_filepath)
if __name__ == "__main__":
main()
More information about the Python-list
mailing list