Repository navigation
Expand file tree
/
Copy pathsmqueue.cpp
More file actions
3392 lines (2951 loc) · 102 KB
/
Copy pathsmqueue.cpp
File metadata and controls
3392 lines (2951 loc) · 102 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
/*
* Smqueue.cpp - In-memory queue manager for Short Messages (SMS's) for OpenBTS.
* Written by John Gilmore, July 2009.
*
* Copyright 2009, 2014 Free Software Foundation, Inc.
* Copyright 2014 Range Networks, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* See the COPYING file in the main directory for details.
*/
#include "smqueue.h"
#include "smnet.h"
#include "smsc.h"
#include <time.h>
#include <osipparser2/osip_message.h> /* from osipparser2 */
#include <iostream>
#include <fstream>
#include <cstdlib> // strtol
#include <errno.h>
#include <sys/types.h> // open
#include <sys/stat.h> // open
#include <fcntl.h> // open
#include <ctype.h> // isdigit
#include <string>
#include <stdlib.h>
#undef WARNING
#include <Globals.h>
#include <NodeManager.h>
#include <Logger.h>
#include <Timeval.h>
#include "QueuedMsgHdrs.h"
#include "SmqMessageHandler.h"
#include "SmqTest.h"
using namespace std;
using namespace SMqueue;
/* The global config table. */
// DAB
ConfigurationKeyMap getConfigurationKeys();
ConfigurationTable gConfig("/etc/OpenBTS/smqueue.db", "smqueue", getConfigurationKeys());
// Global Smqueue object
SMqueue::SMq smq; // smq defined
/* The global CDR file. */
FILE * gCDRFile = NULL;
/** The remote node manager. */
NodeManager gNodeManager;
/** rate limiting timer */
Timeval spacingTimer;
/* We try to centralize most of the timeout values into this table.
Occasionally the code might do something different where it knows
better, but most state transitions just use this table to set the
timeout that will fire if nothing happens in the new state for X
seconds. */
/* Timeouts when going from NO_STATE into each subsequent state
* Timeouts are in MS
* */
#define NT 3000*1000 /* msseconds = 50 minutes - "No Timeout" - for states
where we will only time out if something is really
broken. Changed to MS */
#define RT 300*1000 /* msseconds = 5 minutes - "Re Try" - for state
transitions where we're starting over from
scratch due to some error. Changed to MS */
#define TT 60*1000 /* 60 seconds the amount of time we add to a transaction
when we get a 100 TRYING message Changed to MS */
/* Timeout when moving from this state to new state:
NS IS RF AF WD RD AD WS RS AS WM RM AM DM WR RH AR */
int timeouts_NO_STATE[STATE_MAX_PLUS_ONE] = {
NT, 0, 0, NT, NT, 0, NT, NT, 0, NT, NT, 0, NT, 0, NT, NT, NT,};
int timeouts_INITIAL_STATE[STATE_MAX_PLUS_ONE] = {
0, 0, 0, NT, NT, NT, NT, NT, NT, NT, NT, 0, NT, 0, NT, NT, NT,};
int timeouts_REQUEST_FROM_ADDRESS_LOOKUP[STATE_MAX_PLUS_ONE] = {
0, NT, 10, 10, NT, 0, NT, NT, NT, NT, NT, NT, NT, 0, 1, 0, NT,};
int timeouts_ASKED_FOR_FROM_ADDRESS_LOOKUP[STATE_MAX_PLUS_ONE] = {
0, NT, 60, NT, NT, NT, NT, NT, NT, NT, NT, NT, NT, 0, NT, NT, NT,};
int timeouts_AWAITING_TRY_DESTINATION_IMSI[STATE_MAX_PLUS_ONE] = {
0, NT, RT, NT, RT, NT, NT, NT, NT, NT, NT, NT, NT, 0, NT, NT, NT,};
int timeouts_REQUEST_DESTINATION_IMSI[STATE_MAX_PLUS_ONE] = { // 5
0, NT, RT, NT, RT, NT, NT, NT, 0, NT, NT, NT, NT, 0, NT, NT, NT,};
int timeouts_ASKED_FOR_DESTINATION_IMSI[STATE_MAX_PLUS_ONE] = {
0, NT, RT, NT, RT, NT, NT, NT, NT, NT, NT, NT, NT, 0, NT, NT, NT,};
int timeouts_AWAITING_TRY_DESTINATION_SIPURL[STATE_MAX_PLUS_ONE] = {
0, NT, RT, NT, RT, NT, NT, NT, NT, NT, NT, NT, NT, 0, NT, NT, NT,};
int timeouts_REQUEST_DESTINATION_SIPURL[STATE_MAX_PLUS_ONE] = {
0, NT, RT, NT, RT, NT, NT, NT, NT, NT, NT, 0, NT, 0, NT, NT, NT,};
int timeouts_ASKED_FOR_DESTINATION_SIPURL[STATE_MAX_PLUS_ONE] = { // 8
0, NT, RT, NT, RT, NT, NT, NT, NT, NT, NT, NT, NT, 0, NT, NT, NT,};
int timeouts_AWAITING_TRY_MSG_DELIVERY[STATE_MAX_PLUS_ONE] = {
0, NT, RT, NT, RT, NT, NT, NT, NT, NT, 75*1000, 0, NT, 0, NT, NT, NT,};
int timeouts_REQUEST_MSG_DELIVERY[STATE_MAX_PLUS_ONE] = { // 10
// 0, NT, RT, NT, RT, NT, NT, NT, 75*1000, NT, 75*1000, 75, 15, 0, NT, NT, NT,};
0, NT, RT, NT, RT, NT, NT, NT, 15*1000, NT, 75*1000, 75*1000, 15*1000, 0, NT, NT, NT,};
int timeouts_ASKED_FOR_MSG_DELIVERY[STATE_MAX_PLUS_ONE] = { // 11
0, NT, RT, NT, NT, NT, NT, NT, NT, NT, 60*1000, 10*1000, TT, 0, NT, NT, NT,}; // changed 11 -> 12 from NT to TT
int timeouts_DELETE_ME_STATE[STATE_MAX_PLUS_ONE] = { // 12
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,};
int timeouts_AWAITING_REGISTER_HANDSET[STATE_MAX_PLUS_ONE] = {
0, NT, 0, NT, RT, NT, NT, NT, NT, NT, NT, NT, NT, 0, 1*1000, 0, NT,};
int timeouts_REGISTER_HANDSET[STATE_MAX_PLUS_ONE] = {
0, NT, 0, NT, RT, NT, NT, NT, NT, NT, NT, NT, NT, 0, 1*1000, 1*1000, 2*1000,};
int timeouts_ASKED_TO_REGISTER_HANDSET[STATE_MAX_PLUS_ONE] = {
0, NT, 0, NT, RT, NT, NT, NT, NT, NT, NT, NT, NT, 0, 1*1000, 1*1000, 10*1000,};
/* Timeout when moving from this state to new state:
NS IS RF AF WD RD AD WS RS AS WM RM AM DM WR RH AR */
#undef NT /* No longer needed */
#undef RT
/* Index to all timeouts. Keep in order! */
int (*SMqueue::timeouts[STATE_MAX_PLUS_ONE])[STATE_MAX_PLUS_ONE] = {
&timeouts_NO_STATE,
&timeouts_INITIAL_STATE,
&timeouts_REQUEST_FROM_ADDRESS_LOOKUP,
&timeouts_ASKED_FOR_FROM_ADDRESS_LOOKUP, // 3
&timeouts_AWAITING_TRY_DESTINATION_IMSI,
&timeouts_REQUEST_DESTINATION_IMSI,
&timeouts_ASKED_FOR_DESTINATION_IMSI,
&timeouts_AWAITING_TRY_DESTINATION_SIPURL, //
&timeouts_REQUEST_DESTINATION_SIPURL, // 8
&timeouts_ASKED_FOR_DESTINATION_SIPURL,
&timeouts_AWAITING_TRY_MSG_DELIVERY,
&timeouts_REQUEST_MSG_DELIVERY, //11
&timeouts_ASKED_FOR_MSG_DELIVERY,
&timeouts_DELETE_ME_STATE,
&timeouts_AWAITING_REGISTER_HANDSET,
&timeouts_REGISTER_HANDSET,
&timeouts_ASKED_TO_REGISTER_HANDSET,
};
string SMqueue::sm_state_strings[STATE_MAX_PLUS_ONE] = {
"No State",
"Initial State",
"Request From-Address Lookup",
"Asked for From-Address",
"Awaiting Try Destination IMSI",
"Request Destination IMSI",
"Asked for Destination IMSI",
"Awaiting Try Destination SIP URL",
"Request Destination SIP URL",
"Asked for Destination SIP URL",
"Awaiting Try Message Delivery",
"Request Message Delivery",
"Asked for Message Delivery",
"Delete Me",
"Awaiting Register Handset",
"Register Handset",
"Asked to Register Handset",
};
string SMqueue::sm_state_string(enum sm_state astate)
{
if (astate < STATE_MAX_PLUS_ONE)
return sm_state_strings[astate];
else return "Invalid State Number";
}
/* Global variables */
bool SMqueue::osip_initialized = false; // Have we called lib's initializer?
struct osip *SMqueue::osipptr = NULL; // Ptr to struct sorta used by library
const char *short_msg_pending::smp_my_ipaddress = NULL; // Accessible copy
const char *short_msg_pending::smp_my_2nd_ipaddress = NULL; // Accessible copy
bool print_as_we_validate = false; // Debugging
/*
* Associative map between target phone numbers (short codes) and
* function pointers that implement those numbers.
*/
short_code_map_t short_code_map; // *********** Defined here does not change after startup
/* Release memory from osip library */
void
osip_mem_release()
{
if (osip_initialized) {
osip_release (SMqueue::osipptr);
SMqueue::osipptr = NULL;
SMqueue::osip_initialized = false;
}
}
/* ==== FIXME KLUDGE ====
* Table of IMSIs and phone numbers, for translation.
* This is only for test-bench use. Real life uses the Home Location
* Register (../HLR), currently implemented via Asterisk.
*/
static
struct imsi_phone { char imsi[4+15+1]; char phone[1+15+1]; } imsi_phone[] = {
// {"IMSI310260550682564", "100"}, /* Siemens A52 */
{"IMSI666410186585295", "+17074700741"}, /* Nokia 8890 */
{"IMSI777100223456161", "+17074700746"}, /* Palm Treo */
{{0}, {0}}
};
/* Functions */
enum sm_state
handle_sms_message(short_msg_pending *qmsg);
bool
check_to_user(char *user);
char *
read_short_msg_from_file(char *file);
/*
* Utility functions
*/
// C++ wants you to use <string>. Fuck that. When we want dynamically
// allocated char *'s, then we'll use them. strdup uses malloc, tho, so
// we need a "new/delete" oriented strdup. Ok, simple.
char *
SMqueue::new_strdup(const char *orig)
{
int len = strlen(orig);
char *result = new char[len+1];
strncpy(result, orig, len+1);
return result;
}
void
increase_acked_msg_timeout(short_msg_pending *msg)
{
time_t timeout = SMq::INCREASEACKEDMSGTMOMS;
if (gConfig.defines("SIP.Timeout.ACKedMessageResend")) {
timeout = gConfig.getNum("SIP.Timeout.ACKedMessageResend");
}
msg->set_state(msg->state, msg->msgettime() + timeout);
}
/*
* We have received a SIP response message (with a status code like 200,
* a message like "Okay", and various other fields). Find the outgoing
* message that matches this response, and do the right thing. The response
* message has already been parsed and validated.
*
* If the response says the message is delivered, delete both the response
* and the message.
*
* In general, delete the response so it won't stay at the front of the
* queue.
*/
void
SMq::handle_response(short_msg_p_list::iterator qmsgit)
{
short_msg_pending *qmsg = &*qmsgit;
short_msg_p_list::iterator sent_msg;
short_msg_p_list resplist;
// First, remove this response message from the queue. That way,
// when we search the queue, we won't find OURSELF. We also don't
// want the response hanging around in the queue anyway.
// Lock
lockSortedList();
resplist.splice(resplist.begin(), time_sorted_list, qmsgit);
// We'll delete the list element on our way out of this function as
// resplist goes out of scope.
// figure out what message we're responding to.
if (!find_queued_msg_by_tag(sent_msg, qmsg->qtag, qmsg->qtaghash)) {
// No message in queue.
LOG(NOTICE) << "Couldn't find message for response tag '"
<< qmsg->qtag << "'; response is:" << endl
<< qmsg->text;
// no big problem, just ignore it.
unlockSortedList();
return;
}
// Keep message locked so it won't get deleted while being modified
// Check what kind of response we got, based on its status code.
// FIXME, logfile output would be useful here.
LOG(NOTICE) << "Got " << qmsg->parsed->status_code
<< " response for sent msg '" << sent_msg->qtag << "' in state "
<< sent_msg->state;
if ( sent_msg->state != ASKED_FOR_MSG_DELIVERY
&& sent_msg->state != REQUEST_MSG_DELIVERY
&& sent_msg->state != REQUEST_DESTINATION_SIPURL
&& sent_msg->state != AWAITING_TRY_MSG_DELIVERY) {
LOG(ERR) << "*** That's not a pleasant state. ***";
// Don't abort here -- if a msg gets forked, one fork
// gets a redirect/reject, this puts us back into a lookup
// state, then we get a response from another fork, don't die.
// Just quietly keep going.
}
switch (qmsg->parsed->status_code / 100) {
case 1: // 1xx -- interim response
//While a 100 doesn't mean anything really,
//we should increase the timeout because
//we know the network worked
increase_acked_msg_timeout(&(*sent_msg));
break;
case 2: // 2xx -- success.
// Done! Extract original msg from queue, and toss it.
sent_msg->parse();
if (sent_msg->parsed &&
sent_msg->parsed->sip_method &&
0 == strcmp("REGISTER", sent_msg->parsed->sip_method)) {
// This was a SIP REGISTER message, so we need
// to free up the original SMS Shortcode message that
// started the registration process.
short_msg_p_list::iterator oldsms;
if (!get_link(oldsms, sent_msg)) {
LOG(NOTICE) << "Can't find SMS message for newly "
"registered handset, linktag '"
<< qmsg->linktag << "'.";
// Assume this was a dup after a retry of
// the REGISTER message -- thus this is a
// second REGISTER response, after we already
// handled the original reg SMS. Ignore it.
} else if (
oldsms->state == ASKED_TO_REGISTER_HANDSET
|| oldsms->state == REGISTER_HANDSET
|| oldsms->state == AWAITING_REGISTER_HANDSET) {
// Go back in and rerun the SMS message,
// now that we think we can reply to it.
// Special code in registration processing
// will notice it's a re-reg and just reply
// with a welcome message.
oldsms->set_state(INITIAL_STATE);
} else {
// Orig SMS exists, but not in a normal state.
// Assume that the original SMS is in a
// retry loop somewhere. Ignore it.
// Eventually it'll notice...? FIXME.
}
}
if (sent_msg->parsed &&
sent_msg->parsed->sip_method &&
0 == strcmp("MESSAGE", sent_msg->parsed->sip_method)) {
sent_msg->write_cdr(my_hlr);
}
// Whether a response to a REGISTER or a MESSAGE, delete
// the datagram that we sent, which has been responded to.
LOG(INFO) << "Deleting sent message.";
resplist.splice(resplist.begin(),
time_sorted_list, sent_msg);
resplist.pop_front(); // pop and delete the sent_msg.
// FIXME, consider breaking loose any other messages for
// the same destination now.
break;
case 4: // 4xx -- failure by client
// 486 Busy - means we have to retry later.
// 480 Temporarily Unavailable - means we have to retry later.
// Most likely this means that a subscriber left network coverage
// without unregistering from the network. Try again later.
// Eventually we should have a hook for their return
if (qmsg->parsed->status_code == 480 || qmsg->parsed->status_code == 486){
increase_acked_msg_timeout(&(*sent_msg));
}
// Other 4xx codes mean the original message was bad. Bounce it.
else {
ostringstream errmsg;
errmsg << qmsg->parsed->status_code << " "
<< qmsg->parsed->reason_phrase;
sent_msg->set_state(
bounce_message((&*sent_msg), errmsg.str().c_str()));
}
break;
case 5: // 5xx -- failure by server (poss. congestion)
// FIXME, perhaps we should change its timeout value?? Shorter
// or longer???
LOG(WARNING) << "CONGESTION at OpenBTS\?\?!";
increase_acked_msg_timeout(&(*sent_msg));
break;
case 3: // 3xx -- message ngConfigeeds redirection
case 6: // 6xx -- message rejected (by this destination).
// Try going back through looking up the destination again.
sent_msg->set_state(REQUEST_DESTINATION_IMSI);
break;
default:
LOG(WARNING) << "Unknown status code in SIP response.";
break;
}
//Unlock
unlockSortedList();
// On exit, we delete the response message we've been examining
// when resplist goes out of scope.
} // handle_response
/*
* Find a queued message, based on its tag value. Return an iterator
* that can be used to remove it from the list if desired.
*/
bool
SMq::find_queued_msg_by_tag(short_msg_p_list::iterator &mymsg,
const char *tag, int taghash)
{
lockSortedList();
short_msg_p_list::iterator x;
for (x = time_sorted_list.begin(); x != time_sorted_list.end(); x++) {
if (taghash == x->qtaghash && !strcmp (tag, x->qtag)) {
mymsg = x;
unlockSortedList();
return true;
}
}
unlockSortedList();
return false;
}
// Same, but figure out the taghash manually.
bool
SMq::find_queued_msg_by_tag(short_msg_p_list::iterator &mymsg,
const char *tag)
{
return find_queued_msg_by_tag(mymsg, tag, mymsg->taghash_of(tag));
}
static bool relaxed_verify_relay(osip_list_t *vias, const char *host, const char *port)
{
bool from_relay = false;
if (vias && host && port) {
int size = osip_list_size(vias);
for (int i = 0; i < size; i++) {
osip_via_t *via = (osip_via_t *)osip_list_get(vias, i);
const char *via_host = via_get_host(via);
const char *via_port = via_get_port(via);
if (via_host && via_port &&
!strcasecmp(host, via_host) && !strcasecmp(port, via_port)) {
from_relay = true;
break;
}
}
}
return from_relay;
}
/*
* Validate a short_msg by parsing it and then checking the parse
* to make sure it has *everything* we need to process and forward it.
* **ALL** validity checks on incoming short_msg's are centralized here.
* Thus the rest of the code doesn't need to muck around checking
* every possible thing -- it can just look at the parts of the message
* that it needs to.
*
* Also, if the qtag hasn't been set yet, set it, based on the message's
* fields.
*
* If we reject a message, return the SIP response code that we should
* return to the sender, diagnosing the problem. If the message is OK,
* result is zero.
* Return
* 0 Is okay
* Error code if failed
*
*/
int
short_msg_pending::validate_short_msg(SMq *manager, bool should_early_check)
{
osip_message_t *p;
__node_t *plist;
osip_generic_param_t *param;
char *user;
size_t clen;
char *fromtag;
char *endptr;
if (print_as_we_validate) { // debugging
make_text_valid();
LOG(DEBUG) << "MSG = " << this->text;
}
if (!parsed_is_valid) {
if (!parse()) {
LOG(DEBUG) << "Invalid parse";
return 400;
}
}
/* The message has been parsed. Now check that we like its
structure and contents. */
p = parsed;
if (!p) {
LOG(DEBUG) << "Parse is NULL";
return 400;
}
if (!p->sip_version || 0 != strcmp("SIP/2.0", p->sip_version)) {
LOG(DEBUG) << "Invalid SIP version";
return 400;
}
// If it's an ack, check some things. If it's a message,
// check others.
if (MSG_IS_RESPONSE(p)) {
// It's an ack.
if (p->status_code < 0
|| !p->reason_phrase) {
LOG(DEBUG) << "Status code invalid or no reason";
return 400;
}
clen = 0;
// Leave this test in for responses
if (p->content_length && p->content_length->value) {
errno = 0;
clen = strtol(p->content_length->value, &endptr, 10);
if (*endptr != '\0' || errno != 0) {
LOG(DEBUG) << "Invalid Content Length";
return 400;
}
} else {
LOG(DEBUG) << "Content Length zero";
}
if (clen != 0) {
LOG(DEBUG) << "ACK has a content length";
return 400; // Acks have no content!
}
if (p->bodies.nb_elt != 0) {
LOG(DEBUG) << "ACK has a body";
return 400; // Acks have no bodies!
}
} else {
// It's a message.
if (!p->req_uri || !p->req_uri->scheme) {
LOG(DEBUG) << "No scheme or uri";
return 400;
}
if (0 != strcmp("sip", p->req_uri->scheme)) {
LOG(DEBUG) << "Not SIP scheme";
return 416;
}
if (!check_host_port(p->req_uri->host,p->req_uri->port)) {
LOG(DEBUG) << "Host port check failed";
return 484;
}
if (!p->sip_method) {
LOG(DEBUG) << "SIP method not set";
return 405;
}
if (0 == strcmp("MESSAGE", p->sip_method)) {
user = p->req_uri->username;
if (!user)
return 484;
if (!check_to_user(user)) // Check user does nothing
return 484;
// FIXME, URL versus To: might have different username
// requirements?
// FIXME, add support for more Content-Type's.
if (!p->content_type || !p->content_type->type
|| !p->content_type->subtype
|| !( (0 == strcmp("text", p->content_type->type)
&& 0 == strcmp("plain", p->content_type->subtype))
||(0 == strcmp("application", p->content_type->type)
&& 0 == strcmp("vnd.3gpp.sms", p->content_type->subtype))
)
) {
LOG(DEBUG) << "Content type not supported";
return 415;
}
int len;
if (p->content_length && p->content_length->value && ((len=strtol(p->content_length->value, NULL, 10)) > 0) ) {
//If length is greater than zero check this
// Bad if any of these are true nb_elt!=1, node=0, node->next!=0, node->element=0
if (p->bodies.nb_elt != 1 // p->bodies.nb_elt should always be one
|| 0 == p->bodies.node
|| 0 != p->bodies.node->next
|| 0 == p->bodies.node->element) {
LOG(DEBUG) << "Message entity-body too large";
return 413; // Request entity-body too large
}
} else {
LOG(DEBUG) << "Content length is zero";
}
if (!p->cseq || !p->cseq->method
|| 0 != strcmp("MESSAGE", p->cseq->method)
|| !p->cseq->number) { // FIXME, validate number??
LOG(DEBUG) << "Invalid sequence number";
return 400;
}
} else if (0 == strcmp("REGISTER", p->sip_method)) {
// Null username is OK in register message.
// Null content-type is OK.
// Null message body also OK.
if (!p->cseq || !p->cseq->method
|| 0 != strcmp("REGISTER", p->cseq->method)
|| !p->cseq->number) { // FIXME, validate number??
LOG(DEBUG) << "Invalid REGISTER";
return 400;
}
} else {
LOG(DEBUG) << "Unknown SIP datagram";
return 405; // Unknown SIP datagram type
}
}
// accepts - no restrictions
// accept_encodings - no restrictions?
// accept_langauges - no restrictions?
// alert_infos - no restrictions?
// allows - no restrictions?
// authentication_infos - no restrictions?
// authorizations - no restrictions
if (!p->call_id) {
LOG(DEBUG) << "No call-id";
return 400;
}
// Remove content length check
// According to rfc3261 length can be 0 or greater svg 03/20/2014
// From address needs to exist but a tag in the from address is optional
if (!p->from || !p->from->url
//|| p->from->gen_params.nb_elt < 1 // Message tag is not required
//|| !p->from->gen_params.node // Message tag is not required SVG 03/12/14
)
{
LOG(DEBUG) << "Invalid from address in header from " << p->from << " fromurl " << p->from->url
<< " nb.elt " << p->from->gen_params.nb_elt << " params.node " << p->from->gen_params.node;
return 400;
}
fromtag = NULL;
plist = (__node_t *) p->from->gen_params.node;
if (plist) {
do {
param = (osip_generic_param_t *) plist->element;
if (param) {
LOG(DEBUG) << "Param " << param->gname << "=" << param->gvalue;
if (!strcmp("tag", param->gname)) {
LOG(DEBUG) << "Got from tag";
fromtag = param->gvalue;
break; // Only need one
}
plist = (__node_t *)plist->next;
} else {
LOG(DEBUG) << "No element in list"; // This is valid
break;
}
} while (plist); // while
if (!fromtag) {
LOG(DEBUG) << "No from tag"; // This is valid
}
}
else {
LOG(DEBUG) << "No node list element"; // Will not cause a problem. Not sure is this is normal
}
if (!p->mime_version) {
; // No mime version, OK
} else if (!p->mime_version->value // Version 1.0 is OK.
|| 0 != strcmp("1.0", p->mime_version->value)) {
LOG(DEBUG) << "Wrong mime version";
return 415; // Any other is NOPE.
}
// proxy_authenticates - no restrictions
// proxy_authentication_infos -- no restriction
// record_routes -- no restriction
// require -- RFC 3261 sec 20.32: If received, reject this msg!
// Unfortunately, the parser doesn't even seem to recognize it!
// routes -- no restrictions
if (!p->to || !p->to->url || !p->to->url->scheme
|| 0 != strcmp("sip", p->to->url->scheme)
|| !check_host_port(p->to->url->host, p->to->url->port)
|| !p->to->url->username
#if 0
// Asterisk returns a tag on the To: line of its SIP REGISTER
// responses. This violates the RFC but we'd better allow it.
// (We don't really care -- we just ignore it anyway.)
// A from tag is not required
// || p->to->gen_params.nb_elt != 0
#endif
) { // no tag field allowed; see
LOG(DEBUG) << "Invalid To header"; // RFC 3261 sec 8.1.1.2
return 400;
}
user = p->to->url->username;
if (!check_to_user(user)) {
LOG(DEBUG) << "Invalid To user";
return 400;
}
// We need to see if this is a message form the relay. If it is, we can process a user lookup here
// BUT ONLY IF the message is not a response (ACK) AND MUST BE a SIP MESSAGE.
if (should_early_check && !MSG_IS_RESPONSE(p) && (0 == strcmp("MESSAGE", p->sip_method))
&& (manager->my_network.msg_is_from_relay(srcaddr, srcaddrlen,
manager->global_relay.c_str(), manager->global_relay_port.c_str()) ||
(gConfig.getBool("SIP.GlobalRelay.RelaxedVerify") &&
relaxed_verify_relay(&p->vias, manager->global_relay.c_str(), manager->global_relay_port.c_str())
))) {
// We cannot deliver the message since we cannot resolve the TO
if (!manager->to_is_deliverable(user)) {
LOG(DEBUG) << "To address not deliverable";
return 404;
}
// We need to reject the message, because we cannot resolve the FROM
// TODO: Don't do this. From coming in through the relay is probably not resolvable.
/*if (!manager->from_is_deliverable(p->from->url->username))
return 403;*/
from_relay = true;
LOG(DEBUG) << "In bound message from " << p->from->url->username << " to " << user << " is from relay";
}
// www_authenticates - no restrictions
// headers - ???
// message_property ??? FIXME
// message ??? FIXME
// message_length ??? FIXME
// application_data - no restrictions
// Set the qtag from the parsed fields, if it hasn't been set yet.
return (set_qtag());
}
// Set the qtag from the parsed fields, if it hasn't been set yet.
// Whenever we change any of these fields, we have to recalculate
// the qtag.
// FIXME, we assume that the CSEQ, Call-ID, and From tag all are
// components that, in combination, identify the message uniquely.
// (pat) There should not be a from-tag in a MESSAGE; the from- and to-tags are used only for INVITE.
// FIXME! The spec is unpleasantly unclear about this.
// (pat) RFC3261 17.1.3 is clear: we are supposed to use either the via-branch or the call-id+cseq to identify the message.
// Result is 0 for success, or 3-digit integer error code if error.
// FIXME! The Call-ID changes each time we re-send an SMS.
// When we get a 200 "Delivered" message for ANY of those
// different Call-ID's, we should accept that the msg was
// delivered and delete it. Therefore, remove the Call-ID
// from the qtag.
int
short_msg_pending::set_qtag()
{
osip_message_t *p;
__node_t *plist;
osip_generic_param_t *param;
char *fromtag;
int error;
//LOG(DEBUG) << "Enter parse";
if (!parsed_is_valid) {
if (!parse()) {
LOG(DEBUG) << "Parse failed in setqtag";
return 400;
}
}
p = parsed;
if (!p->from) {
LOG(DEBUG) << "No from address in setqtag";
return 400;
}
#if 0
plist = (__node_t *) p->from->gen_params.node;
if (!plist) {
LOG(DEBUG) << "No node in from param list";
return 400;
}
#endif
// Handle from tag which is optional
fromtag = NULL;
plist = (__node_t *) p->from->gen_params.node;
if (plist) {
do {
param = (osip_generic_param_t *) plist->element;
if (param) {
LOG(DEBUG) << "Param " << param->gname << "=" << param->gvalue;
if (!strcmp("tag", param->gname)) {
LOG(DEBUG) << "Got from tag";
fromtag = param->gvalue;
break; // Only need one
}
plist = (__node_t *)plist->next;
} else {
LOG(DEBUG) << "No element in list"; // This is valid
break;
}
} while (plist); // while
if (!fromtag) {
LOG(DEBUG) << "No from tag"; // This is valid
}
}
else {
LOG(DEBUG) << "No node list element"; // Will not cause a problem. Not sure is this is normal
}
if (!p->call_id) {
LOG(DEBUG) << "No callID";
return 401;
}
if (!p->cseq) {
LOG(DEBUG) << "No sequence number";
return 402;
}
delete [] qtag; // slag the old one, if any.
int len = strlen(p->cseq->number) + 2 // crlf or --
#ifdef USE_CALL_ID_TAG
+ strlen(p->call_id->number) + 1 // @
+ strlen(p->call_id->host) + 2 // crlf or --
#endif
+ strlen(fromtag) + 1; // null at end
qtag = new char[len];
// There's probably some fancy C++ way to do this. FIXME.
strcpy(qtag, p->cseq->number);
strcat(qtag, "--");
#ifdef USE_CALL_ID_TAG
strcat(qtag, p->call_id->number);
strcat(qtag, "@");
strcat(qtag, p->call_id->host);
strcat(qtag, "--");
#endif
strcat(qtag, fromtag);
// Check the length calculation, abort if bad.
if (qtag[len-1] != '\0'
|| qtag[len-2] == '\0') {
LOG(DEBUG) << "qtag length check failed"; // Not sure why this is being done svg
return 400;
}
// Set the taghash too.
// FIXME, if we set this with a good hash function,
// our linear searches will run much faster, avoiding
// almost all strcmp's. For now, punt easy.
qtaghash = taghash_of(qtag);
return 0;
}
/*
* Hash a tag value for fast searches.
*/
// FIXME, if we set this with a good hash function,
// our linear searches will run much faster, avoiding
// almost all strcmp's. For now, punt easy.
int
short_msg_pending::taghash_of (const char *fromtag)
{
return fromtag[0];
}
/* Check the host and port number specified.
* Currently, be conservative and only take localhost refs.
* We know FIXME that this will have to be expanded...
*/
bool
short_msg_pending::check_host_port (char *host, char *port)
{
static int warn_once;
if (!host)
return false;
if (!strcmp ("localhost", host) ||
!strcmp ("127.0.0.1", host) ||
(smp_my_ipaddress && !strcmp (smp_my_ipaddress, host)) ||
(smp_my_2nd_ipaddress && !strcmp (smp_my_2nd_ipaddress, host))) {
;
} else {
if (0 == warn_once++) {
LOG(NOTICE) << "Accepting SIP Message from " << host <<
" for SMS delivery, even though it's not "
"from localhost.";
}
// In theory we should be *routing* it to where it
// specifies -- but the address is *probably* us, and
// we have no way to tell what our own address is,
// since (in a real configuration) we're behind a NAT
// firewall at an address that never appears in ifconfig,
// for example. Must assume it's OK -- for now. FIXME.
return true;
}
// port can either be specified or not.
// we could check whether it's all digits... FIXME
return true;
}
void short_msg_pending::write_cdr(SubscriberRegistry& hlr) const
{
char * from = parsed->from->url->username;
char * dest = parsed->to->url->username;
time_t now = time(NULL); // Need real time for CDR
if (gCDRFile) {
char * user = hlr.getIMSI2(from); // I am not a fan of this hlr call here. Probably a decent performance hit...
// source, sourceIMSI, dest, date
fprintf(gCDRFile,"%s,%s,%s,%s", from, user, dest, ctime(&now));
fflush(gCDRFile);
} else {
LOG(ALERT) << "CDR file at " << gConfig.getStr("CDRFile").c_str() << " could not be created or opened!";
}
}
/*
* Check the username in the To: field, perhaps in the From: fiend,
* perhaps in the URI in the MESSAGE line at the top...
*/
bool
check_to_user (char *user)
{
// For now, don't check -- but port some checks up from the
// code below in lookup_from_address. FIXME.
return true;
}
/*
Main state machine for Short Message processing
Called from SmqWriter on a periodic basis
Processes message from the queue
*/
void SMq::process_timeout()
{
time_t now = msgettime();
short_msg_p_list::iterator qmsg;
enum sm_state newstate;
int msSMSRateLimit;
lockSortedList();
//LOG(DEBUG) << "Begin process_timeout";
/* When we modify a timestamp below (in the set_state function),
we re-queue the message within the queue, so we have to
restart the iterator every time around the loop. In effect,
we're always looking at the top thing on the list (thus the
earliest one in time). */
bool empty = false;
qmsg = time_sorted_list.begin();
if (qmsg == time_sorted_list.end())
empty = true;
if (empty) {
unlockSortedList();
//LOG(DEBUG) << "Message queue is empty";
return; /* Empty queue */
}
//LOG(DEBUG) << "Queue size " << time_sorted_list.size();
if (qmsg->next_action_time > now) {
unlockSortedList();
//LOG(DEBUG) << "Not time to processs message";