X-Git-Url: https://git.ralfj.de/saartuer.git/blobdiff_plain/01b0198699d9871bf642930ece770d0d1be917b9..afd14c9b67b6fb41219abf0dcd5e7fda37a1b8a9:/tuerd?ds=inline diff --git a/tuerd b/tuerd index a283f26..f679fa8 100755 --- a/tuerd +++ b/tuerd @@ -1,7 +1,8 @@ #!/usr/bin/python3 -import time, socket, os, stat +import time, socket, os, stat, atexit, errno, struct from datetime import datetime import RPi.GPIO as GPIO +SO_PEERCRED = 17 # DO - NOT - TOUCH GPIO.setmode(GPIO.BOARD) # ******** definitions ********* @@ -23,6 +24,15 @@ def doNothing (conn): waynesend(conn,b"0") pass +# delete a file, don't care if it did not exist in the first place +def forcerm(name): + try: + os.unlink (name) + except OSError as e: + # only ignore error if it was "file didn't exist" + if e.errno != errno.ENOENT: + raise + # commands: on a pin do a series of timed on/off switches class Pinoutput: # name is for logging and also used for mapping command names to instances of this class @@ -52,6 +62,9 @@ pinlist = [Pinoutput("open", 12, [(True, 0.3), (False, 5.0)]), # ******** main ********* +# at the end do a cleanup +atexit.register(GPIO.cleanup); + # convert list of pin objects to dictionary for command lookup pindict = {} for pin in pinlist: @@ -60,12 +73,12 @@ for pin in pinlist: # create socket sock = socket.socket (socket.AF_UNIX, socket.SOCK_STREAM) # delete old socket file and don't bitch around if it's not there -try: - os.unlink (socketname) -except OSError: - pass +forcerm(socketname) # bind socket to file name sock.bind (socketname) +# ensure we close and delete the socket when we quit (atexit.register is LIFO!) +atexit.register(forcerm, socketname) +atexit.register(sock.close) # allow only users in the tuergroup to write to the socket os.chown (socketname, 0, tuergroupid) os.chmod (socketname, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP) @@ -77,7 +90,8 @@ sock.listen(1) while True: # accept connections conn, addr = sock.accept() - # TODO: use addr to determine the client for logging + # get peer information (TODO use it for logging) + (pid, uid, gid) = (struct.unpack('3i', conn.getsockopt(socket.SOL_SOCKET, SO_PEERCRED, struct.calcsize('3i')))) # get some data from the client (enough to hold any valid command) data = conn.recv (32) # log the command @@ -88,6 +102,3 @@ while True: # close connection cleanly conn.close() -# FIXME will this be executed after receiving a terminating signal? -GPIO.cleanup() -