-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
299 lines (268 loc) · 10.6 KB
/
main.py
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
"""
Mark Liebrand 2024
This file is part of FindMyGUI which is released under the Apache 2.0 License
See file LICENSE or go to for full license details https://github.com/liebrandapps/FindMyGUI
"""
import base64
import glob
import json
import logging
import signal
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from logging.handlers import RotatingFileHandler
from os import makedirs, chmod
from os.path import join, exists, splitext
from pathlib import Path
from threading import Thread
from urllib.parse import parse_qs, urlparse
from Crypto.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_OAEP, AES
from airTag import AirTag
from api import API
from config import Config
from context import Context
from daemon import Daemon
from imap.imapScheduler import IMAPScheduler
from mqtt import MQTT
APP = "findMyGUI"
CONFIG_DIR = "./data"
CONFIG_FILE = "findMyGUI.ini"
def setupLogger():
global runAsDaemon
try:
_log = logging.Logger(APP)
loghdl = RotatingFileHandler(cfg.logging_logFile, 'a', cfg.logging_maxFilesize, 4)
loghdl.setFormatter(logging.Formatter(cfg.logging_msgFormat))
loghdl.setLevel(cfg.logging_logLevel)
_log.addHandler(loghdl)
if cfg.logging_stdout and not runAsDaemon:
loghdl = logging.StreamHandler(sys.stdout)
loghdl.setFormatter(logging.Formatter(cfg.logging_msgFormat))
loghdl.setLevel(cfg.logging_logLevel)
_log.addHandler(loghdl)
_log.disabled = False
return _log
except Exception as e:
print("[%s] Unable to initialize logging. Reason: %s" % (APP, e))
return None
def terminate(sigNo, _):
global doTerminate
global myServer
global httpIsRunning
global scheduler
if doTerminate:
return
doTerminate = True
ctx.log.info(f"[{APP}] Terminating with Signal {sigNo} {sigs[sigNo]}")
if scheduler is not None:
scheduler.terminate()
if httpIsRunning:
Thread(target=myServer.shutdown).start()
def loadAirTags():
global ctx
airTagDir = ctx.cfg.general_airTagDirectory
airTagSuffix = ctx.cfg.general_airTagSuffix
if not exists(airTagDir):
ctx.log.info(
f"[loadAirTags] Airtags Directory '{airTagDir}' does not exist, creating it. This will be used to store "
f"Airtag key information.")
makedirs(airTagDir)
tags = glob.glob(join(airTagDir, '*' + airTagSuffix))
for t in tags:
airtag = AirTag(ctx, jsonFile=t)
ctx.airtags[airtag.id] = airtag
def getKeys():
global ctx
if ctx.privKey is None:
ctx.log.info(f"[getKeys] Generating key for encrypted MQTT communication")
key = RSA.generate(2048)
ctx.privKey = base64.b64encode(key.exportKey('DER')).decode('ascii')
ctx.save()
def mqttCBKey(topic, payload):
global ctx
ctx.log.debug(f"[MQTT] Received {payload}")
jsn = json.loads(payload)
key = RSA.importKey(base64.b64decode(ctx.privKey))
publicKey = key.publickey()
resp = {'uid': jsn['uid'], 'publicKey': base64.b64encode(publicKey.exportKey('DER')).decode('ascii')}
# ctx.mqtt.publish(jsn['responseTopic'], resp)
def mqttCBAirTag(topic, payload):
global ctx
ctx.log.debug(f"[MQTT] Received {payload}")
jsn = json.loads(payload)
key = RSA.importKey(base64.b64decode(ctx.privKey))
encData = base64.b64decode(jsn['encData'])
cipher_rsa = PKCS1_OAEP.new(key)
aesKey = cipher_rsa.decrypt(encData)
ctx._aesKeys[jsn['uid']] = aesKey
resp = {'uid': jsn['uid']}
for airtag in ctx.airtags.values():
cipher = AES.new(aesKey, AES.MODE_CTR)
dta = airtag.toJSON()
ciphertext = cipher.encrypt(dta.encode('utf-8'))
resp['encDta'] = base64.b64encode(ciphertext).decode('ascii')
resp['nonce'] = base64.b64encode(cipher.nonce).decode('ascii')
ctx.mqtt.publish(jsn['responseTopic'], resp)
def mqttCBLocationUpdate(topic, payload):
global ctx
ctx.log.debug(f"[MQTT] Location update received {payload}")
jsn = json.loads(payload)
if jsn['uid'] not in ctx.aesKeys:
# request aeskey ...
mqttCBKey(topic, payload)
else:
nonce = base64.b64decode(jsn['nonce'])
aesKey = ctx.aesKeys[jsn['uid']]
cipher = AES.new(aesKey, AES.MODE_CTR, nonce=nonce)
encData = base64.b64decode(jsn['encDta'])
clearData = cipher.decrypt(encData).decode('utf-8')
jsn = json.loads(clearData)
if not jsn['known']:
advKey = jsn['advKey']
for airtag in ctx.airtags.values():
if airtag.advertisementKey == advKey:
cipher = AES.new(aesKey, AES.MODE_CTR)
dta = airtag.toJSON()
ciphertext = cipher.encrypt(dta.encode('utf-8'))
resp = {'uid': jsn['uid'], 'encDta': base64.b64encode(ciphertext).decode('ascii'),
'nonce': base64.b64encode(cipher.nonce).decode('ascii')}
ctx.mqtt.publish(jsn['responseTopic'], resp)
airtag.updateLocation(jsn['timestamp'], jsn['lat'], jsn['lon'], direct=True)
break
if jsn['known'] and jsn['tagId'] in ctx.airtags.keys():
airtag = ctx.airtags[jsn['tagId']]
airtag.updateLocation(jsn['timestamp'], jsn['lat'], jsn['lon'], jsn['status'], direct=True)
class FindMyServer(BaseHTTPRequestHandler):
""" Extension: ContentType, Encode """
contentTypeDct = {'.html': ["text/html", True],
'.js': ["application/javascript", True],
'.css': ["text/css", True],
'.png': ["image/png", False],
}
def do_GET(self):
if self.path.startswith('/api'):
api = API(ctx)
query_components = parse_qs(urlparse(self.path).query)
cmd = query_components["command"]
result = api.call(cmd[0], params=query_components)
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(result.encode('UTF-8'))
else:
file = "/index.html" if self.path == "/" else self.path
file = join('www', file[1:])
ext = splitext(file)[1]
ct = self.contentTypeDct[ext] if ext in self.contentTypeDct.keys() else None
if exists(file) and ct is not None:
contentType = ct[0]
encode = ct[1]
self.send_response(200)
self.send_header("Content-type", contentType)
self.end_headers()
with open(file, 'r' if encode else 'rb') as f:
data = f.read()
self.wfile.write(data.encode('UTF-8') if encode else data)
else:
self.send_response(404)
self.end_headers()
if __name__ == '__main__':
doTerminate = False
initialConfig = {
"general": {
"httpHost": ['String', '0.0.0.0'],
"httpPort": ['Integer', 8008],
"httpFiles": ['String', 'www'],
"anisetteHost": ['String', 'http://192.168.2.15'],
"anisettePort": ['Integer', 6969],
"airTagDirectory": ['String', 'data/airtags'],
"airTagSuffix": ['String', '.json'],
"history": ["Integer", 30],
"automaticQuery": ["Integer", 0],
},
"logging": {
"logFile": ["String", "./data/log/findMyGUI.log"],
"maxFilesize": ["Integer", 1000000],
"msgFormat": ["String", "%(asctime)s, %(levelname)s, %(module)s {%(process)d}, %(lineno)d, %(message)s"],
"logLevel": ["Integer", 10],
"stdout": ["Boolean", True],
},
"appleId": {
"appleId": ["String", ''],
"password": ["String", ''],
"trustedDevice": ["Boolean", False],
},
"mqtt": {
"enable": ["Boolean", False],
"server": ["String", ],
"port": ["Integer", 1883],
"user": ["String", ""],
"password": ["String", ],
"keepAlive": ["Integer", 60],
"subscribeTopic": ["String", None],
"retainedMsgs": ["Boolean", False],
"debug": ["Boolean", False],
"reconnect": ["Integer", 24, "Reconnect every 24 hours"],
"silent": ["Boolean", False, "If set to true, no received mqtt messages are logged. (Default: False)"],
"topic": ["String", "findmygui/app/"],
},
"imap": {
"host": ['String', ''],
"user": ['String', ''],
"password": ['String', ''],
"useSSL": ['Boolean', True],
"folder": ['String', ''],
"sender": ['String', 'FindMyGUI'],
"markAsRead": ['Boolean', False],
"removeOldReports": ['Boolean', False],
},
}
path = join(CONFIG_DIR, CONFIG_FILE)
if not (exists(path)):
print(f"[{APP}] No config file {CONFIG_FILE} found at {CONFIG_DIR}, using defaults")
cfg = Config(path)
cfg.addScope(initialConfig)
runAsDaemon = False
if len(sys.argv) > 1:
todo = sys.argv[1]
if todo in ['start', 'stop', 'restart', 'status']:
runAsDaemon = True
pidFile = cfg.general_pidFile
logFile = cfg.logging_logFile
d = Daemon(pidFile, APP, logFile)
d.startstop(todo, stdout=logFile, stderr=logFile)
log = setupLogger()
if log is None:
sys.exit(-126)
ctx = Context(cfg, log)
ctx.load()
if cfg.mqtt_enable:
getKeys()
mqtt = MQTT(ctx)
mqtt.start()
ctx.mqtt = mqtt
mqtt.subscribe(cfg.mqtt_topic + "key_request", mqttCBKey)
mqtt.subscribe(cfg.mqtt_topic + "airtag_request", mqttCBAirTag)
mqtt.subscribe(cfg.mqtt_topic + "location_update", mqttCBLocationUpdate)
signal.signal(signal.SIGINT, terminate)
signal.signal(signal.SIGTERM, terminate)
sigs = {signal.SIGINT: signal.SIGINT.name,
signal.SIGTERM: signal.SIGTERM.name}
httpHost = cfg.general_httpHost
httpPort = cfg.general_httpPort
loadAirTags()
if cfg.general_automaticQuery > 0:
scheduler = IMAPScheduler(ctx)
scheduler.start()
else:
scheduler = None
myServer = ThreadingHTTPServer((httpHost, httpPort), FindMyServer)
log.info(f"[{APP}] HTTP Server is starting: {httpHost}:{httpPort}")
httpIsRunning = True
try:
myServer.serve_forever()
finally:
httpIsRunning = False
myServer.server_close()
log.info(f"{APP} HTTP Server is terminating: {httpHost}:{httpPort}")