1 import socket, os, stat, struct, pwd, errno
2 from statemachine import StateMachine
3 from libtuer import logger
4 SO_PEERCRED = 17 # DO - NOT - TOUCH
7 socketname = "/run/tuer.sock"
9 # send to client for information but don't care if it arrives
10 def waynesend (conn, what):
12 conn.send(what.encode())
16 # delete a file, don't care if it did not exist in the first place
21 # only ignore error if it was "file didn't exist"
22 if e.errno != errno.ENOENT:
25 # the class doing the actual work
28 b'buzz': StateMachine.CMD_BUZZ,
29 b'unlock': StateMachine.CMD_UNLOCK,
30 b'lock': StateMachine.CMD_LOCK,
31 b'fallback_mode_on': StateMachine.CMD_FALLBACK_ON,
32 b'fallback_mode_off': StateMachine.CMD_FALLBACK_OFF,
35 def __init__(self, sm):
38 self._sock = socket.socket (socket.AF_UNIX, socket.SOCK_STREAM)
39 # delete old socket file and don't bitch around if it's not there
41 # bind socket to file name
42 self._sock.bind (socketname)
43 # allow only users in the tuergroup to write to the socket
44 os.chown (socketname, 0, tuergroupid)
45 os.chmod (socketname, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP)
46 # listen to the people, but not too many at once
49 def _answer(self, conn):
50 def answer(msg, lastMsg = True):
51 # this is called in another thread, so it should be quick and not touch the TySocket
58 '''Handles incoming connections and keyboard events'''
59 self._sock.settimeout(None)
62 conn, addr = self._sock.accept()
65 # get peer information
66 (pid, uid, gid) = struct.unpack('3i', conn.getsockopt(socket.SOL_SOCKET, SO_PEERCRED, struct.calcsize('3i')))
67 # get some data from the client (enough to hold any valid command)
70 logger.info("TySocket: Received command from %s (uid %d): %s" % (pwd.getpwuid(uid).pw_name, uid, str(data)))
71 # lookup the command, send it to state machine
73 self._sm.callback(self.CMDs[data], self._answer(conn))
74 # _answer will be called, and it will close the connection
76 waynesend(conn, 'Command not found')
77 except KeyboardInterrupt:
78 raise # forward Ctrl-C to the outside
79 except socket.timeout:
81 logger.info("TySocket: Connection timed out")
82 except Exception as e:
83 logger.critical("TySocket: Something went wrong: %s" % str(e))