1 /*
2 * FILE: rtp.c
3 * AUTHOR: Colin Perkins <csp@isi.edu>
4 * MODIFIED: Orion Hodson <o.hodson@cs.ucl.ac.uk>
5 * Markus Germeier <mager@tzi.de>
6 * Bill Fenner <fenner@research.att.com>
7 * Timur Friedman <timur@research.att.com>
8 *
9 * The routines in this file implement the Real-time Transport Protocol,
10 * RTP, as specified in RFC1889 with current updates under discussion in
11 * the IETF audio/video transport working group. Portions of the code are
12 * derived from the algorithms published in that specification.
13 *
14 * $Revision: 1.139 $
15 * $Date: 2002/04/15 22:40:05 $
16 *
17 * Copyright (c) 1998-2001 University College London
18 * All rights reserved.
19 *
20 * Redistribution and use in source and binary forms, with or without
21 * modification, is permitted provided that the following conditions
22 * are met:
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
28 * 3. All advertising materials mentioning features or use of this software
29 * must display the following acknowledgement:
30 * This product includes software developed by the Computer Science
31 * Department at University College London.
32 * 4. Neither the name of the University nor of the Department may be used
33 * to endorse or promote products derived from this software without
34 * specific prior written permission.
35 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
36 * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 * SUCH DAMAGE.
46 *
47 */
48
49 #include "config_unix.h"
50 #include "config_win32.h"
51 #include "memory.h"
52 #include "debug.h"
53 #include "net_udp.h"
54 #include "crypt_random.h"
55 #include "rijndael-api-fst.h"
56 #include "drand48.h"
57 #include "gettimeofday.h"
58 #include "qfDES.h"
59 #include "md5.h"
60 #include "ntp.h"
61
62 #include "rtp.h"
63
64 /*
65 * Encryption stuff.
66 */
67 #define MAX_ENCRYPTION_PAD 16
68
69 static int rijndael_initialize(struct rtp *session, u_char *hash, int hash_len);
70 static int rijndael_decrypt(struct rtp *session, unsigned char *data,
71 unsigned int size, unsigned char *initVec);
72 static int rijndael_encrypt(struct rtp *session, unsigned char *data,
73 unsigned int size, unsigned char *initVec);
74
75 static int des_initialize(struct rtp *session, u_char *hash, int hash_len);
76 static int des_decrypt(struct rtp *session, unsigned char *data,
77 unsigned int size, unsigned char *initVec);
78 static int des_encrypt(struct rtp *session, unsigned char *data,
79 unsigned int size, unsigned char *initVec);
80
81 #define MAX_DROPOUT 3000
82 #define MAX_MISORDER 100
83 #define MIN_SEQUENTIAL 2
84
85 /*
86 * Definitions for the RTP/RTCP packets on the wire...
87 */
88
89 #define RTP_SEQ_MOD 0x10000
90 #define RTP_MAX_SDES_LEN 256
91
92 #define RTP_LOWER_LAYER_OVERHEAD 28 /* IPv4 + UDP */
93
94 #define RTCP_SR 200
95 #define RTCP_RR 201
96 #define RTCP_SDES 202
97 #define RTCP_BYE 203
98 #define RTCP_APP 204
99
100 typedef struct {
101 #ifdef WORDS_BIGENDIAN
102 unsigned short version:2; /* packet type */
103 unsigned short p:1; /* padding flag */
104 unsigned short count:5; /* varies by payload type */
105 unsigned short pt:8; /* payload type */
106 #else
107 unsigned short count:5; /* varies by payload type */
108 unsigned short p:1; /* padding flag */
109 unsigned short version:2; /* packet type */
110 unsigned short pt:8; /* payload type */
111 #endif
112 uint16_t length; /* packet length */
113 } rtcp_common;
114
115 typedef struct {
116 rtcp_common common;
117 union {
118 struct {
119 rtcp_sr sr;
120 rtcp_rr rr[1]; /* variable-length list */
121 } sr;
122 struct {
123 uint32_t ssrc; /* source this RTCP packet is coming from */
124 rtcp_rr rr[1]; /* variable-length list */
125 } rr;
126 struct rtcp_sdes_t {
127 uint32_t ssrc;
128 rtcp_sdes_item item[1]; /* list of SDES */
129 } sdes;
130 struct {
131 uint32_t ssrc[1]; /* list of sources */
132 /* can't express the trailing text... */
133 } bye;
134 struct {
135 uint32_t ssrc;
136 uint8_t name[4];
137 uint8_t data[1];
138 } app;
139 } r;
140 } rtcp_t;
141
142 typedef struct _rtcp_rr_wrapper {
143 struct _rtcp_rr_wrapper *next;
144 struct _rtcp_rr_wrapper *prev;
145 uint32_t reporter_ssrc;
146 rtcp_rr *rr;
147 struct timeval *ts; /* Arrival time of this RR */
148 } rtcp_rr_wrapper;
149
150 /*
151 * The RTP database contains source-specific information needed
152 * to make it all work.
153 */
154
155 typedef struct _source {
156 struct _source *next;
157 struct _source *prev;
158 uint32_t ssrc;
159 char *cname;
160 char *name;
161 char *email;
162 char *phone;
163 char *loc;
164 char *tool;
165 char *note;
166 char *priv;
167 rtcp_sr *sr;
168 struct timeval last_sr;
169 struct timeval last_active;
170 int should_advertise_sdes; /* TRUE if this source is a CSRC which we need to advertise SDES for */
171 int sender;
172 int got_bye; /* TRUE if we've received an RTCP bye from this source */
173 uint32_t base_seq;
174 uint16_t max_seq;
175 uint32_t bad_seq;
176 uint32_t cycles;
177 int received;
178 int received_prior;
179 int expected_prior;
180 int probation;
181 uint32_t jitter;
182 uint32_t transit;
183 uint32_t init;
184 uint32_t magic; /* For debugging... */
185 } source;
186
187 /* The size of the hash table used to hold the source database. */
188 /* Should be large enough that we're unlikely to get collisions */
189 /* when sources are added, but not too large that we waste too */
190 /* much memory. Sedgewick ("Algorithms", 2nd Ed, Addison-Wesley */
191 /* 1988) suggests that this should be around 1/10th the number */
192 /* of entries that we expect to have in the database and should */
193 /* be a prime number. Everything continues to work if this is */
194 /* too low, it just goes slower... for now we assume around 100 */
195 /* participants is a sensible limit so we set this to 11. */
196 #define RTP_DB_SIZE 11
197
198 /*
199 * Options for an RTP session are stored in the "options" struct.
200 */
201
202 typedef struct {
203 int promiscuous_mode;
204 int wait_for_rtcp;
205 int filter_my_packets;
206 int reuse_bufs;
207 } options;
208
209 /*
210 * Encryption function types
211 */
212 typedef int (*rtp_encrypt_func)(struct rtp *, unsigned char *data,
213 unsigned int size, unsigned char *initvec);
214 typedef int (*rtp_decrypt_func)(struct rtp *, unsigned char *data,
215 unsigned int size, unsigned char *initvec);
216
217 /*
218 * The "struct rtp" defines an RTP session.
219 */
220
221 struct rtp {
222 socket_udp *rtp_socket;
223 socket_udp *rtcp_socket;
224 char *addr;
225 uint16_t rx_port;
226 uint16_t tx_port;
227 int ttl;
228 uint32_t my_ssrc;
229 int last_advertised_csrc;
230 source *db[RTP_DB_SIZE];
231 rtcp_rr_wrapper rr[RTP_DB_SIZE][RTP_DB_SIZE]; /* Indexed by [hash(reporter)][hash(reportee)] */
232 options *opt;
233 uint8_t *userdata;
234 int invalid_rtp_count;
235 int invalid_rtcp_count;
236 int bye_count;
237 int csrc_count;
238 int ssrc_count;
239 int ssrc_count_prev; /* ssrc_count at the time we last recalculated our RTCP interval */
240 int sender_count;
241 int initial_rtcp;
242 int sending_bye; /* TRUE if we're in the process of sending a BYE packet */
243 double avg_rtcp_size;
244 int we_sent;
245 double rtcp_bw; /* RTCP bandwidth fraction, in octets per second. */
246 struct timeval last_update;
247 struct timeval last_rtp_send_time;
248 struct timeval last_rtcp_send_time;
249 struct timeval next_rtcp_send_time;
250 double rtcp_interval;
251 int sdes_count_pri;
252 int sdes_count_sec;
253 int sdes_count_ter;
254 uint16_t rtp_seq;
255 uint32_t rtp_pcount;
256 uint32_t rtp_bcount;
257 char *encryption_algorithm;
258 int encryption_enabled;
259 rtp_encrypt_func encrypt_func;
260 rtp_decrypt_func decrypt_func;
261 int encryption_pad_length;
262 union {
263 struct {
264 keyInstance keyInstEncrypt;
265 keyInstance keyInstDecrypt;
266 cipherInstance cipherInst;
267 } rijndael;
268 struct {
269 char *encryption_key;
270 } des;
271 } crypto_state;
272 rtp_callback callback;
273 uint32_t magic; /* For debugging... */
274 };
275
276 static inline int
filter_event(struct rtp * session,uint32_t ssrc)277 filter_event(struct rtp *session, uint32_t ssrc)
278 {
279 return session->opt->filter_my_packets && (ssrc == rtp_my_ssrc(session));
280 }
281
282 static inline double
tv_diff(struct timeval curr_time,struct timeval prev_time)283 tv_diff(struct timeval curr_time, struct timeval prev_time)
284 {
285 /* Return curr_time - prev_time */
286 double ct, pt;
287
288 ct = (double) curr_time.tv_sec + (((double) curr_time.tv_usec) / 1000000.0);
289 pt = (double) prev_time.tv_sec + (((double) prev_time.tv_usec) / 1000000.0);
290 return (ct - pt);
291 }
292
tv_add(struct timeval * ts,double offset)293 static void tv_add(struct timeval *ts, double offset)
294 {
295 /* Add offset seconds to ts */
296 double offset_sec, offset_usec;
297
298 offset_usec = modf(offset, &offset_sec) * 1000000;
299 ts->tv_sec += (long) offset_sec;
300 ts->tv_usec += (long) offset_usec;
301 if (ts->tv_usec > 1000000) {
302 ts->tv_sec++;
303 ts->tv_usec -= 1000000;
304 }
305 }
306
tv_gt(struct timeval a,struct timeval b)307 static int tv_gt(struct timeval a, struct timeval b)
308 {
309 /* Returns (a>b) */
310 if (a.tv_sec > b.tv_sec) {
311 return TRUE;
312 }
313 if (a.tv_sec < b.tv_sec) {
314 return FALSE;
315 }
316 assert(a.tv_sec == b.tv_sec);
317 return a.tv_usec > b.tv_usec;
318 }
319
next_csrc(struct rtp * session)320 static uint32_t next_csrc(struct rtp *session)
321 {
322 /* This returns each source marked "should_advertise_sdes" in turn. */
323 int chain, cc;
324 source *s;
325
326 cc = 0;
327 for (chain = 0; chain < RTP_DB_SIZE; chain++) {
328 /* Check that the linked lists making up the chains in */
329 /* the hash table are correctly linked together... */
330 for (s = session->db[chain]; s != NULL; s = s->next) {
331 if (s->should_advertise_sdes) {
332 if (cc == session->last_advertised_csrc) {
333 session->last_advertised_csrc++;
334 if (session->last_advertised_csrc == session->csrc_count) {
335 session->last_advertised_csrc = 0;
336 }
337 return s->ssrc;
338 } else {
339 cc++;
340 }
341 }
342 }
343 }
344 /* We should never get here... */
345 abort();
346 }
347
ssrc_hash(uint32_t ssrc)348 static int ssrc_hash(uint32_t ssrc)
349 {
350 /* Hash from an ssrc to a position in the source database. */
351 /* Assumes that ssrc values are uniformly distributed, which */
352 /* should be true but probably isn't (Rosenberg has reported */
353 /* that many implementations generate ssrc values which are */
354 /* not uniformly distributed over the space, and the H.323 */
355 /* spec requires that they are non-uniformly distributed). */
356 /* This routine is written as a function rather than inline */
357 /* code to allow it to be made smart in future: probably we */
358 /* should run MD5 on the ssrc and derive a hash value from */
359 /* that, to ensure it's more uniformly distributed? */
360 return ssrc % RTP_DB_SIZE;
361 }
362
insert_rr(struct rtp * session,uint32_t reporter_ssrc,rtcp_rr * rr,struct timeval * ts)363 static void insert_rr(struct rtp *session, uint32_t reporter_ssrc, rtcp_rr *rr, struct timeval *ts)
364 {
365 /* Insert the reception report into the receiver report */
366 /* database. This database is a two dimensional table of */
367 /* rr_wrappers indexed by hashes of reporter_ssrc and */
368 /* reportee_src. The rr_wrappers in the database are */
369 /* sentinels to reduce conditions in list operations. */
370 /* The ts is used to determine when to timeout this rr. */
371
372 rtcp_rr_wrapper *cur, *start;
373
374 start = &session->rr[ssrc_hash(reporter_ssrc)][ssrc_hash(rr->ssrc)];
375 cur = start->next;
376
377 while (cur != start) {
378 if (cur->reporter_ssrc == reporter_ssrc && cur->rr->ssrc == rr->ssrc) {
379 /* Replace existing entry in the database */
380 xfree(cur->rr);
381 xfree(cur->ts);
382 cur->rr = rr;
383 cur->ts = (struct timeval *) xmalloc(sizeof(struct timeval));
384 memcpy(cur->ts, ts, sizeof(struct timeval));
385 return;
386 }
387 cur = cur->next;
388 }
389
390 /* No entry in the database so create one now. */
391 cur = (rtcp_rr_wrapper*)xmalloc(sizeof(rtcp_rr_wrapper));
392 cur->reporter_ssrc = reporter_ssrc;
393 cur->rr = rr;
394 cur->ts = (struct timeval *) xmalloc(sizeof(struct timeval));
395 memcpy(cur->ts, ts, sizeof(struct timeval));
396 /* Fix links */
397 cur->next = start->next;
398 cur->next->prev = cur;
399 cur->prev = start;
400 cur->prev->next = cur;
401
402 debug_msg("Created new rr entry for 0x%08lx from source 0x%08lx\n", rr->ssrc, reporter_ssrc);
403 return;
404 }
405
remove_rr(struct rtp * session,uint32_t ssrc)406 static void remove_rr(struct rtp *session, uint32_t ssrc)
407 {
408 /* Remove any RRs from "s" which refer to "ssrc" as either */
409 /* reporter or reportee. */
410 rtcp_rr_wrapper *start, *cur, *tmp;
411 int i;
412
413 /* Remove rows, i.e. ssrc == reporter_ssrc */
414 for(i = 0; i < RTP_DB_SIZE; i++) {
415 start = &session->rr[ssrc_hash(ssrc)][i];
416 cur = start->next;
417 while (cur != start) {
418 if (cur->reporter_ssrc == ssrc) {
419 tmp = cur;
420 cur = cur->prev;
421 tmp->prev->next = tmp->next;
422 tmp->next->prev = tmp->prev;
423 xfree(tmp->ts);
424 xfree(tmp->rr);
425 xfree(tmp);
426 }
427 cur = cur->next;
428 }
429 }
430
431 /* Remove columns, i.e. ssrc == reporter_ssrc */
432 for(i = 0; i < RTP_DB_SIZE; i++) {
433 start = &session->rr[i][ssrc_hash(ssrc)];
434 cur = start->next;
435 while (cur != start) {
436 if (cur->rr->ssrc == ssrc) {
437 tmp = cur;
438 cur = cur->prev;
439 tmp->prev->next = tmp->next;
440 tmp->next->prev = tmp->prev;
441 xfree(tmp->ts);
442 xfree(tmp->rr);
443 xfree(tmp);
444 }
445 cur = cur->next;
446 }
447 }
448 }
449
timeout_rr(struct rtp * session,struct timeval * curr_ts)450 static void timeout_rr(struct rtp *session, struct timeval *curr_ts)
451 {
452 /* Timeout any reception reports which have been in the database for more than 3 */
453 /* times the RTCP reporting interval without refresh. */
454 rtcp_rr_wrapper *start, *cur, *tmp;
455 rtp_event event;
456 int i, j;
457
458 for(i = 0; i < RTP_DB_SIZE; i++) {
459 for(j = 0; j < RTP_DB_SIZE; j++) {
460 start = &session->rr[i][j];
461 cur = start->next;
462 while (cur != start) {
463 if (tv_diff(*curr_ts, *(cur->ts)) > (session->rtcp_interval * 3)) {
464 /* Signal the application... */
465 if (!filter_event(session, cur->reporter_ssrc)) {
466 event.ssrc = cur->reporter_ssrc;
467 event.type = RR_TIMEOUT;
468 event.data = cur->rr;
469 event.ts = curr_ts;
470 session->callback(session, &event);
471 }
472 /* Delete this reception report... */
473 tmp = cur;
474 cur = cur->prev;
475 tmp->prev->next = tmp->next;
476 tmp->next->prev = tmp->prev;
477 xfree(tmp->ts);
478 xfree(tmp->rr);
479 xfree(tmp);
480 }
481 cur = cur->next;
482 }
483 }
484 }
485 }
486
get_rr(struct rtp * session,uint32_t reporter_ssrc,uint32_t reportee_ssrc)487 static const rtcp_rr* get_rr(struct rtp *session, uint32_t reporter_ssrc, uint32_t reportee_ssrc)
488 {
489 rtcp_rr_wrapper *cur, *start;
490
491 start = &session->rr[ssrc_hash(reporter_ssrc)][ssrc_hash(reportee_ssrc)];
492 cur = start->next;
493 while (cur != start) {
494 if (cur->reporter_ssrc == reporter_ssrc &&
495 cur->rr->ssrc == reportee_ssrc) {
496 return cur->rr;
497 }
498 cur = cur->next;
499 }
500 return NULL;
501 }
502
503 static inline void
check_source(source * s)504 check_source(source *s)
505 {
506 #ifdef DEBUG
507 assert(s != NULL);
508 assert(s->magic == 0xc001feed);
509 #else
510 UNUSED(s);
511 #endif
512 }
513
514 static inline void
check_database(struct rtp * session)515 check_database(struct rtp *session)
516 {
517 /* This routine performs a sanity check on the database. */
518 /* This should not call any of the other routines which */
519 /* manipulate the database, to avoid common failures. */
520 #ifdef DEBUG
521 source *s;
522 int source_count;
523 int chain;
524
525 assert(session != NULL);
526 assert(session->magic == 0xfeedface);
527 /* Check that we have a database entry for our ssrc... */
528 /* We only do this check if ssrc_count > 0 since it is */
529 /* performed during initialisation whilst creating the */
530 /* source entry for my_ssrc. */
531 if (session->ssrc_count > 0) {
532 for (s = session->db[ssrc_hash(session->my_ssrc)]; s != NULL; s = s->next) {
533 if (s->ssrc == session->my_ssrc) {
534 break;
535 }
536 }
537 assert(s != NULL);
538 }
539
540 source_count = 0;
541 for (chain = 0; chain < RTP_DB_SIZE; chain++) {
542 /* Check that the linked lists making up the chains in */
543 /* the hash table are correctly linked together... */
544 for (s = session->db[chain]; s != NULL; s = s->next) {
545 check_source(s);
546 source_count++;
547 if (s->prev == NULL) {
548 assert(s == session->db[chain]);
549 } else {
550 assert(s->prev->next == s);
551 }
552 if (s->next != NULL) {
553 assert(s->next->prev == s);
554 }
555 /* Check that the SR is for this source... */
556 if (s->sr != NULL) {
557 assert(s->sr->ssrc == s->ssrc);
558 }
559 }
560 }
561 /* Check that the number of entries in the hash table */
562 /* matches session->ssrc_count */
563 assert(source_count == session->ssrc_count);
564 #else
565 UNUSED(session);
566 #endif
567 }
568
569 static inline source *
get_source(struct rtp * session,uint32_t ssrc)570 get_source(struct rtp *session, uint32_t ssrc)
571 {
572 source *s;
573
574 check_database(session);
575 for (s = session->db[ssrc_hash(ssrc)]; s != NULL; s = s->next) {
576 if (s->ssrc == ssrc) {
577 check_source(s);
578 return s;
579 }
580 }
581 return NULL;
582 }
583
584 static source *
create_source(struct rtp * session,uint32_t ssrc,int probation)585 create_source(struct rtp *session, uint32_t ssrc, int probation)
586 {
587 /* Create a new source entry, and add it to the database. */
588 /* The database is a hash table, using the separate chaining */
589 /* algorithm. */
590 rtp_event event;
591 struct timeval event_ts;
592 source *s = get_source(session, ssrc);
593 int h;
594
595 if (s != NULL) {
596 /* Source is already in the database... Mark it as */
597 /* active and exit (this is the common case...) */
598 gettimeofday(&(s->last_active), NULL);
599 return s;
600 }
601 check_database(session);
602 /* This is a new source, we have to create it... */
603 h = ssrc_hash(ssrc);
604 s = (source *) xmalloc(sizeof(source));
605 memset(s, 0, sizeof(source));
606 s->magic = 0xc001feed;
607 s->init = 0;
608 s->next = session->db[h];
609 s->ssrc = ssrc;
610 if (probation) {
611 /* This is a probationary source, which only counts as */
612 /* valid once several consecutive packets are received */
613 s->probation = -1;
614 } else {
615 s->probation = 0;
616 }
617
618 gettimeofday(&(s->last_active), NULL);
619 /* Now, add it to the database... */
620 if (session->db[h] != NULL) {
621 session->db[h]->prev = s;
622 }
623 session->db[ssrc_hash(ssrc)] = s;
624 session->ssrc_count++;
625 check_database(session);
626
627 debug_msg("Created database entry for ssrc 0x%08lx (%d valid sources)\n", ssrc, session->ssrc_count);
628 if (ssrc != session->my_ssrc) {
629 /* Do not send during rtp_init since application cannot map the address */
630 /* of the rtp session to anything since rtp_init has not returned yet. */
631 if (!filter_event(session, ssrc)) {
632 gettimeofday(&event_ts, NULL);
633 event.ssrc = ssrc;
634 event.type = SOURCE_CREATED;
635 event.data = NULL;
636 event.ts = &event_ts;
637 session->callback(session, &event);
638 }
639 }
640
641 return s;
642 }
643
delete_source(struct rtp * session,uint32_t ssrc)644 static void delete_source(struct rtp *session, uint32_t ssrc)
645 {
646 /* Remove a source from the RTP database... */
647 source *s = get_source(session, ssrc);
648 int h = ssrc_hash(ssrc);
649 rtp_event event;
650 struct timeval event_ts;
651
652 assert(s != NULL); /* Deleting a source which doesn't exist is an error... */
653
654 gettimeofday(&event_ts, NULL);
655
656 check_source(s);
657 check_database(session);
658 if (session->db[h] == s) {
659 /* It's the first entry in this chain... */
660 session->db[h] = s->next;
661 if (s->next != NULL) {
662 s->next->prev = NULL;
663 }
664 } else {
665 assert(s->prev != NULL); /* Else it would be the first in the chain... */
666 s->prev->next = s->next;
667 if (s->next != NULL) {
668 s->next->prev = s->prev;
669 }
670 }
671 /* Free the memory allocated to a source... */
672 if (s->cname != NULL) xfree(s->cname);
673 if (s->name != NULL) xfree(s->name);
674 if (s->email != NULL) xfree(s->email);
675 if (s->phone != NULL) xfree(s->phone);
676 if (s->loc != NULL) xfree(s->loc);
677 if (s->tool != NULL) xfree(s->tool);
678 if (s->note != NULL) xfree(s->note);
679 if (s->priv != NULL) xfree(s->priv);
680 if (s->sr != NULL) xfree(s->sr);
681
682 remove_rr(session, ssrc);
683
684 /* Reduce our SSRC count, and perform reverse reconsideration on the RTCP */
685 /* reporting interval (draft-ietf-avt-rtp-new-05.txt, section 6.3.4). To */
686 /* make the transmission rate of RTCP packets more adaptive to changes in */
687 /* group membership, the following "reverse reconsideration" algorithm */
688 /* SHOULD be executed when a BYE packet is received that reduces members */
689 /* to a value less than pmembers: */
690 /* o The value for tn is updated according to the following formula: */
691 /* tn = tc + (members/pmembers)(tn - tc) */
692 /* o The value for tp is updated according the following formula: */
693 /* tp = tc - (members/pmembers)(tc - tp). */
694 /* o The next RTCP packet is rescheduled for transmission at time tn, */
695 /* which is now earlier. */
696 /* o The value of pmembers is set equal to members. */
697 session->ssrc_count--;
698 if (session->ssrc_count < session->ssrc_count_prev) {
699 gettimeofday(&(session->next_rtcp_send_time), NULL);
700 gettimeofday(&(session->last_rtcp_send_time), NULL);
701 tv_add(&(session->next_rtcp_send_time), (session->ssrc_count / session->ssrc_count_prev)
702 * tv_diff(session->next_rtcp_send_time, event_ts));
703 tv_add(&(session->last_rtcp_send_time), - ((session->ssrc_count / session->ssrc_count_prev)
704 * tv_diff(event_ts, session->last_rtcp_send_time)));
705 session->ssrc_count_prev = session->ssrc_count;
706 }
707
708 /* Reduce our csrc count... */
709 if (s->should_advertise_sdes == TRUE) {
710 session->csrc_count--;
711 }
712 if (session->last_advertised_csrc == session->csrc_count) {
713 session->last_advertised_csrc = 0;
714 }
715
716 /* Signal to the application that this source is dead... */
717 if (!filter_event(session, ssrc)) {
718 event.ssrc = ssrc;
719 event.type = SOURCE_DELETED;
720 event.data = NULL;
721 event.ts = &event_ts;
722 session->callback(session, &event);
723 }
724 xfree(s);
725 check_database(session);
726 }
727
728 static inline void
init_seq(source * s,uint16_t seq)729 init_seq(source *s, uint16_t seq)
730 {
731 /* Taken from draft-ietf-avt-rtp-new-01.txt */
732 check_source(s);
733 s->base_seq = seq;
734 s->max_seq = seq;
735 s->bad_seq = RTP_SEQ_MOD + 1;
736 s->cycles = 0;
737 s->received = 0;
738 s->received_prior = 0;
739 s->expected_prior = 0;
740 s->init = 1;
741 }
742
update_seq(source * s,uint16_t seq)743 static int update_seq(source *s, uint16_t seq)
744 {
745 /* Taken from draft-ietf-avt-rtp-new-01.txt */
746 uint16_t udelta = seq - s->max_seq;
747
748 /*
749 * Source is not valid until MIN_SEQUENTIAL packets with
750 * sequential sequence numbers have been received.
751 */
752 check_source(s);
753 if (s->probation) {
754 /* packet is in sequence */
755 if (seq == s->max_seq + 1) {
756 s->probation--;
757 s->max_seq = seq;
758 if (s->probation == 0) {
759 init_seq(s, seq);
760 s->received++;
761 return 1;
762 }
763 } else {
764 s->probation = MIN_SEQUENTIAL - 1;
765 s->max_seq = seq;
766 }
767 return 0;
768 } else if (udelta < MAX_DROPOUT) {
769 /* in order, with permissible gap */
770 if (seq < s->max_seq) {
771 /*
772 * Sequence number wrapped - count another 64K cycle.
773 */
774 s->cycles += RTP_SEQ_MOD;
775 }
776 s->max_seq = seq;
777 } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
778 /* the sequence number made a very large jump */
779 if (seq == s->bad_seq) {
780 /*
781 * Two sequential packets -- assume that the other side
782 * restarted without telling us so just re-sync
783 * (i.e., pretend this was the first packet).
784 */
785 init_seq(s, seq);
786 } else {
787 s->bad_seq = (seq + 1) & (RTP_SEQ_MOD-1);
788 return 0;
789 }
790 } else {
791 /* duplicate or reordered packet */
792 }
793 s->received++;
794 return 1;
795 }
796
797 static double
rtcp_interval(struct rtp * session)798 rtcp_interval(struct rtp *session)
799 {
800 /* Minimum average time between RTCP packets from this site (in */
801 /* seconds). This time prevents the reports from `clumping' when */
802 /* sessions are small and the law of large numbers isn't helping */
803 /* to smooth out the traffic. It also keeps the report interval */
804 /* from becoming ridiculously small during transient outages like */
805 /* a network partition. */
806 double const RTCP_MIN_TIME = 5.0;
807 /* Fraction of the RTCP bandwidth to be shared among active */
808 /* senders. (This fraction was chosen so that in a typical */
809 /* session with one or two active senders, the computed report */
810 /* time would be roughly equal to the minimum report time so that */
811 /* we don't unnecessarily slow down receiver reports.) The */
812 /* receiver fraction must be 1 - the sender fraction. */
813 double const RTCP_SENDER_BW_FRACTION = 0.25;
814 double const RTCP_RCVR_BW_FRACTION = (1-RTCP_SENDER_BW_FRACTION);
815 /* To compensate for "unconditional reconsideration" converging */
816 /* to a value below the intended average. */
817 double const COMPENSATION = 2.71828 - 1.5;
818
819 double t; /* interval */
820 double rtcp_min_time = RTCP_MIN_TIME;
821 int n; /* no. of members for computation */
822 double rtcp_bw = session->rtcp_bw;
823
824 /* Very first call at application start-up uses half the min */
825 /* delay for quicker notification while still allowing some time */
826 /* before reporting for randomization and to learn about other */
827 /* sources so the report interval will converge to the correct */
828 /* interval more quickly. */
829 if (session->initial_rtcp) {
830 rtcp_min_time /= 2;
831 }
832
833 /* If there were active senders, give them at least a minimum */
834 /* share of the RTCP bandwidth. Otherwise all participants share */
835 /* the RTCP bandwidth equally. */
836 if (session->sending_bye) {
837 n = session->bye_count;
838 } else {
839 n = session->ssrc_count;
840 }
841 if (session->sender_count > 0 && session->sender_count < n * RTCP_SENDER_BW_FRACTION) {
842 if (session->we_sent) {
843 rtcp_bw *= RTCP_SENDER_BW_FRACTION;
844 n = session->sender_count;
845 } else {
846 rtcp_bw *= RTCP_RCVR_BW_FRACTION;
847 n -= session->sender_count;
848 }
849 }
850
851 /* The effective number of sites times the average packet size is */
852 /* the total number of octets sent when each site sends a report. */
853 /* Dividing this by the effective bandwidth gives the time */
854 /* interval over which those packets must be sent in order to */
855 /* meet the bandwidth target, with a minimum enforced. In that */
856 /* time interval we send one report so this time is also our */
857 /* average time between reports. */
858 t = session->avg_rtcp_size * n / rtcp_bw;
859 if (t < rtcp_min_time) {
860 t = rtcp_min_time;
861 }
862 session->rtcp_interval = t;
863
864 /* To avoid traffic bursts from unintended synchronization with */
865 /* other sites, we then pick our actual next report interval as a */
866 /* random number uniformly distributed between 0.5*t and 1.5*t. */
867 return (t * (drand48() + 0.5)) / COMPENSATION;
868 }
869
870 #define MAXCNAMELEN 255
871
get_cname(socket_udp * s)872 static char *get_cname(socket_udp *s)
873 {
874 /* Set the CNAME. This is "user@hostname" or just "hostname" if the username cannot be found. */
875 const char *hname;
876 char *uname;
877 char *cname;
878 #ifndef WIN32
879 struct passwd *pwent;
880 #else
881 char *name;
882 int namelen;
883 #endif
884
885 cname = (char *) xmalloc(MAXCNAMELEN + 1);
886 cname[0] = '\0';
887
888 /* First, fill in the username... */
889 #ifdef WIN32
890 name = NULL;
891 namelen = 0;
892 GetUserName(NULL, &namelen);
893 if (namelen > 0) {
894 name = (char*)xmalloc(namelen+1);
895 GetUserName(name, &namelen);
896 } else {
897 uname = getenv("USER");
898 if (uname != NULL) {
899 name = xstrdup(uname);
900 }
901 }
902 if (name != NULL) {
903 strncpy(cname, name, MAXCNAMELEN - 1);
904 strcat(cname, "@");
905 xfree(name);
906 }
907 #else
908 pwent = getpwuid(getuid());
909 uname = pwent->pw_name;
910 if (uname != NULL) {
911 strncpy(cname, uname, MAXCNAMELEN - 1);
912 strcat(cname, "@");
913 }
914
915 #endif
916
917 /* Now the hostname. Must be dotted-quad IP address. */
918 hname = udp_host_addr(s);
919 if (hname == NULL) {
920 /* If we can't get our IP address we use the loopback address... */
921 /* This is horrible, but it stops the code from failing. */
922 hname = "127.0.0.1";
923 }
924 strncpy(cname + strlen(cname), hname, MAXCNAMELEN - strlen(cname));
925 return cname;
926 }
927
init_opt(struct rtp * session)928 static void init_opt(struct rtp *session)
929 {
930 /* Default option settings. */
931 rtp_set_option(session, RTP_OPT_PROMISC, FALSE);
932 rtp_set_option(session, RTP_OPT_WEAK_VALIDATION, FALSE);
933 rtp_set_option(session, RTP_OPT_FILTER_MY_PACKETS, FALSE);
934 rtp_set_option(session, RTP_OPT_REUSE_PACKET_BUFS, FALSE);
935 }
936
init_rng(const char * s)937 static void init_rng(const char *s)
938 {
939 #ifdef WIN32
940 int32_t i, n;
941 #endif
942 static uint32_t seed;
943 if (s == NULL) {
944 /* This should never happen, but just in case */
945 s = "ARANDOMSTRINGSOWEDONTCOREDUMP";
946 }
947 if (seed == 0) {
948 pid_t p = getpid();
949 while (*s) {
950 seed += (uint32_t)*s++;
951 seed = seed * 31 + 1;
952 }
953 seed = 1 + seed * 31 + (uint32_t)p;
954 srand48(seed);
955 /* At time of writing we use srand48 -> srand on Win32
956 which is only 16 bit. lrand48 -> rand which is only
957 15 bits, step a long way through table seq */
958 #ifdef WIN32
959 n = (seed >> 16) & 0xffff;
960 for(i = 0; i < n; i++) {
961 seed = lrand48();
962 }
963 #endif /* WIN32 */
964 }
965 }
966
967 /* See rtp_init_if(); calling rtp_init() is just like calling
968 * rtp_init_if() with a NULL interface argument.
969 */
970
971 /**
972 * rtp_init:
973 * @addr: IP destination of this session (unicast or multicast),
974 * as an ASCII string. May be a host name, which will be looked up,
975 * or may be an IPv4 dotted quad or IPv6 literal adddress.
976 * @rx_port: The port to which to bind the UDP socket
977 * @tx_port: The port to which to send UDP packets
978 * @ttl: The TTL with which to send multicasts
979 * @rtcp_bw: The total bandwidth (in units of bytes per second) that is
980 * allocated to RTCP.
981 * @callback: See section on #rtp_callback.
982 * @userdata: Opaque data associated with the session. See
983 * rtp_get_userdata().
984 *
985 *
986 * Returns: An opaque session identifier to be used in future calls to
987 * the RTP library functions, or NULL on failure.
988 */
rtp_init(const char * addr,uint16_t rx_port,uint16_t tx_port,int ttl,double rtcp_bw,rtp_callback callback,uint8_t * userdata)989 struct rtp *rtp_init(const char *addr,
990 uint16_t rx_port, uint16_t tx_port,
991 int ttl, double rtcp_bw,
992 rtp_callback callback,
993 uint8_t *userdata)
994 {
995 return rtp_init_if(addr, NULL, rx_port, tx_port, ttl, rtcp_bw, callback, userdata);
996 }
997
998 /**
999 * rtp_init_if:
1000 * @addr: IP destination of this session (unicast or multicast),
1001 * as an ASCII string. May be a host name, which will be looked up,
1002 * or may be an IPv4 dotted quad or IPv6 literal adddress.
1003 * @iface: If the destination of the session is multicast,
1004 * the optional interface to bind to. May be NULL, in which case
1005 * the default multicast interface as determined by the system
1006 * will be used.
1007 * @rx_port: The port to which to bind the UDP socket
1008 * @tx_port: The port to which to send UDP packets
1009 * @ttl: The TTL with which to send multicasts
1010 * @rtcp_bw: The total bandwidth (in units of ___) that is
1011 * allocated to RTCP.
1012 * @callback: See section on #rtp_callback.
1013 * @userdata: Opaque data associated with the session. See
1014 * rtp_get_userdata().
1015 *
1016 * Creates and initializes an RTP session.
1017 *
1018 * Returns: An opaque session identifier to be used in future calls to
1019 * the RTP library functions, or NULL on failure.
1020 */
rtp_init_if(const char * addr,char * iface,uint16_t rx_port,uint16_t tx_port,int ttl,double rtcp_bw,rtp_callback callback,uint8_t * userdata)1021 struct rtp *rtp_init_if(const char *addr, char *iface,
1022 uint16_t rx_port, uint16_t tx_port,
1023 int ttl, double rtcp_bw,
1024 rtp_callback callback,
1025 uint8_t *userdata)
1026 {
1027 struct rtp *session;
1028 int i, j;
1029 char *cname;
1030
1031 if (ttl < 0) {
1032 debug_msg("ttl must be greater than zero\n");
1033 return NULL;
1034 }
1035 if (rx_port % 2) {
1036 debug_msg("rx_port must be even\n");
1037 return NULL;
1038 }
1039 if (tx_port % 2) {
1040 debug_msg("tx_port must be even\n");
1041 return NULL;
1042 }
1043
1044 session = (struct rtp *) xmalloc(sizeof(struct rtp));
1045 memset (session, 0, sizeof(struct rtp));
1046
1047 session->magic = 0xfeedface;
1048 session->opt = (options *) xmalloc(sizeof(options));
1049 session->userdata = userdata;
1050 session->addr = xstrdup(addr);
1051 session->rx_port = rx_port;
1052 session->tx_port = tx_port;
1053 session->ttl = min(ttl, 127);
1054 session->rtp_socket = udp_init_if(addr, iface, rx_port, tx_port, ttl);
1055 session->rtcp_socket = udp_init_if(addr, iface, (uint16_t) (rx_port+1), (uint16_t) (tx_port+1), ttl);
1056
1057 init_opt(session);
1058
1059 if (session->rtp_socket == NULL || session->rtcp_socket == NULL) {
1060 xfree(session);
1061 return NULL;
1062 }
1063
1064 init_rng(udp_host_addr(session->rtp_socket));
1065
1066 session->my_ssrc = (uint32_t) lrand48();
1067 session->callback = callback;
1068 session->invalid_rtp_count = 0;
1069 session->invalid_rtcp_count = 0;
1070 session->bye_count = 0;
1071 session->csrc_count = 0;
1072 session->ssrc_count = 0;
1073 session->ssrc_count_prev = 0;
1074 session->sender_count = 0;
1075 session->initial_rtcp = TRUE;
1076 session->sending_bye = FALSE;
1077 session->avg_rtcp_size = -1; /* Sentinal value: reception of first packet starts initial value... */
1078 session->we_sent = FALSE;
1079 session->rtcp_bw = rtcp_bw;
1080 session->sdes_count_pri = 0;
1081 session->sdes_count_sec = 0;
1082 session->sdes_count_ter = 0;
1083 session->rtp_seq = (uint16_t) lrand48();
1084 session->rtp_pcount = 0;
1085 session->rtp_bcount = 0;
1086 gettimeofday(&(session->last_update), NULL);
1087 gettimeofday(&(session->last_rtcp_send_time), NULL);
1088 gettimeofday(&(session->next_rtcp_send_time), NULL);
1089 session->encryption_enabled = 0;
1090 session->encryption_algorithm = NULL;
1091
1092 /* Calculate when we're supposed to send our first RTCP packet... */
1093 tv_add(&(session->next_rtcp_send_time), rtcp_interval(session));
1094
1095 /* Initialise the source database... */
1096 for (i = 0; i < RTP_DB_SIZE; i++) {
1097 session->db[i] = NULL;
1098 }
1099 session->last_advertised_csrc = 0;
1100
1101 /* Initialize sentinels in rr table */
1102 for (i = 0; i < RTP_DB_SIZE; i++) {
1103 for (j = 0; j < RTP_DB_SIZE; j++) {
1104 session->rr[i][j].next = &session->rr[i][j];
1105 session->rr[i][j].prev = &session->rr[i][j];
1106 }
1107 }
1108
1109 /* Create a database entry for ourselves... */
1110 create_source(session, session->my_ssrc, FALSE);
1111 cname = get_cname(session->rtp_socket);
1112 rtp_set_sdes(session, session->my_ssrc, RTCP_SDES_CNAME, cname, strlen(cname));
1113 xfree(cname); /* cname is copied by rtp_set_sdes()... */
1114
1115 return session;
1116 }
1117
1118 /**
1119 * rtp_set_my_ssrc:
1120 * @session: the RTP session
1121 * @ssrc: the SSRC to be used by the RTP session
1122 *
1123 * This function coerces the local SSRC identifer to be ssrc. For
1124 * this function to succeed it must be called immediately after
1125 * rtp_init or rtp_init_if. The intended purpose of this
1126 * function is to co-ordinate SSRC's between layered sessions, it
1127 * should not be used otherwise.
1128 *
1129 * Returns: TRUE on success, FALSE otherwise.
1130 */
rtp_set_my_ssrc(struct rtp * session,uint32_t ssrc)1131 int rtp_set_my_ssrc(struct rtp *session, uint32_t ssrc)
1132 {
1133 source *s;
1134 uint32_t h;
1135
1136 if (session->ssrc_count != 1 && session->sender_count != 0) {
1137 return FALSE;
1138 }
1139 /* Remove existing source */
1140 h = ssrc_hash(session->my_ssrc);
1141 s = session->db[h];
1142 session->db[h] = NULL;
1143 /* Fill in new ssrc */
1144 session->my_ssrc = ssrc;
1145 s->ssrc = ssrc;
1146 h = ssrc_hash(ssrc);
1147 /* Put source back */
1148 session->db[h] = s;
1149 return TRUE;
1150 }
1151
1152 /**
1153 * rtp_set_option:
1154 * @session: The RTP session.
1155 * @optname: The option name, see #rtp_option.
1156 * @optval: The value to set.
1157 *
1158 * Sets the value of a session option. See #rtp_option for
1159 * documentation on the options and their legal values.
1160 *
1161 * Returns: TRUE on success, else FALSE.
1162 */
rtp_set_option(struct rtp * session,rtp_option optname,int optval)1163 int rtp_set_option(struct rtp *session, rtp_option optname, int optval)
1164 {
1165 assert((optval == TRUE) || (optval == FALSE));
1166
1167 switch (optname) {
1168 case RTP_OPT_WEAK_VALIDATION:
1169 session->opt->wait_for_rtcp = optval;
1170 break;
1171 case RTP_OPT_PROMISC:
1172 session->opt->promiscuous_mode = optval;
1173 break;
1174 case RTP_OPT_FILTER_MY_PACKETS:
1175 session->opt->filter_my_packets = optval;
1176 break;
1177 case RTP_OPT_REUSE_PACKET_BUFS:
1178 session->opt->reuse_bufs = optval;
1179 break;
1180 default:
1181 debug_msg("Ignoring unknown option (%d) in call to rtp_set_option().\n", optname);
1182 return FALSE;
1183 }
1184 return TRUE;
1185 }
1186
1187 /**
1188 * rtp_get_option:
1189 * @session: The RTP session.
1190 * @optname: The option name, see #rtp_option.
1191 * @optval: The return value.
1192 *
1193 * Retrieves the value of a session option. See #rtp_option for
1194 * documentation on the options and their legal values.
1195 *
1196 * Returns: TRUE and the value of the option in optval on success, else FALSE.
1197 */
rtp_get_option(struct rtp * session,rtp_option optname,int * optval)1198 int rtp_get_option(struct rtp *session, rtp_option optname, int *optval)
1199 {
1200 switch (optname) {
1201 case RTP_OPT_WEAK_VALIDATION:
1202 *optval = session->opt->wait_for_rtcp;
1203 break;
1204 case RTP_OPT_PROMISC:
1205 *optval = session->opt->promiscuous_mode;
1206 break;
1207 case RTP_OPT_FILTER_MY_PACKETS:
1208 *optval = session->opt->filter_my_packets;
1209 break;
1210 case RTP_OPT_REUSE_PACKET_BUFS:
1211 *optval = session->opt->reuse_bufs;
1212 break;
1213 default:
1214 *optval = 0;
1215 debug_msg("Ignoring unknown option (%d) in call to rtp_get_option().\n", optname);
1216 return FALSE;
1217 }
1218 return TRUE;
1219 }
1220
1221 /**
1222 * rtp_get_userdata:
1223 * @session: The RTP session.
1224 *
1225 * This function returns the userdata pointer that was passed to the
1226 * rtp_init() or rtp_init_if() function when creating this session.
1227 *
1228 * Returns: pointer to userdata.
1229 */
rtp_get_userdata(struct rtp * session)1230 uint8_t *rtp_get_userdata(struct rtp *session)
1231 {
1232 check_database(session);
1233 return session->userdata;
1234 }
1235
1236 /**
1237 * rtp_my_ssrc:
1238 * @session: The RTP Session.
1239 *
1240 * Returns: The SSRC we are currently using in this session. Note that our
1241 * SSRC can change at any time (due to collisions) so applications must not
1242 * store the value returned, but rather should call this function each time
1243 * they need it.
1244 */
rtp_my_ssrc(struct rtp * session)1245 uint32_t rtp_my_ssrc(struct rtp *session)
1246 {
1247 check_database(session);
1248 return session->my_ssrc;
1249 }
1250
process_rtp(struct rtp * session,uint32_t curr_rtp_ts,rtp_packet * packet,source * s)1251 static void process_rtp(struct rtp *session, uint32_t curr_rtp_ts, rtp_packet *packet, source *s)
1252 {
1253 int i, d, transit;
1254 rtp_event event;
1255 struct timeval event_ts;
1256
1257 if (packet->cc > 0) {
1258 for (i = 0; i < packet->cc; i++) {
1259 create_source(session, packet->csrc[i], FALSE);
1260 }
1261 }
1262 /* Update the source database... */
1263 if (s->sender == FALSE) {
1264 s->sender = TRUE;
1265 session->sender_count++;
1266 }
1267 transit = curr_rtp_ts - packet->ts;
1268 d = transit - s->transit;
1269 s->transit = transit;
1270 if (d < 0) {
1271 d = -d;
1272 }
1273 s->jitter += d - ((s->jitter + 8) / 16);
1274
1275 /* Callback to the application to process the packet... */
1276 if (!filter_event(session, packet->ssrc)) {
1277 gettimeofday(&event_ts, NULL);
1278 event.ssrc = packet->ssrc;
1279 event.type = RX_RTP;
1280 event.data = (void *) packet; /* The callback function MUST free this! */
1281 event.ts = &event_ts;
1282 session->callback(session, &event);
1283 }
1284 }
1285
validate_rtp2(rtp_packet * packet,int len)1286 static int validate_rtp2(rtp_packet *packet, int len)
1287 {
1288 /* Check for valid payload types..... 72-76 are RTCP payload type numbers, with */
1289 /* the high bit missing so we report that someone is running on the wrong port. */
1290 if (packet->pt >= 72 && packet->pt <= 76) {
1291 debug_msg("rtp_header_validation: payload-type invalid");
1292 if (packet->m) {
1293 debug_msg(" (RTCP packet on RTP port?)");
1294 }
1295 debug_msg("\n");
1296 return FALSE;
1297 }
1298 /* Check that the length of the packet is sensible... */
1299 if (len < (12 + (4 * packet->cc))) {
1300 debug_msg("rtp_header_validation: packet length is smaller than the header\n");
1301 return FALSE;
1302 }
1303 /* Check that the amount of padding specified is sensible. */
1304 /* Note: have to include the size of any extension header! */
1305 if (packet->p) {
1306 int payload_len = len - 12 - (packet->cc * 4);
1307 if (packet->x) {
1308 /* extension header and data */
1309 payload_len -= 4 * (1 + packet->extn_len);
1310 }
1311 if (packet->data[packet->data_len - 1] > payload_len) {
1312 debug_msg("rtp_header_validation: padding greater than payload length\n");
1313 return FALSE;
1314 }
1315 if (packet->data[packet->data_len - 1] < 1) {
1316 debug_msg("rtp_header_validation: padding zero\n");
1317 return FALSE;
1318 }
1319 }
1320 return TRUE;
1321 }
1322
1323 static inline int
validate_rtp(struct rtp * session,rtp_packet * packet,int len)1324 validate_rtp(struct rtp *session, rtp_packet *packet, int len)
1325 {
1326 /* This function checks the header info to make sure that the packet */
1327 /* is valid. We return TRUE if the packet is valid, FALSE otherwise. */
1328 /* See Appendix A.1 of the RTP specification. */
1329
1330 /* We only accept RTPv2 packets... */
1331 if (packet->v != 2) {
1332 debug_msg("rtp_header_validation: v != 2\n");
1333 return FALSE;
1334 }
1335
1336 if (!session->opt->wait_for_rtcp) {
1337 /* We prefer speed over accuracy... */
1338 return TRUE;
1339 }
1340 return validate_rtp2(packet, len);
1341 }
1342
1343 static void
rtp_recv_data(struct rtp * session,uint32_t curr_rtp_ts)1344 rtp_recv_data(struct rtp *session, uint32_t curr_rtp_ts)
1345 {
1346 /* This routine preprocesses an incoming RTP packet, deciding whether to process it. */
1347 static rtp_packet *packet = NULL;
1348 static uint8_t *buffer = NULL;
1349 static uint8_t *buffer12 = NULL;
1350 int buflen;
1351 source *s;
1352
1353 if (!session->opt->reuse_bufs || (packet == NULL)) {
1354 packet = (rtp_packet *) xmalloc(RTP_MAX_PACKET_LEN);
1355 buffer = ((uint8_t *) packet) + RTP_PACKET_HEADER_SIZE;
1356 buffer12 = buffer + 12;
1357 }
1358
1359 buflen = udp_recv(session->rtp_socket, (char *)buffer, RTP_MAX_PACKET_LEN - RTP_PACKET_HEADER_SIZE);
1360 if (buflen > 0) {
1361 if (session->encryption_enabled) {
1362 uint8_t initVec[8] = {0,0,0,0,0,0,0,0};
1363 (session->decrypt_func)(session, buffer, buflen, initVec);
1364 }
1365 /* Convert header fields to host byte order... */
1366 packet->seq = ntohs(packet->seq);
1367 packet->ts = ntohl(packet->ts);
1368 packet->ssrc = ntohl(packet->ssrc);
1369 /* Setup internal pointers, etc... */
1370 if (packet->cc) {
1371 int i;
1372 packet->csrc = (uint32_t *)(buffer12);
1373 for (i = 0; i < packet->cc; i++) {
1374 packet->csrc[i] = ntohl(packet->csrc[i]);
1375 }
1376 } else {
1377 packet->csrc = NULL;
1378 }
1379 if (packet->x) {
1380 packet->extn = buffer12 + (packet->cc * 4);
1381 packet->extn_len = (packet->extn[2] << 8) | packet->extn[3];
1382 packet->extn_type = (packet->extn[0] << 8) | packet->extn[1];
1383 } else {
1384 packet->extn = NULL;
1385 packet->extn_len = 0;
1386 packet->extn_type = 0;
1387 }
1388 packet->data = (char *)buffer12 + (packet->cc * 4);
1389 packet->data_len = buflen - (packet->cc * 4) - 12;
1390 if (packet->extn != NULL) {
1391 packet->data += ((packet->extn_len + 1) * 4);
1392 packet->data_len -= ((packet->extn_len + 1) * 4);
1393 }
1394 if (validate_rtp(session, packet, buflen)) {
1395 if (session->opt->wait_for_rtcp) {
1396 s = create_source(session, packet->ssrc, TRUE);
1397 } else {
1398 s = get_source(session, packet->ssrc);
1399 }
1400 if (session->opt->promiscuous_mode) {
1401 if (s == NULL) {
1402 create_source(session, packet->ssrc, FALSE);
1403 s = get_source(session, packet->ssrc);
1404 }
1405 process_rtp(session, curr_rtp_ts, packet, s);
1406 return; /* We don't free "packet", that's done by the callback function... */
1407 }
1408 if (s != NULL) {
1409 if (s->probation == -1) {
1410 s->probation = MIN_SEQUENTIAL;
1411 s->max_seq = packet->seq - 1;
1412 }
1413 if (update_seq(s, packet->seq)) {
1414 process_rtp(session, curr_rtp_ts, packet, s);
1415 return; /* we don't free "packet", that's done by the callback function... */
1416 } else {
1417 /* This source is still on probation... */
1418 debug_msg("RTP packet from probationary source ignored...\n");
1419 }
1420 } else {
1421 debug_msg("RTP packet from unknown source ignored\n");
1422 }
1423 } else {
1424 session->invalid_rtp_count++;
1425 debug_msg("Invalid RTP packet discarded\n");
1426 }
1427 }
1428 if (!session->opt->reuse_bufs) {
1429 xfree(packet);
1430 }
1431 }
1432
validate_rtcp(uint8_t * packet,int len)1433 static int validate_rtcp(uint8_t *packet, int len)
1434 {
1435 /* Validity check for a compound RTCP packet. This function returns */
1436 /* TRUE if the packet is okay, FALSE if the validity check fails. */
1437 /* */
1438 /* The following checks can be applied to RTCP packets [RFC1889]: */
1439 /* o RTP version field must equal 2. */
1440 /* o The payload type field of the first RTCP packet in a compound */
1441 /* packet must be equal to SR or RR. */
1442 /* o The padding bit (P) should be zero for the first packet of a */
1443 /* compound RTCP packet because only the last should possibly */
1444 /* need padding. */
1445 /* o The length fields of the individual RTCP packets must total to */
1446 /* the overall length of the compound RTCP packet as received. */
1447
1448 rtcp_t *pkt = (rtcp_t *) packet;
1449 rtcp_t *end = (rtcp_t *) (((char *) pkt) + len);
1450 rtcp_t *r = pkt;
1451 int l = 0;
1452 int pc = 1;
1453 int p = 0;
1454
1455 /* All RTCP packets must be compound packets (RFC1889, section 6.1) */
1456 if (((ntohs(pkt->common.length) + 1) * 4) == len) {
1457 debug_msg("Bogus RTCP packet: not a compound packet\n");
1458 return FALSE;
1459 }
1460
1461 /* Check the RTCP version, payload type and padding of the first in */
1462 /* the compund RTCP packet... */
1463 if (pkt->common.version != 2) {
1464 debug_msg("Bogus RTCP packet: version number != 2 in the first sub-packet\n");
1465 return FALSE;
1466 }
1467 if (pkt->common.p != 0) {
1468 debug_msg("Bogus RTCP packet: padding bit is set on first packet in compound\n");
1469 return FALSE;
1470 }
1471 if ((pkt->common.pt != RTCP_SR) && (pkt->common.pt != RTCP_RR)) {
1472 debug_msg("Bogus RTCP packet: compund packet does not start with SR or RR\n");
1473 return FALSE;
1474 }
1475
1476 /* Check all following parts of the compund RTCP packet. The RTP version */
1477 /* number must be 2, and the padding bit must be zero on all apart from */
1478 /* the last packet. */
1479 do {
1480 if (p == 1) {
1481 debug_msg("Bogus RTCP packet: padding bit set before last in compound (sub-packet %d)\n", pc);
1482 return FALSE;
1483 }
1484 if (r->common.p) {
1485 p = 1;
1486 }
1487 if (r->common.version != 2) {
1488 debug_msg("Bogus RTCP packet: version number != 2 in sub-packet %d\n", pc);
1489 return FALSE;
1490 }
1491 l += (ntohs(r->common.length) + 1) * 4;
1492 r = (rtcp_t *) (((uint32_t *) r) + ntohs(r->common.length) + 1);
1493 pc++; /* count of sub-packets, for debugging... */
1494 } while (r < end);
1495
1496 /* Check that the length of the packets matches the length of the UDP */
1497 /* packet in which they were received... */
1498 if (l != len) {
1499 debug_msg("Bogus RTCP packet: RTCP packet length does not match UDP packet length (%d != %d)\n", l, len);
1500 return FALSE;
1501 }
1502 if (r != end) {
1503 debug_msg("Bogus RTCP packet: RTCP packet length does not match UDP packet length (%p != %p)\n", r, end);
1504 return FALSE;
1505 }
1506
1507 return TRUE;
1508 }
1509
process_report_blocks(struct rtp * session,rtcp_t * packet,uint32_t ssrc,rtcp_rr * rrp,struct timeval * event_ts)1510 static void process_report_blocks(struct rtp *session, rtcp_t *packet, uint32_t ssrc, rtcp_rr *rrp, struct timeval *event_ts)
1511 {
1512 int i;
1513 rtp_event event;
1514 rtcp_rr *rr;
1515
1516 /* ...process RRs... */
1517 if (packet->common.count == 0) {
1518 if (!filter_event(session, ssrc)) {
1519 event.ssrc = ssrc;
1520 event.type = RX_RR_EMPTY;
1521 event.data = NULL;
1522 event.ts = event_ts;
1523 session->callback(session, &event);
1524 }
1525 } else {
1526 for (i = 0; i < packet->common.count; i++, rrp++) {
1527 rr = (rtcp_rr *) xmalloc(sizeof(rtcp_rr));
1528 rr->ssrc = ntohl(rrp->ssrc);
1529 rr->fract_lost = rrp->fract_lost; /* Endian conversion handled in the */
1530 rr->total_lost = rrp->total_lost; /* definition of the rtcp_rr type. */
1531 rr->last_seq = ntohl(rrp->last_seq);
1532 rr->jitter = ntohl(rrp->jitter);
1533 rr->lsr = ntohl(rrp->lsr);
1534 rr->dlsr = ntohl(rrp->dlsr);
1535
1536 /* Create a database entry for this SSRC, if one doesn't already exist... */
1537 create_source(session, rr->ssrc, FALSE);
1538
1539 /* Store the RR for later use... */
1540 insert_rr(session, ssrc, rr, event_ts);
1541
1542 /* Call the event handler... */
1543 if (!filter_event(session, ssrc)) {
1544 event.ssrc = ssrc;
1545 event.type = RX_RR;
1546 event.data = (void *) rr;
1547 event.ts = event_ts;
1548 session->callback(session, &event);
1549 }
1550 }
1551 }
1552 }
1553
process_rtcp_sr(struct rtp * session,rtcp_t * packet,struct timeval * event_ts)1554 static void process_rtcp_sr(struct rtp *session, rtcp_t *packet, struct timeval *event_ts)
1555 {
1556 uint32_t ssrc;
1557 rtp_event event;
1558 rtcp_sr *sr;
1559 source *s;
1560
1561 ssrc = ntohl(packet->r.sr.sr.ssrc);
1562 s = create_source(session, ssrc, FALSE);
1563 if (s == NULL) {
1564 debug_msg("Source 0x%08x invalid, skipping...\n", ssrc);
1565 return;
1566 }
1567
1568 /* Mark as an active sender, if we get a sender report... */
1569 if (s->sender == FALSE) {
1570 s->sender = TRUE;
1571 session->sender_count++;
1572 }
1573
1574 /* Process the SR... */
1575 sr = (rtcp_sr *) xmalloc(sizeof(rtcp_sr));
1576 sr->ssrc = ssrc;
1577 sr->ntp_sec = ntohl(packet->r.sr.sr.ntp_sec);
1578 sr->ntp_frac = ntohl(packet->r.sr.sr.ntp_frac);
1579 sr->rtp_ts = ntohl(packet->r.sr.sr.rtp_ts);
1580 sr->sender_pcount = ntohl(packet->r.sr.sr.sender_pcount);
1581 sr->sender_bcount = ntohl(packet->r.sr.sr.sender_bcount);
1582
1583 /* Store the SR for later retrieval... */
1584 if (s->sr != NULL) {
1585 xfree(s->sr);
1586 }
1587 s->sr = sr;
1588 s->last_sr = *event_ts;
1589
1590 /* Call the event handler... */
1591 if (!filter_event(session, ssrc)) {
1592 event.ssrc = ssrc;
1593 event.type = RX_SR;
1594 event.data = (void *) sr;
1595 event.ts = event_ts;
1596 session->callback(session, &event);
1597 }
1598
1599 process_report_blocks(session, packet, ssrc, packet->r.sr.rr, event_ts);
1600
1601 if (((packet->common.count * 6) + 1) < (ntohs(packet->common.length) - 5)) {
1602 debug_msg("Profile specific SR extension ignored\n");
1603 }
1604 }
1605
process_rtcp_rr(struct rtp * session,rtcp_t * packet,struct timeval * event_ts)1606 static void process_rtcp_rr(struct rtp *session, rtcp_t *packet, struct timeval *event_ts)
1607 {
1608 uint32_t ssrc;
1609 source *s;
1610
1611 ssrc = ntohl(packet->r.rr.ssrc);
1612 s = create_source(session, ssrc, FALSE);
1613 if (s == NULL) {
1614 debug_msg("Source 0x%08x invalid, skipping...\n", ssrc);
1615 return;
1616 }
1617
1618 process_report_blocks(session, packet, ssrc, packet->r.rr.rr, event_ts);
1619
1620 if (((packet->common.count * 6) + 1) < ntohs(packet->common.length)) {
1621 debug_msg("Profile specific RR extension ignored\n");
1622 }
1623 }
1624
process_rtcp_sdes(struct rtp * session,rtcp_t * packet,struct timeval * event_ts)1625 static void process_rtcp_sdes(struct rtp *session, rtcp_t *packet, struct timeval *event_ts)
1626 {
1627 int count = packet->common.count;
1628 struct rtcp_sdes_t *sd = &packet->r.sdes;
1629 rtcp_sdes_item *rsp;
1630 rtcp_sdes_item *rspn;
1631 rtcp_sdes_item *end = (rtcp_sdes_item *) ((uint32_t *)packet + packet->common.length + 1);
1632 source *s;
1633 rtp_event event;
1634
1635 while (--count >= 0) {
1636 rsp = &sd->item[0];
1637 if (rsp >= end) {
1638 break;
1639 }
1640 sd->ssrc = ntohl(sd->ssrc);
1641 s = create_source(session, sd->ssrc, FALSE);
1642 if (s == NULL) {
1643 debug_msg("Can't get valid source entry for 0x%08x, skipping...\n", sd->ssrc);
1644 } else {
1645 for (; rsp->type; rsp = rspn ) {
1646 rspn = (rtcp_sdes_item *)((char*)rsp+rsp->length+2);
1647 if (rspn >= end) {
1648 rsp = rspn;
1649 break;
1650 }
1651 if (rtp_set_sdes(session, sd->ssrc, rsp->type, rsp->data, rsp->length)) {
1652 if (!filter_event(session, sd->ssrc)) {
1653 event.ssrc = sd->ssrc;
1654 event.type = RX_SDES;
1655 event.data = (void *) rsp;
1656 event.ts = event_ts;
1657 session->callback(session, &event);
1658 }
1659 } else {
1660 debug_msg("Invalid sdes item for source 0x%08x, skipping...\n", sd->ssrc);
1661 }
1662 }
1663 }
1664 sd = (struct rtcp_sdes_t *) ((uint32_t *)sd + (((char *)rsp - (char *)sd) >> 2)+1);
1665 }
1666 if (count >= 0) {
1667 debug_msg("Invalid RTCP SDES packet, some items ignored.\n");
1668 }
1669 }
1670
process_rtcp_bye(struct rtp * session,rtcp_t * packet,struct timeval * event_ts)1671 static void process_rtcp_bye(struct rtp *session, rtcp_t *packet, struct timeval *event_ts)
1672 {
1673 int i;
1674 uint32_t ssrc;
1675 rtp_event event;
1676 source *s;
1677
1678 for (i = 0; i < packet->common.count; i++) {
1679 ssrc = ntohl(packet->r.bye.ssrc[i]);
1680 /* This is kind-of strange, since we create a source we are about to delete. */
1681 /* This is done to ensure that the source mentioned in the event which is */
1682 /* passed to the user of the RTP library is valid, and simplify client code. */
1683 create_source(session, ssrc, FALSE);
1684 /* Call the event handler... */
1685 if (!filter_event(session, ssrc)) {
1686 event.ssrc = ssrc;
1687 event.type = RX_BYE;
1688 event.data = NULL;
1689 event.ts = event_ts;
1690 session->callback(session, &event);
1691 }
1692 /* Mark the source as ready for deletion. Sources are not deleted immediately */
1693 /* since some packets may be delayed and arrive after the BYE... */
1694 s = get_source(session, ssrc);
1695 s->got_bye = TRUE;
1696 check_source(s);
1697 session->bye_count++;
1698 }
1699 }
1700
process_rtcp_app(struct rtp * session,rtcp_t * packet,struct timeval * event_ts)1701 static void process_rtcp_app(struct rtp *session, rtcp_t *packet, struct timeval *event_ts)
1702 {
1703 uint32_t ssrc;
1704 rtp_event event;
1705 rtcp_app *app;
1706 source *s;
1707 int data_len;
1708
1709 /* Update the database for this source. */
1710 ssrc = ntohl(packet->r.app.ssrc);
1711 create_source(session, ssrc, FALSE);
1712 s = get_source(session, ssrc);
1713 if (s == NULL) {
1714 /* This should only occur in the event of database malfunction. */
1715 debug_msg("Source 0x%08x invalid, skipping...\n", ssrc);
1716 return;
1717 }
1718 check_source(s);
1719
1720 /* Copy the entire packet, converting the header (only) into host byte order. */
1721 app = (rtcp_app *) xmalloc(RTP_MAX_PACKET_LEN);
1722 app->version = packet->common.version;
1723 app->p = packet->common.p;
1724 app->subtype = packet->common.count;
1725 app->pt = packet->common.pt;
1726 app->length = ntohs(packet->common.length);
1727 app->ssrc = ssrc;
1728 app->name[0] = packet->r.app.name[0];
1729 app->name[1] = packet->r.app.name[1];
1730 app->name[2] = packet->r.app.name[2];
1731 app->name[3] = packet->r.app.name[3];
1732 data_len = (app->length - 2) * 4;
1733 memcpy(app->data, packet->r.app.data, data_len);
1734
1735 /* Callback to the application to process the app packet... */
1736 if (!filter_event(session, ssrc)) {
1737 event.ssrc = ssrc;
1738 event.type = RX_APP;
1739 event.data = (void *) app; /* The callback function MUST free this! */
1740 event.ts = event_ts;
1741 session->callback(session, &event);
1742 }
1743 }
1744
rtp_process_ctrl(struct rtp * session,uint8_t * buffer,int buflen)1745 static void rtp_process_ctrl(struct rtp *session, uint8_t *buffer, int buflen)
1746 {
1747 /* This routine processes incoming RTCP packets */
1748 rtp_event event;
1749 struct timeval event_ts;
1750 rtcp_t *packet;
1751 uint8_t initVec[8] = {0,0,0,0,0,0,0,0};
1752 int first;
1753 uint32_t packet_ssrc = rtp_my_ssrc(session);
1754
1755 gettimeofday(&event_ts, NULL);
1756 if (buflen > 0) {
1757 if (session->encryption_enabled)
1758 {
1759 /* Decrypt the packet... */
1760 (session->decrypt_func)(session, buffer, buflen, initVec);
1761 buffer += 4; /* Skip the random prefix... */
1762 buflen -= 4;
1763 }
1764 if (validate_rtcp(buffer, buflen)) {
1765 first = TRUE;
1766 packet = (rtcp_t *) buffer;
1767 while (packet < (rtcp_t *) (buffer + buflen)) {
1768 switch (packet->common.pt) {
1769 case RTCP_SR:
1770 if (first && !filter_event(session, ntohl(packet->r.sr.sr.ssrc))) {
1771 event.ssrc = ntohl(packet->r.sr.sr.ssrc);
1772 event.type = RX_RTCP_START;
1773 event.data = &buflen;
1774 event.ts = &event_ts;
1775 packet_ssrc = event.ssrc;
1776 session->callback(session, &event);
1777 }
1778 process_rtcp_sr(session, packet, &event_ts);
1779 break;
1780 case RTCP_RR:
1781 if (first && !filter_event(session, ntohl(packet->r.rr.ssrc))) {
1782 event.ssrc = ntohl(packet->r.rr.ssrc);
1783 event.type = RX_RTCP_START;
1784 event.data = &buflen;
1785 event.ts = &event_ts;
1786 packet_ssrc = event.ssrc;
1787 session->callback(session, &event);
1788 }
1789 process_rtcp_rr(session, packet, &event_ts);
1790 break;
1791 case RTCP_SDES:
1792 if (first && !filter_event(session, ntohl(packet->r.sdes.ssrc))) {
1793 event.ssrc = ntohl(packet->r.sdes.ssrc);
1794 event.type = RX_RTCP_START;
1795 event.data = &buflen;
1796 event.ts = &event_ts;
1797 packet_ssrc = event.ssrc;
1798 session->callback(session, &event);
1799 }
1800 process_rtcp_sdes(session, packet, &event_ts);
1801 break;
1802 case RTCP_BYE:
1803 if (first && !filter_event(session, ntohl(packet->r.bye.ssrc[0]))) {
1804 event.ssrc = ntohl(packet->r.bye.ssrc[0]);
1805 event.type = RX_RTCP_START;
1806 event.data = &buflen;
1807 event.ts = &event_ts;
1808 packet_ssrc = event.ssrc;
1809 session->callback(session, &event);
1810 }
1811 process_rtcp_bye(session, packet, &event_ts);
1812 break;
1813 case RTCP_APP:
1814 if (first && !filter_event(session, ntohl(packet->r.app.ssrc))) {
1815 event.ssrc = ntohl(packet->r.app.ssrc);
1816 event.type = RX_RTCP_START;
1817 event.data = &buflen;
1818 event.ts = &event_ts;
1819 packet_ssrc = event.ssrc;
1820 session->callback(session, &event);
1821 }
1822 process_rtcp_app(session, packet, &event_ts);
1823 break;
1824 default:
1825 debug_msg("RTCP packet with unknown type (%d) ignored.\n", packet->common.pt);
1826 break;
1827 }
1828 packet = (rtcp_t *) ((char *) packet + (4 * (ntohs(packet->common.length) + 1)));
1829 first = FALSE;
1830 }
1831 if (session->avg_rtcp_size < 0) {
1832 /* This is the first RTCP packet we've received, set our initial estimate */
1833 /* of the average packet size to be the size of this packet. */
1834 session->avg_rtcp_size = buflen + RTP_LOWER_LAYER_OVERHEAD;
1835 } else {
1836 /* Update our estimate of the average RTCP packet size. The constants are */
1837 /* 1/16 and 15/16 (section 6.3.3 of draft-ietf-avt-rtp-new-02.txt). */
1838 session->avg_rtcp_size = (0.0625 * (buflen + RTP_LOWER_LAYER_OVERHEAD)) + (0.9375 * session->avg_rtcp_size);
1839 }
1840 /* Signal that we've finished processing this packet */
1841 if (!filter_event(session, packet_ssrc)) {
1842 event.ssrc = packet_ssrc;
1843 event.type = RX_RTCP_FINISH;
1844 event.data = NULL;
1845 event.ts = &event_ts;
1846 session->callback(session, &event);
1847 }
1848 } else {
1849 debug_msg("Invalid RTCP packet discarded\n");
1850 session->invalid_rtcp_count++;
1851 }
1852 }
1853 }
1854
1855 /**
1856 * rtp_recv:
1857 * @session: the session pointer (returned by rtp_init())
1858 * @timeout: the amount of time that rtcp_recv() is allowed to block
1859 * @curr_rtp_ts: the current time expressed in units of the media
1860 * timestamp.
1861 *
1862 * Receive RTP packets and dispatch them.
1863 *
1864 * Returns: TRUE if data received, FALSE if the timeout occurred.
1865 */
rtp_recv(struct rtp * session,struct timeval * timeout,uint32_t curr_rtp_ts)1866 int rtp_recv(struct rtp *session, struct timeval *timeout, uint32_t curr_rtp_ts)
1867 {
1868 check_database(session);
1869 udp_fd_zero();
1870 udp_fd_set(session->rtp_socket);
1871 udp_fd_set(session->rtcp_socket);
1872 if (udp_select(timeout) > 0) {
1873 if (udp_fd_isset(session->rtp_socket)) {
1874 rtp_recv_data(session, curr_rtp_ts);
1875 }
1876 if (udp_fd_isset(session->rtcp_socket)) {
1877 uint8_t buffer[RTP_MAX_PACKET_LEN];
1878 int buflen;
1879 buflen = udp_recv(session->rtcp_socket, (char *)buffer, RTP_MAX_PACKET_LEN);
1880 rtp_process_ctrl(session, buffer, buflen);
1881 }
1882 check_database(session);
1883 return TRUE;
1884 }
1885 check_database(session);
1886 return FALSE;
1887 }
1888
1889
1890
1891 /**
1892 * rtp_add_csrc:
1893 * @session: the session pointer (returned by rtp_init())
1894 * @csrc: Constributing SSRC identifier
1895 *
1896 * Adds @csrc to list of contributing sources used in SDES items.
1897 * Used by mixers and transcoders.
1898 *
1899 * Return value: TRUE.
1900 **/
rtp_add_csrc(struct rtp * session,uint32_t csrc)1901 int rtp_add_csrc(struct rtp *session, uint32_t csrc)
1902 {
1903 /* Mark csrc as something for which we should advertise RTCP SDES items, */
1904 /* in addition to our own SDES. */
1905 source *s;
1906
1907 check_database(session);
1908 s = get_source(session, csrc);
1909 if (s == NULL) {
1910 s = create_source(session, csrc, FALSE);
1911 debug_msg("Created source 0x%08x as CSRC\n", csrc);
1912 }
1913 check_source(s);
1914 if (!s->should_advertise_sdes) {
1915 s->should_advertise_sdes = TRUE;
1916 session->csrc_count++;
1917 debug_msg("Added CSRC 0x%08lx as CSRC %d\n", csrc, session->csrc_count);
1918 }
1919 return TRUE;
1920 }
1921
1922 /**
1923 * rtp_del_csrc:
1924 * @session: the session pointer (returned by rtp_init())
1925 * @csrc: Constributing SSRC identifier
1926 *
1927 * Removes @csrc from list of contributing sources used in SDES items.
1928 * Used by mixers and transcoders.
1929 *
1930 * Return value: TRUE on success, FALSE if @csrc is not a valid source.
1931 **/
rtp_del_csrc(struct rtp * session,uint32_t csrc)1932 int rtp_del_csrc(struct rtp *session, uint32_t csrc)
1933 {
1934 source *s;
1935
1936 check_database(session);
1937 s = get_source(session, csrc);
1938 if (s == NULL) {
1939 debug_msg("Invalid source 0x%08x\n", csrc);
1940 return FALSE;
1941 }
1942 check_source(s);
1943 s->should_advertise_sdes = FALSE;
1944 session->csrc_count--;
1945 if (session->last_advertised_csrc >= session->csrc_count) {
1946 session->last_advertised_csrc = 0;
1947 }
1948 return TRUE;
1949 }
1950
1951 /**
1952 * rtp_set_sdes:
1953 * @session: the session pointer (returned by rtp_init())
1954 * @ssrc: the SSRC identifier of a participant
1955 * @type: the SDES type represented by @value
1956 * @value: the SDES description
1957 * @length: the length of the description
1958 *
1959 * Sets session description information associated with participant
1960 * @ssrc. Under normal circumstances applications always use the
1961 * @ssrc of the local participant, this SDES information is
1962 * transmitted in receiver reports. Setting SDES information for
1963 * other participants affects the local SDES entries, but are not
1964 * transmitted onto the network.
1965 *
1966 * Return value: Returns TRUE if participant exists, FALSE otherwise.
1967 **/
rtp_set_sdes(struct rtp * session,uint32_t ssrc,rtcp_sdes_type type,const char * value,int length)1968 int rtp_set_sdes(struct rtp *session, uint32_t ssrc, rtcp_sdes_type type, const char *value, int length)
1969 {
1970 source *s;
1971 char *v;
1972
1973 check_database(session);
1974
1975 s = get_source(session, ssrc);
1976 if (s == NULL) {
1977 debug_msg("Invalid source 0x%08x\n", ssrc);
1978 return FALSE;
1979 }
1980 check_source(s);
1981
1982 v = (char *) xmalloc(length + 1);
1983 memset(v, '\0', length + 1);
1984 memcpy(v, value, length);
1985
1986 switch (type) {
1987 case RTCP_SDES_CNAME:
1988 if (s->cname) xfree(s->cname);
1989 s->cname = v;
1990 break;
1991 case RTCP_SDES_NAME:
1992 if (s->name) xfree(s->name);
1993 s->name = v;
1994 break;
1995 case RTCP_SDES_EMAIL:
1996 if (s->email) xfree(s->email);
1997 s->email = v;
1998 break;
1999 case RTCP_SDES_PHONE:
2000 if (s->phone) xfree(s->phone);
2001 s->phone = v;
2002 break;
2003 case RTCP_SDES_LOC:
2004 if (s->loc) xfree(s->loc);
2005 s->loc = v;
2006 break;
2007 case RTCP_SDES_TOOL:
2008 if (s->tool) xfree(s->tool);
2009 s->tool = v;
2010 break;
2011 case RTCP_SDES_NOTE:
2012 if (s->note) xfree(s->note);
2013 s->note = v;
2014 break;
2015 case RTCP_SDES_PRIV:
2016 if (s->priv) xfree(s->priv);
2017 s->priv = v;
2018 break;
2019 default :
2020 debug_msg("Unknown SDES item (type=%d, value=%s)\n", type, v);
2021 xfree(v);
2022 check_database(session);
2023 return FALSE;
2024 }
2025 check_database(session);
2026 return TRUE;
2027 }
2028
2029 /**
2030 * rtp_get_sdes:
2031 * @session: the session pointer (returned by rtp_init())
2032 * @ssrc: the SSRC identifier of a participant
2033 * @type: the SDES information to retrieve
2034 *
2035 * Recovers session description (SDES) information on participant
2036 * identified with @ssrc. The SDES information associated with a
2037 * source is updated when receiver reports are received. There are
2038 * several different types of SDES information, e.g. username,
2039 * location, phone, email. These are enumerated by #rtcp_sdes_type.
2040 *
2041 * Return value: pointer to string containing SDES description if
2042 * received, NULL otherwise.
2043 */
rtp_get_sdes(struct rtp * session,uint32_t ssrc,rtcp_sdes_type type)2044 const char *rtp_get_sdes(struct rtp *session, uint32_t ssrc, rtcp_sdes_type type)
2045 {
2046 source *s;
2047
2048 check_database(session);
2049
2050 s = get_source(session, ssrc);
2051 if (s == NULL) {
2052 debug_msg("Invalid source 0x%08x\n", ssrc);
2053 return NULL;
2054 }
2055 check_source(s);
2056
2057 switch (type) {
2058 case RTCP_SDES_CNAME:
2059 return s->cname;
2060 case RTCP_SDES_NAME:
2061 return s->name;
2062 case RTCP_SDES_EMAIL:
2063 return s->email;
2064 case RTCP_SDES_PHONE:
2065 return s->phone;
2066 case RTCP_SDES_LOC:
2067 return s->loc;
2068 case RTCP_SDES_TOOL:
2069 return s->tool;
2070 case RTCP_SDES_NOTE:
2071 return s->note;
2072 case RTCP_SDES_PRIV:
2073 return s->priv;
2074 default:
2075 /* This includes RTCP_SDES_PRIV and RTCP_SDES_END */
2076 debug_msg("Unknown SDES item (type=%d)\n", type);
2077 }
2078 return NULL;
2079 }
2080
2081 /**
2082 * rtp_get_sr:
2083 * @session: the session pointer (returned by rtp_init())
2084 * @ssrc: identifier of source
2085 *
2086 * Retrieve the latest sender report made by sender with @ssrc identifier.
2087 *
2088 * Return value: A pointer to an rtcp_sr structure on success, NULL
2089 * otherwise. The pointer must not be freed.
2090 **/
rtp_get_sr(struct rtp * session,uint32_t ssrc)2091 const rtcp_sr *rtp_get_sr(struct rtp *session, uint32_t ssrc)
2092 {
2093 /* Return the last SR received from this ssrc. The */
2094 /* caller MUST NOT free the memory returned to it. */
2095 source *s;
2096
2097 check_database(session);
2098
2099 s = get_source(session, ssrc);
2100 if (s == NULL) {
2101 return NULL;
2102 }
2103 check_source(s);
2104 return s->sr;
2105 }
2106
2107 /**
2108 * rtp_get_rr:
2109 * @session: the session pointer (returned by rtp_init())
2110 * @reporter: participant originating receiver report
2111 * @reportee: participant included in receiver report
2112 *
2113 * Retrieve the latest receiver report on @reportee made by @reporter.
2114 * Provides an indication of other receivers reception service.
2115 *
2116 * Return value: A pointer to a rtcp_rr structure on success, NULL
2117 * otherwise. The pointer must not be freed.
2118 **/
rtp_get_rr(struct rtp * session,uint32_t reporter,uint32_t reportee)2119 const rtcp_rr *rtp_get_rr(struct rtp *session, uint32_t reporter, uint32_t reportee)
2120 {
2121 check_database(session);
2122 return get_rr(session, reporter, reportee);
2123 }
2124
2125 /**
2126 * rtp_send_data:
2127 * @session: the session pointer (returned by rtp_init())
2128 * @rtp_ts: The timestamp reflects the sampling instant of the first octet of the RTP data to be sent. The timestamp is expressed in media units.
2129 * @pt: The payload type identifying the format of the data.
2130 * @m: Marker bit, interpretation defined by media profile of payload.
2131 * @cc: Number of contributing sources (excluding local participant)
2132 * @csrc: Array of SSRC identifiers for contributing sources.
2133 * @data: The RTP data to be sent.
2134 * @data_len: The size @data in bytes.
2135 * @extn: Extension data (if present).
2136 * @extn_len: size of @extn in bytes.
2137 * @extn_type: extension type indicator.
2138 *
2139 * Send an RTP packet. Most media applications will only set the
2140 * @session, @rtp_ts, @pt, @m, @data, @data_len arguments.
2141 *
2142 * Mixers and translators typically set additional contributing sources
2143 * arguments (@cc, @csrc).
2144 *
2145 * Extensions fields (@extn, @extn_len, @extn_type) are for including
2146 * application specific information. When the widest amount of
2147 * inter-operability is required these fields should be avoided as
2148 * some applications discard packets with extensions they do not
2149 * recognize.
2150 *
2151 * Return value: Number of bytes transmitted.
2152 **/
rtp_send_data(struct rtp * session,uint32_t rtp_ts,char pt,int m,int cc,uint32_t * csrc,char * data,int data_len,char * extn,uint16_t extn_len,uint16_t extn_type)2153 int rtp_send_data(struct rtp *session, uint32_t rtp_ts, char pt, int m,
2154 int cc, uint32_t* csrc,
2155 char *data, int data_len,
2156 char *extn, uint16_t extn_len, uint16_t extn_type)
2157 {
2158 int buffer_len, i, rc, pad, pad_len;
2159 uint8_t *buffer;
2160 rtp_packet *packet;
2161 uint8_t initVec[8] = {0,0,0,0,0,0,0,0};
2162
2163 check_database(session);
2164
2165 assert(data_len > 0);
2166
2167 buffer_len = data_len + 12 + (4 * cc);
2168 if (extn != NULL) {
2169 buffer_len += (extn_len + 1) * 4;
2170 }
2171
2172 /* Do we need to pad this packet to a multiple of 64 bits? */
2173 /* This is only needed if encryption is enabled, since DES */
2174 /* only works on multiples of 64 bits. We just calculate */
2175 /* the amount of padding to add here, so we can reserve */
2176 /* space - the actual padding is added later. */
2177 if ((session->encryption_enabled) &&
2178 ((buffer_len % session->encryption_pad_length) != 0)) {
2179 pad = TRUE;
2180 pad_len = session->encryption_pad_length - (buffer_len % session->encryption_pad_length);
2181 buffer_len += pad_len;
2182 assert((buffer_len % session->encryption_pad_length) == 0);
2183 } else {
2184 pad = FALSE;
2185 pad_len = 0;
2186 }
2187
2188 /* Allocate memory for the packet... */
2189 buffer = (uint8_t *) xmalloc(buffer_len + RTP_PACKET_HEADER_SIZE);
2190 packet = (rtp_packet *) buffer;
2191
2192 /* These are internal pointers into the buffer... */
2193 packet->csrc = (uint32_t *) (buffer + RTP_PACKET_HEADER_SIZE + 12);
2194 packet->extn = (uint8_t *) (buffer + RTP_PACKET_HEADER_SIZE + 12 + (4 * cc));
2195 packet->data = (char *) (buffer + RTP_PACKET_HEADER_SIZE + 12 + (4 * cc));
2196 if (extn != NULL) {
2197 packet->data += (extn_len + 1) * 4;
2198 }
2199 /* ...and the actual packet header... */
2200 packet->v = 2;
2201 packet->p = pad;
2202 packet->x = (extn != NULL);
2203 packet->cc = cc;
2204 packet->m = m;
2205 packet->pt = pt;
2206 packet->seq = htons(session->rtp_seq++);
2207 packet->ts = htonl(rtp_ts);
2208 packet->ssrc = htonl(rtp_my_ssrc(session));
2209 /* ...now the CSRC list... */
2210 for (i = 0; i < cc; i++) {
2211 packet->csrc[i] = htonl(csrc[i]);
2212 }
2213 /* ...a header extension? */
2214 if (extn != NULL) {
2215 /* We don't use the packet->extn_type field here, that's for receive only... */
2216 uint16_t *base = (uint16_t *) packet->extn;
2217 base[0] = htons(extn_type);
2218 base[1] = htons(extn_len);
2219 memcpy(packet->extn + 4, extn, extn_len * 4);
2220 }
2221 /* ...and the media data... */
2222 memcpy(packet->data, data, data_len);
2223 /* ...and any padding... */
2224 if (pad) {
2225 for (i = 0; i < pad_len; i++) {
2226 buffer[buffer_len + RTP_PACKET_HEADER_SIZE - pad_len + i] = 0;
2227 }
2228 buffer[buffer_len + RTP_PACKET_HEADER_SIZE - 1] = (char) pad_len;
2229 }
2230
2231 /* Finally, encrypt if desired... */
2232 if (session->encryption_enabled)
2233 {
2234 assert((buffer_len % session->encryption_pad_length) == 0);
2235 (session->encrypt_func)(session, buffer + RTP_PACKET_HEADER_SIZE,
2236 buffer_len, initVec);
2237 }
2238
2239 rc = udp_send(session->rtp_socket, (char *)buffer + RTP_PACKET_HEADER_SIZE, buffer_len);
2240 xfree(buffer);
2241
2242 /* Update the RTCP statistics... */
2243 session->we_sent = TRUE;
2244 session->rtp_pcount += 1;
2245 session->rtp_bcount += buffer_len;
2246 gettimeofday(&session->last_rtp_send_time, NULL);
2247
2248 check_database(session);
2249 return rc;
2250 }
2251
2252 #ifndef _WIN32
rtp_send_data_iov(struct rtp * session,uint32_t rtp_ts,char pt,int m,int cc,uint32_t csrc[],struct iovec * iov,int iov_count,char * extn,uint16_t extn_len,uint16_t extn_type)2253 int rtp_send_data_iov(struct rtp *session, uint32_t rtp_ts, char pt, int m, int cc, uint32_t csrc[], struct iovec *iov, int iov_count, char *extn, uint16_t extn_len, uint16_t extn_type)
2254 {
2255 int buffer_len, i, rc;
2256 uint8_t *buffer;
2257 rtp_packet *packet;
2258 int my_iov_count = iov_count + 1;
2259 struct iovec *my_iov;
2260
2261 /* operation not supported on encrypted sessions */
2262 if ((session->encryption_enabled)) {
2263 return -1;
2264 }
2265
2266 check_database(session);
2267
2268 buffer_len = 12 + (4 * cc);
2269 if (extn != NULL) {
2270 buffer_len += (extn_len + 1) * 4;
2271 }
2272
2273 /* Allocate memory for the packet... */
2274 buffer = (uint8_t *) xmalloc(buffer_len + RTP_PACKET_HEADER_SIZE);
2275 packet = (rtp_packet *) buffer;
2276
2277 /* These are internal pointers into the buffer... */
2278 packet->csrc = (uint32_t *) (buffer + RTP_PACKET_HEADER_SIZE + 12);
2279 packet->extn = (uint8_t *) (buffer + RTP_PACKET_HEADER_SIZE + 12 + (4 * cc));
2280 packet->data = (char *) (buffer + RTP_PACKET_HEADER_SIZE + 12 + (4 * cc));
2281 if (extn != NULL) {
2282 packet->data += (extn_len + 1) * 4;
2283 }
2284 /* ...and the actual packet header... */
2285 packet->v = 2;
2286 packet->p = 0;
2287 packet->x = (extn != NULL);
2288 packet->cc = cc;
2289 packet->m = m;
2290 packet->pt = pt;
2291 packet->seq = htons(session->rtp_seq++);
2292 packet->ts = htonl(rtp_ts);
2293 packet->ssrc = htonl(rtp_my_ssrc(session));
2294 /* ...now the CSRC list... */
2295 for (i = 0; i < cc; i++) {
2296 packet->csrc[i] = htonl(csrc[i]);
2297 }
2298 /* ...a header extension? */
2299 if (extn != NULL) {
2300 /* We don't use the packet->extn_type field here, that's for receive only... */
2301 uint16_t *base = (uint16_t *) packet->extn;
2302 base[0] = htons(extn_type);
2303 base[1] = htons(extn_len);
2304 memcpy(packet->extn + 4, extn, extn_len * 4);
2305 }
2306
2307 /* Add the RTP packet header to the beginning of the iov list */
2308 my_iov = (struct iovec*)xmalloc(my_iov_count * sizeof(struct iovec));
2309
2310 my_iov[0].iov_base = buffer + RTP_PACKET_HEADER_SIZE;
2311 my_iov[0].iov_len = buffer_len;
2312
2313 for (i = 1; i < my_iov_count; i++) {
2314 my_iov[i].iov_base = iov[i-1].iov_base;
2315 my_iov[i].iov_len = iov[i-1].iov_len;
2316 buffer_len += my_iov[i].iov_len;
2317 }
2318
2319 /* Send the data */
2320 rc = udp_sendv(session->rtp_socket, my_iov, my_iov_count);
2321
2322 /* Update the RTCP statistics... */
2323 session->we_sent = TRUE;
2324 session->rtp_pcount += 1;
2325 session->rtp_bcount += buffer_len;
2326
2327 check_database(session);
2328 return rc;
2329 }
2330 #endif
2331
format_report_blocks(rtcp_rr * rrp,int remaining_length,struct rtp * session)2332 static int format_report_blocks(rtcp_rr *rrp, int remaining_length, struct rtp *session)
2333 {
2334 int nblocks = 0;
2335 int h;
2336 source *s;
2337 struct timeval now;
2338
2339 gettimeofday(&now, NULL);
2340
2341 for (h = 0; h < RTP_DB_SIZE; h++) {
2342 for (s = session->db[h]; s != NULL; s = s->next) {
2343 check_source(s);
2344 if ((nblocks == 31) || (remaining_length < 24)) {
2345 break; /* Insufficient space for more report blocks... */
2346 }
2347 if (!s->init)
2348 break;
2349
2350 if (s->sender) {
2351 /* Much of this is taken from A.3 of draft-ietf-avt-rtp-new-01.txt */
2352 int extended_max = s->cycles + s->max_seq;
2353 int expected = extended_max - s->base_seq + 1;
2354 int lost = expected - s->received;
2355 int expected_interval = expected - s->expected_prior;
2356 int received_interval = s->received - s->received_prior;
2357 int lost_interval = expected_interval - received_interval;
2358 int fraction;
2359 uint32_t lsr;
2360 uint32_t dlsr;
2361
2362 s->expected_prior = expected;
2363 s->received_prior = s->received;
2364 if (expected_interval == 0 || lost_interval <= 0) {
2365 fraction = 0;
2366 } else {
2367 fraction = (lost_interval << 8) / expected_interval;
2368 }
2369
2370 if (s->sr == NULL) {
2371 lsr = 0;
2372 dlsr = 0;
2373 } else {
2374 lsr = ntp64_to_ntp32(s->sr->ntp_sec, s->sr->ntp_frac);
2375 dlsr = (uint32_t)(tv_diff(now, s->last_sr) * 65536);
2376 }
2377 rrp->ssrc = htonl(s->ssrc);
2378 rrp->fract_lost = fraction;
2379 rrp->total_lost = lost & 0x00ffffff;
2380 rrp->last_seq = htonl(extended_max);
2381 rrp->jitter = htonl(s->jitter / 16);
2382 rrp->lsr = htonl(lsr);
2383 rrp->dlsr = htonl(dlsr);
2384 rrp++;
2385 remaining_length -= 24;
2386 nblocks++;
2387 s->sender = FALSE;
2388 session->sender_count--;
2389 if (session->sender_count == 0) {
2390 break; /* No point continuing, since we've reported on all senders... */
2391 }
2392 }
2393 }
2394 }
2395 return nblocks;
2396 }
2397
format_rtcp_sr(uint8_t * buffer,int buflen,struct rtp * session,uint32_t rtp_ts)2398 static uint8_t *format_rtcp_sr(uint8_t *buffer, int buflen, struct rtp *session, uint32_t rtp_ts)
2399 {
2400 /* Write an RTCP SR into buffer, returning a pointer to */
2401 /* the next byte after the header we have just written. */
2402 rtcp_t *packet = (rtcp_t *) buffer;
2403 int remaining_length;
2404 uint32_t ntp_sec, ntp_frac;
2405
2406 assert(buflen >= 28); /* ...else there isn't space for the header and sender report */
2407
2408 packet->common.version = 2;
2409 packet->common.p = 0;
2410 packet->common.count = 0;
2411 packet->common.pt = RTCP_SR;
2412 packet->common.length = htons(1);
2413
2414 ntp64_time(&ntp_sec, &ntp_frac);
2415
2416 packet->r.sr.sr.ssrc = htonl(rtp_my_ssrc(session));
2417 packet->r.sr.sr.ntp_sec = htonl(ntp_sec);
2418 packet->r.sr.sr.ntp_frac = htonl(ntp_frac);
2419 packet->r.sr.sr.rtp_ts = htonl(rtp_ts);
2420 packet->r.sr.sr.sender_pcount = htonl(session->rtp_pcount);
2421 packet->r.sr.sr.sender_bcount = htonl(session->rtp_bcount);
2422
2423 /* Add report blocks, until we either run out of senders */
2424 /* to report upon or we run out of space in the buffer. */
2425 remaining_length = buflen - 28;
2426 packet->common.count = format_report_blocks(packet->r.sr.rr, remaining_length, session);
2427 packet->common.length = htons((uint16_t) (6 + (packet->common.count * 6)));
2428 return buffer + 28 + (24 * packet->common.count);
2429 }
2430
format_rtcp_rr(uint8_t * buffer,int buflen,struct rtp * session)2431 static uint8_t *format_rtcp_rr(uint8_t *buffer, int buflen, struct rtp *session)
2432 {
2433 /* Write an RTCP RR into buffer, returning a pointer to */
2434 /* the next byte after the header we have just written. */
2435 rtcp_t *packet = (rtcp_t *) buffer;
2436 int remaining_length;
2437
2438 assert(buflen >= 8); /* ...else there isn't space for the header */
2439
2440 packet->common.version = 2;
2441 packet->common.p = 0;
2442 packet->common.count = 0;
2443 packet->common.pt = RTCP_RR;
2444 packet->common.length = htons(1);
2445 packet->r.rr.ssrc = htonl(session->my_ssrc);
2446
2447 /* Add report blocks, until we either run out of senders */
2448 /* to report upon or we run out of space in the buffer. */
2449 remaining_length = buflen - 8;
2450 packet->common.count = format_report_blocks(packet->r.rr.rr, remaining_length, session);
2451 packet->common.length = htons((uint16_t) (1 + (packet->common.count * 6)));
2452 return buffer + 8 + (24 * packet->common.count);
2453 }
2454
add_sdes_item(uint8_t * buf,int buflen,int type,const char * val)2455 static int add_sdes_item(uint8_t *buf, int buflen, int type, const char *val)
2456 {
2457 /* Fill out an SDES item. It is assumed that the item is a NULL */
2458 /* terminated string. */
2459 rtcp_sdes_item *shdr = (rtcp_sdes_item *) buf;
2460 int namelen;
2461
2462 if (val == NULL) {
2463 debug_msg("Cannot format SDES item. type=%d val=%xp\n", type, val);
2464 return 0;
2465 }
2466 shdr->type = type;
2467 namelen = strlen(val);
2468 shdr->length = namelen;
2469 strncpy(shdr->data, val, buflen - 2); /* The "-2" accounts for the other shdr fields */
2470 return namelen + 2;
2471 }
2472
format_rtcp_sdes(uint8_t * buffer,int buflen,uint32_t ssrc,struct rtp * session)2473 static uint8_t *format_rtcp_sdes(uint8_t *buffer, int buflen, uint32_t ssrc, struct rtp *session)
2474 {
2475 /* From draft-ietf-avt-profile-new-00: */
2476 /* "Applications may use any of the SDES items described in the */
2477 /* RTP specification. While CNAME information is sent every */
2478 /* reporting interval, other items should be sent only every third */
2479 /* reporting interval, with NAME sent seven out of eight times */
2480 /* within that slot and the remaining SDES items cyclically taking */
2481 /* up the eighth slot, as defined in Section 6.2.2 of the RTP */
2482 /* specification. In other words, NAME is sent in RTCP packets 1, */
2483 /* 4, 7, 10, 13, 16, 19, while, say, EMAIL is used in RTCP packet */
2484 /* 22". */
2485 uint8_t *packet = buffer;
2486 rtcp_common *common = (rtcp_common *) buffer;
2487 const char *item;
2488 size_t remaining_len;
2489 int pad;
2490
2491 assert(buflen > (int) sizeof(rtcp_common));
2492
2493 common->version = 2;
2494 common->p = 0;
2495 common->count = 1;
2496 common->pt = RTCP_SDES;
2497 common->length = 0;
2498 packet += sizeof(common);
2499
2500 *((uint32_t *) packet) = htonl(ssrc);
2501 packet += 4;
2502
2503 remaining_len = buflen - (packet - buffer);
2504 item = rtp_get_sdes(session, ssrc, RTCP_SDES_CNAME);
2505 if ((item != NULL) && ((strlen(item) + (size_t) 2) <= remaining_len)) {
2506 packet += add_sdes_item(packet, remaining_len, RTCP_SDES_CNAME, item);
2507 }
2508
2509 remaining_len = buflen - (packet - buffer);
2510 item = rtp_get_sdes(session, ssrc, RTCP_SDES_NOTE);
2511 if ((item != NULL) && ((strlen(item) + (size_t) 2) <= remaining_len)) {
2512 packet += add_sdes_item(packet, remaining_len, RTCP_SDES_NOTE, item);
2513 }
2514
2515 remaining_len = buflen - (packet - buffer);
2516 if ((session->sdes_count_pri % 3) == 0) {
2517 session->sdes_count_sec++;
2518 if ((session->sdes_count_sec % 8) == 0) {
2519 /* Note that the following is supposed to fall-through the cases */
2520 /* until one is found to send... The lack of break statements in */
2521 /* the switch is not a bug. */
2522 switch (session->sdes_count_ter % 5) {
2523 case 0: item = rtp_get_sdes(session, ssrc, RTCP_SDES_TOOL);
2524 if ((item != NULL) && ((strlen(item) + (size_t) 2) <= remaining_len)) {
2525 packet += add_sdes_item(packet, remaining_len, RTCP_SDES_TOOL, item);
2526 break;
2527 }
2528 case 1: item = rtp_get_sdes(session, ssrc, RTCP_SDES_EMAIL);
2529 if ((item != NULL) && ((strlen(item) + (size_t) 2) <= remaining_len)) {
2530 packet += add_sdes_item(packet, remaining_len, RTCP_SDES_EMAIL, item);
2531 break;
2532 }
2533 case 2: item = rtp_get_sdes(session, ssrc, RTCP_SDES_PHONE);
2534 if ((item != NULL) && ((strlen(item) + (size_t) 2) <= remaining_len)) {
2535 packet += add_sdes_item(packet, remaining_len, RTCP_SDES_PHONE, item);
2536 break;
2537 }
2538 case 3: item = rtp_get_sdes(session, ssrc, RTCP_SDES_LOC);
2539 if ((item != NULL) && ((strlen(item) + (size_t) 2) <= remaining_len)) {
2540 packet += add_sdes_item(packet, remaining_len, RTCP_SDES_LOC, item);
2541 break;
2542 }
2543 case 4: item = rtp_get_sdes(session, ssrc, RTCP_SDES_PRIV);
2544 if ((item != NULL) && ((strlen(item) + (size_t) 2) <= remaining_len)) {
2545 packet += add_sdes_item(packet, remaining_len, RTCP_SDES_PRIV, item);
2546 break;
2547 }
2548 }
2549 session->sdes_count_ter++;
2550 } else {
2551 item = rtp_get_sdes(session, ssrc, RTCP_SDES_NAME);
2552 if (item != NULL) {
2553 packet += add_sdes_item(packet, remaining_len, RTCP_SDES_NAME, item);
2554 }
2555 }
2556 }
2557 session->sdes_count_pri++;
2558
2559 /* Pad to a multiple of 4 bytes... */
2560 pad = 4 - ((packet - buffer) & 0x3);
2561 while (pad--) {
2562 *packet++ = RTCP_SDES_END;
2563 }
2564
2565 common->length = htons((uint16_t) (((int) (packet - buffer) / 4) - 1));
2566
2567 return packet;
2568 }
2569
format_rtcp_app(uint8_t * buffer,int buflen,uint32_t ssrc,rtcp_app * app)2570 static uint8_t *format_rtcp_app(uint8_t *buffer, int buflen, uint32_t ssrc, rtcp_app *app)
2571 {
2572 /* Write an RTCP APP into the outgoing packet buffer. */
2573 rtcp_app *packet = (rtcp_app *) buffer;
2574 int pkt_octets = (app->length + 1) * 4;
2575 int data_octets = pkt_octets - 12;
2576
2577 assert(data_octets >= 0); /* ...else not a legal APP packet. */
2578 assert(buflen >= pkt_octets); /* ...else there isn't space for the APP packet. */
2579
2580 /* Copy one APP packet from "app" to "packet". */
2581 packet->version = RTP_VERSION;
2582 packet->p = app->p;
2583 packet->subtype = app->subtype;
2584 packet->pt = RTCP_APP;
2585 packet->length = htons(app->length);
2586 packet->ssrc = htonl(ssrc);
2587 memcpy(packet->name, app->name, 4);
2588 memcpy(packet->data, app->data, data_octets);
2589
2590 /* Return a pointer to the byte that immediately follows the last byte written. */
2591 return buffer + pkt_octets;
2592 }
2593
send_rtcp(struct rtp * session,uint32_t rtp_ts,rtcp_app_callback appcallback)2594 static void send_rtcp(struct rtp *session, uint32_t rtp_ts,
2595 rtcp_app_callback appcallback)
2596 {
2597 /* Construct and send an RTCP packet. The order in which packets are packed into a */
2598 /* compound packet is defined by section 6.1 of draft-ietf-avt-rtp-new-03.txt and */
2599 /* we follow the recommended order. */
2600 uint8_t buffer[RTP_MAX_PACKET_LEN + MAX_ENCRYPTION_PAD]; /* The +8 is to allow for padding when encrypting */
2601 uint8_t *ptr = buffer;
2602 uint8_t *old_ptr;
2603 uint8_t *lpt; /* the last packet in the compound */
2604 rtcp_app *app;
2605 uint8_t initVec[8] = {0,0,0,0,0,0,0,0};
2606
2607 check_database(session);
2608 /* If encryption is enabled, add a 32 bit random prefix to the packet */
2609 if (session->encryption_enabled)
2610 {
2611 *((uint32_t *) ptr) = lbl_random();
2612 ptr += 4;
2613 }
2614
2615 /* The first RTCP packet in the compound packet MUST always be a report packet... */
2616 if (session->we_sent) {
2617 ptr = format_rtcp_sr(ptr, RTP_MAX_PACKET_LEN - (ptr - buffer), session, rtp_ts);
2618 } else {
2619 ptr = format_rtcp_rr(ptr, RTP_MAX_PACKET_LEN - (ptr - buffer), session);
2620 }
2621 /* Add the appropriate SDES items to the packet... This should really be after the */
2622 /* insertion of the additional report blocks, but if we do that there are problems */
2623 /* with us being unable to fit the SDES packet in when we run out of buffer space */
2624 /* adding RRs. The correct fix would be to calculate the length of the SDES items */
2625 /* in advance and subtract this from the buffer length but this is non-trivial and */
2626 /* probably not worth it. */
2627 lpt = ptr;
2628 ptr = format_rtcp_sdes(ptr, RTP_MAX_PACKET_LEN - (ptr - buffer), rtp_my_ssrc(session), session);
2629
2630 /* If we have any CSRCs, we include SDES items for each of them in turn... */
2631 if (session->csrc_count > 0) {
2632 ptr = format_rtcp_sdes(ptr, RTP_MAX_PACKET_LEN - (ptr - buffer), next_csrc(session), session);
2633 }
2634
2635 /* Following that, additional RR packets SHOULD follow if there are more than 31 */
2636 /* senders, such that the reports do not fit into the initial packet. We give up */
2637 /* if there is insufficient space in the buffer: this is bad, since we always drop */
2638 /* the reports from the same sources (those at the end of the hash table). */
2639 while ((session->sender_count > 0) && ((RTP_MAX_PACKET_LEN - (ptr - buffer)) >= 8)) {
2640 lpt = ptr;
2641 ptr = format_rtcp_rr(ptr, RTP_MAX_PACKET_LEN - (ptr - buffer), session);
2642 }
2643
2644 /* Finish with as many APP packets as the application will provide. */
2645 old_ptr = ptr;
2646 if (appcallback) {
2647 while ((app = (*appcallback)(session, rtp_ts, RTP_MAX_PACKET_LEN - (ptr - buffer)))) {
2648 lpt = ptr;
2649 ptr = format_rtcp_app(ptr, RTP_MAX_PACKET_LEN - (ptr - buffer), rtp_my_ssrc(session), app);
2650 assert(ptr > old_ptr);
2651 old_ptr = ptr;
2652 assert(RTP_MAX_PACKET_LEN - (ptr - buffer) >= 0);
2653 }
2654 }
2655
2656 /* And encrypt if desired... */
2657 if (session->encryption_enabled)
2658 {
2659 if (((ptr - buffer) % session->encryption_pad_length) != 0) {
2660 /* Add padding to the last packet in the compound, if necessary. */
2661 /* We don't have to worry about overflowing the buffer, since we */
2662 /* intentionally allocated it 8 bytes longer to allow for this. */
2663 int padlen = session->encryption_pad_length - ((ptr - buffer) % session->encryption_pad_length);
2664 int i;
2665
2666 for (i = 0; i < padlen-1; i++) {
2667 *(ptr++) = '\0';
2668 }
2669 *(ptr++) = (uint8_t) padlen;
2670 assert(((ptr - buffer) % session->encryption_pad_length) == 0);
2671
2672 ((rtcp_t *) lpt)->common.p = TRUE;
2673 ((rtcp_t *) lpt)->common.length = htons((int16_t)(((ptr - lpt) / 4) - 1));
2674 }
2675 (session->encrypt_func)(session, buffer, ptr - buffer, initVec);
2676 }
2677 udp_send(session->rtcp_socket, (char *)buffer, ptr - buffer);
2678
2679 /* Loop the data back to ourselves so local participant can */
2680 /* query own stats when using unicast or multicast with no */
2681 /* loopback. */
2682 rtp_process_ctrl(session, buffer, ptr - buffer);
2683 check_database(session);
2684 }
2685
2686 /**
2687 * rtp_send_ctrl:
2688 * @session: the session pointer (returned by rtp_init())
2689 * @rtp_ts: the current time expressed in units of the media timestamp.
2690 * @appcallback: a callback to create an APP RTCP packet, if needed.
2691 *
2692 * Checks RTCP timer and sends RTCP data when nececessary. The
2693 * interval between RTCP packets is randomized over an interval that
2694 * depends on the session bandwidth, the number of participants, and
2695 * whether the local participant is a sender. This function should be
2696 * called at least once per second, and can be safely called more
2697 * frequently.
2698 */
rtp_send_ctrl(struct rtp * session,uint32_t rtp_ts,rtcp_app_callback appcallback)2699 void rtp_send_ctrl(struct rtp *session, uint32_t rtp_ts, rtcp_app_callback appcallback)
2700 {
2701 /* Send an RTCP packet, if one is due... */
2702 struct timeval curr_time;
2703
2704 check_database(session);
2705 gettimeofday(&curr_time, NULL);
2706 if (tv_gt(curr_time, session->next_rtcp_send_time)) {
2707 /* The RTCP transmission timer has expired. The following */
2708 /* implements draft-ietf-avt-rtp-new-02.txt section 6.3.6 */
2709 int h;
2710 source *s;
2711 struct timeval new_send_time;
2712 double new_interval;
2713
2714 new_interval = rtcp_interval(session) / (session->csrc_count + 1);
2715 new_send_time = session->last_rtcp_send_time;
2716 tv_add(&new_send_time, new_interval);
2717 if (tv_gt(curr_time, new_send_time)) {
2718 send_rtcp(session, rtp_ts, appcallback);
2719 session->initial_rtcp = FALSE;
2720 session->last_rtcp_send_time = curr_time;
2721 session->next_rtcp_send_time = curr_time;
2722 tv_add(&(session->next_rtcp_send_time), rtcp_interval(session) / (session->csrc_count + 1));
2723 /* We're starting a new RTCP reporting interval, zero out */
2724 /* the per-interval statistics. */
2725 session->sender_count = 0;
2726 for (h = 0; h < RTP_DB_SIZE; h++) {
2727 for (s = session->db[h]; s != NULL; s = s->next) {
2728 check_source(s);
2729 s->sender = FALSE;
2730 }
2731 }
2732 } else {
2733 session->next_rtcp_send_time = new_send_time;
2734 }
2735 session->ssrc_count_prev = session->ssrc_count;
2736 }
2737 check_database(session);
2738 }
2739
2740 /**
2741 * rtp_update:
2742 * @session: the session pointer (returned by rtp_init())
2743 *
2744 * Trawls through the internal data structures and performs
2745 * housekeeping. This function should be called at least once per
2746 * second. It uses an internal timer to limit the number of passes
2747 * through the data structures to once per second, it can be safely
2748 * called more frequently.
2749 */
rtp_update(struct rtp * session)2750 void rtp_update(struct rtp *session)
2751 {
2752 /* Perform housekeeping on the source database... */
2753 int h;
2754 source *s, *n;
2755 struct timeval curr_time;
2756 double delay;
2757
2758 gettimeofday(&curr_time, NULL);
2759 if (tv_diff(curr_time, session->last_update) < 1.0) {
2760 /* We only perform housekeeping once per second... */
2761 return;
2762 }
2763 session->last_update = curr_time;
2764
2765 /* Update we_sent (section 6.3.8 of RTP spec) */
2766 delay = tv_diff(curr_time, session->last_rtp_send_time);
2767 if (delay >= 2 * rtcp_interval(session)) {
2768 session->we_sent = FALSE;
2769 }
2770
2771 check_database(session);
2772
2773 for (h = 0; h < RTP_DB_SIZE; h++) {
2774 for (s = session->db[h]; s != NULL; s = n) {
2775 check_source(s);
2776 n = s->next;
2777 /* Expire sources which haven't been heard from for a long time. */
2778 /* Section 6.2.1 of the RTP specification details the timers used. */
2779
2780 /* How long since we last heard from this source? */
2781 delay = tv_diff(curr_time, s->last_active);
2782
2783 /* Check if we've received a BYE packet from this source. */
2784 /* If we have, and it was received more than 2 seconds ago */
2785 /* then the source is deleted. The arbitrary 2 second delay */
2786 /* is to ensure that all delayed packets are received before */
2787 /* the source is timed out. */
2788 if (s->got_bye && (delay > 2.0)) {
2789 debug_msg("Deleting source 0x%08lx due to reception of BYE %f seconds ago...\n", s->ssrc, delay);
2790 delete_source(session, s->ssrc);
2791 }
2792
2793 /* Sources are marked as inactive if they haven't been heard */
2794 /* from for more than 2 intervals (RTP section 6.3.5) */
2795 if ((s->ssrc != rtp_my_ssrc(session)) && (delay > (session->rtcp_interval * 2))) {
2796 if (s->sender) {
2797 s->sender = FALSE;
2798 session->sender_count--;
2799 }
2800 }
2801
2802 /* If a source hasn't been heard from for more than 5 RTCP */
2803 /* reporting intervals, we delete it from our database... */
2804 if ((s->ssrc != rtp_my_ssrc(session)) && (delay > (session->rtcp_interval * 5))) {
2805 debug_msg("Deleting source 0x%08lx due to timeout...\n", s->ssrc);
2806 delete_source(session, s->ssrc);
2807 }
2808 }
2809 }
2810
2811 /* Timeout those reception reports which haven't been refreshed for a long time */
2812 timeout_rr(session, &curr_time);
2813 check_database(session);
2814 }
2815
rtp_send_bye_now(struct rtp * session)2816 static void rtp_send_bye_now(struct rtp *session)
2817 {
2818 /* Send a BYE packet immediately. This is an internal function, */
2819 /* hidden behind the rtp_send_bye() wrapper which implements BYE */
2820 /* reconsideration for the application. */
2821 uint8_t buffer[RTP_MAX_PACKET_LEN + MAX_ENCRYPTION_PAD]; /* + 8 to allow for padding when encrypting */
2822 uint8_t *ptr = buffer;
2823 rtcp_common *common;
2824 uint8_t initVec[8] = {0,0,0,0,0,0,0,0};
2825
2826 check_database(session);
2827 /* If encryption is enabled, add a 32 bit random prefix to the packet */
2828 if (session->encryption_enabled) {
2829 *((uint32_t *) ptr) = lbl_random();
2830 ptr += 4;
2831 }
2832
2833 ptr = format_rtcp_rr(ptr, RTP_MAX_PACKET_LEN - (ptr - buffer), session);
2834 common = (rtcp_common *) ptr;
2835
2836 common->version = 2;
2837 common->p = 0;
2838 common->count = 1;
2839 common->pt = RTCP_BYE;
2840 common->length = htons(1);
2841 ptr += sizeof(common);
2842
2843 *((uint32_t *) ptr) = htonl(session->my_ssrc);
2844 ptr += 4;
2845
2846 if (session->encryption_enabled) {
2847 if (((ptr - buffer) % session->encryption_pad_length) != 0) {
2848 /* Add padding to the last packet in the compound, if necessary. */
2849 /* We don't have to worry about overflowing the buffer, since we */
2850 /* intentionally allocated it 8 bytes longer to allow for this. */
2851 int padlen = session->encryption_pad_length - ((ptr - buffer) % session->encryption_pad_length);
2852 int i;
2853
2854 for (i = 0; i < padlen-1; i++) {
2855 *(ptr++) = '\0';
2856 }
2857 *(ptr++) = (uint8_t) padlen;
2858
2859 common->p = TRUE;
2860 common->length = htons((int16_t)(((ptr - (uint8_t *) common) / 4) - 1));
2861 }
2862 assert(((ptr - buffer) % session->encryption_pad_length) == 0);
2863 (session->encrypt_func)(session, buffer, ptr - buffer, initVec);
2864 }
2865 udp_send(session->rtcp_socket, (char *)buffer, ptr - buffer);
2866 /* Loop the data back to ourselves so local participant can */
2867 /* query own stats when using unicast or multicast with no */
2868 /* loopback. */
2869 rtp_process_ctrl(session, buffer, ptr - buffer);
2870 check_database(session);
2871 }
2872
2873 /**
2874 * rtp_send_bye:
2875 * @session: The RTP session
2876 *
2877 * Sends a BYE message on the RTP session, indicating that this
2878 * participant is leaving the session. The process of sending a
2879 * BYE may take some time, and this function will block until
2880 * it is complete. During this time, RTCP events are reported
2881 * to the application via the callback function (data packets
2882 * are silently discarded).
2883 */
rtp_send_bye(struct rtp * session)2884 void rtp_send_bye(struct rtp *session)
2885 {
2886 struct timeval curr_time, timeout, new_send_time;
2887 uint8_t buffer[RTP_MAX_PACKET_LEN];
2888 int buflen;
2889 double new_interval;
2890
2891 check_database(session);
2892
2893 /* "...a participant which never sent an RTP or RTCP packet MUST NOT send */
2894 /* a BYE packet when they leave the group." (section 6.3.7 of RTP spec) */
2895 if ((session->we_sent == FALSE) && (session->initial_rtcp == TRUE)) {
2896 debug_msg("Silent BYE\n");
2897 return;
2898 }
2899
2900 /* If the session is small, send an immediate BYE. Otherwise, we delay and */
2901 /* perform BYE reconsideration as needed. */
2902 if (session->ssrc_count < 50) {
2903 rtp_send_bye_now(session);
2904 } else {
2905 gettimeofday(&curr_time, NULL);
2906 session->sending_bye = TRUE;
2907 session->last_rtcp_send_time = curr_time;
2908 session->next_rtcp_send_time = curr_time;
2909 session->bye_count = 1;
2910 session->initial_rtcp = TRUE;
2911 session->we_sent = FALSE;
2912 session->sender_count = 0;
2913 session->avg_rtcp_size = 70.0 + RTP_LOWER_LAYER_OVERHEAD; /* FIXME */
2914 tv_add(&session->next_rtcp_send_time, rtcp_interval(session) / (session->csrc_count + 1));
2915
2916 debug_msg("Preparing to send BYE...\n");
2917 while (1) {
2918 /* Schedule us to block in udp_select() until the time we are due to send our */
2919 /* BYE packet. If we receive an RTCP packet from another participant before */
2920 /* then, we are woken up to handle it... */
2921 timeout.tv_sec = 0;
2922 timeout.tv_usec = 0;
2923 tv_add(&timeout, tv_diff(session->next_rtcp_send_time, curr_time));
2924 udp_fd_zero();
2925 udp_fd_set(session->rtcp_socket);
2926 if ((udp_select(&timeout) > 0) && udp_fd_isset(session->rtcp_socket)) {
2927 /* We woke up because an RTCP packet was received; process it... */
2928 buflen = udp_recv(session->rtcp_socket, (char *)buffer, RTP_MAX_PACKET_LEN);
2929 rtp_process_ctrl(session, buffer, buflen);
2930 }
2931 /* Is it time to send our BYE? */
2932 gettimeofday(&curr_time, NULL);
2933 new_interval = rtcp_interval(session) / (session->csrc_count + 1);
2934 new_send_time = session->last_rtcp_send_time;
2935 tv_add(&new_send_time, new_interval);
2936 if (tv_gt(curr_time, new_send_time)) {
2937 debug_msg("Sent BYE...\n");
2938 rtp_send_bye_now(session);
2939 break;
2940 }
2941 /* No, we reconsider... */
2942 session->next_rtcp_send_time = new_send_time;
2943 debug_msg("Reconsidered sending BYE... delay = %f\n", tv_diff(session->next_rtcp_send_time, curr_time));
2944 /* ...and perform housekeeping in the usual manner */
2945 rtp_update(session);
2946 }
2947 }
2948 }
2949
2950 /**
2951 * rtp_done:
2952 * @session: the RTP session to finish
2953 *
2954 * Free the state associated with the given RTP session. This function does
2955 * not send any packets (e.g. an RTCP BYE) - an application which wishes to
2956 * exit in a clean manner should call rtp_send_bye() first.
2957 */
rtp_done(struct rtp * session)2958 void rtp_done(struct rtp *session)
2959 {
2960 int i;
2961 source *s, *n;
2962
2963 check_database(session);
2964 /* In delete_source, check database gets called and this assumes */
2965 /* first added and last removed is us. */
2966 for (i = 0; i < RTP_DB_SIZE; i++) {
2967 s = session->db[i];
2968 while (s != NULL) {
2969 n = s->next;
2970 if (s->ssrc != session->my_ssrc) {
2971 delete_source(session,session->db[i]->ssrc);
2972 }
2973 s = n;
2974 }
2975 }
2976
2977 delete_source(session, session->my_ssrc);
2978
2979 /*
2980 * Introduce a memory leak until we add algorithm-specific
2981 * cleanup functions.
2982 if (session->encryption_key != NULL) {
2983 xfree(session->encryption_key);
2984 }
2985 */
2986
2987 udp_exit(session->rtp_socket);
2988 udp_exit(session->rtcp_socket);
2989 xfree(session->addr);
2990 xfree(session->opt);
2991 xfree(session);
2992 }
2993
2994 /**
2995 * rtp_set_encryption_key:
2996 * @session: The RTP session.
2997 * @passphrase: The user-provided "pass phrase" to map to an encryption key.
2998 *
2999 * Converts the user supplied key into a form suitable for use with RTP
3000 * and install it as the active key. Passing in NULL as the passphrase
3001 * disables encryption. The passphrase is converted into a DES key as
3002 * specified in RFC1890, that is:
3003 *
3004 * - convert to canonical form
3005 *
3006 * - derive an MD5 hash of the canonical form
3007 *
3008 * - take the first 56 bits of the MD5 hash
3009 *
3010 * - add parity bits to form a 64 bit key
3011 *
3012 * Note that versions of rat prior to 4.1.2 do not convert the passphrase
3013 * to canonical form before taking the MD5 hash, and so will
3014 * not be compatible for keys which are non-invarient under this step.
3015 *
3016 * Determine from the user's encryption key which encryption
3017 * mechanism we're using. Per the RTP RFC, if the key is of the form
3018 *
3019 * string/key
3020 *
3021 * then "string" is the name of the encryption algorithm, and
3022 * "key" is the key to be used. If no / is present, then the
3023 * algorithm is assumed to be (the appropriate variant of) DES.
3024 *
3025 * Returns: TRUE on success, FALSE on failure.
3026 */
rtp_set_encryption_key(struct rtp * session,const char * passphrase)3027 int rtp_set_encryption_key(struct rtp* session, const char *passphrase)
3028 {
3029 char *canonical_passphrase;
3030 u_char hash[16];
3031 MD5_CTX context;
3032 char *slash;
3033
3034 check_database(session);
3035 if (session->encryption_algorithm != NULL) {
3036 xfree(session->encryption_algorithm);
3037 session->encryption_algorithm = NULL;
3038 }
3039
3040 if (passphrase == NULL) {
3041 /* A NULL passphrase means disable encryption... */
3042 session->encryption_enabled = 0;
3043 check_database(session);
3044 return TRUE;
3045 }
3046
3047 debug_msg("Enabling RTP/RTCP encryption\n");
3048 session->encryption_enabled = 1;
3049
3050 /*
3051 * Determine which algorithm we're using.
3052 */
3053
3054 slash = strchr(passphrase, '/');
3055 if (slash == 0)
3056 {
3057 session->encryption_algorithm = xstrdup("DES");
3058 }
3059 else
3060 {
3061 int l = slash - passphrase;
3062 session->encryption_algorithm = xmalloc(l + 1);
3063 strncpy(session->encryption_algorithm, passphrase, l);
3064 session->encryption_algorithm[l] = '\0';
3065 passphrase = slash + 1;
3066 }
3067
3068 debug_msg("Initializing encryption, algorithm is '%s'\n",
3069 session->encryption_algorithm);
3070
3071 /* Step 1: convert to canonical form, comprising the following steps: */
3072 /* a) convert the input string to the ISO 10646 character set, using */
3073 /* the UTF-8 encoding as specified in Annex P to ISO/IEC */
3074 /* 10646-1:1993 (ASCII characters require no mapping, but ISO */
3075 /* 8859-1 characters do); */
3076 /* b) remove leading and trailing white space characters; */
3077 /* c) replace one or more contiguous white space characters by a */
3078 /* single space (ASCII or UTF-8 0x20); */
3079 /* d) convert all letters to lower case and replace sequences of */
3080 /* characters and non-spacing accents with a single character, */
3081 /* where possible. */
3082 canonical_passphrase = (char *) xstrdup(passphrase); /* FIXME */
3083
3084 /* Step 2: derive an MD5 hash */
3085 MD5Init(&context);
3086 MD5Update(&context, (u_char *) canonical_passphrase, strlen(canonical_passphrase));
3087 MD5Final((u_char *) hash, &context);
3088
3089 /* Initialize the encryption algorithm we've received */
3090
3091 if (strcmp(session->encryption_algorithm, "DES") == 0)
3092 {
3093 return des_initialize(session, hash, sizeof(hash));
3094 }
3095 else if (strcmp(session->encryption_algorithm, "Rijndael") == 0)
3096 {
3097 return rijndael_initialize(session, hash, sizeof(hash));
3098 }
3099 else
3100 {
3101 debug_msg("Encryption algorithm \"%s\" not found\n",
3102 session->encryption_algorithm);
3103 return FALSE;
3104 }
3105 }
3106
des_initialize(struct rtp * session,u_char * hash,int hashlen)3107 static int des_initialize(struct rtp *session, u_char *hash, int hashlen)
3108 {
3109 char *key;
3110 int i, j, k;
3111
3112 UNUSED(hashlen);
3113
3114 session->encryption_pad_length = 8;
3115 session->encrypt_func = des_encrypt;
3116 session->decrypt_func = des_decrypt;
3117
3118 if (session->crypto_state.des.encryption_key != NULL) {
3119 xfree(session->crypto_state.des.encryption_key);
3120 }
3121
3122 key = session->crypto_state.des.encryption_key = (char *) xmalloc(8);
3123
3124 /* Step 3: take first 56 bits of the MD5 hash */
3125 key[0] = hash[0];
3126 key[1] = hash[0] << 7 | hash[1] >> 1;
3127 key[2] = hash[1] << 6 | hash[2] >> 2;
3128 key[3] = hash[2] << 5 | hash[3] >> 3;
3129 key[4] = hash[3] << 4 | hash[4] >> 4;
3130 key[5] = hash[4] << 3 | hash[5] >> 5;
3131 key[6] = hash[5] << 2 | hash[6] >> 6;
3132 key[7] = hash[6] << 1;
3133
3134 /* Step 4: add parity bits */
3135 for (i = 0; i < 8; ++i) {
3136 k = key[i] & 0xfe;
3137 j = k;
3138 j ^= j >> 4;
3139 j ^= j >> 2;
3140 j ^= j >> 1;
3141 j = (j & 1) ^ 1;
3142 key[i] = k | j;
3143 }
3144
3145 check_database(session);
3146 return TRUE;
3147 }
3148
des_encrypt(struct rtp * session,unsigned char * data,unsigned int size,unsigned char * initVec)3149 static int des_encrypt(struct rtp *session, unsigned char *data,
3150 unsigned int size, unsigned char *initVec)
3151 {
3152 qfDES_CBC_e((unsigned char *)session->crypto_state.des.encryption_key,
3153 data, size, initVec);
3154 return TRUE;
3155 }
3156
des_decrypt(struct rtp * session,unsigned char * data,unsigned int size,unsigned char * initVec)3157 static int des_decrypt(struct rtp *session, unsigned char *data,
3158 unsigned int size, unsigned char *initVec)
3159 {
3160 qfDES_CBC_d((unsigned char *)session->crypto_state.des.encryption_key,
3161 data, size, initVec);
3162 return TRUE;
3163 }
3164
rijndael_initialize(struct rtp * session,u_char * hash,int hash_len)3165 static int rijndael_initialize(struct rtp *session, u_char *hash, int hash_len)
3166 {
3167 int rc;
3168
3169 session->encryption_pad_length = 16;
3170 session->encrypt_func = rijndael_encrypt;
3171 session->decrypt_func = rijndael_decrypt;
3172
3173 rc = makeKey(&session->crypto_state.rijndael.keyInstEncrypt,
3174 DIR_ENCRYPT, hash_len * 8, (char *) hash);
3175 if (rc < 0)
3176 {
3177 debug_msg("makeKey failed: %d\n", rc);
3178 return FALSE;
3179 }
3180
3181 rc = makeKey(&session->crypto_state.rijndael.keyInstDecrypt,
3182 DIR_DECRYPT, hash_len * 8, (char *) hash);
3183 if (rc < 0)
3184 {
3185 debug_msg("makeKey failed: %d\n", rc);
3186 return FALSE;
3187 }
3188
3189 rc = cipherInit(&session->crypto_state.rijndael.cipherInst,
3190 MODE_ECB, NULL);
3191 if (rc < 0)
3192 {
3193 debug_msg("cipherInst failed: %d\n", rc);
3194 return FALSE;
3195 }
3196 return TRUE;
3197 }
3198
rijndael_encrypt(struct rtp * session,unsigned char * data,unsigned int size,unsigned char * initVec)3199 static int rijndael_encrypt(struct rtp *session, unsigned char *data,
3200 unsigned int size, unsigned char *initVec)
3201 {
3202 int rc;
3203
3204 UNUSED(initVec);
3205
3206 /*
3207 * Try doing this in place. If it doesn't work that way,
3208 * we'll have to allocate a buffer and copy back.
3209 */
3210 rc = blockEncrypt(&session->crypto_state.rijndael.cipherInst,
3211 &session->crypto_state.rijndael.keyInstEncrypt,
3212 data, size * 8, data);
3213 return rc;
3214 }
3215
rijndael_decrypt(struct rtp * session,unsigned char * data,unsigned int size,unsigned char * initVec)3216 static int rijndael_decrypt(struct rtp *session, unsigned char *data,
3217 unsigned int size, unsigned char *initVec)
3218 {
3219 int rc;
3220 UNUSED(initVec);
3221
3222 /*
3223 * Try doing this in place. If it doesn't work that way,
3224 * we'll have to allocate a buffer and copy back.
3225 */
3226 rc = blockDecrypt(&session->crypto_state.rijndael.cipherInst,
3227 &session->crypto_state.rijndael.keyInstDecrypt,
3228 data, size * 8, data);
3229 return rc;
3230 }
3231
3232 /**
3233 * rtp_get_addr:
3234 * @session: The RTP Session.
3235 *
3236 * Returns: The session's destination address, as set when creating the
3237 * session with rtp_init() or rtp_init_if().
3238 */
rtp_get_addr(struct rtp * session)3239 char *rtp_get_addr(struct rtp *session)
3240 {
3241 check_database(session);
3242 return session->addr;
3243 }
3244
3245 /**
3246 * rtp_get_rx_port:
3247 * @session: The RTP Session.
3248 *
3249 * Returns: The UDP port to which this session is bound, as set when
3250 * creating the session with rtp_init() or rtp_init_if().
3251 */
rtp_get_rx_port(struct rtp * session)3252 uint16_t rtp_get_rx_port(struct rtp *session)
3253 {
3254 check_database(session);
3255 return session->rx_port;
3256 }
3257
3258 /**
3259 * rtp_get_tx_port:
3260 * @session: The RTP Session.
3261 *
3262 * Returns: The UDP port to which RTP packets are transmitted, as set
3263 * when creating the session with rtp_init() or rtp_init_if().
3264 */
rtp_get_tx_port(struct rtp * session)3265 uint16_t rtp_get_tx_port(struct rtp *session)
3266 {
3267 check_database(session);
3268 return session->tx_port;
3269 }
3270
3271 /**
3272 * rtp_get_ttl:
3273 * @session: The RTP Session.
3274 *
3275 * Returns: The session's TTL, as set when creating the session with
3276 * rtp_init() or rtp_init_if().
3277 */
rtp_get_ttl(struct rtp * session)3278 int rtp_get_ttl(struct rtp *session)
3279 {
3280 check_database(session);
3281 return session->ttl;
3282 }
3283
3284