-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver
More file actions
executable file
·242 lines (213 loc) · 7.46 KB
/
server
File metadata and controls
executable file
·242 lines (213 loc) · 7.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#!/usr/bin/env python3.4
import sys,os
sys.path.insert(0, os.path.expanduser("~/.lir/libraries"))
_version = float(str(sys.version_info[0]) + '.' + str(sys.version_info[1]))
if _version < 3.0:
#to avoid syntax error in 3.0 +
exec("print \"Python 3.0 or higher is required\"")
sys.exit(1)
HOST = ''
import socket,pickle,base64
import os,time
#TODO replace with threading module
from _thread import *
import subprocess,select
import lir
#listeners are clients waiting to receive updates from the server
listeners = []
triggers = {}
signals = {}
IGNORED_SIGNALS = ["settings.py","lang.py","fs.py","lir.py"]
def execute(command,directory = "~/.lir/bin"):
d = os.getcwd()
os.chdir(lir.FileSystem.expand_path(directory))
out = subprocess.getoutput("./"+command)
os.chdir(d)
return out
def action(mode,data,device):
command = None
#human speech for parsing with the dictionaries
if mode == "speech":
#TODO dictionaries active when certain programs running
#TODO dictionaries active when certain programs focused
device.send(execute(subprocess.getoutput(lir.FileSystem.home()+"/.lir/dictionary \""+data+"\" "+lir.FileSystem.home()+"/.lir/actions/default.dic")) + "\n")
#a direct command to be ran
elif mode == "direct":
device.out.info("Executing",data)
sendData = execute(data)
if len(sendData) < 1024:
if sendData.startswith("Traceback"):
device.out.fail(sendData)
else:
device.out.info(sendData)
else:
device.out.info("Sending",len(sendData),"bytes")
device.send(sendData + "\n")
elif mode == "follow":
if data in triggers:
triggers[data].append(device.conn.getpeername()[0])
else:
triggers[data] = [device.conn.getpeername()[0]]
device.out.info("Following",data)
elif mode == "interact":
device.out.info("Preparing Interaction")
d = os.getcwd()
os.chdir(lir.FileSystem.expand_path("~/.lir/bin"))
device.out.debug("Moved to","~/.lir/bin")
outs = device.conn.makefile('w', buffering=None)
ins = device.conn.makefile('r', buffering=None)
p = subprocess.Popen(data,shell=True,stdout=outs,stderr=outs,stdin=ins)
while p.poll() == None:
time.sleep(0.1)
device.close()
#the message is encrypted
elif mode == "enc":
iv = device.readLine()
did = device.readLine()
ddb = lir.DataStorage.Devices(lir.FileSystem.expand_path("~/.lir/devices.db"))
ddata = ddb.getDeviceByID(did)
ddb.close()
out2 = lir.Output.Writer(device.out.name,True)
out2.info("Encrypted Connection")
device2 = lir.Communication.Device(out2,device.conn,ddata['key'],True)
msg = device2.decrypt(data,iv)
try:
mode,msg = msg.split(":",1)
except:
mode = "speech"
action(mode,msg,device2)
def resp(conn,out):
device = lir.Communication.Device(out,conn)
#Receiving from client
data = device.readLine()
if data == "":
return
#data = str(data)[2:-1]
#cleanup telnet or other methods of input
if data.endswith("\\r\\n"):
data = data[:-4]
#android adds newline
if data.endswith("\\n"):
data = data[:-2]
try:
mode,data = data.split(":",1)
except:
mode = "speech"
action(mode,data,device)
def handle(conn):
peer = conn.getpeername()
ip = peer[0]
port = str(peer[1])
out = lir.Output.Writer(ip+":"+port)
out.success("Connected")
resp(conn,out)
try:
conn.close()
except:
pass
out.warning("Disconnected")
def handleSig(conn):
peer = conn.getpeername()
ip = peer[0]
port = str(peer[1])
out = lir.Output.Writer("SIG "+ip+":"+port)
out.success("Connected")
device = lir.Communication.Device(out,conn)
data = device.readLine()
if data == "":
return
#data = str(data)[2:-1]
#cleanup telnet or other methods of input
if data.endswith("\\r\\n"):
data = data[:-4]
#android adds newline
if data.endswith("\\n"):
data = data[:-2]
try:
mode,data = data.split(":",1)
except:
mode = "listen"
if mode == "enc":
iv = device.readLine()
did = device.readLine()
ddb = lir.DataStorage.Devices(lir.FileSystem.expand_path("~/.lir/devices.db"))
ddata = ddb.getDeviceByID(did)
ddb.close()
out = lir.Output.Writer(device.out.name,True)
out.info("Encrypted Connection")
device = lir.Communication.Device(out,device.conn,ddata['key'],True)
data = device.decrypt(data,iv)
try:
mode,data = data.split(":",1)
except:
mode = "listen"
if mode == "listen":
out.info("New Listener Started")
listeners.append(device)
def executeSignal(f,p):
out = lir.Output.Writer("SIGNAL - "+f)
while True:
data = execute(f,'~/.lir/signals/'+p)
try:
datap = pickle.loads(base64.b64decode(data[2:-1]))
data = datap
except:
pass
if p+'/'+f in signals:
if signals[p+'/'+f] != data:
if p+'/'+f in triggers:
for each in listeners:
try:
if each.conn.getpeername()[0] in triggers[p+'/'+f]:
each.send(p+"/"+f+":::"+str(data))
except:
listeners.remove(each)
each.out.warning("Unable to Reach")
signals[p+'/'+f] = data
time.sleep(0.5)
def signal_check():
for p in os.listdir(lir.FileSystem.home()+'/.lir/signals/'):
if os.path.isdir(lir.FileSystem.home()+'/.lir/signals/'+p):
for f in os.listdir(lir.FileSystem.home()+'/.lir/signals/'+p):
start_new_thread(executeSignal,(f,p))
def main():
masterout = lir.Output.Writer("SERVER")
masterout.helper()
print()
print()
info = lir.Settings.ini(lir.FileSystem.home()+"/.lir/main.ini")
PORT = int(info.get("server","port"))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sig = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sig.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
masterout.info("Created Sockets")
try:
s.bind((HOST,PORT))
sig.bind((HOST,PORT+1))
except socket.error as e:
masterout.fail("Bind Failed.",e)
return False
masterout.info("Bind Complete.")
masterout.info("Starting Signal Check")
s.listen(10)
sig.listen(10)
masterout.success("Socket Listening on port " + str(PORT))
masterout.success("Signal Listening on port " + str(PORT + 1))
start_new_thread(signal_check, ())
listen = True
inputs = [s,sig]
try:
while listen:
inready,outread,exceptready = select.select(inputs,[],[])
for i in inready:
if i == s:
con,addr = s.accept()
start_new_thread(handle ,(con,))
elif i == sig:
con,addr = sig.accept()
start_new_thread(handleSig ,(con,))
except KeyboardInterrupt as e:
masterout.warning("Killed by user")
if __name__ == "__main__":
main()