-
Notifications
You must be signed in to change notification settings - Fork 10
/
app_rtsp_sip.c
executable file
·4228 lines (3743 loc) · 125 KB
/
app_rtsp_sip.c
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
/*
* Asterisk -- An open source telephony toolkit.
*
* Sergio Garcia Murillo <sergio.garcia@fontventa.com>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief MP4 application -- save and play mp4 files
*
* \ingroup applications
*/
/*
* Tommy Long
* Port to Asterisk version 17.3 and 17.5.
*
* Port 17.3 upgrades this code to run on Asterisk version 17.3, and adds
* a thin SIP protocol in order to send audio to the same target device.
* The development environment is Ubuntu 16.04 Desktop on 32bit machine.
* Porting Generals:
* malloc() is now ast_malloc()
* free() is now ast_free()
* strdup() is now ast_strdup
* strndup() is now ast_strndup()
* memcpy() of overlapping memory is being changed to memmove().
* This code was using memcpy to copy overlapping memory which is prone to errors (as I found out).
* memmove() is recommended instead.
* ast_log(LOG_DEBUG,....) change to ast_debug(<level>,...)
*
* SIP is added for sending a one-way call to the same end device.
* The SIP protocol used is very simple and lite and completely self-contained within this module.
* (The exception is that it uses PJSIP's digest authentication).
* There will be for sure various aspects of SIP not supported.
*
* Documentation: in-line documentation is added.
*
* Port 17.5
* Development environment is Ubuntu 20.04 server cloud image running on KVM on 64 bit machine.
* Fixes a few minor compiler warnings that show up in newer Ubuntu.
* Primariy fixes a problem with the ast_frame and buffer structure
* used for receiving RTP from end device (using RTSP).
*
* Has not been tested for:
* 1) IPv6
* 2) RTSP Digest Authentication (newly added).
* 3) RTSP Tunnel
* 4) Use DTMF to stop RTSP.
*/
/* Use the following to test for Buffer length issues */
/* #define TEST_BUFFER */
#include <asterisk.h>
#include "asterisk/app.h" /* PORT 17.3 ADDed for parsing args */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <arpa/inet.h> /* NEW. needed for getsockname() */
#include <asterisk/lock.h>
#include <asterisk/file.h>
#include <asterisk/logger.h>
#include <asterisk/channel.h>
#include <asterisk/pbx.h>
#include <asterisk/module.h>
#include <asterisk/utils.h>
#include <asterisk/translate.h>
#include <asterisk/format_compatibility.h>
/* For use with pjsip digest authentication */
#include <pjsua-lib/pjsua.h>
#include <pj/string.h>
/*** DOCUMENTATION
<application name="RTSP-SIP" language="en_US">
<synopsis>
<para>Attempt to connect to another device/endpoint using RTSP
and play streaming audio (video has not been tested). </para>
<para>If commanded, will also attempt to connect to the same device/endpoint
using SIP and send an audio stream to it. </para>
</synopsis>
<description>
<para>This 'endpoint' application is intended to be used as an execution
step of an extension in a Dialplan. When executed, the application will
first attempt to contact and authenticate with the specified target device using RTSP,
gather the video and audio media types supported by the target device and match them
with the media types supported by the Asterisk channel connecting to this application.
It will choose the "best" media types for audio as well as video (if any) and play them
using RTP into the Asterisk channel and consequently to the calling party.</para>
<para>Once an audio stream is identifed and played using RTSP,
if sip has been specifically enabled, it will next attempt to contact the device using SIP.
Once contacted, it will setup an audio stream from the Asterisk channel (that is connected to
this application) to the target device using the same audio media chosen by RTSP.
Consequently it will play audio from the calling party to the target device using RTP.
This application uses its own 'lite' version of SIP and is intended
for simple uses cases, namely connecting this application as a sip UA
directly to the target device over a local area network.</para>
<example title="Dial extension 103 to talk two-way with a surveillance camera">
exten = 103,1,Answer()
same = n,Wait(1)
same = n,RTSP-SIP(rtsp://2001:mypasswd@192.168.0.34:554/live.sdp,1,streaming_server,5060)
same = n,Wait(5)
same = n,Hangup()
</example>
<example title="Dial extension 101 to receive audio only from a surveillance camera">
exten = 101,1,Answer()
same = n,Wait(1)
same = n,RTSP-SIP(rtsp://user:mypasswd@192.168.0.34:554/live.sdp,0)
same = n,Wait(5)
same = n,Hangup()
</example>
</description>
<syntax>
<parameter name="RTSP-URL" required="true">
<para>RTSP url of the target device to be played.
Format: rtsp://username:password@address/stream-id.
'username' and 'password' are optional for login to the device using Basic Authentication.
'address' is domain name or ip address of target device.
'stream-id' optionally identifies the stream to be played.</para>
</parameter>
<parameter name="enable-sip" required="true">
<para>0 if using this only to play RTSP streams.
1 if an audio stream is also to be setup to the target device.</para>
</parameter>
<parameter name="realm" required="false">
<para>If enable-sip = 1, this parameter is required.
SIP uses Digest Authentication, and uses the supplied
realm string as part of the authentication.</para>
</parameter>
<parameter name="port" required="false">
<para>If enable-sip = 1, this optional parameter can be used
to specify a different SIP port for the target device to listen on. Default is 5060. </para>
</parameter>
</syntax>
<see-also>
<ref type="application">Dial</ref>
</see-also>
</application>
***/
/* NEW SIP: messaging sip:MY_NAME@blah_blah */
#define MY_NAME "agbell"
/* PORT 17.3
* Adaptive MultiRate (AMR) Narrow Band (IETF RFC4867) is no longer supported in Asterisk.
* This file is using it to determine MIME type and
* for some unknown reason is ORing this to determine best audio formats.
* For now just zero it out .
*/
#ifndef AST_FORMAT_AMRNB
/* #define AST_FORMAT_AMRNB (1 << 13) OLD */
#define AST_FORMAT_AMRNB 0
#endif
/* PORT 17.3 AST_FORMAT_MPEG4 is now AST_FORMAT_MP4 (1LL << 22). The following longer needed. */
/* #ifndef AST_FORMAT_MPEG4 OLD
* #define AST_FORMAT_MPEG4 (1 << 22) OLD
* #endif OLD
*/
/* PORT17.3. Update to use xml based loading and documentation */
/* static char *name_rtsp_sip = "rtsp_sip"; OLD */
/* static char *syn_rtsp_sip = "sip caller with rtsp player"; */
/* static char *des_rtsp_sip = " rtsp(url): Play url. \n"; */
static const char app[] = "RTSP-SIP";
/* RTSP states */
#define RTSP_NONE 0
#define RTSP_DESCRIBE 1
#define RTSP_SETUP_AUDIO 2
#define RTSP_SETUP_VIDEO 3
#define RTSP_PLAY 4
#define RTSP_PLAYING 5
#define RTSP_RELEASED 6
/* NEW SIP states */
#define SIP_STATE_NONE 0
#define SIP_STATE_OPTIONS 1
#define SIP_STATE_INVITE 2
#define SIP_STATE_ACK 3
#define SIP_STATE_CANCEL 4
#define SIP_STATE_BYE 5
#define SIP_STATE_REFER 6
#define SIP_STATE_NOTIFY 7
#define SIP_STATE_MESSAGE 8
#define SIP_STATE_SUBSCRIBE 9
#define SIP_STATE_INFO 10
#define PKT_PAYLOAD 1450
#define PKT_SIZE (sizeof(struct ast_frame) + AST_FRIENDLY_OFFSET + PKT_PAYLOAD)
#define PKT_OFFSET (sizeof(struct ast_frame) + AST_FRIENDLY_OFFSET)
/* PORT 17.3
* Some of the following AST_FORMAT_xx were tweaked in format_compatibility.h;
* Plus the bit list is now 64bits
*/
static struct
{
/* int format; OLD */
uint64_t format;
char* name;
} mimeTypes[] = {
{ AST_FORMAT_G723, "G723"}, /* OLD { AST_FORMAT_G723_1, "G723"}, */
{ AST_FORMAT_GSM, "GSM"},
{ AST_FORMAT_ULAW, "PCMU"},
{ AST_FORMAT_ALAW, "PCMA"},
{ AST_FORMAT_G726, "G726-32"},
{ AST_FORMAT_ADPCM, "DVI4"},
{ AST_FORMAT_SLIN, "L16"}, /* OLD { AST_FORMAT_SLINEAR, "L16"}, */
{ AST_FORMAT_LPC10, "LPC"},
{ AST_FORMAT_G729, "G729"}, /* { AST_FORMAT_G729A, "G729"}, */
{ AST_FORMAT_SPEEX, "speex"},
{ AST_FORMAT_ILBC, "iLBC"},
{ AST_FORMAT_G722, "G722"},
{ AST_FORMAT_G726_AAL2, "AAL2-G726-32"},
{ AST_FORMAT_AMRNB, "AMR"},
{ AST_FORMAT_JPEG, "JPEG"},
{ AST_FORMAT_PNG, "PNG"},
{ AST_FORMAT_H261, "H261"},
{ AST_FORMAT_H263, "H263"},
/*{ AST_FORMAT_H263_PLUS, "H263-1998"}, OLD removed*/
{ AST_FORMAT_H263P, "H263-2000"},/* OLD { AST_FORMAT_H263_PLUS, "H263-2000"}, */
{ AST_FORMAT_H264, "H264"},
/* { AST_FORMAT_MPEG4, "MP4V-ES"}, OLD */
{ AST_FORMAT_MP4, "MP4V-ES"},
};
typedef enum
{
RTCP_SR = 200,
RTCP_RR = 201,
RTCP_SDES = 202,
RTCP_BYE = 203,
RTCP_APP = 204
} RtcpType;
typedef enum
{
RTCP_SDES_END = 0,
RTCP_SDES_CNAME = 1,
RTCP_SDES_NAME = 2,
RTCP_SDES_EMAIL = 3,
RTCP_SDES_PHONE = 4,
RTCP_SDES_LOC = 5,
RTCP_SDES_TOOL = 6,
RTCP_SDES_NOTE = 7,
RTCP_SDES_PRIV = 8,
RTCP_SDES_IMG = 9,
RTCP_SDES_DOOR = 10,
RTCP_SDES_SOURCE = 11
} RtcpSdesType;
struct RtcpCommonHeader
{
unsigned short count:5; /* varies by payload type */
unsigned short p:1; /* padding flag */
unsigned short version:2; /* protocol version */
unsigned short pt:8; /* payload type */
unsigned short length; /* packet length in words, without this word */
};
struct RtcpReceptionReport
{
unsigned int ssrc; /* data source being reported */
unsigned int fraction:8; /* fraction lost since last SR/RR */
int lost:24; /* cumulative number of packets lost (signed!) */
unsigned int last_seq; /* extended last sequence number received */
unsigned int jitter; /* interarrival jitter */
unsigned int lsr; /* last SR packet from this source */
unsigned int dlsr; /* delay since last SR packet */
};
struct RtcpSdesItem
{
unsigned char type; /* type of SDES item (rtcp_sdes_type_t) */
unsigned char length; /* length of SDES item (in octets) */
char data[1]; /* text, not zero-terminated */
};
struct Rtcp
{
struct RtcpCommonHeader common; /* common header */
union
{
/* sender report (SR) */
struct
{
unsigned int ssrc; /* source this RTCP packet refers to */
unsigned int ntp_sec; /* NTP timestamp */
unsigned int ntp_frac;
unsigned int rtp_ts; /* RTP timestamp */
unsigned int psent; /* packets sent */
unsigned int osent; /* octets sent */
/* variable-length list */
struct RtcpReceptionReport rr[1];
} sr;
/* reception report (RR) */
struct
{
unsigned int ssrc; /* source this generating this report */
/* variable-length list */
struct RtcpReceptionReport rr[1];
} rr;
/* BYE */
struct
{
unsigned int src[1]; /* list of sources */
/* can't express trailing text */
} bye;
/* source description (SDES) */
struct rtcp_sdes_t
{
unsigned int src; /* first SSRC/CSRC */
struct RtcpSdesItem item[1]; /* list of SDES items */
} sdes;
} r;
};
struct RtpHeader
{
unsigned int cc:4; /* CSRC count */
unsigned int x:1; /* header extension flag */
unsigned int p:1; /* padding flag */
unsigned int version:2; /* protocol version */
unsigned int pt:7; /* payload type */
unsigned int m:1; /* marker bit */
unsigned int seq:16; /* sequence number */
unsigned int ts; /* timestamp */
unsigned int ssrc; /* synchronization source */
/* unsigned int csrc[1]; * optional CSRC list. REMOVE. Not supported BY SIP. */
};
struct MediaStats
{
unsigned int count;
unsigned int minSN;
unsigned int maxSN;
unsigned int lastTS;
unsigned int ssrc;
struct timeval time;
};
static void MediaStatsReset(struct MediaStats *stats)
{
stats->count = 0;
stats->minSN = 0;
stats->maxSN = 0;
stats->lastTS = 0;
stats->time = ast_tvnow();
}
static void MediaStatsUpdate(struct MediaStats *stats,unsigned int ts,unsigned int sn,unsigned int ssrc)
{
stats->ssrc = ssrc;
stats->count++;
if (!stats->minSN)
stats->minSN = sn;
if (stats->maxSN<sn)
stats->maxSN = sn;
stats->lastTS = ts;
}
static void MediaStatsRR(struct MediaStats *stats, struct Rtcp *rtcp)
{
/* Set pointer as ssrc */
/* COMMENT
* Build a Receiver Report packet.
* An RR RTCP packet starts with the common header followed
* by the SSRC assigned to this receiver followed by report blocks
* of sender1 and sender2.
*/
/*
* COMMENT
* The next line originally set the SSRC to a pointer's value
* because the pointer value is fairly random as the SSRC value.
* However it doesn't always port/compile very well. Let's use random() instead.
*/
/* rtcp->r.rr.ssrc = htonl(stats); OLD */
rtcp->r.rr.ssrc = htonl((uint32_t)random()); /* PORT17.5 fix compiler warning */
/* data source being reported */
rtcp->r.rr.rr[0].ssrc = htonl(stats->ssrc);
/* fraction lost since last SR/RR */
if (stats->maxSN-stats->minSN>0)
rtcp->r.rr.rr[0].fraction = (signed)(255*stats->count/(stats->maxSN-stats->minSN));
else
rtcp->r.rr.rr[0].fraction = 0xFF;
/* cumulative number of packets lost (signed!) */
rtcp->r.rr.rr[0].lost = htonl((signed int)(stats->maxSN-stats->minSN-stats->count));
/* extended last sequence number received */
rtcp->r.rr.rr[0].last_seq = htonl(stats->maxSN);
/* interarrival jitter */
rtcp->r.rr.rr[0].jitter = htonl(0xFF);
/* last SR packet from this source */
rtcp->r.rr.rr[0].lsr = htonl(stats->lastTS);
/* delay since last SR packet */
rtcp->r.rr.rr[0].dlsr = htonl(ast_tvdiff_ms(ast_tvnow(),stats->time));
/* Set common headers */
rtcp->common.version = 2;
rtcp->common.p = 0;
rtcp->common.count = 1;
rtcp->common.pt = 201;
/* Length */
rtcp->common.length = htons(7);
}
/* NEW. For SIP */
enum SipMethodsIndex
{
INVITE, /* 0 */
OPTIONS,
ACK,
CANCEL,
BYE,
REFER,
NOTIFY,
MESSAGE,
SUBSCRIBE,
INFO,
MAX_METHODS
};
struct RtspPlayer
{
int fd;
int state;
int cseq;
char* session[2];
int numSessions;
int end; /* Used to exit the main loop */
char* ip; /* destination ip string */
int port; /* destination port */
char* hostport; /* string ip:port */
char* url;
int isIPv6;
char* authorization;
int audioRtp; /* file descriptor */
int audioRtcp; /* file descriptor */
int videoRtp; /* file descriptor */
int videoRtcp; /* file descriptor */
int audioRtpPort; /* source udp port */
int audioRtcpPort; /* source udp port */
int videoRtpPort; /* source udp port */
int videoRtcpPort; /* source udp port */
struct MediaStats audioStats;
struct MediaStats videoStats;
/* NEW. SIP */
char* local_ctrl_ip; /* source IPv4 address string used by SIP */
uint16_t local_ctrl_port; /* source port used by SIP */
int cseqm[MAX_METHODS]; /* SIP differentiates CSeq by sequence number plus Method Sec 20.16 */
int in_a_dialog; /* SIP has a dialog going T/F */
char src_tag[20]; /* SIP random source tag value. Fixed when in a dialog. Hopefully only one dialog per time. */
char peer_tag[20]; /* SIP random tag value received from peer. */
char call_id[100]; /* SIP random call_id value when in a dialog. Hopefully only one call-id per time. */
char branch_id[100];/* SIP random branch_id last transaction. Hopefully only on transaction per time. */
/* SDP */
char session_id[64];/* SDP for SIP sessionID */
};
/* NEW Digest Auth Data */
struct DigestAuthData
{
char nonce[64];
char nc[64];
char cnonce[64];
char qop[16];
char uri[64];
char rx_realm[32];
char opaque[64];
};
/* NEW. For SIP */
static int generateSrcTag(struct RtspPlayer *player)
{
sprintf(player->src_tag,"%08lx", ast_random()); /* Set SIP source Tag */
return 1;
}
/* NEW. For SIP */
static int generateBranch(struct RtspPlayer *player)
{
sprintf(player->branch_id,"z9hG4bKi-%08lx%08lx%08lx%08lx",random(),random(),random(), random() );
return 1;
}
/* NEW. For SIP */
static int generateCallId(struct RtspPlayer *player)
{
if(player->local_ctrl_ip == NULL)
sprintf(player->call_id,"%08lx%08lx%08lx%08lx@foo.bar.com",random(),random(),random(), random() );
else
sprintf(player->call_id,"%08lx%08lx%08lx%08lx@%s",random(),random(),random(), random(),player->local_ctrl_ip );
return 1;
}
/* NEW. For SIP */
static int generateSessionId(struct RtspPlayer *player)
{
sprintf(player->session_id,"158%8ld",random()); /*SDP for SIP RFC3264 Sec 5 requires 64bits; we'll use 32bits */
return 1;
}
static struct RtspPlayer* RtspPlayerCreate(void)
{
/* malloc */
/* struct RtspPlayer* player = (struct RtspPlayer*) malloc(sizeof(struct RtspPlayer)); OLD */
struct RtspPlayer* player = (struct RtspPlayer*) ast_malloc(sizeof(struct RtspPlayer)); /* PORT 17.3 */
/* Initialize */
player->cseq = 1;
player->session[0] = NULL;
player->session[1] = NULL;
player->numSessions = 0;
player->state = RTSP_NONE;
player->end = 0;
player->ip = NULL;
player->hostport = NULL;
player->isIPv6 = 0;
player->port = 0;
player->url = NULL;
player->authorization = NULL;
player->fd = 0; /* Control Protocol (RTSP or SIP) file descriptor */
player->audioRtp = 0; /* file descriptor */
player->audioRtcp = 0; /* file descriptor */
player->videoRtp = 0; /* file descriptor */
player->videoRtcp = 0; /* file descriptor */
player->audioRtpPort = 0; /* Source udp ports */
player->audioRtcpPort = 0; /* Source udp ports */
player->videoRtpPort = 0; /* Source udp ports */
player->videoRtcpPort = 0; /* Source udp ports */
/* ADD. SIP */
player->local_ctrl_ip = NULL; /* source IPv4 address string*/
player->local_ctrl_port = 0; /* source port used by SIP */
int i;
for(i=0;i<MAX_METHODS;i++)
player->cseqm[i] = 1;
player->in_a_dialog = 0; /* SIP has a dialog going T/F */
generateSrcTag(player); /* Set SIP source Tag */
generateBranch(player);
generateCallId(player);
generateSessionId(player);
/* Return */
return player;
}
static void RtspPlayerDestroy(struct RtspPlayer* player)
{
/* free members*/
/* if (player->ip) free(player->ip); OLD */
if (player->ip) ast_free(player->ip);
/* if (player->hostport) free(player->hostport); OLD */
if (player->hostport) ast_free(player->hostport);
/* if (player->url) free(player->url); OLD */
if (player->url) ast_free(player->url);
/* if (player->session[0]) free(player->session[0]); OLD */
if (player->session[0]) ast_free(player->session[0]);
/* if (player->session[1]) free(player->session[1]); OLD */
if (player->session[1]) ast_free(player->session[1]);
/* if (player->authorization) free(player->authorization); OLD */
if (player->authorization) ast_free(player->authorization);
/* ADDED */
if (player->local_ctrl_ip) ast_free(player->local_ctrl_ip);
/* free */
/* free(player); OLD */
ast_free(player);
}
static void RtspPlayerBasicAuthorization(struct RtspPlayer* player,char *username,char *password)
{
char base64[256];
char clear[256];
/* Create authorization header */
/* player->authorization = malloc(128); OLD */
player->authorization = ast_malloc(128); /* PORT 17.3 */
/* Get base 64 from username and password*/
sprintf(clear,"%s:%s",username,password);
/* Encode */
/* ast_base64encode(base64,clear,strlen(clear),256); OLD */
ast_base64encode(base64,(const unsigned char*)clear,strlen(clear),256); /* PORT 17.3. Fix compiler warning */
/* Set heather */
sprintf(player->authorization, "Authorization: Basic %s",base64);
}
/* NEW.
* Use PJSIP to do Digest Authentication
*/
static int RtspPlayerDigestAuthorization(struct RtspPlayer *player,char *cfg_username,\
char *cfg_password, char *cfg_realm, char *nonce, char *nc, \
char *cnonce, char *qop, char *uri, char* rx_realm, char *method, int isSIP)
{
/* PJSIP Notes:
* 1.PJSIP only supports MD5 and AKAv1-MD5.
* Here we assume "algorithm" is "MD5". Others such as SHA-256 are not supported.
* 2.PJSIP appears to support: qop none, or qop=auth, but not qop=auth-int.
* 3.PJSIP requires any char string to have the following structure:
* typedef struct pj_str_t {
* char *ptr;
* pj_size_t slen;
* } pj_str_t;
* These strings are not null terminated, so when used outside of PJSIP, have to add termination.
*/
/* See if Received realm differs from Configured realm */
if (strcmp(cfg_realm,rx_realm)!=0){ /* are not equal */
ast_log(LOG_ERROR,"Received realm %s doesn't match configured realm %s.\n",rx_realm,cfg_realm);
return -1;
}
/* Create authorization header */
player->authorization = ast_malloc(256); /* Freed in RtspPlayerDestroy */
int string_len = 0;
char digest_result[64];
pj_str_t pj_digest_result;
pj_str_t pj_nonce;
pj_str_t pj_nc;
pj_str_t pj_cnonce;
pj_str_t pj_qop;
pj_str_t pj_uri;
pj_str_t pj_rx_realm;
pj_str_t pj_method;
pj_digest_result = pj_str(digest_result);
pj_nonce = pj_str(nonce);
pj_nc = pj_str(nc);
pj_cnonce = pj_str(cnonce);
pj_qop = pj_str(qop);
pj_uri = pj_str(uri);
pj_rx_realm = pj_str(rx_realm);
pj_method = pj_str(method);
pjsip_cred_info cred_info;
cred_info.realm = pj_str(cfg_realm);
cred_info.scheme = pj_str("digest");
cred_info.username = pj_str(cfg_username);
/* cred_info.data_type = PJSIP_CRED_DATA_DIGEST;*/
cred_info.data_type = PJSIP_CRED_DATA_PLAIN_PASSWD;
cred_info.data = pj_str(cfg_password);
pjsip_auth_create_digest(&pj_digest_result,&pj_nonce,&pj_nc,\
&pj_cnonce,&pj_qop,&pj_uri,\
&pj_rx_realm, &cred_info, &pj_method);
digest_result[pj_digest_result.slen]='\0'; /*Need to NULL terminate the string */
ast_debug(3,"Digest Result: %s\n",digest_result);
if(isSIP){
/*
* RFC 3261 p226: dig-resp: username="string",realm="string",
* nonce="string",uri="string",response="32LHex",
* no one quotes MD5 algorithm=<"MD5"|token>,cnonce="string",opaque="string",
* no one quotes qopvalue qop="qop-value",nc=8Lhex,token=<token|"string'>
*/
/* Auth Header should look something like the following:
* Note: comma-separated list (space after comma) ex. sect 20.44, 22.2
* Authorization: Digest\r\n username="my_name", realm="streaming_server",
* nonce="a50392b361ce351d9a95e73a45a6b133", uri="sip:0002D151D42F@192.168.0.43:5060",
* response="b8325b600081488dde51435dda7e3162", algorithm=MD5\r\n
*/
string_len = sprintf(player->authorization,
"Authorization: Digest "
"username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\", algorithm=MD5",
cfg_username,rx_realm,nonce,uri,digest_result);
if(cnonce != NULL)
string_len += sprintf(player->authorization+string_len,",cnonce\"%s\"",cnonce);
if(qop != NULL)
string_len += sprintf(player->authorization+string_len,",qop\"%s\"",qop);
if(nc != NULL)
string_len += sprintf(player->authorization+string_len,",nc\"%s\"",nc);
}
else{ /* RTSP NOT BEEN TESTED FOR DIGEST AUTH */
sprintf(player->authorization, "Authorization: Digest %s",pj_digest_result.ptr);
ast_log(LOG_WARNING,"RTSP not tested for Digest Authentication.\n");
}
ast_debug(3,"Auth: \n%s\n",player->authorization);
return 1;
}
/*
* COMMENT:
* GetUdpPorts() forces the source ports for RTP/RTCP to be paired odd/even respectively.
*/
static void GetUdpPorts(int *a,int *b,int *p,int *q,int isIPv6)
{
struct sockaddr *sendAddr;
int size;
int len;
int PF;
unsigned short *port;
/* If it is ipv6 */
if (isIPv6)
{
/* Set size*/
size = sizeof(struct sockaddr_in6);
/*Create address */
/* sendAddr = (struct sockaddr *)malloc(size); OLD */
sendAddr = (struct sockaddr *)ast_malloc(size);
/* empty addres */
memset(sendAddr,0,size);
/*Set family */
((struct sockaddr_in6*)sendAddr)->sin6_family = AF_INET6;
/* Set PF */
PF = PF_INET6;
/* Get port */
port = &(((struct sockaddr_in6 *)sendAddr)->sin6_port);
} else {
/* Set size*/
size = sizeof(struct sockaddr_in);
/*Create address */
/* sendAddr = (struct sockaddr *)malloc(size); OLD */
sendAddr = (struct sockaddr *)ast_malloc(size);
/* empty addres */
memset(sendAddr,0,size);
/*Set family */
((struct sockaddr_in *)sendAddr)->sin_family = AF_INET;
/* Set PF */
PF = PF_INET;
/* Get port */
port = &(((struct sockaddr_in *)sendAddr)->sin_port);
}
/* Create sockets */
*a = socket(PF,SOCK_DGRAM,0);
bind(*a,sendAddr,size);
*b = socket(PF,SOCK_DGRAM,0);
bind(*b,sendAddr,size);
/* Get socket ports */
len = size;
/* getsockname(*a,sendAddr,&len); OLD */
getsockname(*a,sendAddr,(socklen_t*)&len); /* PORT17.3. fix compiler warning */
*p = ntohs(*port);
len = size;
/* getsockname(*b,sendAddr,&len); OLD */
getsockname(*b,sendAddr,(socklen_t*)&len); /* PORT17.3. fix compiler warning */
*q = ntohs(*port);
/* ast_log(LOG_DEBUG,"-GetUdpPorts [%d,%d]\n",*p,*q); OLD */
ast_debug(4,"-GetUdpPorts initial [%d,%d]\n",*p,*q);
/* Create audio sockets */
while ( *p%2 || *p+1!=*q )
{
/* Close first */
close(*a);
/* Move one forward */
*a = *b;
*p = *q;
/* Create new socket */
*b = socket(PF,SOCK_DGRAM,0);
/* Get port */
if (*p>0)
*port = htons(*p+1);
else
*port = htons(0);
bind(*b,sendAddr,size);
len = size;
/* getsockname(*b,sendAddr,&len); OLD */
getsockname(*b,sendAddr,(socklen_t*)&len); /* PORT17.3. fix complier warning */
*q = ntohs(*port);
/* ast_log(LOG_DEBUG,"-GetUdpPorts [%d,%d]\n",*p,*q); OLD */
ast_debug(4,"-GetUdpPorts loop [%d,%d]\n",*p,*q);
}
ast_debug(3,"-GetUdpPorts final [%d,%d]\n",*p,*q); /* ADDED */
/* Free Address*/
/* free(sendAddr); OLD */
ast_free(sendAddr);
}
static void SetNonBlocking(int fd)
{
/* Get flags */
int flags = fcntl(fd,F_GETFD);
/* Set socket non-blocking */
fcntl(fd,F_SETFD,flags | O_NONBLOCK);
}
/*
* COMMENT:
* The following only sets up the socket structure for destination ip address and port.
* It does not get the ip address.
*/
static struct sockaddr* GetIPAddr(const char *ip, int port,int isIPv6,int *size,int *PF)
{
struct sockaddr * sendAddr;
/* If it is ipv6 */
if (isIPv6)
{
/* Set size*/
*size = sizeof(struct sockaddr_in6);
/*Create address */
/* sendAddr = (struct sockaddr *)malloc(*size); OLD */
sendAddr = (struct sockaddr *)ast_malloc(*size);
/* empty addres */
memset(sendAddr,0,*size);
/* Set PF */
*PF = PF_INET6;
/*Set family */
((struct sockaddr_in6 *)sendAddr)->sin6_family = AF_INET6;
/* Set Address */
inet_pton(AF_INET6,ip,&((struct sockaddr_in6*)sendAddr)->sin6_addr);
/* Set port */
((struct sockaddr_in6 *)sendAddr)->sin6_port = htons(port);
} else {
/* Set size*/
*size = sizeof(struct sockaddr_in);
/*Create address */
/* sendAddr = (struct sockaddr *)malloc(*size); OLD */
sendAddr = (struct sockaddr *)ast_malloc(*size);
/* empty addres */
memset(sendAddr,0,*size);
/*Set family */
((struct sockaddr_in*)sendAddr)->sin_family = AF_INET;
/* Set PF */
*PF = PF_INET;
/* Set Address */
((struct sockaddr_in*)sendAddr)->sin_addr.s_addr = inet_addr(ip);
/* Set port */
((struct sockaddr_in *)sendAddr)->sin_port = htons(port);
}
return sendAddr;
}
static int RtspPlayerConnect(struct RtspPlayer *player, const char *ip, int port,int isIPv6, int isUDP) /*ADDED isUDP */
{
struct sockaddr * sendAddr;
int size;
int PF;
/* ADDED */
char local_ip[100];
uint16_t local_port;
struct sockaddr_in name;
socklen_t namelen = sizeof(name);
int err;
/* Setup struct for Dest address port */
sendAddr = GetIPAddr(ip,port,isIPv6,&size,&PF);
/* open Control socket */
if(isUDP) /* ADDED. SIP uses UDP. RTSP uses TCP*/
player->fd = socket(PF,SOCK_DGRAM,0);
else
player->fd = socket(PF,SOCK_STREAM,0);
/* Create/Open audio datagram sockets and ports for RTP and RTCP*/
GetUdpPorts(&player->audioRtp,&player->audioRtcp,&player->audioRtpPort,&player->audioRtcpPort,isIPv6);
/* Create/Open video datagram sockets and ports for RTP and RTCP*/
GetUdpPorts(&player->videoRtp,&player->videoRtcp,&player->videoRtpPort,&player->videoRtcpPort,isIPv6);
/* Set non blocking */
SetNonBlocking(player->fd);
SetNonBlocking(player->audioRtp);
SetNonBlocking(player->audioRtcp);
SetNonBlocking(player->videoRtp);
SetNonBlocking(player->videoRtcp);
/* Connect */
if (connect(player->fd,sendAddr,size)<0)
{
/* Free mem */
/* free(sendAddr); OLD */
ast_free(sendAddr);
/* Exit */
return 0;
}
/* ADDED. Get local IP and source Port in text format for Control Protocol*/
err = getsockname(player->fd, (struct sockaddr*) &name, &namelen);
if(err !=0)
ast_log(LOG_ERROR,"Could not get local IP address\n");
const char* p = inet_ntop(AF_INET, &name.sin_addr, local_ip, 100);
if(p ==NULL)
ast_log(LOG_ERROR,"Could not convert local IP address\n");
local_port = ntohs(name.sin_port);
player->local_ctrl_ip = ast_strdup(local_ip);
player->local_ctrl_port = local_port;
ast_debug(3,"Local Ctrl IP: %s, Port: %i\n",player->local_ctrl_ip,player->local_ctrl_port);
/* Set ip v6 */
player->isIPv6 = isIPv6;
/* copy ip & port*/
/* player->ip = strdup(ip); OLD */
player->ip = ast_strdup(ip);
player->port = port;
/* create hostport */
/* player->hostport = (char*)malloc(strlen(ip)+8); OLD */
player->hostport = (char*)ast_malloc(strlen(ip)+8);
/* If it is ipv6 */
if (isIPv6)
/* In brackets */
sprintf(player->hostport,"[%s]",player->ip);
else
/* normal*/
strcpy(player->hostport,player->ip);
/* If not standard port */
if (port!=554)
{
/* Append port to ip */
/* PORT 17.5, fix compiler warning about sprintf arg1 alias w. arg3 */
/* sprintf(player->hostport,"%s:%d",player->hostport,player->port); OLD */
char temp[100];
strcpy(temp,player->hostport);
sprintf(player->hostport,"%s:%d",temp,player->port);
}
/* Free mem */
/* free(sendAddr); OLD */
ast_free(sendAddr);
/* conected */
return 1;
}
static int RtspPlayerAddSession(struct RtspPlayer *player,char *session)
{
int i;
char *p;
/* If max sessions reached */
if (player->numSessions == 2)
/* Exit */
return 0;
/* Check if it has parameters */
if ((p=strchr(session,';'))>0)
/* Remove then */
*p = 0;
/* Check if we have that session already */
for (i=0;i<player->numSessions;i++)