-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSMPPConnection.cs
625 lines (543 loc) · 23.3 KB
/
SMPPConnection.cs
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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net.Sockets;
using System.Net.Security;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Jannesen.Library.Tasks;
using Jannesen.Protocol.SMPP.Internal;
namespace Jannesen.Protocol.SMPP
{
public sealed class SMPPConnection: IDisposable
{
public delegate void DelegateStateChanged(ConnectionState prevState, ConnectionState newState);
public delegate Task DelegateDeliverSm(SMPPDeliverSm message);
private const int EnquirePoll = 60;
private sealed class ActiveRequest
{
public SMPPMessage Message { get; set; }
public Task SendTask { get; set; }
public int TimeoutTicks { get; set; }
public TaskCompletionSource<SMPPMessage> TaskCompletion { get; }
public ActiveRequest(SMPPMessage message)
{
Message = message;
TimeoutTicks = 15;
TaskCompletion = new TaskCompletionSource<SMPPMessage>();
}
}
private sealed class ActiveRequestList
{
public int ActiveCount
{
get {
lock(_list) {
return _list.Count;
}
}
}
public bool isBusy
{
get {
lock(_list) {
return _list.Count > 0;
}
}
}
private readonly List<ActiveRequest> _list;
public ActiveRequest AddMessage(SMPPMessage message)
{
var sendingMessage = new ActiveRequest(message);
lock(_list) {
_list.Add(sendingMessage);
}
return sendingMessage;
}
public ActiveRequestList()
{
_list = new List<ActiveRequest>();
}
public void CompleteError(ActiveRequest sendingMessage, Exception err)
{
lock(_list) {
_list.Remove(sendingMessage);
}
sendingMessage.TaskCompletion.TrySetException(err);
}
public void CompleteResp(SMPPMessage message)
{
ActiveRequest sendingMessage;
lock(_list) {
var idx = _findMessage(message);
sendingMessage = _list[idx];
_list.RemoveAt(idx);
}
sendingMessage.TaskCompletion.SetResult(message);
}
public void TimeoutPoll()
{
List<ActiveRequest> timeoutMessages = null;
lock(_list) {
for (var i = 0 ; i < _list.Count ; ++i) {
if (--(_list[i].TimeoutTicks) <= 0) {
if (timeoutMessages == null) {
timeoutMessages = new List<ActiveRequest>();
}
timeoutMessages.Add(_list[i]);
}
}
}
if (timeoutMessages != null) {
foreach(var m in timeoutMessages)
CompleteError(m, new TimeoutException("Timeout"));
}
}
public void ConnectionDown()
{
lock(_list) {
while (_list.Count > 0) {
var msg = _list[0];
_list.RemoveAt(0);
CompleteError(msg, new SMPPException("Connection down."));
}
}
}
private int _findMessage(SMPPMessage message)
{
for (var i = 0 ; i < _list.Count ; ++i) {
if (_list[i].Message.Sequence == message.Sequence &&
(_list[i].Message.Command == (message.Command & ~CommandSet.Response) || message.Command == CommandSet.GenericNack))
return i;
}
throw new SMPPException("Received response for a unknown message.");
}
}
public string Hostname { get; set; }
public int Port { get; set; }
public bool Tls { get; set; }
public SMPPBind Bind { get; }
public string Url
{
get {
return (Tls ? "smpps://" : "smpp://") + Hostname + ":" + Port.ToString(CultureInfo.InvariantCulture);
}
set {
var url = new Uri(value);
switch(url.Scheme) {
case "smpp": Tls = false; Port = 2775; break;
case "smpps": Tls = true; Port = 2776; break;
default: throw new ArgumentException("Invalid connection schema.");
}
Hostname = url.Host;
if (url.Port > 0)
Port = url.Port;
}
}
public ConnectionState State { get { return _state; } }
public int ActiveRequests { get { return _activeRequests.ActiveCount; } }
public Exception Error { get { return _error; } }
public DelegateStateChanged OnStateChange;
public DelegateDeliverSm OnDeliverSm;
private volatile ConnectionState _state;
private UInt32 _sequence;
private TcpClient _tcpClient;
private Stream _stream;
private TaskLock _sendLock;
private readonly ActiveRequestList _activeRequests;
private int _enquirePoll;
private Exception _error;
private bool _isRunning
{
get {
lock(this) {
switch(_state) {
case ConnectionState.StreamConnected:
case ConnectionState.Binding:
case ConnectionState.Connected:
case ConnectionState.Unbinding:
return true;
default:
return false;
}
}
}
}
public SMPPConnection()
{
Bind = new SMPPBind()
{
BindingType = BindingType.Transceiver,
InterfaceVersion = SmppVersionType.Version3_4
};
_state = ConnectionState.Closed;
_activeRequests = new ActiveRequestList();
}
public void Dispose()
{
Close();
}
public async Task ConnectAsync()
{
// Init
lock (this) {
if (_state != ConnectionState.Closed)
throw new SMPPException("SMPPConnection busy.");
_tcpClient = new TcpClient();
_sendLock = new TaskLock();
_error = null;
_sequence = 1;
}
Exception error = null;
// Connect to SMPP server
try {
Stream stream;
using (new System.Threading.Timer((object state) =>
{
lock(this) {
if (_state == ConnectionState.Connecting || _state == ConnectionState.SslHandshake) {
error = new TimeoutException("Timeout");
_tcpClient.Close();
}
}
},
null, 15 * 1000, System.Threading.Timeout.Infinite))
{
_setState(ConnectionState.Connecting);
await _tcpClient.ConnectAsync(Hostname, Port);
stream = _tcpClient.GetStream();
if (Tls) {
_setState(ConnectionState.SslHandshake);
var sslStream = new SslStream(stream, true);
await sslStream.AuthenticateAsClientAsync(Hostname);
stream = sslStream;
}
}
lock(this) {
if (error != null)
throw error;
_setState(ConnectionState.StreamConnected);
_stream = stream;
}
}
catch(Exception err) {
if (err is ObjectDisposedException || err is NullReferenceException) {
lock(this) {
if (error != null)
err = error;
else
if (_state == ConnectionState.Closed)
err = new SMPPException("Connect aborted by close.");
}
}
err = _setFailed(new SMPPException("Connect failed.", err));
Close();
throw err;
}
// Start comtask
var _ = _run();
// Bind
try {
_setState(ConnectionState.Binding);
var response = await _submitMessage(Bind);
if (response.Status != CommandStatus.ESME_ROK)
throw new SMPPException("Response from server " + response.Status + ".");
_setState(ConnectionState.Connected);
_enquirePoll = EnquirePoll;
}
catch(Exception err) {
throw _setFailed(new SMPPException("Bind failed", err));
}
}
public Task<SMPPMessage> SubmitMessageAsync(SMPPMessage message)
{
if (_state != ConnectionState.Connected)
throw new SMPPException("Not connected.");
return _submitMessage(message);
}
public async Task StopAsync()
{
ConnectionState curState;
lock(this) {
if ((curState = _state) != ConnectionState.Connected) {
_setState(ConnectionState.Unbinding);
}
}
try {
if (curState == ConnectionState.Connected) {
var response = await _submitMessage(new SMPPUnbind());
if (response.Status != CommandStatus.ESME_ROK) {
throw new SMPPException("Response from server " + response.Status + ".");
}
}
}
catch(Exception err) {
throw _setFailed(new SMPPException("Unbind failed.", err));
}
// Wait until read has finished.
for (var i = 0 ; i < 100 ; ++i) {
if (_state == ConnectionState.Closed) {
return;
}
await Task.Delay(25);
}
// Force close
Close();
}
public void Close()
{
_closeTcpClient();
_activeRequests.ConnectionDown();
_sendLock.Dispose();
_setState(ConnectionState.Closed);
}
private async Task _run()
{
try {
_enquirePoll = int.MaxValue;
using (new System.Threading.Timer(_poll, null, 1000, 1000)) {
while (_isRunning) {
var message = await _recvMessage();
switch (message.Command) {
case CommandSet.EnquireLink:
_recvEnquireLink((SMPPEnquireLink)message);
break;
case CommandSet.DeliverSm:
_recvDeliverSm((SMPPDeliverSm)message);
break;
case CommandSet.Unbind:
await _recvUnbind((SMPPUnbind)message);
break;
case CommandSet.GenericNack:
case CommandSet.BindReceiverResp:
case CommandSet.BindTransceiverResp:
case CommandSet.BindTransmitterResp:
case CommandSet.SubmitSmResp:
case CommandSet.EnquireLinkResp:
_activeRequests.CompleteResp(message);
break;
case CommandSet.UnbindResp:
_activeRequests.CompleteResp(message);
_setState(ConnectionState.Stopped);
break;
default: throw new NotImplementedException("No handler for " + message.Command);
}
}
}
}
catch(Exception err) {
if (_isRunning) {
_setFailed(err);
}
}
Close();
}
private void _poll(object state)
{
_activeRequests.TimeoutPoll();
if (_state == ConnectionState.Connected) {
if (--_enquirePoll < 0) {
_enquirePoll = int.MaxValue;
_cmdEnquire();
}
}
}
private async void _cmdEnquire()
{
try {
if (_state == ConnectionState.Connected) {
var response = await _submitMessage(new SMPPEnquireLink());
if (response.Status != CommandStatus.ESME_ROK)
throw new SMPPException("Response from server " + response.Status + ".");
_enquirePoll = EnquirePoll;
}
}
catch(Exception err) {
lock(this) {
if (_state == ConnectionState.Connected) {
_setFailed(new SMPPException("EnquireLink failed", err));
_tcpClient?.Client.Close();
}
}
}
}
private async void _recvDeliverSm(SMPPDeliverSm message)
{
if (OnDeliverSm != null) {
await OnDeliverSm(message);
}
_sendMessageAsync(new SMPPDeliverSmResp(message.Sequence));
}
private void _recvEnquireLink(SMPPEnquireLink message)
{
_sendMessageAsync(new SMPPEnquireLinkResp(message.Sequence));
}
private async Task _recvUnbind(SMPPUnbind message)
{
await _sendMessage(new SMPPUnbindResp(message.Sequence));
await Task.Delay(1000);
throw new SMPPException("UNBind received from remote.");
}
private Task<SMPPMessage> _submitMessage(SMPPMessage message)
{
var sendingMessage = _activeRequests.AddMessage(message);
sendingMessage.SendTask = _sendMessage(message);
sendingMessage.SendTask.ContinueWith((task) =>
{
if (task.Status != TaskStatus.RanToCompletion)
_activeRequests.CompleteError(sendingMessage, task.Exception);
});
return sendingMessage.TaskCompletion.Task;
}
private async Task<SMPPMessage> _recvMessage()
{
var buf = new byte[16];
await _streamRead(buf, 0, buf.Length);
var commandLength = PduReader.ParseInteger(buf, 0);
if (commandLength < 16 || commandLength > (1 << 18))
throw new SMPPException("Invalid command_length " + commandLength + "received.");
if (commandLength > 16) {
Array.Resize(ref buf, (int)commandLength);
await _streamRead(buf, 16, (int)commandLength - 16);
}
var pduReader = new PduReader(buf);
#if DEBUG
Debug.WriteLine("SMPPConnection: RecvMessage size=" + pduReader.CommandLength + " id=" + pduReader.CommandId + " status=" + pduReader.CommandStatus + " seq=" + pduReader.CommandSequence);
#endif
try {
switch (pduReader.CommandId) {
case CommandSet.GenericNack: return new SMPPGenericNack(pduReader);
case CommandSet.BindReceiverResp: return new SMPPBindResp(CommandSet.BindReceiverResp, pduReader);
case CommandSet.BindTransceiverResp: return new SMPPBindResp(CommandSet.BindTransceiverResp, pduReader);
case CommandSet.BindTransmitterResp: return new SMPPBindResp(CommandSet.BindTransmitterResp, pduReader);
case CommandSet.SubmitSmResp: return new SMPPSubmitSmResp(pduReader);
case CommandSet.DeliverSm: return new SMPPDeliverSm(pduReader);
case CommandSet.EnquireLink: return new SMPPEnquireLink(pduReader);
case CommandSet.EnquireLinkResp: return new SMPPEnquireLinkResp(pduReader);
case CommandSet.Unbind: return new SMPPUnbind(pduReader);
case CommandSet.UnbindResp: return new SMPPUnbindResp(pduReader);
default:
throw new SMPPException("Invalid command.");
// TODO set nack
}
}
catch(Exception err) {
throw new SMPPPDUException("Error while parsing received PDU command " + pduReader.CommandId.ToString() + ".", buf, err);
}
}
private async Task _sendMessage(SMPPMessage message)
{
using (await _sendLock.Enter()) {
if (!_isRunning)
throw new SMPPException("Connection is down.");
var writer = new PduWriter();
if ((message.Command & CommandSet.Response) == 0) {
lock(this) {
message.Sequence = _sequence;
_sequence = (_sequence < 1000000000) ? _sequence + 1 : 1;
}
}
writer.WriteMessage(message);
var pduData = writer.PduData();
#if DEBUG
Debug.WriteLine("SMPPConnection: SendMessage size=" + pduData.Length + " id=" + message.Command + " status=" + message.Status + " seq=" + message.Sequence);
#endif
try {
await _stream.WriteAsync(new ReadOnlyMemory<byte>(pduData, 0, pduData.Length));
}
catch(Exception err) {
throw _setFailed(new SMPPException("Send data to SMPP server failed", err));
}
}
}
private async void _sendMessageAsync(SMPPMessage message)
{
try {
await _sendMessage(message);
}
catch(Exception err) {
if (_isRunning) {
_setFailed(new SMPPException("SendMessage failed.", err));
}
}
}
private async Task _streamRead(byte[] buf, int offset, int size)
{
int rs;
while (size > 0 && (rs = await _stream.ReadAsync(new Memory<byte>(buf, offset, size))) > 0) {
offset += rs;
size -= rs;
}
if (size > 0)
throw new SMPPException("Connection closed by remote.");
}
private void _closeTcpClient()
{
lock(this) {
if (_tcpClient != null) {
try {
_tcpClient.Close();
_stream?.Dispose();
}
catch(Exception err) {
Debug.WriteLine("SMPPConnection: close failed: " + err.Message);
}
_tcpClient = null;
_stream = null;
}
}
}
private void _setState(ConnectionState newState)
{
var prevState = ConnectionState.Unknown;
lock(this) {
if (_tcpClient == null && newState != ConnectionState.Closed) {
return ;
}
if (_state != newState) {
prevState = _state;
_state = newState;
}
}
if (prevState != ConnectionState.Unknown) {
#if DEBUG
Debug.WriteLine("SMPPConnection: state=" + newState);
#endif
if (OnStateChange != null) {
try {
OnStateChange(prevState, newState);
}
catch(Exception) {
}
}
}
}
private Exception _setFailed(Exception err)
{
var prevState = ConnectionState.Unknown;
lock(this) {
if (_state != ConnectionState.Failed) {
prevState = _state;
_error = err;
_state = ConnectionState.Failed;
}
}
if (prevState != ConnectionState.Unknown) {
#if DEBUG
Debug.WriteLine("SMPPConnection: state=" + ConnectionState.Failed);
#endif
if (OnStateChange != null) {
try {
OnStateChange(prevState, ConnectionState.Failed);
}
catch(Exception) {
}
}
}
_closeTcpClient();
return err;
}
}
}