forked from chanakalin/hilinkapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HiLinkAPI.py
1590 lines (1459 loc) · 69.4 KB
/
HiLinkAPI.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 logging
from threading import Thread
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import xmltodict
import uuid
import base64
import hashlib
import binascii
import hmac
import time
from binascii import hexlify
from collections import OrderedDict
from bs4 import BeautifulSoup
from datetime import datetime
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
class hilinkException(Exception):
"""
HiLink API exception
:param modemname: Unique name of the modem will be used in raising an exceptions to identify the
respective modem
:param message: Error message body for the raising exception
:type modemname: string
:type message: string
"""
def __init__(self, modemname, message):
self.message = message
self.modemname = modemname
def __str__(self):
return "Huawei HLink API Error ({}) : {}".format(self.modemname, self.message)
class webui(Thread):
"""
This class facilitate to open, authenticate and operate functions of supported Huawei HiLink modems.
:param modemname: A uniquely identifiable name for the modem will useful when debugging or tracing with logs
:param host: IP address of the modem
:param username: Username if authentication required
:param password: Password if authentication required
:param logger: Logger object if using already configured :class:`logging.Logger`
:param scheme: how to access the modem, http or https
:type url: string
:type host: string
:type username: string, defaults to None
:type password: string, defaults to None
:type logger: :class:`logging.Logger`, defaults to None
:type scheme: string
"""
errorCodes = {
# System errors
100002: "ERROR_SYSTEM_NO_SUPPORT",
100003: "ERROR_SYSTEM_NO_RIGHTS",
100004: "ERROR_BUSY",
# Authentication errors
108001: "ERROR_LOGIN_USERNAME_WRONG",
108002: "ERROR_LOGIN_PASSWORD_WRONG",
108003: "ERROR_LOGIN_ALREADY_LOGIN",
108005: "ERROR_LOGIN_TOO_MANY_USERS_LOGINED",
108006: "ERROR_LOGIN_USERNAME_OR_PASSWORD_ERROR",
108007: "ERROR_LOGIN_TOO_MANY_TIMES",
108008: "MODIFYPASSWORD_ERROR",
108009: "ERROR_LOGIN_IN_DEFFERENT_DEVICES",
108010: "ERROR_LOGIN_FREQUENTLY_LOGIN",
# SIM errors
101001: "ERROR_NO_SIM_CARD_OR_INVALID_SIM_CARD",
101002: "ERROR_CHECK_SIM_CARD_PIN_LOCK",
101003: "ERROR_CHECK_SIM_CARD_PUN_LOCK",
101004: "ERROR_CHECK_SIM_CARD_CAN_UNUSEABLE",
101005: "ERROR_ENABLE_PIN_FAILED",
101006: "ERROR_DISABLE_PIN_FAILED",
101007: "ERROR_UNLOCK_PIN_FAILED",
101008: "ERROR_DISABLE_AUTO_PIN_FAILED",
101009: "ERROR_ENABLE_AUTO_PIN_FAILED",
103002: "ERROR_DEVICE_PIN_VALIDATE_FAILED",
103003: "ERROR_DEVICE_PIN_MODIFFY_FAILED",
103004: "ERROR_DEVICE_PUK_MODIFFY_FAILED",
103008: "ERROR_DEVICE_SIM_CARD_BUSY",
103009: "ERROR_DEVICE_SIM_LOCK_INPUT_ERROR",
103011: "ERROR_DEVICE_PUK_DEAD_LOCK",
# Network errors
112001: "ERROR_SET_NET_MODE_AND_BAND_WHEN_DAILUP_FAILED",
112002: "ERROR_SET_NET_SEARCH_MODE_WHEN_DAILUP_FAILED",
112003: "ERROR_SET_NET_MODE_AND_BAND_FAILED",
112005: "ERROR_NET_REGISTER_NET_FAILED",
112008: "ERROR_NET_SIM_CARD_NOT_READY_STATUS",
# Session errors
125001: "ERROR_WRONG_TOKEN",
125002: "ERROR_WRONG_SESSION",
125003: "ERROR_WRONG_SESSION_TOKEN",
}
def __init__(self, modemname, host, username=None, password=None, logger=None, httptimeout=10, scheme='http'):
"""
Initialize webui
"""
self._modemname = modemname
self._host = host
# assign empty strings if none
self._username = username if username is not None else ""
self._password = password if password is not None else ""
# initialize logger if not provided
if logger is None:
self.logger = logging.getLogger()
else:
self.logger = logger
# build http host URL
self._httpHost = f"{scheme}://{self._host}"
# timeout for a HTTP call (seconds)
self._HTTPcallTimeOut = httptimeout
# variables required for webui session
self._sessionId = None
self._RequestVerificationToken = None
# Authenticaion required or not
self._loginRequired = False
#### WebUI variables####
self._sessionId = None
self._RequestVerificationToken = None
self._deviceClassify = None
self._deviceName = None
self._loginState = False # Logged in to the session or not
self._webuiversion = None # Has to be 10 or 17/21
# webui initialization succeeded or not
self._isWebUIInitialized = False
# in an operation or not
self._inOperation = False
# session refresh interval in seconds
self._sessionRefreshInterval = 10
# session refreshed after an operation
self._sessionRefreshed = False
# Last operation ended time
self._lastOperationEndedTime = None
# valid session or not (not logged in)
self._validSession = False
# login wait time
self._loginWaitTime = 0
# active error code
self._activeErrorCode = 0
# initialize thread stop
self._stopped = True
# thread stopped
self._isStopped = True
# network modes
# LTE=3, WCDMA=2, GSM=1 network modes
self._netModePrimary = 3
self._netModeSecondary = 2
###############################
# device info
self._deviceName = None
self._imei = None
self._serial = None
self._imsi = None
self._iccid = None
self._supportedModes = None
self._hwversion = None
self._swversion = None
self._webui = None
# connection info
self._workmode = None
self._wanIP = None
self._networkName = None
# data connection info
self._roamingEnabled = False
self._maxIdleTimeOut = 0
######### Initialize ###########
# Initialize the thread
Thread.__init__(self)
def start(self):
"""
This method will start the thread.
"""
# initialize variables and webui
self._stopped = False
self._isStopped = False
self.initialize()
# Thread start
Thread.start(self)
def stop(self):
"""
This method will initialize thread stop.
"""
self._stopped = True
def isStopped(self):
"""
This method will return successfully stopped or not.
:return: Return deinited or not
:rtype: boolean
"""
return self._isStopped
def setCredentials(self, username, password):
"""
This method will set/update username and password for authentication after initializing.
:param username: Username if authentication required
:param password: Password if authentication required
:type username: string, defaults to None
:type password: string, defaults to None
"""
self._username = username
self._password = password
def processHTTPHeaders(self, response):
"""
This method will retrieve *SessionID* from cookies and *__RequestVerificationToken* from HTTP headers.
This method has to be called after each :class:`requests.get` or :class:`requests.post` as mismatch with *SessionID*
or *__RequestVerificationToken* between API(webui) and HTTP request call leading to return errors in API calls.
:param response: Response object from :class:`requests.get` or :class:`requests.post`
:type response: :class:`requests.Response`
"""
if 'SessionID' in response.cookies:
self._sessionId = response.cookies['SessionID']
self.logger.debug(f"Updating SessionID = {self._sessionId}")
headers = OrderedDict(response.headers)
if '__RequestVerificationToken' in headers:
self.logger.debug("Updating RequestVerificationToken = {}".format(self._RequestVerificationToken))
self._RequestVerificationToken = None
self._RequestVerificationToken = headers['__RequestVerificationToken'].split("#")[0]
self.logger.debug("Updated RequestVerificationToken to = {}".format(self._RequestVerificationToken))
def buildCookies(self):
"""
This method will build a dictionary object containing *SessionID* which is provided as cookies to HTTP requests.
Each call of :meth:`~httpGet` and :meth:`~httpPost` will generate default cookies set if cookies not provided in parameters.
:return: Return a dictionary containing cookies
:rtype: dictionary
"""
cookies = None
if self._sessionId:
cookies = {
'SessionID': self._sessionId
}
# return
return cookies
def httpGet(self, endpoint, cookies=None, headers=None):
"""
Call an API end point using a HTTP GET request. If :attr:`cookies` are not provided (when defaulted to None) will build cookies
by calling :meth:`~buildCookies`.
At the end of each call :meth:`~processHTTPHeaders` will call to retrieve *SessionID* and *__RequestVerificationToken*.
:param endpoint: API end point (eg:- /api/device/information)
:param cookies: cookies, defaults to None
:param headers: HTTP headers, defaults to None
:type endpoint: string
:type postBody: string
:type cookies: dictionary
:type headers: dictionary
:return: Return the HTTP response as a requests.Response
:rtype: :class:`requests.Response`
"""
if(cookies == None):
cookies = self.buildCookies()
# request
try:
_response = requests.get(f"{self._httpHost}{endpoint}", cookies=cookies, timeout=self._HTTPcallTimeOut, verify=False)
self.processHTTPHeaders(_response)
return _response
except Exception as e:
self.logger.error(e)
raise hilinkException(self._modemname, f"Calling {self._httpHost}{endpoint} failed")
def httpPost(self, endpoint, postBody, cookies=None, headers=None):
"""
Call an API end point using a HTTP POST request. If :attr:`cookies` are not provided (when defaulted to None) will build cookies
by calling :meth:`~buildCookies`.
At the end of each call :meth:`~processHTTPHeaders` will call to retrieve *SessionID* and *__RequestVerificationToken*.
:param endpoint: API end point (eg:- /api/user/authentication_login)
:param postBody: HTTP body
:param cookies: cookies
:param headers: HTTP headers
:type endpoint: string
:type postBody: string
:type cookies: dictionary
:type headers: dictionary
:return: Return the HTTP response as a requests.Response
:rtype: :class:`requests.Response`
"""
if(cookies == None):
cookies = self.buildCookies()
# request
try:
_response = requests.post(f"{self._httpHost}{endpoint}", data=postBody, cookies=cookies, headers=headers, timeout=self._HTTPcallTimeOut, verify=False)
self.processHTTPHeaders(_response)
return _response
except Exception as e:
self.logger.error(e)
raise hilinkException(self._modemname, f"Calling {self._httpHost}{endpoint} failed")
def initialize(self):
"""
Calling this method will initialize API calls by
* Initialize session and fetch *SessionID*
* Request initial *__RequestVerificationToken*
* Query authentication required or not
* Identify webUI version
"""
self._sessionId = None
self._RequestVerificationToken = None
self._webuiversion = None
self._deviceClassify = None
self._deviceName = None
# Initialize session
try:
self.httpGet(endpoint="/")
self._isWebUIInitialized = True
except Exception as e:
# WebUI initialization failed
self._isWebUIInitialized = False
self.logger.error(e)
# get request verification token
# first webUI 10 or 21
try:
self.logger.debug(f"Trying for webUI version 10")
response = self.httpGet("/api/webserver/token")
tokenJson = xmltodict.parse(response.text)
if "response" in tokenJson:
loginToken = tokenJson['response']['token']
self.logger.debug(f"Got new loginToken = {tokenJson}")
size = len(loginToken)
self._RequestVerificationToken = loginToken[(size - 32):(size)]
self.logger.debug(f"Got new RequestVerificationToken = {self._RequestVerificationToken}")
# set supporting webUI version is 10 as default
self._webuiversion = 10
# check if it's 21
response = self.httpGet("/api/device/basic_information")
tokenJson21Check = xmltodict.parse(response.text)
if "response" in tokenJson21Check: # valid response
if "WebUIVersion" in tokenJson21Check["response"]:
if "21." in tokenJson21Check["response"]["WebUIVersion"]:
self._webuiversion = 21
except:
self._RequestVerificationToken = None
self._webuiversion = None
# If haven't fetched try for webUI version 17
if self._RequestVerificationToken is None:
self.logger.debug(f"Trying for webUI version 17")
response = self.httpGet("/html/home.html")
soup = BeautifulSoup(response.text, "html.parser")
meta = soup.head.meta
if meta is not None:
self._RequestVerificationToken = meta.get("content", None)
self.logger.debug(f"Got new RequestVerificationToken = {self._RequestVerificationToken}")
if self._RequestVerificationToken is None:
raise hilinkException(self._modemname, "Failed to get a request verification token")
else:
self._webuiversion = 17
# End of request verification token fetching and webUI version
self.logger.info(f"Huawei webUI version = {self._webuiversion}")
###############################################################
# Get basic device info
try:
headers = {'X-Requested-With':'XMLHttpRequest'}
response = self.httpGet("/api/device/basic_information", headers=headers)
deviceInfo = xmltodict.parse(response.text)
if "response" in deviceInfo:
self._deviceClassify = deviceInfo['response']['classify']
self._deviceName = deviceInfo['response']['devicename']
else:
self.sessionErrorCheck(deviceInfo)
raise hilinkException(self._modemname, "Failed to get device info")
except Exception as e:
self.logger.error(e)
raise hilinkException(self._modemname, "Failed to get device info")
###############################################################
################## Authentication required check ##############
if str(self._deviceClassify).upper() == "CPE":
self._loginRequired = True
else:
# common API endpoint for webui version 10,17 & 21
try:
response = self.httpGet("/api/user/hilink_login")
hilinkLogin = xmltodict.parse(response.text)
if "response" in hilinkLogin:
if int(hilinkLogin['response']['hilink_login']) == 0:
# wingles always comes with authentication even hilink_login==0
if str(self._deviceClassify).upper() == "WINGLE" or str(self._deviceClassify).upper() == "MOBILE-WIFI":
self._loginRequired = True
else:
self._loginRequired = False
elif int(hilinkLogin['response']['hilink_login']) == 1:
self._loginRequired = True
else:
self.sessionErrorCheck(hilinkLogin)
raise hilinkException(self._modemname, "Invalid response while getting user hilink state")
except Exception as e:
self.logger.error(e)
raise hilinkException(self._modemname, "Failed to get user login state")
#############Authentication required check end#################
def sessionErrorCheck(self, responseDict):
"""
This method will use to validate error responses
"""
self.logger.error(responseDict)
# check for errors & if exist set as active error code
if "error" in responseDict:
try:
self._activeErrorCode = int(responseDict["error"]["code"])
if self._activeErrorCode in self.errorCodes:
self.logger.error(f"{self._activeErrorCode} -- {self.errorCodes[self._activeErrorCode]}")
else:
self.logger.error(f"Unidentified error code - {self._activeErrorCode}")
########################################################
####### Try to recover identified / known errors #######
# Wrong session token
if self._activeErrorCode == 125003:
self.logger.info(f"Re-initializing webui due to wrong session token error")
# re-initialize, validate and start
self.initialize()
self.validateSession()
self.logger.info(f"Re-initialization of webui due to wrong session token error completed")
###### End of recovering identified / known errors #####
########################################################
except Exception as e:
self.logger.error("Error code extraction failed")
self.logger.error(e)
def resetActiveErrorCode(self):
"""
This method will reset active error code
"""
self._activeErrorCode = 0
def login_b64_sha256(self, data):
"""
This method will used to SHA256 hashing and base64 encoding for WebUI version 10.x.x authentication in :meth:`~login_WebUI10`.
:param data: Data to hash and encode
:type data: string
:return: Return hashed and encoded data string
:rtype: string
"""
s256 = hashlib.sha256()
s256.update(data.encode('utf-8'))
dg = s256.digest()
hs256 = binascii.hexlify(dg)
return base64.urlsafe_b64encode(hs256).decode('utf-8', 'ignore')
def validateSession(self):
"""
This method will validate session
* Check if a valid authenticated session
* If authentication required will login
:return: Return valid session or not
:rtype: boolean
"""
# wait if in an operation
while self._inOperation:
time.sleep(0.5)
#******fine tune the wait******
# update in an operation
self._inOperation = True
#####################################
######### Login state check #########
response = self.httpGet("/api/user/state-login")
stateLogin = xmltodict.parse(response.text)
if "response" in stateLogin:
self._loginState = True if int(stateLogin['response']['State']) == 0 else False
self._passwordType = stateLogin['response']['password_type']
self._loginWaitTime = int(stateLogin['response']['remainwaittime']) if 'remainwaittime' in stateLogin['response'] else 0
# in response lockstatus=1 if locked
# update active error code if has a login wait time
if self._loginWaitTime > 0:
self._activeErrorCode = 108007
else:
self.logger.error("Invalid response while getting user login state")
###### Login state check end ########
#####################################
###### Login if required ############
# In webui 10 self._loginState is -1 even login not enabled so hilink_state check is also required
# print(f"Login required = {self._loginRequired} \t LoginState = {self._loginState} \t time = {datetime.now()}")
if not self._loginState and self._loginRequired:
# check for login wait time
if self._loginWaitTime <= 0:
# invalidate session
self._validSession = False
# check username and password have provided
if self._username is not None and self._password is not None:
# login for webui 17 & 21
if self._webuiversion in (17, 21):
self.logger.debug(f"Login initiated fot WebUI version 17 & 21")
self.logger.debug(f"Having session ID = {self._sessionId}")
self.logger.debug(f"Having request verification token = {self._RequestVerificationToken}")
# generate password value
# base64encode(SHA256(name + base64encode(SHA256($('#password').val())) + g_requestVerificationToken[0]));
passwd_string = f"{self._password}"
s256 = hashlib.sha256()
s256.update(passwd_string.encode('utf-8'))
dg = s256.digest()
hs256 = binascii.hexlify(dg)
hassed_password = base64.urlsafe_b64encode(hs256).decode('utf-8', 'ignore')
s2562 = hashlib.sha256()
s2562.update(f"{self._username}{hassed_password}{self._RequestVerificationToken}".encode('utf-8'))
dg2 = s2562.digest()
hs2562 = binascii.hexlify(dg2)
hashed_username_password = base64.urlsafe_b64encode(hs2562).decode('utf-8', 'ignore')
xml_body = f"""
<?xml version="1.0" encoding="UTF-8"?>
<request>
<Username>{self._username}</Username>
<Password>{hashed_username_password}</Password>
<password_type>{self._passwordType}</password_type>
</request>
""".replace("b\'", "").replace("\'", "")
# challenge headers
headers = {
'X-Requested-With':'XMLHttpRequest',
'__RequestVerificationToken': self._RequestVerificationToken
}
# challenge_login
response = self.httpPost("/api/user/login", xml_body, cookies=None, headers=headers)
loginResponse = xmltodict.parse(response.text)
# validate login & session
if "response" in loginResponse:
if loginResponse['response'] == "OK":
self._validSession = True
# reset if theres any active error
self.resetActiveErrorCode()
else:
self.sessionErrorCheck(loginResponse)
self.logger.error(f"Login failed -- {response.text}")
else:
self.logger.error(f"Login failed -- {response.text}")
# validate login & session end
# else webui 10 login as default
else:
# login to webui 10
self.logger.debug(f"Login initiated fot WebUI version 10")
# grab the verification token
self.logger.debug("Querying for token")
response = self.httpGet("/api/webserver/token")
tokenJson = xmltodict.parse(response.text)
self.logger.debug(response.text)
if "response" in tokenJson:
_tmpToken = tokenJson['response']['token']
self._RequestVerificationToken = _tmpToken[len(_tmpToken) - 32:len(_tmpToken)]
# log
self.logger.debug(f"Having session ID = {self._sessionId}")
self.logger.debug(f"Having request verification token = {self._RequestVerificationToken}")
# generate password value
password_value = self.login_b64_sha256(self._username + self.login_b64_sha256(self._password) + self._RequestVerificationToken)
# challenge login
client_nonce = uuid.uuid4().hex + uuid.uuid4().hex
# generate request XML body
xml_body = """
<?xml version="1.0" encoding="UTF-8"?>
<request>
<username>{}</username>
<firstnonce>{}</firstnonce>
<mode>1</mode>
</request>
""".format(self._username, client_nonce)
# challenge headers
headers = {
'X-Requested-With':'XMLHttpRequest',
'__RequestVerificationToken': self._RequestVerificationToken
}
# challenge_login
response = self.httpPost("/api/user/challenge_login", xml_body, cookies=None, headers=headers)
challangeDict = xmltodict.parse(response.text)
self.logger.debug("Login challangeDict")
# check for response
if 'response' in challangeDict:
salt = challangeDict['response']['salt']
server_nonce = challangeDict['response']['servernonce']
iterations = int(challangeDict['response']['iterations'])
# authenticate login
msg = "%s,%s,%s" % (client_nonce, server_nonce, server_nonce)
salted_pass = hashlib.pbkdf2_hmac('sha256', bytearray(self._password.encode('utf-8')), bytearray.fromhex(salt), iterations)
client_key = hmac.new(b'Client Key', msg=salted_pass, digestmod=hashlib.sha256)
stored_key = hashlib.sha256()
stored_key.update(client_key.digest())
signature = hmac.new(msg.encode('utf_8'), msg=stored_key.digest(), digestmod=hashlib.sha256)
client_key_digest = client_key.digest()
signature_digest = signature.digest()
client_proof = bytearray()
i = 0
while i < client_key.digest_size:
val = ord(client_key_digest[i:i + 1]) ^ ord(signature_digest[i:i + 1])
client_proof.append(val)
i = i + 1
HexClientProof = hexlify(client_proof)
xml_body = """
<?xml version="1.0" encoding="UTF-8"?>
<request>
<clientproof>{}</clientproof>
<finalnonce>{}</finalnonce>
</request>
""".format(HexClientProof, server_nonce).replace("b\'", "").replace("\'", "")
# login headers
headers = {
'X-Requested-With':'XMLHttpRequest',
'__RequestVerificationToken': self._RequestVerificationToken
}
response = self.httpPost("/api/user/authentication_login", xml_body, cookies=None, headers=headers)
loginResponse = xmltodict.parse(response.text)
# validate login & session
if "response" in loginResponse:
self._validSession = True
# reset if theres any active error
self.resetActiveErrorCode()
else:
self.sessionErrorCheck(loginResponse)
self.logger.error(f"Login failed -- {response.text}")
else:
self.sessionErrorCheck(challangeDict)
self.logger.error("Invalid response for Login challageDict")
else:
self.logger.error("Username & password are mandatory")
# login waittime is available have to wait
else:
self.logger.error(f"Login wait time is available {self._loginWaitTime} minutes")
# login not required
else:
# validate session
self._validSession = True
##############################
# update in an operation
self._inOperation = False
# update session refreshed
self._sessionRefreshed = True
# return session validation
return self._validSession
def run(self):
"""
This is the overriding method for :class:threading.Thread.run()
* Check login state of the session
* Perform login when required
"""
# init session refreshed
self._lastSessionRefreshed = 0
# set default stopped into false
self._isStopped = False
#if webUI successfully initialized start the thread
if self._isWebUIInitialized:
# if not stop initialized
while not self._stopped:
if time.time() >= (self._lastSessionRefreshed + self.getSessionRefreshInteval()):
# validate session
self.validateSession()
# reset last session refreshed
self._lastSessionRefreshed = time.time()
# 0.5 second delay in loop
time.sleep(0.5)
####### Loop delay ###########
# at the end of termination mark as stopped
self._isStopped = True
####################################################
###################### Query methods ###############
####################################################
def HiLinkPOST2(self, PATH, xml_body):
"""
Switch on or off data connection based on :attr:`status`.
:param status: Either set status of the connection On or Off
:type status: bool
:return: Return either requested connection switching succeeded or failed
:rtype: bool
"""
# if session is not refreshed validate and refresh session again
if not self._sessionRefreshed:
self.validateSession()
# wait if in an operation
while self._inOperation:
time.sleep(0.5)
# if session is valid start switching data connection
if self._validSession:
try:
# data switch
headers = {
'X-Requested-With':'XMLHttpRequest',
'__RequestVerificationToken': self._RequestVerificationToken
}
# call
self.logger.info(f"calling POST {PATH}")
response = self.httpPost(PATH, xml_body, cookies=None, headers=headers)
ret = xmltodict.parse(response.text)
if "response" in ret:
self.logger.info(f"POST OK {PATH}")
# invalidate refresh
self._sessionRefreshed = False
# reset if theres any active error
self.resetActiveErrorCode()
# return success
return ret
else:
self._sessionRefreshed = False
self.sessionErrorCheck(dataswitchInfo)
self.logger.error(f"POST ERR {PATH}")
# Return failed
return False
####### switching data connection end ########
except Exception as e:
# invalidate refresh
self._sessionRefreshed = False
self.logger.error(e)
self.logger.error(f"POST ERR2 {PATH}")
return False
else:
# invalidate refresh
self._sessionRefreshed = False
self.logger.error(f"POST ERR3 {PATH}")
return False
def HiLinkGET(self, PATH):
"""
This method will query device information and update existing.
If session need a refresh :meth:`~validateSession` before calling device information API end point.
:return: Return querying device info succeed or not
:rtype: boolean
"""
# if session is not refreshed validate and refresh session again
if not self._sessionRefreshed:
self.validateSession()
# wait if in an operation
while self._inOperation:
time.sleep(0.5)
# if session is valid query device info
if self._validSession:
try:
######### query device info ##########
headers = {'X-Requested-With':'XMLHttpRequest'}
response = self.httpGet(PATH, headers=headers)
ret = xmltodict.parse(response.text)
if "response" in ret:
# invalidate refresh
self._sessionRefreshed = False
# reset if theres any active error
self.resetActiveErrorCode()
# return success
return ret
else:
self._sessionRefreshed = False
return False
####### query device info end ########
except Exception as e:
# invalidate refresh
self._sessionRefreshed = False
self.logger.error(e)
self.logger.error(f"{self._modemname} Failed to get {PATH}")
return False
else:
# invalidate refresh
self._sessionRefreshed = False
self.logger.error(f"{self._modemname} Failed to get {PATH}")
return False
def queryDeviceInfo(self):
"""
This method will query device information and update existing.
If session need a refresh :meth:`~validateSession` before calling device information API end point.
:return: Return querying device info succeed or not
:rtype: boolean
"""
# if session is not refreshed validate and refresh session again
if not self._sessionRefreshed:
self.validateSession()
# wait if in an operation
while self._inOperation:
time.sleep(0.5)
# if session is valid query device info
if self._validSession:
try:
######### query device info ##########
headers = {'X-Requested-With':'XMLHttpRequest'}
response = self.httpGet("/api/device/information", headers=headers)
deviceInfo = xmltodict.parse(response.text)
if "response" in deviceInfo:
self._deviceClassify = deviceInfo['response']['Classify']
self._deviceName = deviceInfo['response']['DeviceName']
self._workmode = deviceInfo['response']['workmode']
if "Imei" in deviceInfo['response']:
self._imei = deviceInfo['response']['Imei']
if "SerialNumber" in deviceInfo['response']:
self._serial = deviceInfo['response']['SerialNumber']
if "Imsi" in deviceInfo['response']:
self._imsi = deviceInfo['response']['Imsi']
if "Iccid" in deviceInfo['response']:
self._iccid = deviceInfo['response']['Iccid']
if "supportmode" in deviceInfo['response']:
try:
self._supportedModes = deviceInfo['response']['supportmode'].split("|")
except:
self._supportedModes = []
if "HardwareVersion" in deviceInfo['response']:
self._hwversion = deviceInfo['response']['HardwareVersion']
if "SoftwareVersion" in deviceInfo['response']:
self._swversion = deviceInfo['response']['SoftwareVersion']
if "WebUIVersion" in deviceInfo['response']:
self._webui = deviceInfo['response']['WebUIVersion']
# invalidate refresh
self._sessionRefreshed = False
# reset if theres any active error
self.resetActiveErrorCode()
# return success
return True
else:
self.sessionErrorCheck(deviceInfo)
self._sessionRefreshed = False
return False
####### query device info end ########
except Exception as e:
# invalidate refresh
self._sessionRefreshed = False
self.logger.error(e)
self.logger.error(f"{self._modemname} Failed to get device info")
return False
else:
# invalidate refresh
self._sessionRefreshed = False
self.logger.error(f"{self._modemname} Failed to get device info")
return False
def querySupportedNetworkMethods(self):
"""
This method will query supported network modes
If session need a refresh :meth:`~validateSession` before calling device information API end point.
:return: Return querying supported network modes succeeded or not
:rtype: boolean
"""
# if session is not refreshed validate and refresh session again
if not self._sessionRefreshed:
self.validateSession()
# wait if in an operation
while self._inOperation:
time.sleep(0.5)
# if session is valid query wan ip info
if self._validSession:
#### Query supported network modes ####
headers = {'X-Requested-With':'XMLHttpRequest'}
response = self.httpGet("/config/network/networkmode.xml", headers=headers)
supportedNetModes = xmltodict.parse(response.text)
print(response.text)
# print(supportedNetModes)
else:
# invalidate refresh
self._sessionRefreshed = False
self.logger.error(f"{self._modemname} Failed to get supported network modes")
return False
def queryWANIP(self):
"""
This method will query WAN IP from the carrier network and update existing.
If session need a refresh :meth:`~validateSession` before calling device information API end point.
Separate API end points will be called as per the WebUI version.
:return: Return querying WAN IP succeed or not
:rtype: boolean
"""
# if session is not refreshed validate and refresh session again
if not self._sessionRefreshed:
self.validateSession()
# wait if in an operation
while self._inOperation:
time.sleep(0.5)
# if session is valid query wan ip info
if self._validSession:
# Make WAN IP None
self._wanIP = None
try:
######### query WAN IP info ##########
headers = {'X-Requested-With':'XMLHttpRequest'}
# API endpoint is defer relavant to webui version
if self._webuiversion in (10, 21):
wanIPAPIEndPoint = "/api/device/information"
else: # webui version 17
wanIPAPIEndPoint = "/api/monitoring/status"
response = self.httpGet(wanIPAPIEndPoint, headers=headers)
wanIPInfo = xmltodict.parse(response.text)
if "response" in wanIPInfo:
if "WanIPAddress" in wanIPInfo['response']:
self._wanIP = wanIPInfo['response']['WanIPAddress']
# invalidate refresh
self._sessionRefreshed = False
# reset if theres any active error
self.resetActiveErrorCode()
# return success
return True
else:
self.sessionErrorCheck(wanIPInfo)
self._sessionRefreshed = False
return False
####### query WAN IP info end ########
except Exception as e:
# invalidate refresh
self._sessionRefreshed = False
self.logger.error(e)
self.logger.error(f"{self._modemname} Failed to get WAN IP info")
return False
else:
# invalidate refresh
self._sessionRefreshed = False
self.logger.error(f"{self._modemname} Failed to get WAN IP info")
return False
def queryDataConnection(self):
"""
This method will query following data connection properties and update existing.
* Data roaming enabled or disabled
* Max connection idle timeout
If session need a refresh :meth:`~validateSession` before calling device information API end point.
:return: Return querying data connection properties succeed or not
:rtype: boolean
"""
# if session is not refreshed validate and refresh session again
if not self._sessionRefreshed:
self.validateSession()
# wait if in an operation
while self._inOperation:
time.sleep(0.5)
# if session is valid query data connection info
if self._validSession:
try:
headers = {'X-Requested-With':'XMLHttpRequest'}
response = self.httpGet("/api/dialup/connection", headers=headers)
dataConnectionInfo = xmltodict.parse(response.text)
if "response" in dataConnectionInfo:
self._roamingEnabled = True if int(dataConnectionInfo["response"]["RoamAutoConnectEnable"]) == 1 else False
self._maxIdleTimeOut = int(dataConnectionInfo["response"]["MaxIdelTime"])
else:
self.sessionErrorCheck(dataConnectionInfo)
self._sessionRefreshed = False
# invalidate refresh
self._sessionRefreshed = False
# reset if theres any active error
self.resetActiveErrorCode()
# return success
return True
####### query data connection info end ########
except Exception as e:
# invalidate refresh
self._sessionRefreshed = False
self.logger.error(e)
self.logger.error(f"{self._modemname} Failed to get data connection configuration info")
return False
else:
# invalidate refresh
self._sessionRefreshed = False
self.logger.error(f"{self._modemname} Failed to get data connection configuration info")
return False
def queryNetwork(self):
"""
This method will query network name of the carrier network and update existing.
If session need a refresh :meth:`~validateSession` before calling device information API end point.
:return: Return querying network succeed or not
:rtype: boolean
"""
# if session is not refreshed validate and refresh session again
if not self._sessionRefreshed:
self.validateSession()
# wait if in an operation
while self._inOperation:
time.sleep(0.5)
# if session is valid query network info
if self._validSession:
try:
headers = {'X-Requested-With':'XMLHttpRequest'}
response = self.httpGet("/api/net/current-plmn", headers=headers)
connectionInfo = xmltodict.parse(response.text)
if "response" in connectionInfo: