-
-
Notifications
You must be signed in to change notification settings - Fork 143
Expand file tree
/
Copy pathclient.py
More file actions
348 lines (277 loc) · 10.9 KB
/
client.py
File metadata and controls
348 lines (277 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
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
#
# smpplib -- SMPP Library for Python
# Copyright (c) 2005 Martynas Jocius <mjoc@akl.lt>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
#
# Modified by Yusuf Kaka <yusufk at gmail>
# Added support for Optional TLV's
"""SMPP client module"""
import binascii
import logging
import select
import socket
import struct
from smpplib import consts, exceptions, smpp
logger = logging.getLogger('smpplib.client')
class SimpleSequenceGenerator(object):
MIN_SEQUENCE = 0x00000001
MAX_SEQUENCE = 0x7FFFFFFF
def __init__(self):
self._sequence = self.MIN_SEQUENCE
@property
def sequence(self):
return self._sequence
def next_sequence(self):
if self._sequence == self.MAX_SEQUENCE:
self._sequence = self.MIN_SEQUENCE
else:
self._sequence += 1
return self._sequence
class Client(object):
"""SMPP client class"""
state = consts.SMPP_CLIENT_STATE_CLOSED
host = None
port = None
vendor = None
_socket = None
sequence_generator = None
def __init__(self, host, port, timeout=5, sequence_generator=None):
self.host = host
self.port = int(port)
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.settimeout(timeout)
if sequence_generator is None:
sequence_generator = SimpleSequenceGenerator()
self.sequence_generator = sequence_generator
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if self._socket is not None:
try:
self.unbind()
except (exceptions.PDUError, exceptions.ConnectionError) as e:
if len(getattr(e, 'args', tuple())) > 1:
logger.warning('(%d) %s. Ignored', e.args[1], e.args[0])
else:
logger.warning('%s. Ignored', e)
self.disconnect()
def __del__(self):
if self._socket is not None:
logger.warning('%s was not closed' % self)
@property
def sequence(self):
return self.sequence_generator.sequence
def next_sequence(self):
return self.sequence_generator.next_sequence()
def connect(self):
"""Connect to SMSC"""
logger.info('Connecting to %s:%s...', self.host, self.port)
try:
if self._socket is None:
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.connect((self.host, self.port))
self.state = consts.SMPP_CLIENT_STATE_OPEN
except socket.error:
raise exceptions.ConnectionError("Connection refused")
def disconnect(self):
"""Disconnect from the SMSC"""
logger.info('Disconnecting...')
if self.state != consts.SMPP_CLIENT_STATE_OPEN:
logger.warning('%s is disconnecting in the bound state' % self)
if self._socket is not None:
self._socket.close()
self._socket = None
self.state = consts.SMPP_CLIENT_STATE_CLOSED
def _bind(self, command_name, **kwargs):
"""Send bind_transmitter command to the SMSC"""
if command_name in ('bind_receiver', 'bind_transceiver'):
logger.debug('Receiver mode')
p = smpp.make_pdu(command_name, client=self, **kwargs)
self.send_pdu(p)
try:
resp = self.read_pdu()
except socket.timeout:
raise exceptions.ConnectionError()
if resp.is_error():
raise exceptions.PDUError('({}) {}: {}'.format(
resp.status,
resp.command,
consts.DESCRIPTIONS.get(resp.status, 'Unknown code')),
int(resp.status),
)
return resp
def bind_transmitter(self, **kwargs):
"""Bind as a transmitter"""
return self._bind('bind_transmitter', **kwargs)
def bind_receiver(self, **kwargs):
"""Bind as a receiver"""
return self._bind('bind_receiver', **kwargs)
def bind_transceiver(self, **kwargs):
"""Bind as a transmitter and receiver at once"""
return self._bind('bind_transceiver', **kwargs)
def unbind(self):
"""Unbind from the SMSC"""
p = smpp.make_pdu('unbind', client=self)
self.send_pdu(p)
try:
return self.read_pdu()
except socket.timeout:
raise exceptions.ConnectionError()
def send_pdu(self, p):
"""Send PDU to the SMSC"""
if self.state not in consts.COMMAND_STATES[p.command]:
raise exceptions.PDUError("Command %s failed: %s" % (
p.command,
consts.DESCRIPTIONS[consts.SMPP_ESME_RINVBNDSTS],
))
logger.debug('Sending %s PDU', p.command)
generated = p.generate()
logger.debug('>>%s (%d bytes)', binascii.b2a_hex(generated), len(generated))
sent = 0
while sent < len(generated):
try:
sent_last = self._socket.send(generated[sent:])
except socket.error as e:
logger.warning(e)
raise exceptions.ConnectionError()
if sent_last == 0:
raise exceptions.ConnectionError()
sent += sent_last
return True
def read_pdu(self):
"""Read PDU from the SMSC"""
logger.debug('Waiting for PDU...')
try:
raw_len = self._socket.recv(4)
except socket.timeout:
raise
except socket.error as e:
logger.warning(e)
raise exceptions.ConnectionError()
if not raw_len:
raise exceptions.ConnectionError()
try:
length = struct.unpack('>L', raw_len)[0]
except struct.error:
logger.warning('Receive broken pdu... %s', repr(raw_len))
raise exceptions.PDUError('Broken PDU')
raw_pdu = self._socket.recv(length - 4)
raw_pdu = raw_len + raw_pdu
logger.debug('<<%s (%d bytes)', binascii.b2a_hex(raw_pdu), len(raw_pdu))
pdu = smpp.parse_pdu(raw_pdu, client=self)
logger.debug('Read %s PDU', pdu.command)
if pdu.is_error():
return pdu
elif pdu.command in consts.STATE_SETTERS:
self.state = consts.STATE_SETTERS[pdu.command]
return pdu
def accept(self, obj):
"""Accept an object"""
raise NotImplementedError('not implemented')
def _message_received(self, pdu):
"""Handler for received message event"""
status = self.message_received_handler(pdu=pdu)
if status is None:
status = consts.SMPP_ESME_ROK
dsmr = smpp.make_pdu('deliver_sm_resp', client=self, status=status)
dsmr.sequence = pdu.sequence
self.send_pdu(dsmr)
def _enquire_link_received(self):
"""Response to enquire_link"""
ler = smpp.make_pdu('enquire_link_resp', client=self)
self.send_pdu(ler)
logger.debug("Link Enquiry...")
def _alert_notification(self, pdu):
"""Handler for alert notification event"""
self.message_received_handler(pdu=pdu)
def set_message_received_handler(self, func):
"""Set new function to handle message receive event"""
self.message_received_handler = func
def set_message_sent_handler(self, func):
"""Set new function to handle message sent event"""
self.message_sent_handler = func
@staticmethod
def message_received_handler(pdu, **kwargs):
"""Custom handler to process received message. May be overridden"""
logger.warning('Message received handler (Override me)')
@staticmethod
def message_sent_handler(pdu, **kwargs):
"""
Called when SMPP server accept message (SUBMIT_SM_RESP).
May be overridden
"""
logger.warning('Message sent handler (Override me)')
def read_once(self, ignore_error_codes=None):
"""Read a PDU and act"""
try:
try:
pdu = self.read_pdu()
except socket.timeout:
logger.debug('Socket timeout, listening again')
pdu = smpp.make_pdu('enquire_link', client=self)
self.send_pdu(pdu)
return
if pdu.is_error():
raise exceptions.PDUError('({}) {}: {}'.format(
pdu.status,
pdu.command,
consts.DESCRIPTIONS.get(pdu.status, 'Unknown status')),
int(pdu.status),
)
if pdu.command == 'unbind': # unbind_res
logger.info('Unbind command received')
return
elif pdu.command == 'submit_sm_resp':
self.message_sent_handler(pdu=pdu)
elif pdu.command == 'deliver_sm':
self._message_received(pdu)
elif pdu.command == 'enquire_link':
self._enquire_link_received()
elif pdu.command == 'enquire_link_resp':
pass
elif pdu.command == 'alert_notification':
self._alert_notification(pdu)
else:
logger.warning('Unhandled SMPP command "%s"', pdu.command)
except exceptions.PDUError as e:
if ignore_error_codes and len(e.args) > 1 and e.args[1] in ignore_error_codes:
logging.warning('(%d) %s. Ignored.', e.args[1], e.args[0])
else:
raise
def poll(self, ignore_error_codes=None):
"""Act on available PDUs and return"""
while True:
readable, writable, exceptional = select.select([self._socket], [], [], 0)
if not readable:
break
self.read_once(ignore_error_codes)
def listen(self, ignore_error_codes=None):
"""Listen for PDUs and act"""
while True:
self.read_once(ignore_error_codes)
def send_message(self, **kwargs):
"""Send message
Required Arguments:
source_addr_ton -- Source address TON
source_addr -- Source address (string)
dest_addr_ton -- Destination address TON
destination_addr -- Destination address (string)
short_message -- Message text (string)
"""
ssm = smpp.make_pdu('submit_sm', client=self, **kwargs)
self.send_pdu(ssm)
return ssm