-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1777 lines (1449 loc) · 70 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import re
import logging as log
import time
try:
from tkinter import Tk, Frame, Label, PhotoImage, LabelFrame, TclError, LEFT, Entry, \
Checkbutton, Button, ACTIVE, IntVar, Toplevel
except ModuleNotFoundError as err:
log.error(f" {err}. On linux-based systems this module should be installed via 'apt install':"
f"\n\n sudo apt install python3-tk\n\nAdditional building requirements "
f"and instructions for different OS can be found in the 'BUILD.md' file.")
sys.exit(1)
from tkinter import ttk, font
import tkinter.messagebox as mb
import tkinter.simpledialog as sd
from errno import ENOPROTOOPT
import socket
import ifaddr
import webbrowser as wb
import xml.etree.ElementTree as ET
import urllib.request
import ast
import threading
from src import ProcessThread, SSDPSearchThread, ParseDevicesThread
import traceback
from version import Version
from src import RevealerTable
from src import RevealerDeviceTag
RESULT_OK = 0
RESULT_ERROR = 1
RESULT_UNKNOWN = 2 # code to indicate unknown result of the action - setting settings via multicast for example
DEFAULT_TEXT_COLOR = "black"
CURSOR_POINTER = "hand2"
CURSOR_POINTER_MACOS = "pointinghand"
DEFAULT_BG_COLOR = "white"
URL_REGEX_PORT = "https?:\\/\\/((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}:\\d{1,5}"
URL_REGEX_WITHOUT_PORT = "https?:\\/\\/((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}"
IP_ADDRES_REGEX = "((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}"
PORT_REGEX = ":\\d{1,5}"
# name of the font for tkinter to use in all widgets
# This may not be the solution for the fontconfig error on the newer Linux systems but it should stop tkinter
# from trying to use some other fonts.
# See #92174 for the discussion.
FONT_NAME = "TkDefaultFont"
def fix_env():
try:
lib_key = "LD_LIBRARY_PATH"
env_backup = os.environ.get(lib_key)
orig = os.environ.get(lib_key + "_ORIG")
if orig is None:
os.environ.pop(lib_key)
else:
os.environ[lib_key] = orig
return env_backup
except KeyError:
return None
def restore_env(env_backup):
if env_backup is not None:
os.environ["LD_LIBRARY_PATH"] = env_backup
def center(win):
"""
centers a tkinter window
:param win: the main window or Toplevel window to center
"""
win.update_idletasks()
width = win.winfo_width()
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * frm_width
height = win.winfo_height()
titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = height + titlebar_height + frm_width
x = win.winfo_screenwidth() // 2 - win_width // 2
y = win.winfo_screenheight() // 2 - win_height // 2
win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
win.deiconify()
class SSDPEnhancedDevice:
def __init__(self, ssdp_device_name, enhanced_ssdp_support_min_fw, enhanced_ssdp_version):
self.ssdp_device_name = ssdp_device_name
self.enhanced_ssdp_support_min_fw = enhanced_ssdp_support_min_fw
self.enhanced_ssdp_version = enhanced_ssdp_version
class Revealer2:
SSDP_HEADER_HTTP = "http"
SSDP_HEADER_SERVER = "server"
SSDP_HEADER_LOCATION = "location"
SSDP_HEADER_USN = "usn"
SSDP_HEADER_MIPAS = "mipas"
SSDP_MIPAS_RESULT_OK = "Accepted"
SSDP_MIPAS_RESULT_ERROR = "Rejected"
MULTICAST_SSDP_PORT = 1900
# time for redrawing all widgets in milliseconds
UPDATE_TIME_MS = 100
# To add support of our new device add it in ths dictionary
#
# Format: "Name of its SSDP-server": "version of the firmware from which setting IP via multicast is supported"
# If this device is not supporting setting IP address via multicast yet just leave this string blank and put "".
#
# Take note that "Name of its SSDP-server" must be equal to the name in the SERVER string which this device is
# sending to the SSDP M_SEARCH.
# OUR_DEVICE_DICT = {"8SMC5-USB": "4.7.8", "Eth232-4P": "1.0.13", "mDrive": "6.0.1"}
SSDP_ENHANCED_DEVICES = [
SSDPEnhancedDevice(
ssdp_device_name="8SMC5-USB",
enhanced_ssdp_support_min_fw="4.7.9",
enhanced_ssdp_version="1.0.0"
),
SSDPEnhancedDevice(
ssdp_device_name="Eth232-4P",
enhanced_ssdp_support_min_fw="1.0.13",
enhanced_ssdp_version="1.0.0"
),
SSDPEnhancedDevice(
ssdp_device_name="mDrive",
enhanced_ssdp_support_min_fw="6.0.1",
enhanced_ssdp_version="1.0.0"
)
]
def __init__(self):
# some search initial objects
self._notify_stop_flag = False
# tk initial objects
self.root = Tk(className="revealer")
self.root.title("Revealer " + Version.full)
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
self.root.propagate(False)
self.root.geometry("580x400")
self.root.minsize(width=500, height=200)
center(self.root)
# get font object from its name
self.main_font = font.nametofont(FONT_NAME)
self.main_font.actual()
# set this font as default for all tkinter widgets
self.root.option_add("*Font", self.main_font)
# configure ttk to use this font for all widgets (main button) as well
s = ttk.Style()
s.configure('.', font=self.main_font)
# try to use mac os specific cursor - if exception is raised we are not on mac os and should use default
self.pointer_cursor = CURSOR_POINTER_MACOS
try:
test_label = Label(self.root, text='', cursor=self.pointer_cursor)
test_label.destroy()
except TclError:
self.pointer_cursor = CURSOR_POINTER
# add revealer icon
try:
self.root.iconphoto(False, PhotoImage(file=os.path.join(os.path.dirname(__file__),
"resources/appicon.png")))
except Exception:
pass
mainframe = ttk.Frame(self.root, padding="8 3 8 8")
mainframe.grid(column=0, row=0, sticky="news")
mainframe.grid_rowconfigure(1, weight=1)
mainframe.grid_columnconfigure(0, weight=1)
mainframe.propagate(False)
# add Search-button
self.button = ttk.Button(mainframe, text="Search", command=self.start_thread_search, cursor=self.pointer_cursor)
self.button.grid(column=0, row=0, sticky='new')
# add main revealer table
self.main_table = RevealerTable(mainframe, col=0, row=1, height=300, left_click_url_func=self.open_link,
settings_func=self.change_ip_click,
properties_view_func=self.view_prop,
os_main_root=os.path.dirname(__file__),
font_name=FONT_NAME)
# configure paddings for the main frame
for child in mainframe.winfo_children():
child.grid_configure(padx=5, pady=5)
# store event for using in clicking callbacks
self.event = None
# flag indicating that we are in the process
self.window_updating = False
# prepare notify socket for correct working
self.sock_notify = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.sock_notify.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if hasattr(socket, "SO_REUSEPORT"):
try:
self.sock_notify.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
except socket.error as le:
# RHEL6 defines SO_REUSEPORT but it doesn't work
if le.errno != ENOPROTOOPT:
raise
self.sock_notify.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
try:
self.sock_notify.bind(('', self.MULTICAST_SSDP_PORT))
init_ok = True
except OSError:
# we can't bind to this port number (it may be already taken)
# create window with closing information
mb.showerror(
"Error",
"\nSSDP port (" + str(self.MULTICAST_SSDP_PORT) + ") is already in use.",
parent=self.root
)
# close notify socket
self.sock_notify.close()
self.root.destroy()
init_ok = False
if init_ok:
self.info = ""
# thread with the adding new rows methods
self._update_table_thread = ParseDevicesThread()
self._update_table_thread.start()
# ssdp search thread
self._ssdp_search_thread = ProcessThread()
self._ssdp_search_thread.start()
self._ssdp_threads = SSDPSearchThread()
# legacy search thread
self._old_search_thread = ProcessThread()
self._old_search_thread.start()
# flag of the GUI destroying, is set than user wants to close the window
self._destroy_flag = threading.Event()
# flag of the search in progress
self._in_process = threading.Event()
# thread safe event to indicate that we need to update main table one time after search is ended
self._in_process_after = threading.Event()
# flag of the MIPAS in progress
self._changing_settings = threading.Event()
# flag indicating that main button state was changed for some process
self.buttons_state_changed = False
# flag indicating that table buttons states were changed for MIPAS
self.table_buttons_state_changed = False
def __del__(self):
self.sock_notify.close()
def update_window(self):
"""
Method for updating window state in the main thread. It is important to not use anything GUI-related in the
different threads to avoid closing problems.
:return:
"""
# update buttons
self.update_buttons()
# update table
self.update_main_table()
# update table buttons after
self.update_table_buttons()
# reschedule
if not self._destroy_flag.is_set():
self.window_updating = True
self.root.after(self.UPDATE_TIME_MS, self.update_window)
else:
self.window_updating = False
def update_main_table(self):
"""
Method for updating main table with current lists of the devices.
:return:
"""
if self._in_process.is_set() or not self._update_table_thread.empty() or self._ssdp_threads.in_process():
self.main_table.update_with_rewriting()
self.table_buttons_state_changed = True
self._in_process_after.set()
elif self._in_process_after.is_set():
self._in_process_after.clear()
self.main_table.update_with_rewriting()
self.table_buttons_state_changed = True
return
def update_buttons(self):
if self._in_process.is_set() or not self._update_table_thread.empty() or self._ssdp_threads.in_process():
self.button["state"] = "disabled"
self.button["text"] = "Searching..."
self.button["cursor"] = ""
self.button.update()
self.buttons_state_changed = True
elif self._changing_settings.is_set():
self.button["state"] = "disabled"
self.button["text"] = "Search"
self.button["cursor"] = ""
self.button.update()
self.buttons_state_changed = True
elif self.buttons_state_changed:
self.button["state"] = "normal"
try:
self.button["cursor"] = CURSOR_POINTER_MACOS
except TclError:
self.button["cursor"] = CURSOR_POINTER
self.button["text"] = "Search"
self.button.update()
self.buttons_state_changed = False
def update_table_buttons(self):
if self._in_process.is_set() or self._ssdp_threads.in_process():
self.table_buttons_state_changed = True
elif self._changing_settings.is_set():
self.table_buttons_state_changed = True
self.main_table.disable_all_buttons()
elif self.table_buttons_state_changed:
self.table_buttons_state_changed = False
self.main_table.enable_all_buttons()
def on_closing(self):
"""
Method to be called on X button to close the application.
:return:
"""
# create window with closing information
popup = Toplevel()
# TODO: do we need this _ X for this window ?
# popup.overrideredirect(True)
popup.grab_set()
# add revealer icon
try:
popup.iconphoto(False, PhotoImage(file=os.path.join(os.path.dirname(__file__),
"resources/appicon.png")))
except Exception:
pass
popup_label = Label(popup, text="Revealer is closing. Please wait, it may take some time...")
popup_label.grid(column=0, row=0, sticky="news")
popup_label.grid_configure(padx=15, pady=15)
# center this window
center(popup)
# update this window
popup.update()
self.root.update_idletasks()
# popup.resizable(False, False)
# set destroying flag
self._destroy_flag.set()
# close all threads first
self._update_table_thread.stop_thread()
self._ssdp_search_thread.stop_thread()
self._old_search_thread.stop_thread()
self._ssdp_threads.stop_all()
# wait till all threads are stopped
while self._update_table_thread.task_in_process() or \
self._ssdp_search_thread.task_in_process() or \
self._old_search_thread.task_in_process():
pass
# close notify socket
self.sock_notify.close()
# wait till we stops updating table here for not disturbing tkinter
if self.window_updating:
log.info("We are updating the window so please wait...")
self.root.after(self.UPDATE_TIME_MS, self.destroy_after)
def destroy_after(self):
"""
After callback for destroying everything after our main updating after-method finished its work.
:return:
"""
if not self.window_updating:
# and only after all of this - kill the app
log.info("Now the window can be closed. Bye.")
self.root.destroy()
else:
log.info("We are updating the window so please wait...")
self.root.after(self.UPDATE_TIME_MS, self.destroy_after)
def print_i(self, string):
if len(self.info) > 0:
self.info += "\n\n"
self.info += string
def show_info(self):
"""
Method for catching exceptions and showing them in separate windows.
:return:
"""
if len(self.info) > 0 and not self._destroy_flag.is_set():
mb.showerror('Error', self.info)
def start_thread_search(self):
# remove everything from our table
self.main_table.delete_all_rows()
# and delete all devices from the device list of the table
self.main_table.device_list.clear_all()
# information about this search
self.info = ""
# start thread searches
self._ssdp_search_thread.add_task(self.ssdp_search_task)
self._old_search_thread.add_task(self.old_search_task)
def find_ssdp_enhanced_device(self, device_name):
index = 0
while index < len(self.SSDP_ENHANCED_DEVICES):
if self.SSDP_ENHANCED_DEVICES[index].ssdp_device_name.lower() == device_name.lower():
return index
index += 1
return None
def view_prop(self, prop_dict, link):
try:
# if we have local SSDP device
if prop_dict['friendlyName'] == "Not provided":
name = prop_dict['ssdp_server']
else:
name = prop_dict['friendlyName']
PropDialog(name, prop_dict, link, parent=self.root)
except KeyError:
try:
# if we have not local SSDP device
name = prop_dict['server']
PropDialog(name, prop_dict, link, parent=self.root)
except KeyError:
log.debug('No properties for this device')
pass
def view_prop_old(self):
tree = self.event.widget # get the treeview widget
if tree.winfo_class() == "Treeview":
region = tree.identify_region(self.event.x, self.event.y)
iid = tree.identify('item', self.event.x, self.event.y)
name = ''
if region == 'cell':
prop_dict = ast.literal_eval(tree.item(iid)['values'][4])
try:
# if we have local SSDP device
name = prop_dict['friendlyName']
PropDialog(name, prop_dict, tree.item(iid)['values'][2], parent=self.root)
except KeyError:
try:
# if we have not local SSDP device
name = prop_dict['server']
PropDialog(name, prop_dict, tree.item(iid)['values'][2], parent=self.root)
except KeyError:
prop_dict = tree.item(iid)['values'][1]
log.debug('No properties for this device')
pass
elif tree.winfo_class() == "Label":
if hasattr(tree, "other_data") and hasattr(tree, "link"):
prop_dict = tree.other_data
try:
# if we have local SSDP device
name = prop_dict['friendlyName']
PropDialog(name, prop_dict, tree.link, parent=self.root)
except KeyError:
try:
# if we have not local SSDP device
name = prop_dict['server']
PropDialog(name, prop_dict, tree.link, parent=self.root)
except KeyError:
log.debug('No properties for this device')
pass
def open_link(self, event=None):
if event is not None:
self.event = event
label = self.event.widget # get the label widget
if label.winfo_class() == 'Label':
if hasattr(label, 'link') and hasattr(label, 'tag'):
if (label.tag == RevealerDeviceTag.LOCAL or label.tag == RevealerDeviceTag.OLD_LOCAL) and \
label['foreground'] == "blue":
env_old = fix_env()
wb.open_new_tab(label.link) # open the link in a browser tab
restore_env(env_old)
else:
log.info(f"Can't open {label.link} link.")
def _listen_and_capture_returned_responses_url(self, sock: socket.socket, timer_stop_event):
while not self._destroy_flag.is_set() and not timer_stop_event.is_set():
try:
while not self._destroy_flag.is_set() and not timer_stop_event.is_set():
data, addr = sock.recvfrom(8192)
data_dict = self.parse_ssdp_data(data.decode('utf-8'), addr)
# if we have not received this location before
if data_dict["server"] != "":
self._update_table_thread.add_task(self.add_new_item_task, data_dict, addr)
except socket.timeout:
pass
except OSError:
break
sock.close()
def ssdp_search_task(self):
try:
if not self._destroy_flag.is_set():
self._in_process.set()
self._in_process_after.set()
else:
return
notify_started = False
adapters = ifaddr.get_adapters()
self._ssdp_threads.delete_all()
self._ssdp_threads.add_adapters(adapters)
index = 0
for adapter in adapters:
for ip in adapter.ips:
if self._destroy_flag.is_set():
return
if not isinstance(ip.ip, str):
continue
if ip.ip == '127.0.0.1':
continue
# Send M-Search message to multicast address for UPNP
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
try:
sock.bind((ip.ip, 0))
except Exception:
index += 1
continue
# if ip.ip is suitable for m-search - try to listen for notify messages also
# just ONE time
if not notify_started:
# set notify flag to make that process know that it need to listen answers
self._ssdp_threads.start_notify()
notify_started = True
# listen to notify messages from another network. This should be done from each interface.
# See #109885.
self._ssdp_threads.notify_threads[index].start()
self._ssdp_threads.notify_threads[index].add_task(
self.listen_notify_task, ip.ip, self._ssdp_threads.notify_threads[index].stop_flag
)
# we need to wait a little bit for notify listen to start on
# this ip for correct answers receiving
# See #89128.
time.sleep(0.05)
# adding search task for this ip on this adapter
self._ssdp_threads[index].start()
self._ssdp_threads[index].add_task(self.ssdp_search_adapter_task, sock,
self._ssdp_threads[index].stop_flag)
index += 1
self._in_process.clear()
# set notify flag to false so notify thread will stop when all ssdp searches are finished
self._ssdp_threads.stop_notify()
except Exception:
except_info = traceback.format_exc()
self.print_i(f"Unhandled exception occurred while performing SSDP search:\n{except_info}")
# show info from search if we had some important information (exceptions with errors)
if not self._destroy_flag.is_set():
self.show_info()
return
def ssdp_search_adapter_task(self, sock, timer_stop_event):
# M-Search message body
message = \
'M-SEARCH * HTTP/1.1\r\n' \
'HOST:239.255.255.250:1900\r\n' \
'ST:upnp:rootdevice\r\n' \
'MX:2\r\n' \
'MAN:"ssdp:discover"\r\n' \
'\r\n'
# set timeout
sock.settimeout(0.05)
timer_stop_event.clear()
try:
sock.sendto(message.encode('utf-8'), ("239.255.255.250", 1900))
self._listen_and_capture_returned_responses_url(sock, timer_stop_event)
except OSError:
pass
def _get_uuid_of_found(self, data_dict):
"""
Check if this device is our enhanced device with correct version.
:return:
"""
device_index_in_list = self.find_ssdp_enhanced_device(data_dict["server"])
if device_index_in_list is not None:
version_with_settings = \
self.SSDP_ENHANCED_DEVICES[device_index_in_list].enhanced_ssdp_support_min_fw
uuid = data_dict["uuid"]
# we need to check that if we have our device it supports setting settings via multicast
if version_with_settings != "":
version_with_settings_array = [int(num) for num in version_with_settings.split('.')]
current_version = data_dict["version"].split('.')
current_version_array = [int(num) for num in current_version]
# check that we have version greater than this
if current_version_array[0] < version_with_settings_array[0]:
uuid = ""
elif current_version_array[0] == version_with_settings_array[0]:
if current_version_array[1] < version_with_settings_array[1]:
uuid = ""
elif current_version_array[1] == version_with_settings_array[1]:
if current_version_array[2] < version_with_settings_array[2]:
uuid = ""
elif data_dict['mipas'] != "Not provided":
uuid = data_dict["uuid"]
else:
uuid = None
return uuid
def add_new_item_task(self, data_dict, addr, notify_flag=False):
try:
xml_dict = self.parse_upnp_xml(data_dict["location"])
uuid = self._get_uuid_of_found(data_dict)
if uuid is None and notify_flag:
# we don't need not our device from notify
return
if xml_dict is not None:
# append all datadict field to xml_dict
for name in data_dict:
xml_dict[name] = data_dict[name]
# check that we have our url with correct format
try:
if xml_dict["presentationURL"] is None:
link = data_dict["location_url"]
xml_dict["presentationURL"] = '-'
elif xml_dict["presentationURL"][0:4] != "http":
link = data_dict["location_url"] + xml_dict["presentationURL"]
else:
# from the XML-description we should get relative URL but if we have absolute - use absolute
link = xml_dict["presentationURL"]
except KeyError:
xml_dict["presentationURL"] = '-'
link = addr[0]
# add version and server name from ssdp dict
xml_dict["version"] = data_dict["version"]
xml_dict["ssdp_server"] = data_dict["server"]
# try to avoid all None fields in the xml data
for field in xml_dict:
if xml_dict[field] is None:
xml_dict[field] = "Not provided"
# check friendlyName field
if "friendlyName" not in xml_dict or xml_dict["friendlyName"] == "Not provided":
device_name = xml_dict["ssdp_server"]
else:
device_name = xml_dict["friendlyName"]
if not self._destroy_flag.is_set():
with self.main_table.lock:
self.main_table.add_row_ssdp_item(device_name,
link, data_dict["ssdp_url"], uuid, xml_dict,
tag=RevealerDeviceTag.LOCAL)
else:
if not self._destroy_flag.is_set():
with self.main_table.lock:
self.main_table.add_row_ssdp_item(data_dict["server"],
data_dict["ssdp_url"], data_dict["ssdp_url"],
uuid, data_dict, tag=RevealerDeviceTag.NOT_LOCAL)
except Exception:
except_info = traceback.format_exc()
self.print_i(f"Error while trying to add new device {addr} with data_dict {data_dict} to the table:\n"
f"{except_info}")
def socket_notify_reinit(self):
# close notify socket
self.sock_notify.close()
# prepare notify socket for correct working
self.sock_notify = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.sock_notify.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock_notify.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
try:
self.sock_notify.bind(('', self.MULTICAST_SSDP_PORT))
except OSError:
# we can't bind to this port number (it may be already taken)
# create window with closing information
mb.showerror(
"Error",
"\nSSDP port (" + str(self.MULTICAST_SSDP_PORT) + ") is already in use.",
parent=self.root
)
# close notify socket
self.sock_notify.close()
self.root.destroy()
return
def listen_notify_task(self, interface_ip, timer_stop_event):
"""
Task for search thread where we listen for all notify messages while we sending m-searches since we add too
our device option to send notify with answering to the m-search.
:return:
"""
multicast_group = '239.255.255.250'
try:
self.sock_notify.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(multicast_group) + socket.inet_aton(interface_ip))
except OSError:
pass
timer_stop_event.clear()
self.sock_notify.settimeout(0.1)
while not self._destroy_flag.is_set() and not timer_stop_event.is_set():
# listen and capture returned responses
try:
while not self._destroy_flag.is_set() and not timer_stop_event.is_set():
data, addr = self.sock_notify.recvfrom(8192)
data_strings = data.decode('utf-8').split('\r\n')
if data_strings[0] == 'NOTIFY * HTTP/1.1':
data_dict = self.parse_ssdp_data(data.decode('utf-8'), addr)
# NOTIFY flag at the end of the arguments is set to False since we don't want to filter NOTIFY
# answers. #92687
self._update_table_thread.add_task(self.add_new_item_task, data_dict, addr, False)
except socket.timeout:
pass
except OSError:
break
def _parse_ssdp_header_server(self, string, ssdp_dict) -> None:
"""
Correct format for SERVER header is:
<OS>/<OS version> UPnP/<version of UPnP supported> <product>/<product version>
All fields should be filled according to HTTP/1.1 “product tokens”.
For example, “SERVER: unix/5.1 UPnP/2.0 MyProduct/1.0”
Note: whitespaces are used as separator so should not be used in OS / product strings but if some device has
additional whitespaces in its product tokens revealer should try and parse them as well with logging about that.
:param string: str
String after SERVER header.
:param ssdp_dict: dict
Dict with SSDP properties of this device to be filled with parsed information.
:return:
"""
warning_line = ''
words_string = string.split(' ')
# check that format is correct
if len(words_string) != 3:
warning_line += "SERVER header line with incorrect format: '" + \
string + "'. Whitespaces shouldn't be used in the OS and product names."
# try to find UPnP field
index_upnp = string.index(" UPnP/")
if index_upnp < 0:
warning_line += "Can't parse SERVER header line without UPnP field at all: '" + \
string + "'."
os_version_words = ["Not provided", "Not provided"]
server_version_words = ["Not provided", "Not provided"]
else:
# we want to remember index if UPnP not whitespace before it
index_upnp += 1
os_fields = string[0:index_upnp]
os_version_words = os_fields.split('/')
product_fields = string[index_upnp + 1 + string[index_upnp:].index(" "):]
server_version_words = product_fields.split('/')
else:
os_version = words_string[0]
os_version_words = os_version.split('/')
# TODO: check different lines (with trailing whitespaces and so on)
server_version = words_string[len(words_string) - 1] # last word after ' '
server_version_words = server_version.split('/')
if len(warning_line) > 0:
print("Warning:", warning_line)
try:
ssdp_dict["server"] = server_version_words[0]
except IndexError:
ssdp_dict["server"] = "Not provided"
try:
ssdp_dict["version"] = server_version_words[1]
except IndexError:
ssdp_dict["version"] = "Not provided"
try:
ssdp_dict["os"] = os_version_words[0]
except IndexError:
ssdp_dict["os"] = "Not provided"
try:
ssdp_dict["os_version"] = os_version_words[1]
except IndexError:
ssdp_dict["os_version"] = "Not provided"
@staticmethod
def _parse_location_url(string):
m = re.search(URL_REGEX_PORT, string)
try:
url_raw = m.group()
rest_data = string[len(url_raw):]
ip_address = (re.search(IP_ADDRES_REGEX, url_raw)).group()
port = (re.search(PORT_REGEX, url_raw)).group()
return ip_address, port[1::1], rest_data
except AttributeError:
# try get url without port
m = re.search(URL_REGEX_WITHOUT_PORT, string)
try:
url_raw = m.group()
rest_data = string[len(url_raw):]
ip_address = (re.search(IP_ADDRES_REGEX, url_raw)).group()
return ip_address, None, rest_data
except AttributeError:
return None, None, string
def _parse_ssdp_header_location(self, string, ssdp_dict, addr) -> None:
# get only field value:
field_name = re.match("location:\\s*", string.lower()).group()
value_string = string[len(field_name):]
ip_address, port, xml_raw = self._parse_location_url(value_string)
if ip_address is not None and port is not None:
# we have correct absolute location - save it as location
ssdp_dict["location"] = value_string
elif ip_address is not None and port is None:
# if we don't have port specification
ssdp_dict['location'] = 'http://' + ip_address + ":80" + xml_raw
else:
# if we are here it means we have an invalid LOCATION URL -
# relative one but UPnP standards require an absolute URL.
# See https://openconnectivity.org/upnp-specs/UPnP-arch-DeviceArchitecture-v2.0-20200417.pdf
# on pages 29 and 41 for LOCATION header format
#
# Nevertheless we are trying to get xml-file for these devices with address
ssdp_dict['location'] = 'http://' + addr[0] + ":80" + xml_raw
ip_address = addr[0]
ssdp_dict["ssdp_url"] = ip_address
ssdp_dict["location_url"] = re.match(URL_REGEX_PORT, value_string.lower()).group()
def _parse_ssdp_header_usn(self, string, ssdp_dict, addr) -> None:
words_string = string.split(':') # do this again for symmetry
try:
ssdp_dict["uuid"] = words_string[2]
except IndexError:
except_info = traceback.format_exc()
self.print_i(f"USN of {addr} has incorrect format: {string}. It should be:\n"
f"USN: uuid:00000000-0000-0000-0000-000000000000::<device-type>."
f"\n{except_info}")
def _parse_ssdp_header_mipas(self, string, ssdp_dict) -> None:
words_string = string.split(':')
try:
ssdp_dict["mipas"] = words_string[1].replace(' ', '')
except IndexError:
ssdp_dict["mipas"] = ""
def parse_ssdp_data(self, ssdp_data, addr):
ssdp_dict = {"server": "Not provided", "version": "Not provided", "location": "Not provided",
"ssdp_url": "Not provided", "uuid": "Not provided", "location_url": "Not provided",
"os": "Not provided", "os_version": "Not provided", "mipas": "Not provided"}
ssdp_strings = ssdp_data.split("\r\n")
try:
for string in ssdp_strings:
if string[0:3].lower() != Revealer2.SSDP_HEADER_HTTP:
words_string = string.split(':')
if words_string[0].lower() \
== Revealer2.SSDP_HEADER_SERVER: # format: SERVER: lwIP/1.4.1 UPnP/2.0 8SMC5-USB/4.7.7
# remove header from string
string = string[len(Revealer2.SSDP_HEADER_SERVER) + 1:]
if len(string) > 0 and string[0] == ' ':
string = string[1:]
if len(string) > 0:
self._parse_ssdp_header_server(string, ssdp_dict)
elif words_string[0].lower() == \
Revealer2.SSDP_HEADER_LOCATION: # format: LOCATION: http://172.16.130.67:80/Basic_info.xml
self._parse_ssdp_header_location(string, ssdp_dict, addr)
elif words_string[0].lower() == \
Revealer2.SSDP_HEADER_USN:
# USN: uuid:40001d0a-0000-0000-8e31-4010900b00c8::upnp:rootdevice
self._parse_ssdp_header_usn(string, ssdp_dict, addr)
elif words_string[0].lower() == \
Revealer2.SSDP_HEADER_MIPAS:
# MIPAS: - our special field to identifty that this device
# supports network settings changing via multicast
self._parse_ssdp_header_mipas(string, ssdp_dict)
except Exception:
except_info = traceback.format_exc()
self.print_i(f"Error in parsing {addr} SSDP data:\n{except_info}")
return ssdp_dict
return ssdp_dict
@staticmethod
def parse_upnp_xml(url):
xml_dict = {}
try:
response = urllib.request.urlopen(url, timeout=1).read().decode('utf-8')
tree = ET.fromstring(response)
for child in tree:
tag_array = child.tag.split('}')
tag_name = tag_array[len(tag_array) - 1]
xml_dict[tag_name] = child.text
for grandchild in child:
tag_array = grandchild.tag.split('}')
tag_name = tag_array[len(tag_array) - 1]
xml_dict[tag_name] = grandchild.text
return xml_dict
except Exception as err:
print("Exception for xml_dict", url, err)
return None
def change_ip_multicast(self, uuid, settings_dict):
# delete any info from previous process
self.info = ""
# start process for changing settings in another thread