-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtinySIP.cpp
More file actions
4261 lines (3792 loc) · 151 KB
/
Copy pathtinySIP.cpp
File metadata and controls
4261 lines (3792 loc) · 151 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
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
/*
Copyright © 2019, 2020, 2021, 2022 HackEDA, Inc.
Licensed under the WiPhone Public License v.1.0 (the "License"); you
may not use this file except in compliance with the License. You may
obtain a copy of the License at
https://wiphone.io/WiPhone_Public_License_v1.0.txt.
Unless required by applicable law or agreed to in writing, software,
hardware or documentation distributed under the License is distributed
on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
#include "tinySIP.h"
#include "helpers.h"
extern bool UDP_SIP;
// Handle disconnect timeout
bool timeout_disconnect = false;
uint32_t timeout_disconnect_mls = 0;
uint16_t tmpRespSeq = 0;
/*
* This is tiny implementation of the SIP protocol intended to be used in embedded designs.
* The goal is to implement a minimalist SIP user agent (UA) while maintaining a compact
* RAM footprint and support sequential code execution. (The latter goal comes from the
* fact that LwIP sockets do no work well inside FreeRTOS threads on ESP32 platform.)
*
* tinySIP is mostly based on (see tinySIP.h also):
* RFC 3261 "SIP: Session Initiation Protocol"
* RFC 3263 "Session Initiation Protocol (SIP): Locating SIP Servers"
* RFC 4566 "SDP: Session Description Protocol"
* RFC 3428 "Session Initiation Protocol (SIP) Extension for Instant Messaging"
*/
// DEVELOPER NOTES:
// All dynamic variable names must contain "Dyn" suffix
// Don't forget to free memory after:
// - malloc
// - strdup
// - strndup
// Don't forget to `delete` objects after making `new` ones.
// Watch out for `strcspn` and especially `strsep` (latter one is destructive)
#ifdef WIPHONE_PRODUCTION
#define TCP(tcp, fmt, ...) tcp.print(fmt, ##__VA_ARGS__)
#define TCP_PRINTF(tcp, fmt, ...) tcp.printf(fmt, ##__VA_ARGS__)
// why isn't this enabled (disabled) in production?
//#define SIP_DEBUG_DELAY(n)
#else
#include <esp32-hal-log.h>
#define TCP(tcp, fmt, ...) do{/*log_d(fmt, ##__VA_ARGS__);*/tcp.print(fmt, ##__VA_ARGS__);}while(0);
#define TCP_PRINTF(tcp, fmt, ...) do{log_d(fmt, ##__VA_ARGS__);tcp.printf(fmt, ##__VA_ARGS__);}while(0);
#define SIP_DEBUG_DELAY(n) delay(n)
#endif // WIPHONE_PRODUCTION
const uint8_t TinySIP::SUPPORTED_RTP_PAYLOADS[3] = {
G722_RTP_PAYLOAD,
ULAW_RTP_PAYLOAD,
ALAW_RTP_PAYLOAD,
};
AddrSpec::AddrSpec(const char* str)
: _copy(std::unique_ptr<char[]>(strdup(str))),
_host(nullptr) {
_scheme = nullptr;
_hostport = nullptr;
_userinfo = nullptr;
_uriParams = nullptr;
_headers = nullptr;
char* const pStart = _copy.get();
char* pEnd = TinySIP::parseAddrSpec(pStart, &_scheme, &_hostport, &_userinfo, &_uriParams, &_headers);
if (pEnd) {
_copy[pEnd - pStart] = '\0';
// Try to free a little memory in the case that str has irrelevant extra characters
char* ptr = (char*) realloc(pStart, pEnd - pStart + 1);
if (ptr) {
_copy.release();
_copy.reset(ptr);
}
}
}
void AddrSpec::parseHostPort() {
if (_hostport!=nullptr) {
int colon = strcspn(_hostport, ":");
if (_hostport[colon]==':') {
_host = std::unique_ptr<char[]>(strndup(_hostport, colon));
_port = atoi(_hostport+colon+1);
} else {
_host = std::unique_ptr<char[]>(strdup(_hostport)); // TODO: is there a way to do it without duplicating space?
_port = 0;
}
}
}
char* AddrSpec::host() {
if (_host==nullptr) {
parseHostPort();
}
return _host.get();
}
uint16_t AddrSpec::port() {
if (_port<0) {
parseHostPort();
}
return _port<0 ? 0 : _port;
}
void AddrSpec::show() {
if (_scheme) {
log_d("scheme: %s", _scheme);
}
if (_hostport) {
log_d("hostport: %s", _hostport);
}
if (this->host()) {
log_d("host: %s", this->host());
}
if (this->port()) {
log_d("port: %d", this->port());
}
if (_userinfo) {
log_d("userinfo: %s", _userinfo);
}
if (_uriParams) {
log_d("uriParams: %s", _uriParams);
}
if (_headers) {
log_d("headers: %s", _headers);
}
}
bool Connection::stale() {
// This works only for proxy connections, which are regularly pinged
// TODO: include other indicators
return this->everPonged && this->pinged && this->rePinged && timeDiff(this->msLastPing, this->msLastPong) > TinySIP::STALE_CONNECTION_MS;
// elapsedMillis(msNow, tcpProxy->msLastReceived, STALE_CONNECTION_MS) && elapsedMillis(msNow, tcpProxy->msLastConnected, STALE_CONNECTION_MS) ? true : false;
}
TextMessage::TextMessage(const char* msg, const char* src, const char* dst, uint32_t msTime) {
if (msg) {
message = extStrdup(msg);
}
if (src) {
from = extStrdup(src);
}
if (dst) {
to = extStrdup(dst);
}
millisTime = msTime;
}
TextMessage::~TextMessage() {
freeNull((void **) &message);
freeNull((void **) &from);
freeNull((void **) &to);
}
TinySIP::RouteSet::RouteSet() : set(LinearArray<const char*, LA_INTERNAL_RAM>()) {
setReverse = false;
}
TinySIP::RouteSet::RouteSet(RouteSet& other) : RouteSet() {
this->copy(other);
}
TinySIP::RouteSet::~RouteSet() {
this->clear();
}
void TinySIP::RouteSet::copy(RouteSet& other) {
log_v("RouteSet::copy");
this->clear();
this->setReverse = other.setReverse;
for (uint16_t i=0; i<other.set.size(); i++)
if (other.set[i] != NULL) {
this->set.add(strdup(other.set[i]));
}
}
void TinySIP::RouteSet::clear(bool reverse) {
log_v("RouteSet::clear");
for (uint16_t i=0; i<set.size(); i++) {
if (set[i]!=NULL) {
freeNull((void **) &set[i]);
}
}
set.clear();
setReverse = reverse;
}
bool TinySIP::RouteSet::add(const char *rrAddrSpec, const char *rrParams) {
// TODO: rrParams are ignored by this implementation for simplicity; preserve it (low priority, almost never used in practice)
if (rrParams != NULL) {
log_d("WARNING: non-empty route parameter (rr-param)");
}
const char* s = (const char*) strdup(rrAddrSpec);
return (s != nullptr) ? set.add(s) : false;
}
const char* TinySIP::RouteSet::operator[](uint16_t index) const {
return set[setReverse ? set.size()-1-index : index];
}
TinySIP::Dialog::Dialog(bool isCaller)
: caller(isCaller), usageTimeMs(0),
callIdDyn(nullptr), localTagDyn(nullptr), remoteTagDyn(nullptr),
localUriDyn(nullptr), remoteUriDyn(nullptr),
localNameDyn(nullptr), remoteNameDyn(nullptr),
remoteTargetDyn(nullptr),
early(0), confirmed(0), terminated(0), secure(0), accepted(0) {}
TinySIP::Dialog::Dialog(bool isCaller, const char* callId, const char* localTag, const char* remoteTag)
: Dialog(isCaller) {
this->dialogIdHash = 0;
// Remember the dialog ID and calculate its hash
if (callId) {
this->callIdDyn = extStrdup(callId);
this->dialogIdHash = rotate5(this->dialogIdHash) ^ hash_murmur(callId);
}
if (localTag) {
this->localTagDyn = extStrdup(localTag);
this->dialogIdHash = rotate5(this->dialogIdHash) ^ hash_murmur(localTag);
}
if (remoteTag) {
this->remoteTagDyn = extStrdup(remoteTag);
this->dialogIdHash = rotate5(this->dialogIdHash) ^ hash_murmur(remoteTag);
}
// DEBUG
IF_LOG(VERBOSE) {
log_d("Dialog(%s, %s, %s) = 0x%x",
callIdDyn ? callIdDyn : "(null)",
localTagDyn ? localTagDyn : "(null)",
remoteTagDyn ? remoteTagDyn : "(null)",
dialogIdHash);
}
}
TinySIP::Dialog::~Dialog() {
if (this->callIdDyn) {
freeNull((void **) &this->callIdDyn);
}
if (this->localTagDyn) {
freeNull((void **) &this->localTagDyn);
}
if (this->remoteTagDyn) {
freeNull((void **) &this->remoteTagDyn);
}
if (this->localUriDyn) {
freeNull((void **) &this->localUriDyn);
}
if (this->remoteUriDyn) {
freeNull((void **) &this->remoteUriDyn);
}
if (this->localNameDyn) {
freeNull((void **) &this->localNameDyn);
}
if (this->remoteNameDyn) {
freeNull((void **) &this->remoteNameDyn);
}
if (this->remoteTargetDyn) {
freeNull((void **) &this->remoteTargetDyn);
}
}
bool TinySIP::Dialog::operator==(const Dialog& other) const {
// (Relatively) quick check for a mismatch
if (this->dialogIdHash != other.dialogIdHash) {
return false;
}
log_v("dialog ID hash matches");
// Check whether all parts of dialog ID really match
if ( !(this->callIdDyn && other.callIdDyn && !strcmp(this->callIdDyn, other.callIdDyn) &&
this->localTagDyn && other.localTagDyn && !strcmp(this->localTagDyn, other.localTagDyn) &&
(this->remoteTagDyn && other.remoteTagDyn && !strcmp(this->localTagDyn, other.localTagDyn) ||
!this->remoteTagDyn && !other.remoteTagDyn)) ) {
return false;
}
// // It matched -> update usage time
// this->usageTimeMs = other.usageTimeMs = millis();
return true;
}
TinySIP::Dialog* TinySIP::findDialog(const char* callId, const char* tagLocal, const char* tagRemote) {
Dialog* res = nullptr;
// Create the Dialog object
Dialog diag = Dialog(false, callId, tagLocal, tagRemote); // false or true -> doesn't matter here
// Search for the same dialog in the array
for (auto it = this->dialogs.iterator(); it.valid(); ++it) {
if (diag == **it) {
log_v("dialog 0x%x found", (uint32_t)diag);
res = *it;
}
}
if (!res) {
log_e("dialog 0x%x not found", (uint32_t)diag);
}
return res;
}
/* Description:
* find a dialog in the `dialogs` array.
* if it is not found -> create one and add to the array.
* if the array is full while adding -> find the oldest terminated dialog and replace it.
* Implicit parameters:
* on storing a dialog,
*/
TinySIP::Dialog* TinySIP::findCreateDialog(bool isCaller, const char* callId, const char* tagLocal, const char* tagRemote) {
uint32_t now = millis();
// Create the Dialog object
Dialog* diag = new Dialog(isCaller, callId, tagLocal, tagRemote);
// Search for the same dialog in the array
for (auto it = this->dialogs.iterator(); it.valid(); ++it) {
if (*diag == **it) {
delete diag;
// TODO: dialogs: update dialog with new information
(*it)->setUseTime(now);
if (!diag->remoteTargetDyn && respContAddrSpecDyn) {
diag->remoteTargetDyn = extStrdup(respContAddrSpecDyn);
}
// TODO: dialogs: update CSeq
return *it;
}
}
// Dialog not found -> rememeber it
// First: add more information about the dialog using the parsed fields
{
const char* localUri = isCaller ? respFromAddrSpec : respToAddrSpec;
const char* remoteUri = isCaller ? respToAddrSpec : respFromAddrSpec;
diag->localUriDyn = localUri ? extStrdup(localUri) : NULL;
diag->remoteUriDyn = remoteUri ? extStrdup(remoteUri) : NULL;
}
{
log_d("NAME FROM: %s", respFromDispName ? respFromDispName : "null");
log_d("NAME TO: %s", respToDispName ? respToDispName : "null");
const char* localName = isCaller ? respFromDispName : respToDispName;
const char* remoteName = isCaller ? respToDispName : respFromDispName;
if (!localName && !strcmp(tagLocal, localTag)) {
localName = localNameDyn;
}
if (!remoteName && !strcmp(tagRemote, localTag)) {
remoteName = localNameDyn;
}
diag->localNameDyn = localName ? extStrdup(localName) : NULL;
diag->remoteNameDyn = remoteName ? extStrdup(remoteName) : NULL;
log_d("NAME LOCAL: %s", diag->localNameDyn ? diag->localNameDyn : "null");
log_d("NAME REMOTE: %s", diag->remoteNameDyn ? diag->remoteNameDyn : "null");
}
diag->localCSeq = isCaller ? cseq : respCSeq;
diag->remoteCSeq = isCaller ? respCSeq : cseq;
if (respContAddrSpecDyn) {
diag->remoteTargetDyn = extStrdup(respContAddrSpecDyn);
}
if (respRouteSet.size()) {
diag->routeSet.copy(respRouteSet);
}
// Second: add this dialog to the array
diag->setUseTime(now);
if (this->dialogs.size() < MAX_DIALOGS) {
log_v("adding dialog 0x%08x to dialogs (size=%d)", (uint32_t)*diag, this->dialogs.size());
this->dialogs.add(diag);
return diag;
}
// If the array reached it's maximum size -> find a (prefereably terminated) dialog with the oldest usage time and replace it
bool retry = false;
int oldest = -1;
uint32_t oldestTimeDiff = 0; // time diff with the current time, maximum is 49.7 days, since we are looking only at past times
search:
for (auto it = this->dialogs.iterator(); it.valid(); ++it) {
uint32_t timeDiff = now - (*it)->usageTimeMs;
if (((*it)->isTerminated() || retry) && timeDiff > oldestTimeDiff) {
oldestTimeDiff = timeDiff;
oldest = (int)it;
}
}
if (oldest < 0) {
// No terminated dialogs found -> drop terminated requirement
log_e("dialogs array is full with non-terminated dialogs");
retry = true;
goto search;
}
if (oldest >= 0) {
delete this->dialogs[oldest];
this->dialogs[oldest] = diag;
return diag;
}
// Should never be reached
log_e("critical exception: dialog not added");
return nullptr;
}
void TinySIP::restoreDialogContext(Dialog& diag) {
// log_v("restoreDialogContext");
// // TODO: dialogs: see sendResponse to what is needed to reply
// // TODO: dialogs: see sendBye to what is needed to hangup
// // TODO: dialogs: see sendAck to what is needed for ACK
// freeNull((void**) &this->callIdDyn);
//
// if (diag.callIdDyn) this->callIdDyn = strdup(diag.callIdDyn);
}
TinySIP::TinySIP()
: tcpLast(tcpProxy), respRouteSet() {
log_i("TinySIP construct");
connectReturnedFalse = false;
// Dynamic variables
respToTagDyn = NULL;
remoteToFromDyn = NULL;
respFromTagDyn = NULL;
remoteUriDyn = NULL;
outgoingMsgDyn = NULL;
localUserDyn = NULL;
localNameDyn = NULL;
localUriDyn = NULL;
proxyPasswDyn = NULL;
remoteAudioAddrDyn = NULL;
remoteAudioPort = 0;
//dialogsDyn = NULL;
respContDispNameDyn = NULL;
respContAddrSpecDyn = NULL;
guiReasonDyn = NULL;
callIdDyn = NULL;
regCallIdDyn = NULL;
msgCallIdDyn = NULL;
sdpSessionId = 0;
phoneNumber = 0;
cseq = 0;
regCSeq = 0;
nonceCount = 0;
nonFree = 0;
tcpProxy = NULL;
tcpRoute = NULL;
tcpCallee = NULL;
leftOver = false;
// Reset buffer variables
resetBuffer();
// Timing
this->msLastKnownTime = 0;
this->msLastRegistered = 0xffffffff - TinySIP::REGISTER_EXPIRATION_S*1000;
this->msLastRegisterRequest = 0xffffffff - TinySIP::REGISTER_PERIOD_MS + 4500; // register 4.5 seconds after starting
}
/*
* Description:
* (re)initialize dialog identifiers and connect to SIP proxy
* return:
* whether connection was successfull
*/
bool TinySIP::init(const char* name, const char* fromUri, const char* proxyPass, const uint8_t* mac) {
log_v("TinySIP::init");
// re-init logic
clearDynamicState();
resetBuffer();
// Reset bools
this->registered = false;
this->everRegistered = false;
this->registrationRequested = false;
// Caller parameters
AddrSpec addrParsed(fromUri);
localUserDyn = strdup(addrParsed.userinfo());
localNameDyn = strdup(name);
localUriDyn = strdup(fromUri);
proxyPasswDyn = strdup(proxyPass);
// MAC address
memcpy(this->mac, mac, 6);
sprintf(this->macHex, "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
// Connect to the proxy server
log_v("Connecting to proxy");
// If the SYN from the connection attempt gets an immediate RST, such as:
// connect(): socket error on fd 57, errno: 104, "Connection reset by peer"
// it probably means the proxy doesn't support TCP. Better to warn the user instead of failing silently.
// Something like: IP address X.X.X.X not accepting TCP connections on port XXXX.
proxyIpAddr = ensureConnection(tcpProxy, fromUri, false, 500);
if (tcpProxy && tcpProxy->connected()) {
log_i("Connected to proxy!");
log_i(" IP: %s", proxyIpAddr.toString().c_str());
thisIP = WiFi.localIP().toString();
return true;
}
// Else: connection failed
log_e("Could NOT connect to proxy");
return false;
}
/* Description:
* generate random phoneNumber and cseq.
* Important before making any request or sending a response. Should be called after randomness bits are collected.
*/
void TinySIP::randInit() {
// Generate random "phone number" ONCE per existence of this object
if (!phoneNumber) {
phoneNumber = Random.random();
// Ensure phoneNumber has 8 digits
if (!phoneNumber) {
phoneNumber = 12345678;
}
while (phoneNumber>99999999) {
phoneNumber /= 10;
}
while (phoneNumber<10000000) {
phoneNumber *= 3;
}
newLocalTag(true);
// REGISTER Call-ID is should be the same for all registrations from the UA, therefore it's generated only once
newCallId(®CallIdDyn);
}
// cseq can potentially cycle past 65535 (almost impossible), so we initialize it separately
if (!cseq) {
cseq = (uint16_t) Random.random(); // CSeq must be less than 1<<31, but we use only 16-bit value
if (cseq<1000) {
cseq = 1000; // to avoid confusion with other numbers
}
if (cseq>=64000) {
cseq >>= 1; // CSeq withing a dialog must be "strictly monotonically increasing" (RFC 3261, Section 12.2.1.1)
}
}
}
void TinySIP::freeNullConnectionProxyObject(bool isProxy) {
// Clean up connections that are identical to tcpProxy
if (isProxy) {
if (tcpRoute==tcpProxy) {
log_d("tcpRoute nulled");
tcpRoute = NULL;
}
if (tcpCallee==tcpProxy) {
log_d("tcpCallee nulled");
tcpCallee = NULL;
}
tcpProxy = NULL;
}
}
/*
* Description:
* ensure tcp is connected to host specified by IP and port
* Return:
*
*/
bool TinySIP::ensureIpConnection(Connection*& tcp, IPAddress &ipAddr, uint16_t port, bool forceRenew, int32_t timeout) {
// Check if ipAddr is valid
if ((uint32_t) ipAddr == 0) {
log_e("Cannot connect to 0.0.0.0");
return false;
}
// Check if trying to connect to already connected proxy server
bool isProxy = false;
if (!forceRenew && tcpProxy!=NULL && tcp!=tcpProxy && tcpProxy->connected() && ipAddr==tcpProxy->remoteIP() && port==tcpProxy->remotePort() && !tcpProxy->stale()) {
// A new connection is asked to be connected to proxy -> reuse proxy connection instead (useful when tcpRoute has the same address as the proxy)
log_d("Reusing proxy connection");
tcp = tcpProxy;
isProxy = true;
} else if (tcpProxy!=NULL && tcp==tcpProxy) {
// Connection is the same as proxy, but it seems to be disconnected or stale
log_d("Ensuring tcpProxy");
isProxy = true;
}
// Check if already connected
bool good = false; // connection is good as is
bool exist = false;
if (tcp!=NULL) {
exist = true;
if (!forceRenew && tcp->connected() && tcp->remoteIP()==ipAddr && tcp->remotePort()==port && !tcp->stale()) {
// Connection is good -> use existing connection
good = true;
} else {
// Connection is not good -> clean it up
log_d("TCP connection state: %s", forceRenew ? "FORCED RENEWAL" : tcp->stale() ? "stale" : (tcp->connected() ? "new destination" : "not connected"));
tcp->stop();
delete tcp;
freeNullConnectionProxyObject(isProxy);//tcpProxy=null etc.
tcp = NULL;
}
}
uint32_t get_millis = millis();
/*try to connect to tcp again by some seconds interval.*/
if(timeout_disconnect && ( get_millis - timeout_disconnect_mls ) < 10000) {
log_i("Still in disconnect mode");
return good;
}
// Connect
if (!good) {
log_e("%s", exist ? "Reconnecting:" : "Connecting:");
log_e(" IP: %s", ipAddr.toString().c_str());
log_e(" Port: %d", port);
//UDP_SIP=1;
if(UDP_SIP) {
if(tcp && !tcp->isUdp() && !connectReturnedFalse || !tcp) {
tcp = new UDP_SIPConnection;
}
} else {
if(tcp && !tcp->isTcp() && !connectReturnedFalse || !tcp) {
tcp = new TCP_SIPConnection;
}
}
if (tcp->connect(ipAddr, port, timeout)) { // TODO: when there is no connection, this causes HANGING
log_d("Connected!");
//log_d(" Socket handle: %d", tcp->fd());
log_d(" Local port: %d", tcp->localPort());
good = tcp->connected();
if (!good) {
log_d("ERROR: DISCONNECTED");
timeout_disconnect = true;
timeout_disconnect_mls = get_millis;
delete tcp;
freeNullConnectionProxyObject(isProxy);//tcpProxy=null etc.
tcp = NULL;
} else {
tcp->msLastConnected = msLastKnownTime;
timeout_disconnect = false;
}
tcp->msLastConnected = msLastKnownTime;
connectReturnedFalse = false;
} else {
timeout_disconnect = true;
timeout_disconnect_mls = get_millis;
connectReturnedFalse = true;
log_d("Error: could not connect");
if(tcp) {
delete tcp;
freeNullConnectionProxyObject(isProxy);//tcpProxy=null etc.
tcp = NULL;
}
}
} else {
log_d("TCP connection is already good");
}
return good;
}
/*
* Description:
* ensure `tcp` is connected to host specified by addrSpec.
* Return:
* IP address which was resolved from addrSpec
*/
IPAddress TinySIP::ensureConnection(Connection*& tcp, const char* addrSpec, bool forceRenew, int32_t timeout) {
log_d("Ensuring connection: %s", addrSpec);
AddrSpec addrParsed(addrSpec);
IPAddress ipAddr((uint32_t) 0);
if (addrParsed.hostPort()) {
int port = addrParsed.port() ? addrParsed.port() : TINY_SIP_PORT;
log_d(" - host: %s", addrParsed.host());
log_d(" - port: %d", port);
// Connect to IP
// TODO: correctly resolve NAPTR DNS records to IP addresses (this seems to be needed only for sip2sip.info)
if (isdigit(addrParsed.host()[0]) && ipAddr.fromString(addrParsed.host())) {
log_d("Proper IP address: %s", addrParsed.host());
} else if (!strcasecmp(addrParsed.host(), "sip2sip.info")) {
log_d("WARNING: hardcoded IP address");
ipAddr.fromString("85.17.186.7");
// } else if (!strcasecmp(addrParsed.host(), "sip.linphone.org")) {
// log_d("WARNING: hardcoded IP address");
// ipAddr.fromString("91.121.209.194");
// } else if (!strcasecmp(addrParsed.host(), "iptel.org")) {
// log_d("WARNING: hardcoded IP address");
// ipAddr.fromString("212.79.111.155"); // A record of iptel.org, sip.iptel.org
// } else if (!strcasecmp(addrParsed.host(), "antisip.org")) {
// log_d("WARNING: hardcoded IP address");
// ipAddr.fromString("91.121.30.149"); // A record of antisip.com, sip.antisip.com
// } else if (!strcasecmp(addrParsed.host(), "opensips.org")) {
// log_d("WARNING: hardcoded IP address");
// ipAddr.fromString("136.243.23.236"); // A record of opensips.org
} else {
// TODO: this resolves domains only through A-record; need to use NAPTR- and SRV-records
ipAddr = resolveDomain(addrParsed.host());
if ((uint32_t) ipAddr != 0) {
log_d("Resolved: %s -> %s", addrParsed.host(), ipAddr.toString().c_str());
} else {
log_d("Could not resolve: \"%s\"", addrParsed.host());
}
}
ensureIpConnection(tcp, ipAddr, port, forceRenew, timeout);
} else {
log_d("ERROR: no hostport");
}
return ipAddr;
}
/*
* Description:
* determine which IP need to be connected
* Return:
* proper tcp conenction for communication
*/
Connection* TinySIP::getConnection(bool isClient) {
log_d("--- Getting connection ---");
log_d("TinySIP::getConnection as %s", isClient ? "client" : "server");
log_d("TinySIP::getConnection respRouteSet.size() is : %d ", respRouteSet.size());
// UAS found -> connect to UAS directly
if (respRouteSet.size() > 0) {
// Responses should be routed
// The following route set always comes from Record-Route header, but order has different meaning for client and server
log_d("Ensuring route");
ensureConnection(tcpRoute, respRouteSet[0]);
log_d("ensuring tcpRoute: ");
if (tcpRoute!=NULL) {
log_d("OK: port = %d", tcpRoute->localPort());
return tcpRoute;
} else {
log_d("EMPTY");
}
} else if (respClass=='2') {
if (respContAddrSpecDyn!=NULL) {
// Response should be sent to UAS directly
//ensureConnection(tcpCallee, respContAddrSpecDyn, true); // TODO: why forced renewal?
ensureConnection(tcpCallee, respContAddrSpecDyn);
log_d("ensuring tcpCallee: ");
if (tcpCallee!=NULL) {
log_d("OK: port = %d", tcpCallee->localPort());
return tcpCallee;
} else {
log_d("EMPTY");
}
} else {
log_d("EMPTY respContAddrSpecDyn");
}
}
// Fallback to proxy connection
log_d("tcpProxy connection returned (no RouteSet, no Contact known)");
return tcpProxy; // TODO: ensure this one is connected
}
TinySIP::~TinySIP() {
log_d("tinySIP: destruction");
//SIP_DEBUG_DELAY(100); // seems to improve stability
clearDynamicState();
// Clean up all Dialog objects
for (auto it = dialogs.iterator(); it.valid(); ++it)
if (*it) {
delete *it;
}
// Free the linear array itself
dialogs.clear();
freeNull((void **) ®CallIdDyn);
log_d("tinySIP: finishing destruction");
}
/*
* Description:
* free all dynamic variables
*/
void TinySIP::clearDynamicState() {
log_d("TinySIP::clearDynamicState");
//SIP_DEBUG_DELAY(100); // seems to improve stability?
freeNull((void **) &remoteUriDyn);
freeNull((void **) &localUserDyn);
freeNull((void **) &localNameDyn);
freeNull((void **) &localUriDyn);
freeNull((void **) &proxyPasswDyn);
freeNull((void **) &callIdDyn);
freeNull((void **) &msgCallIdDyn);
freeNull((void **) &outgoingMsgDyn);
clearDynamicParsed();
clearDynamicConnections();
}
/*
* Description:
* Free only those dynamic variables that contain parsed values.
* In practice, this contains all the values that are supposed to be stable for a call.
*/
void TinySIP::clearDynamicParsed() {
log_d("TinySIP::clearDynamicParsed");
freeNull((void **) &respToTagDyn);
freeNull((void **) &remoteToFromDyn);
freeNull((void **) &respFromTagDyn);
freeNull((void **) &remoteAudioAddrDyn);
freeNull((void **) &respContDispNameDyn);
freeNull((void **) &respContAddrSpecDyn);
freeNull((void **) &guiReasonDyn);
remoteAudioPort = 0;
this->audioFormat = TinySIP::NULL_RTP_PAYLOAD;
// Forget the route set
respRouteSet.clear();
}
void TinySIP::clearDynamicConnections() {
log_d("clearDynamicConnections");
//SIP_DEBUG_DELAY(100); // seems to improve stability
if (tcpProxy!=NULL) {
delete tcpProxy;
//in order not to delete the same objects twice then cause crashes, we assign null to same pointer with the tcpProxy
freeNullConnectionProxyObject(true);
tcpProxy = NULL;
}
if (tcpRoute!=NULL) {
delete tcpRoute;
tcpRoute = NULL;
}
if (tcpCallee!=NULL) {
delete tcpCallee;
tcpCallee = NULL;
}
leftOver = false;
}
void TinySIP::resetBuffer() {
log_d("reset SIP buffer");
buff[0] = '\0';
buffLength = 0;
buffStart = buff;
resetBufferParsing();
}
void TinySIP::resetBufferParsing() {
log_d("reset SIP buffer parsing");
//log_d(" - resetting digests");
respChallenge = NULL;
digestRealm = NULL;
digestDomain = NULL;
digestNonce = NULL;
digestCNonce = NULL;
digestOpaque = NULL;
digestStale = NULL;
digestAlgorithm = NULL;
digestQopOpt = NULL;
digestQopPref = NULL;
//log_d(" - resetting links");
respCode = 0;
respClass = '0';
respCallId = NULL;
respProtocol = NULL;
respReason = NULL;
respContentLength = 0;
respContentType = NULL;
respBody = NULL;
respMethod = NULL;
respHeaderCnt = 0;
//respToTag[0] = '\0';
respToDispName = NULL;
respToAddrSpec = NULL;
respToParams = NULL;
respFromDispName = NULL;
respFromAddrSpec = NULL;
//log_d(" - reset complete");
// Resetting dynamically allocated variable
//freeNull((void **) &respToTagDyn); // TODO: do we really need to delete these here?
//freeNull((void **) &respFromTagDyn); // TODO: do we really need to delete these here?
}
// INVITE method
int TinySIP::requestInvite(uint32_t msNow, Connection& tcp, const char* toUri, const char* body) {
if (!tcp.connected() || callIdDyn==NULL) {
return TINY_SIP_ERR;
}
randInit();
newBranch(branch);
/*if (respCode==UNAUTHORIZED_401) {
cseq++;
}
else {
cseq;
}*/
cseq++;
freeNull((void **) &respToTagDyn);
// Set timer for next retransmission
msTimerAStart = msNow;
msTimerADuration = msTimerADuration>0 ? 2*msTimerADuration : TinySIP::T1_MS;
if(UDP_SIP) {
tcp.beginPacket(tcp.remoteIP(), tcp.remotePort());
}
// Send INVITE
sendRequestLine(tcp, "INVITE", toUri);
// Headers
sendHeaderVia(tcp, thisIP, tcp.localPort(), branch);
sendHeaderMaxForwards(tcp, 70);
sendHeaderToFromLocal(tcp, 'F'); // From:
sendHeaderToFromRemote(tcp, 'T', false, toUri); // To: we don't know the remote tag at this stage
sendHeaderContact(tcp);
sendHeaderCallId(tcp, callIdDyn);
sendHeaderCSeq(tcp, cseq, "INVITE");
sendHeaderAllow(tcp);
sendHeaderUserAgent(tcp);
sendHeaderAuthorization(tcp, toUri); // Proxy-Authorization or Authorization
// Content headers and body
if (body==NULL) {
const char* cstr = thisIP.c_str();
int len = sdpBody(tcp, cstr, true);
sendBodyHeaders(tcp, len, "application/sdp");
sdpBody(tcp, cstr, false);
} else {
sendBodyHeaders(tcp, strlen(body), "application/sdp");
TCP(tcp, body);
}
tcp.flush();
if(UDP_SIP) {
tcp.endPacket();
}
return TINY_SIP_OK;
}
/*
* Description:
* send SDP body (if not onlyLen) or return length of the SDP body and exit
* Parameters:
* tcp - TCP connection (class Connection)
* ip - IP of the phone as C-string
* onlyLen - whether to return length of the SDP body and exit
* Return:
* of onlyLen is true -> return length of the SDP body to be sent
* otherwise -> return 0
*/
int TinySIP::sdpBody(Connection& tcp, const char* ip, bool onlyLen) {
// SDP session ID has to be different for different sessions
// So we form it randomly and add 1 for each new session.
// Here we just ensure that it cycles withing 8 decimal digits
sdpSessionId = 0x2000000 + (sdpSessionId % 0x2000000); // ensure it has at least 8 digits, but no more: 33554432 .. 67108863
const uint16_t localAudioPort = this->getLocalAudioPort(); // port to which audio should be sent through RTP
const uint16_t localRtcpPort = localAudioPort + 1;
// TODO: send a single format chosen from the invite or 200 OK
// SDP body format for one audio stream
const char format[] PROGMEM = "v=0\r\n"
"o=- 37%d 37%d IN IP4 %s\r\n"