b987567168bd9ca93a23e3ff0252b76a3f0d9c2d
[saartuer.git] / tysock.py
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
5
6 tuergroupid = 1005
7 socketname = "/run/tuer.sock"
8
9 # send to client for information but don't care if it arrives
10 def waynesend (conn, what):
11         try:
12                 conn.send(what.encode())
13         except:
14                 pass # we do not care
15
16 # delete a file, don't care if it did not exist in the first place
17 def forcerm(name):
18         try:
19                 os.unlink (name)
20         except OSError as e:
21                 # only ignore error if it was "file didn't exist"
22                 if e.errno != errno.ENOENT:
23                         raise
24
25 # the class doing the actual work
26 class TySocket():
27         CMDs = {
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,
33                 b'status': StateMachine.CMD_STATUS,
34         }
35         
36         def __init__(self, sm):
37                 self._sm = sm
38                 # create socket
39                 self._sock = socket.socket (socket.AF_UNIX, socket.SOCK_STREAM)
40                 # delete old socket file and don't bitch around if it's not there
41                 forcerm(socketname)
42                 # bind socket to file name
43                 self._sock.bind (socketname)
44                 # allow only users in the tuergroup to write to the socket
45                 os.chown (socketname, 0, tuergroupid)
46                 os.chmod (socketname, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP)
47                 # listen to the people, but not too many at once
48                 self._sock.listen(1)
49         
50         def _answer(self, conn):
51                 def answer(msg, lastMsg = True):
52                         # this is called in another thread, so it should be quick and not touch the TySocket
53                         waynesend(conn, msg)
54                         if lastMsg:
55                                 conn.close()
56                 return answer
57         
58         def accept(self):
59                 '''Handles incoming connections and keyboard events'''
60                 self._sock.settimeout(None)
61                 while True:
62                         # accept connections
63                         conn, addr = self._sock.accept()
64                         conn.settimeout(0.1)
65                         try:
66                                 # get peer information
67                                 (pid, uid, gid) = struct.unpack('3i', conn.getsockopt(socket.SOL_SOCKET, SO_PEERCRED, struct.calcsize('3i')))
68                                 # get some data from the client (enough to hold any valid command)
69                                 data = conn.recv (32)
70                                 # log the command
71                                 logger.info("TySocket: Received command from %s (uid %d): %s" % (pwd.getpwuid(uid).pw_name, uid, str(data)))
72                                 # lookup the command, send it to state machine
73                                 if data in self.CMDs:
74                                         self._sm.callback(self.CMDs[data], self._answer(conn))
75                                         # _answer will be called, and it will close the connection
76                                         continue # make sure we break so we don't close it
77                                 else:
78                                         waynesend(conn, 'Command not found')
79                         except KeyboardInterrupt:
80                                 raise # forward Ctrl-C to the outside
81                         except socket.timeout:
82                                 # it's okay
83                                 logger.info("TySocket: Connection timed out")
84                         except Exception as e:
85                                 logger.critical("TySocket: Something went wrong: %s" % str(e))
86                         conn.close()