-
Notifications
You must be signed in to change notification settings - Fork 2
/
apiclient.py
421 lines (378 loc) · 12.8 KB
/
apiclient.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
# -*- coding: utf-8 -*-
"""
hexonet.apiconnector.apiclient
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module covers all necessary functionality for http communicatiton
with our Backend System.
:copyright: © 2018 by HEXONET GmbH.
:license: MIT, see LICENSE for more details.
"""
from hexonet.apiconnector.response import Response
from hexonet.apiconnector.responsetemplatemanager import ResponseTemplateManager as RTM
from hexonet.apiconnector.socketconfig import SocketConfig
from urllib.parse import quote, unquote, urlparse, urlencode
from urllib.request import urlopen, Request
import re
import copy
import platform
rtm = RTM()
ISPAPI_CONNECTION_URL_PROXY = "http://127.0.0.1/api/call.cgi"
ISPAPI_CONNECTION_URL = "https://api.ispapi.net/api/call.cgi"
class APIClient(object):
def __init__(self):
# API connection url
self.setURL(ISPAPI_CONNECTION_URL)
# Object covering API connection data
self.__socketConfig = SocketConfig()
# activity flag for debug mode
self.__debugMode = False
# API connection timeout setting
self.__socketTimeout = 300000
self.useLIVESystem()
# user agent setting
self.__ua = ""
# additional connection settings
self.__curlopts = {}
def setProxy(self, proxy):
"""
Set Proxy to use for API communication
"""
if proxy == '':
self.__curlopts.pop('PROXY', None)
else:
self.__curlopts["PROXY"] = proxy
return self
def getProxy(self):
"""
Get Proxy configuration value for API communication
"""
if "PROXY" in self.__curlopts:
return self.__curlopts["PROXY"]
return None
def setReferer(self, referer):
"""
Set the Referer Header to use for API communication
"""
if referer == '':
self.__curlopts.pop('REFERER', None)
else:
self.__curlopts["REFERER"] = referer
return self
def getReferer(self):
"""
Get the Referer Header configuration value
"""
if "REFERER" in self.__curlopts:
return self.__curlopts["REFERER"]
return None
def enableDebugMode(self):
"""
Enable Debug Output to STDOUT
"""
self.__debugMode = True
return self
def disableDebugMode(self):
"""
Disable Debug Output
"""
self.__debugMode = False
return self
def getPOSTData(self, cmd, secured=False):
"""
Serialize given command for POST request including connection configuration data
"""
data = self.__socketConfig.getPOSTData()
if secured:
data = re.sub(r's_pw=[^&]+', 's_pw=***', data)
tmp = ""
if not isinstance(cmd, str):
for key in sorted(cmd.keys()):
if (cmd[key] is not None):
tmp += ("{0}={1}\n").format(key, re.sub('[\r\n]', '', str(cmd[key])))
else:
tmp = cmd
tmp = tmp.rstrip('\n')
if secured:
tmp = re.sub(r'PASSWORD=[^\n]+', 'PASSWORD=***', tmp)
return ("{0}{1}={2}").format(data, quote('s_command'), quote(re.sub('\n$', '', tmp)))
def getSession(self):
"""
Get the API Session that is currently set
"""
return self.__socketConfig.getSession()
def getURL(self):
"""
Get the API connection url that is currently set
"""
return self.__socketURL
def getUserAgent(self):
"""
Get the User Agent
"""
if (len(self.__ua) == 0):
pid = "PYTHON-SDK"
pyv = platform.python_version()
pf = platform.system()
arch = platform.architecture()[0]
self.__ua = "%s (%s; %s; rv:%s) python/%s" % (pid, pf, arch, self.getVersion(), pyv)
return self.__ua
def setUserAgent(self, pid, rv, modules=[]):
"""
Possibility to customize default user agent to fit your needs by given string and revision
"""
s = " "
mods = ""
if len(modules) > 0:
mods += " " + s.join(modules)
pyv = platform.python_version()
pf = platform.system()
arch = platform.architecture()[0]
self.__ua = "%s (%s; %s; rv:%s)%s python-sdk/%s python/%s" % (pid, pf, arch, rv, mods, self.getVersion(), pyv)
return self
def getVersion(self):
"""
Get the current module version
"""
return "3.5.1"
def saveSession(self, session):
"""
Apply session data (session id and system entity) to given client request session
"""
session["socketcfg"] = {
"entity": self.__socketConfig.getSystemEntity(),
"session": self.__socketConfig.getSession()
}
return self
def reuseSession(self, session):
"""
Use existing configuration out of session
to rebuild and reuse connection settings
"""
self.__socketConfig.setSystemEntity(session["socketcfg"]["entity"])
self.setSession(session["socketcfg"]["session"])
return self
def setURL(self, value):
"""
Set another connection url to be used for API communication
"""
self.__socketURL = value
return self
def setOTP(self, value):
"""
Set one time password to be used for API communication
"""
self.__socketConfig.setOTP(value)
return self
def setSession(self, value):
"""
Set an API session id to be used for API communication
"""
self.__socketConfig.setSession(value)
return self
def setRemoteIPAddress(self, value):
"""
Set an Remote IP Address to be used for API communication.
To be used in case you have an active ip filter setting.
"""
self.__socketConfig.setRemoteAddress(value)
return self
def setCredentials(self, uid, pw):
"""
Set Credentials to be used for API communication
"""
self.__socketConfig.setLogin(uid)
self.__socketConfig.setPassword(pw)
return self
def setRoleCredentials(self, uid, role, pw):
"""
Set Credentials to be used for API communication
"""
if (role == ''):
return self.setCredentials(uid, pw)
return self.setCredentials(("{0}!{1}").format(uid, role), pw)
def login(self, otp=""):
"""
Perform API login to start session-based communication
"""
self.setOTP(otp)
rr = self.request({"COMMAND": "StartSession"})
if (rr.isSuccess()):
col = rr.getColumn("SESSION")
self.setSession(col.getData()[0] if (col is not None) else None)
return rr
def loginExtended(self, params, otp=""):
"""
Perform API login to start session-based communication.
Use given specific command parameters.
"""
self.setOTP(otp)
cmd = {
"COMMAND": "StartSession"
}
cmd.update(params)
rr = self.request(cmd)
if (rr.isSuccess()):
col = rr.getColumn("SESSION")
self.setSession(col.getData()[0] if (col is not None) else None)
return rr
def logout(self):
"""
Perform API logout to close API session in use
"""
rr = self.request({
"COMMAND": "EndSession",
})
if (rr.isSuccess()):
self.setSession(None)
return rr
def request(self, cmd):
"""
Perform API request using the given command
"""
# flatten nested api command bulk parameters
newcmd = self.__flattenCommand(cmd)
# auto convert umlaut names to punycode
newcmd = self.__autoIDNConvert(newcmd)
# request command to API
cfg = {
"CONNECTION_URL": self.__socketURL
}
data = self.getPOSTData(newcmd).encode('UTF-8')
secured = self.getPOSTData(newcmd, True).encode('UTF-8')
try:
headers = {
'User-Agent': self.getUserAgent()
}
if "REFERER" in self.__curlopts:
headers['Referer'] = self.__curlopts["REFERER"]
req = Request(cfg["CONNECTION_URL"], data, headers)
if "PROXY" in self.__curlopts:
proxyurl = urlparse(self.__curlopts["PROXY"])
req.set_proxy(proxyurl.netloc, proxyurl.scheme)
body = urlopen(req, timeout=self.__socketTimeout).read()
if (self.__debugMode):
print((self.__socketURL, secured, body, '\n', '\n'))
except Exception:
body = rtm.getTemplate("httperror").getPlain()
if (self.__debugMode):
print((self.__socketURL, secured, "HTTP communication failed", body, '\n', '\n'))
return Response(body, newcmd, cfg)
def requestNextResponsePage(self, rr):
"""
Request the next page of list entries for the current list query
Useful for tables
"""
mycmd = rr.getCommand()
if ("LAST" in mycmd):
raise Exception("Parameter LAST in use. Please remove it to avoid issues in requestNextPage.")
first = 0
if ("FIRST" in mycmd):
first = int(mycmd["FIRST"])
total = rr.getRecordsTotalCount()
limit = rr.getRecordsLimitation()
first += limit
if (first < total):
mycmd["FIRST"] = first
mycmd["LIMIT"] = limit
return self.request(mycmd)
else:
return None
def requestAllResponsePages(self, cmd):
"""
Request all pages/entries for the given query command
"""
responses = []
mycmd = copy.deepcopy(cmd)
mycmd["FIRST"] = 0
rr = self.request(mycmd)
tmp = rr
while tmp is not None:
responses.append(tmp)
tmp = self.requestNextResponsePage(tmp)
if tmp is None:
break
return responses
def setUserView(self, uid):
"""
Set a data view to a given subuser
"""
self.__socketConfig.setUser(uid)
return self
def resetUserView(self):
"""
Reset data view back from subuser to user
"""
self.__socketConfig.setUser(None)
return self
def useHighPerformanceConnectionSetup(self):
"""
Activate High Performance Setup
"""
self.setURL(ISPAPI_CONNECTION_URL_PROXY)
return self
def useDefaultConnectionSetup(self):
"""
Activate Default Connection Setup (which is the default anyways)
"""
self.setURL(ISPAPI_CONNECTION_URL)
return self
def useOTESystem(self):
"""
Set OT&E System for API communication
"""
self.__socketConfig.setSystemEntity("1234")
return self
def useLIVESystem(self):
"""
Set LIVE System for API communication (this is the default setting)
"""
self.__socketConfig.setSystemEntity("54cd")
return self
def __flattenCommand(self, cmd):
"""
Flatten API command to handle it easier later on (nested array for bulk params)
"""
newcmd = {}
for key in list(cmd.keys()):
newKey = key.upper()
val = cmd[key]
if val is None:
continue
if isinstance(val, list):
i = 0
while i < len(val):
newcmd[newKey + str(i)] = re.sub(r'[\r\n]', '', str(val[i]))
i += 1
else:
newcmd[newKey] = re.sub(r'[\r\n]', '', str(val))
return newcmd
def __autoIDNConvert(self, cmd):
"""
Auto convert API command parameters to punycode, if necessary.
"""
# don't convert for convertidn command to avoid endless loop
# and ignore commands in string format(even deprecated)
if isinstance(cmd, str) or re.match(r'^CONVERTIDN$', cmd["COMMAND"], re.IGNORECASE):
return cmd
toconvert = []
keys = []
for key in cmd:
if re.match(r'^(DOMAIN|NAMESERVER|DNSZONE)([0-9]*)$', key, re.IGNORECASE):
keys.append(key)
if not keys.count:
return cmd
idxs = []
for key in keys:
if not re.match(r'^[a-z0-9.-]+$', cmd[key], re.IGNORECASE):
toconvert.append(cmd[key])
idxs.append(key)
r = self.request({
"COMMAND": "ConvertIDN",
"DOMAIN": toconvert
})
if r.isSuccess():
col = r.getColumn("ACE")
if col is not None:
for idx, pc in enumerate(col.getData()):
cmd[idxs[idx]] = pc
return cmd