Merged revisions 30874 via svnmerge from
[asterisk-bristuff.git] / udptl.c
blob045c89d8f1ba057b3519a9c6c0c9fbf1482c625d
1 /*
2 * Asterisk -- A telephony toolkit for Linux.
4 * UDPTL support for T.38
5 *
6 * Copyright (C) 2005, Steve Underwood, partly based on RTP code which is
7 * Copyright (C) 1999-2006, Digium, Inc.
9 * Steve Underwood <steveu@coppice.org>
11 * This program is free software, distributed under the terms of
12 * the GNU General Public License
14 * This version is disclaimed to DIGIUM for inclusion in the Asterisk project.
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <sys/time.h>
21 #include <signal.h>
22 #include <errno.h>
23 #include <unistd.h>
24 #include <netinet/in.h>
25 #include <sys/time.h>
26 #include <sys/socket.h>
27 #include <arpa/inet.h>
28 #include <fcntl.h>
30 #include "asterisk.h"
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
34 #include "asterisk/udptl.h"
35 #include "asterisk/frame.h"
36 #include "asterisk/logger.h"
37 #include "asterisk/options.h"
38 #include "asterisk/channel.h"
39 #include "asterisk/acl.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/config.h"
42 #include "asterisk/lock.h"
43 #include "asterisk/utils.h"
44 #include "asterisk/cli.h"
45 #include "asterisk/unaligned.h"
46 #include "asterisk/utils.h"
48 #define UDPTL_MTU 1200
50 #if !defined(FALSE)
51 #define FALSE 0
52 #endif
53 #if !defined(TRUE)
54 #define TRUE (!FALSE)
55 #endif
57 static int udptlstart = 0;
58 static int udptlend = 0;
59 static int udptldebug = 0; /* Are we debugging? */
60 static struct sockaddr_in udptldebugaddr; /* Debug packets to/from this host */
61 #ifdef SO_NO_CHECK
62 static int nochecksums = 0;
63 #endif
64 static int udptlfectype = 0;
65 static int udptlfecentries = 0;
66 static int udptlfecspan = 0;
67 static int udptlmaxdatagram = 0;
69 #define LOCAL_FAX_MAX_DATAGRAM 400
70 #define MAX_FEC_ENTRIES 5
71 #define MAX_FEC_SPAN 5
73 #define UDPTL_BUF_MASK 15
75 typedef struct {
76 int buf_len;
77 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
78 } udptl_fec_tx_buffer_t;
80 typedef struct {
81 int buf_len;
82 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
83 int fec_len[MAX_FEC_ENTRIES];
84 uint8_t fec[MAX_FEC_ENTRIES][LOCAL_FAX_MAX_DATAGRAM];
85 int fec_span;
86 int fec_entries;
87 } udptl_fec_rx_buffer_t;
89 struct ast_udptl {
90 int fd;
91 char resp;
92 struct ast_frame f[16];
93 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
94 unsigned int lasteventseqn;
95 int nat;
96 int flags;
97 struct sockaddr_in us;
98 struct sockaddr_in them;
99 int *ioid;
100 uint16_t seqno;
101 struct sched_context *sched;
102 struct io_context *io;
103 void *data;
104 ast_udptl_callback callback;
105 int udptl_offered_from_local;
107 /*! This option indicates the error correction scheme used in transmitted UDPTL
108 packets. */
109 int error_correction_scheme;
111 /*! This option indicates the number of error correction entries transmitted in
112 UDPTL packets. */
113 int error_correction_entries;
115 /*! This option indicates the span of the error correction entries in transmitted
116 UDPTL packets (FEC only). */
117 int error_correction_span;
119 /*! This option indicates the maximum size of a UDPTL packet that can be accepted by
120 the remote device. */
121 int far_max_datagram_size;
123 /*! This option indicates the maximum size of a UDPTL packet that we are prepared to
124 accept. */
125 int local_max_datagram_size;
127 int verbose;
129 struct sockaddr_in far;
131 int tx_seq_no;
132 int rx_seq_no;
133 int rx_expected_seq_no;
135 udptl_fec_tx_buffer_t tx[UDPTL_BUF_MASK + 1];
136 udptl_fec_rx_buffer_t rx[UDPTL_BUF_MASK + 1];
139 static struct ast_udptl_protocol *protos = NULL;
141 static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, int len);
142 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, uint8_t *ifp, int ifp_len);
144 static inline int udptl_debug_test_addr(struct sockaddr_in *addr)
146 if (udptldebug == 0)
147 return 0;
148 if (udptldebugaddr.sin_addr.s_addr) {
149 if (((ntohs(udptldebugaddr.sin_port) != 0)
150 && (udptldebugaddr.sin_port != addr->sin_port))
151 || (udptldebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
152 return 0;
154 return 1;
157 static int decode_length(uint8_t *buf, int limit, int *len, int *pvalue)
159 if ((buf[*len] & 0x80) == 0) {
160 if (*len >= limit)
161 return -1;
162 *pvalue = buf[*len];
163 (*len)++;
164 return 0;
166 if ((buf[*len] & 0x40) == 0) {
167 if (*len >= limit - 1)
168 return -1;
169 *pvalue = (buf[*len] & 0x3F) << 8;
170 (*len)++;
171 *pvalue |= buf[*len];
172 (*len)++;
173 return 0;
175 if (*len >= limit)
176 return -1;
177 *pvalue = (buf[*len] & 0x3F) << 14;
178 (*len)++;
179 /* Indicate we have a fragment */
180 return 1;
182 /*- End of function --------------------------------------------------------*/
184 static int decode_open_type(uint8_t *buf, int limit, int *len, const uint8_t **p_object, int *p_num_octets)
186 int octet_cnt;
187 int octet_idx;
188 int stat;
189 int i;
190 const uint8_t **pbuf;
192 for (octet_idx = 0, *p_num_octets = 0; ; octet_idx += octet_cnt) {
193 if ((stat = decode_length(buf, limit, len, &octet_cnt)) < 0)
194 return -1;
195 if (octet_cnt > 0) {
196 *p_num_octets += octet_cnt;
198 pbuf = &p_object[octet_idx];
199 i = 0;
200 /* Make sure the buffer contains at least the number of bits requested */
201 if ((*len + octet_cnt) > limit)
202 return -1;
204 *pbuf = &buf[*len];
205 *len += octet_cnt;
207 if (stat == 0)
208 break;
210 return 0;
212 /*- End of function --------------------------------------------------------*/
214 static int encode_length(uint8_t *buf, int *len, int value)
216 int multiplier;
218 if (value < 0x80) {
219 /* 1 octet */
220 buf[*len] = value;
221 (*len)++;
222 return value;
224 if (value < 0x4000) {
225 /* 2 octets */
226 /* Set the first bit of the first octet */
227 buf[*len] = ((0x8000 | value) >> 8) & 0xFF;
228 (*len)++;
229 buf[*len] = value & 0xFF;
230 (*len)++;
231 return value;
233 /* Fragmentation */
234 multiplier = (value < 0x10000) ? (value >> 14) : 4;
235 /* Set the first 2 bits of the octet */
236 buf[*len] = 0xC0 | multiplier;
237 (*len)++;
238 return multiplier << 14;
240 /*- End of function --------------------------------------------------------*/
242 static int encode_open_type(uint8_t *buf, int *len, const uint8_t *data, int num_octets)
244 int enclen;
245 int octet_idx;
246 uint8_t zero_byte;
248 /* If open type is of zero length, add a single zero byte (10.1) */
249 if (num_octets == 0) {
250 zero_byte = 0;
251 data = &zero_byte;
252 num_octets = 1;
254 /* Encode the open type */
255 for (octet_idx = 0; ; num_octets -= enclen, octet_idx += enclen) {
256 if ((enclen = encode_length(buf, len, num_octets)) < 0)
257 return -1;
258 if (enclen > 0) {
259 memcpy(&buf[*len], &data[octet_idx], enclen);
260 *len += enclen;
262 if (enclen >= num_octets)
263 break;
266 return 0;
268 /*- End of function --------------------------------------------------------*/
270 static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, int len)
272 int stat;
273 int stat2;
274 int i;
275 int j;
276 int k;
277 int l;
278 int m;
279 int x;
280 int limit;
281 int which;
282 int ptr;
283 int count;
284 int total_count;
285 int seq_no;
286 const uint8_t *ifp;
287 const uint8_t *data;
288 int ifp_len;
289 int repaired[16];
290 const uint8_t *bufs[16];
291 int lengths[16];
292 int span;
293 int entries;
294 int ifp_no;
296 ptr = 0;
297 ifp_no = 0;
298 s->f[0].prev = NULL;
299 s->f[0].next = NULL;
301 /* Decode seq_number */
302 if (ptr + 2 > len)
303 return -1;
304 seq_no = (buf[0] << 8) | buf[1];
305 ptr += 2;
307 /* Break out the primary packet */
308 if ((stat = decode_open_type(buf, len, &ptr, &ifp, &ifp_len)) != 0)
309 return -1;
310 /* Decode error_recovery */
311 if (ptr + 1 > len)
312 return -1;
313 if ((buf[ptr++] & 0x80) == 0) {
314 /* Secondary packet mode for error recovery */
315 if (seq_no > s->rx_seq_no) {
316 /* We received a later packet than we expected, so we need to check if we can fill in the gap from the
317 secondary packets. */
318 total_count = 0;
319 do {
320 if ((stat2 = decode_length(buf, len, &ptr, &count)) < 0)
321 return -1;
322 for (i = 0; i < count; i++) {
323 if ((stat = decode_open_type(buf, len, &ptr, &bufs[total_count + i], &lengths[total_count + i])) != 0)
324 return -1;
326 total_count += count;
328 while (stat2 > 0);
329 /* Step through in reverse order, so we go oldest to newest */
330 for (i = total_count; i > 0; i--) {
331 if (seq_no - i >= s->rx_seq_no) {
332 /* This one wasn't seen before */
333 /* Decode the secondary IFP packet */
334 //fprintf(stderr, "Secondary %d, len %d\n", seq_no - i, lengths[i - 1]);
335 s->f[ifp_no].frametype = AST_FRAME_MODEM;
336 s->f[ifp_no].subclass = AST_MODEM_T38;
338 s->f[ifp_no].mallocd = 0;
339 //s->f[ifp_no].???seq_no = seq_no - i;
340 s->f[ifp_no].datalen = lengths[i - 1];
341 s->f[ifp_no].data = (uint8_t *) bufs[i - 1];
342 s->f[ifp_no].offset = 0;
343 s->f[ifp_no].src = "UDPTL";
344 if (ifp_no > 0) {
345 s->f[ifp_no].prev = &s->f[ifp_no - 1];
346 s->f[ifp_no - 1].next = &s->f[ifp_no];
348 s->f[ifp_no].next = NULL;
349 ifp_no++;
353 /* If packets are received out of sequence, we may have already processed this packet from the error
354 recovery information in a packet already received. */
355 if (seq_no >= s->rx_seq_no) {
356 /* Decode the primary IFP packet */
357 s->f[ifp_no].frametype = AST_FRAME_MODEM;
358 s->f[ifp_no].subclass = AST_MODEM_T38;
360 s->f[ifp_no].mallocd = 0;
361 //s->f[ifp_no].???seq_no = seq_no;
362 s->f[ifp_no].datalen = ifp_len;
363 s->f[ifp_no].data = (uint8_t *) ifp;
364 s->f[ifp_no].offset = 0;
365 s->f[ifp_no].src = "UDPTL";
366 if (ifp_no > 0) {
367 s->f[ifp_no].prev = &s->f[ifp_no - 1];
368 s->f[ifp_no - 1].next = &s->f[ifp_no];
370 s->f[ifp_no].next = NULL;
373 else
375 /* FEC mode for error recovery */
376 /* Our buffers cannot tolerate overlength IFP packets in FEC mode */
377 if (ifp_len > LOCAL_FAX_MAX_DATAGRAM)
378 return -1;
379 /* Update any missed slots in the buffer */
380 for ( ; seq_no > s->rx_seq_no; s->rx_seq_no++) {
381 x = s->rx_seq_no & UDPTL_BUF_MASK;
382 s->rx[x].buf_len = -1;
383 s->rx[x].fec_len[0] = 0;
384 s->rx[x].fec_span = 0;
385 s->rx[x].fec_entries = 0;
388 x = seq_no & UDPTL_BUF_MASK;
390 memset(repaired, 0, sizeof(repaired));
392 /* Save the new IFP packet */
393 memcpy(s->rx[x].buf, ifp, ifp_len);
394 s->rx[x].buf_len = ifp_len;
395 repaired[x] = TRUE;
397 /* Decode the FEC packets */
398 /* The span is defined as an unconstrained integer, but will never be more
399 than a small value. */
400 if (ptr + 2 > len)
401 return -1;
402 if (buf[ptr++] != 1)
403 return -1;
404 span = buf[ptr++];
405 s->rx[x].fec_span = span;
407 /* The number of entries is defined as a length, but will only ever be a small
408 value. Treat it as such. */
409 if (ptr + 1 > len)
410 return -1;
411 entries = buf[ptr++];
412 s->rx[x].fec_entries = entries;
414 /* Decode the elements */
415 for (i = 0; i < entries; i++) {
416 if ((stat = decode_open_type(buf, len, &ptr, &data, &s->rx[x].fec_len[i])) != 0)
417 return -1;
418 if (s->rx[x].fec_len[i] > LOCAL_FAX_MAX_DATAGRAM)
419 return -1;
421 /* Save the new FEC data */
422 memcpy(s->rx[x].fec[i], data, s->rx[x].fec_len[i]);
423 #if 0
424 fprintf(stderr, "FEC: ");
425 for (j = 0; j < s->rx[x].fec_len[i]; j++)
426 fprintf(stderr, "%02X ", data[j]);
427 fprintf(stderr, "\n");
428 #endif
431 /* See if we can reconstruct anything which is missing */
432 /* TODO: this does not comprehensively hunt back and repair everything that is possible */
433 for (l = x; l != ((x - (16 - span*entries)) & UDPTL_BUF_MASK); l = (l - 1) & UDPTL_BUF_MASK) {
434 if (s->rx[l].fec_len[0] <= 0)
435 continue;
436 for (m = 0; m < s->rx[l].fec_entries; m++) {
437 limit = (l + m) & UDPTL_BUF_MASK;
438 for (which = -1, k = (limit - s->rx[l].fec_span*s->rx[l].fec_entries) & UDPTL_BUF_MASK; k != limit; k = (k + s->rx[l].fec_entries) & UDPTL_BUF_MASK) {
439 if (s->rx[k].buf_len <= 0)
440 which = (which == -1) ? k : -2;
442 if (which >= 0) {
443 /* Repairable */
444 for (j = 0; j < s->rx[l].fec_len[m]; j++) {
445 s->rx[which].buf[j] = s->rx[l].fec[m][j];
446 for (k = (limit - s->rx[l].fec_span*s->rx[l].fec_entries) & UDPTL_BUF_MASK; k != limit; k = (k + s->rx[l].fec_entries) & UDPTL_BUF_MASK)
447 s->rx[which].buf[j] ^= (s->rx[k].buf_len > j) ? s->rx[k].buf[j] : 0;
449 s->rx[which].buf_len = s->rx[l].fec_len[m];
450 repaired[which] = TRUE;
454 /* Now play any new packets forwards in time */
455 for (l = (x + 1) & UDPTL_BUF_MASK, j = seq_no - UDPTL_BUF_MASK; l != x; l = (l + 1) & UDPTL_BUF_MASK, j++) {
456 if (repaired[l]) {
457 //fprintf(stderr, "Fixed packet %d, len %d\n", j, l);
458 s->f[ifp_no].frametype = AST_FRAME_MODEM;
459 s->f[ifp_no].subclass = AST_MODEM_T38;
461 s->f[ifp_no].mallocd = 0;
462 //s->f[ifp_no].???seq_no = j;
463 s->f[ifp_no].datalen = s->rx[l].buf_len;
464 s->f[ifp_no].data = s->rx[l].buf;
465 s->f[ifp_no].offset = 0;
466 s->f[ifp_no].src = "UDPTL";
467 if (ifp_no > 0) {
468 s->f[ifp_no].prev = &s->f[ifp_no - 1];
469 s->f[ifp_no - 1].next = &s->f[ifp_no];
471 s->f[ifp_no].next = NULL;
472 ifp_no++;
475 /* Decode the primary IFP packet */
476 s->f[ifp_no].frametype = AST_FRAME_MODEM;
477 s->f[ifp_no].subclass = AST_MODEM_T38;
479 s->f[ifp_no].mallocd = 0;
480 //s->f[ifp_no].???seq_no = j;
481 s->f[ifp_no].datalen = ifp_len;
482 s->f[ifp_no].data = (uint8_t *) ifp;
483 s->f[ifp_no].offset = 0;
484 s->f[ifp_no].src = "UDPTL";
485 if (ifp_no > 0) {
486 s->f[ifp_no].prev = &s->f[ifp_no - 1];
487 s->f[ifp_no - 1].next = &s->f[ifp_no];
489 s->f[ifp_no].next = NULL;
492 s->rx_seq_no = seq_no + 1;
493 return 0;
495 /*- End of function --------------------------------------------------------*/
497 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, uint8_t *ifp, int ifp_len)
499 uint8_t fec[LOCAL_FAX_MAX_DATAGRAM];
500 int i;
501 int j;
502 int seq;
503 int entry;
504 int entries;
505 int span;
506 int m;
507 int len;
508 int limit;
509 int high_tide;
511 seq = s->tx_seq_no & 0xFFFF;
513 /* Map the sequence number to an entry in the circular buffer */
514 entry = seq & UDPTL_BUF_MASK;
516 /* We save the message in a circular buffer, for generating FEC or
517 redundancy sets later on. */
518 s->tx[entry].buf_len = ifp_len;
519 memcpy(s->tx[entry].buf, ifp, ifp_len);
521 /* Build the UDPTLPacket */
523 len = 0;
524 /* Encode the sequence number */
525 buf[len++] = (seq >> 8) & 0xFF;
526 buf[len++] = seq & 0xFF;
528 /* Encode the primary IFP packet */
529 if (encode_open_type(buf, &len, ifp, ifp_len) < 0)
530 return -1;
532 /* Encode the appropriate type of error recovery information */
533 switch (s->error_correction_scheme)
535 case UDPTL_ERROR_CORRECTION_NONE:
536 /* Encode the error recovery type */
537 buf[len++] = 0x00;
538 /* The number of entries will always be zero, so it is pointless allowing
539 for the fragmented case here. */
540 if (encode_length(buf, &len, 0) < 0)
541 return -1;
542 break;
543 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
544 /* Encode the error recovery type */
545 buf[len++] = 0x00;
546 if (s->tx_seq_no > s->error_correction_entries)
547 entries = s->error_correction_entries;
548 else
549 entries = s->tx_seq_no;
550 /* The number of entries will always be small, so it is pointless allowing
551 for the fragmented case here. */
552 if (encode_length(buf, &len, entries) < 0)
553 return -1;
554 /* Encode the elements */
555 for (i = 0; i < entries; i++) {
556 j = (entry - i - 1) & UDPTL_BUF_MASK;
557 if (encode_open_type(buf, &len, s->tx[j].buf, s->tx[j].buf_len) < 0)
558 return -1;
560 break;
561 case UDPTL_ERROR_CORRECTION_FEC:
562 span = s->error_correction_span;
563 entries = s->error_correction_entries;
564 if (seq < s->error_correction_span*s->error_correction_entries) {
565 /* In the initial stages, wind up the FEC smoothly */
566 entries = seq/s->error_correction_span;
567 if (seq < s->error_correction_span)
568 span = 0;
570 /* Encode the error recovery type */
571 buf[len++] = 0x80;
572 /* Span is defined as an inconstrained integer, which it dumb. It will only
573 ever be a small value. Treat it as such. */
574 buf[len++] = 1;
575 buf[len++] = span;
576 /* The number of entries is defined as a length, but will only ever be a small
577 value. Treat it as such. */
578 buf[len++] = entries;
579 for (m = 0; m < entries; m++) {
580 /* Make an XOR'ed entry the maximum length */
581 limit = (entry + m) & UDPTL_BUF_MASK;
582 high_tide = 0;
583 for (i = (limit - span*entries) & UDPTL_BUF_MASK; i != limit; i = (i + entries) & UDPTL_BUF_MASK) {
584 if (high_tide < s->tx[i].buf_len) {
585 for (j = 0; j < high_tide; j++)
586 fec[j] ^= s->tx[i].buf[j];
587 for ( ; j < s->tx[i].buf_len; j++)
588 fec[j] = s->tx[i].buf[j];
589 high_tide = s->tx[i].buf_len;
590 } else {
591 for (j = 0; j < s->tx[i].buf_len; j++)
592 fec[j] ^= s->tx[i].buf[j];
595 if (encode_open_type(buf, &len, fec, high_tide) < 0)
596 return -1;
598 break;
601 if (s->verbose)
602 fprintf(stderr, "\n");
604 s->tx_seq_no++;
605 return len;
608 int ast_udptl_fd(struct ast_udptl *udptl)
610 return udptl->fd;
613 void ast_udptl_set_data(struct ast_udptl *udptl, void *data)
615 udptl->data = data;
618 void ast_udptl_set_callback(struct ast_udptl *udptl, ast_udptl_callback callback)
620 udptl->callback = callback;
623 void ast_udptl_setnat(struct ast_udptl *udptl, int nat)
625 udptl->nat = nat;
628 static int udptlread(int *id, int fd, short events, void *cbdata)
630 struct ast_udptl *udptl = cbdata;
631 struct ast_frame *f;
633 if ((f = ast_udptl_read(udptl))) {
634 if (udptl->callback)
635 udptl->callback(udptl, f, udptl->data);
637 return 1;
640 struct ast_frame *ast_udptl_read(struct ast_udptl *udptl)
642 int res;
643 struct sockaddr_in sin;
644 socklen_t len;
645 uint16_t seqno = 0;
646 char iabuf[INET_ADDRSTRLEN];
647 uint16_t *udptlheader;
649 len = sizeof(sin);
651 /* Cache where the header will go */
652 res = recvfrom(udptl->fd,
653 udptl->rawdata + AST_FRIENDLY_OFFSET,
654 sizeof(udptl->rawdata) - AST_FRIENDLY_OFFSET,
656 (struct sockaddr *) &sin,
657 &len);
658 udptlheader = (uint16_t *)(udptl->rawdata + AST_FRIENDLY_OFFSET);
659 if (res < 0) {
660 if (errno != EAGAIN)
661 ast_log(LOG_WARNING, "UDPTL read error: %s\n", strerror(errno));
662 if (errno == EBADF)
663 CRASH;
664 return &ast_null_frame;
667 /* Ignore if the other side hasn't been given an address yet. */
668 if (!udptl->them.sin_addr.s_addr || !udptl->them.sin_port)
669 return &ast_null_frame;
671 if (udptl->nat) {
672 /* Send to whoever sent to us */
673 if ((udptl->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
674 (udptl->them.sin_port != sin.sin_port)) {
675 memcpy(&udptl->them, &sin, sizeof(udptl->them));
676 ast_log(LOG_DEBUG, "UDPTL NAT: Using address %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), udptl->them.sin_addr), ntohs(udptl->them.sin_port));
680 if (udptl_debug_test_addr(&sin)) {
681 ast_verbose("Got UDPTL packet from %s:%d (type %d, seq %d, len %d)\n",
682 ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), 0, seqno, res);
684 #if 0
685 printf("Got UDPTL packet from %s:%d (seq %d, len = %d)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), seqno, res);
686 #endif
687 udptl_rx_packet(udptl, udptl->rawdata + AST_FRIENDLY_OFFSET, res);
689 return &udptl->f[0];
692 void ast_udptl_offered_from_local(struct ast_udptl* udptl, int local)
694 if (udptl)
695 udptl->udptl_offered_from_local = local;
696 else
697 ast_log(LOG_WARNING, "udptl structure is null\n");
700 int ast_udptl_get_error_correction_scheme(struct ast_udptl* udptl)
702 if (udptl)
703 return udptl->error_correction_scheme;
704 else {
705 ast_log(LOG_WARNING, "udptl structure is null\n");
706 return -1;
710 void ast_udptl_set_error_correction_scheme(struct ast_udptl* udptl, int ec)
712 if (udptl) {
713 switch (ec) {
714 case UDPTL_ERROR_CORRECTION_FEC:
715 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
716 break;
717 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
718 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
719 break;
720 case UDPTL_ERROR_CORRECTION_NONE:
721 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_NONE;
722 break;
723 default:
724 ast_log(LOG_WARNING, "error correction parameter invalid");
726 } else
727 ast_log(LOG_WARNING, "udptl structure is null\n");
730 int ast_udptl_get_local_max_datagram(struct ast_udptl* udptl)
732 if (udptl)
733 return udptl->local_max_datagram_size;
734 else {
735 ast_log(LOG_WARNING, "udptl structure is null\n");
736 return -1;
740 int ast_udptl_get_far_max_datagram(struct ast_udptl* udptl)
742 if (udptl)
743 return udptl->far_max_datagram_size;
744 else {
745 ast_log(LOG_WARNING, "udptl structure is null\n");
746 return -1;
750 void ast_udptl_set_local_max_datagram(struct ast_udptl* udptl, int max_datagram)
752 if (udptl)
753 udptl->local_max_datagram_size = max_datagram;
754 else
755 ast_log(LOG_WARNING, "udptl structure is null\n");
758 void ast_udptl_set_far_max_datagram(struct ast_udptl* udptl, int max_datagram)
760 if (udptl)
761 udptl->far_max_datagram_size = max_datagram;
762 else
763 ast_log(LOG_WARNING, "udptl structure is null\n");
766 struct ast_udptl *ast_udptl_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int callbackmode, struct in_addr addr)
768 struct ast_udptl *udptl;
769 int x;
770 int startplace;
771 int i;
772 long int flags;
774 if ((udptl = malloc(sizeof(struct ast_udptl))) == NULL)
775 return NULL;
776 memset(udptl, 0, sizeof(struct ast_udptl));
778 if (udptlfectype == 2)
779 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
780 else if (udptlfectype == 1)
781 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
782 else
783 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_NONE;
784 udptl->error_correction_span = udptlfecspan;
785 udptl->error_correction_entries = udptlfecentries;
787 udptl->far_max_datagram_size = udptlmaxdatagram;
788 udptl->local_max_datagram_size = udptlmaxdatagram;
790 memset(&udptl->rx, 0, sizeof(udptl->rx));
791 memset(&udptl->tx, 0, sizeof(udptl->tx));
792 for (i = 0; i <= UDPTL_BUF_MASK; i++) {
793 udptl->rx[i].buf_len = -1;
794 udptl->tx[i].buf_len = -1;
797 udptl->seqno = ast_random() & 0xffff;
798 udptl->them.sin_family = AF_INET;
799 udptl->us.sin_family = AF_INET;
801 if ((udptl->fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
802 free(udptl);
803 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
804 return NULL;
806 flags = fcntl(udptl->fd, F_GETFL);
807 fcntl(udptl->fd, F_SETFL, flags | O_NONBLOCK);
808 #ifdef SO_NO_CHECK
809 if (nochecksums)
810 setsockopt(udptl->fd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
811 #endif
812 /* Find us a place */
813 x = (ast_random() % (udptlend - udptlstart)) + udptlstart;
814 startplace = x;
815 for (;;) {
816 udptl->us.sin_port = htons(x);
817 udptl->us.sin_addr = addr;
818 if (bind(udptl->fd, (struct sockaddr *) &udptl->us, sizeof(udptl->us)) == 0)
819 break;
820 if (errno != EADDRINUSE) {
821 ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
822 close(udptl->fd);
823 free(udptl);
824 return NULL;
826 if (++x > udptlend)
827 x = udptlstart;
828 if (x == startplace) {
829 ast_log(LOG_WARNING, "No UDPTL ports remaining\n");
830 close(udptl->fd);
831 free(udptl);
832 return NULL;
835 if (io && sched && callbackmode) {
836 /* Operate this one in a callback mode */
837 udptl->sched = sched;
838 udptl->io = io;
839 udptl->ioid = ast_io_add(udptl->io, udptl->fd, udptlread, AST_IO_IN, udptl);
841 return udptl;
844 struct ast_udptl *ast_udptl_new(struct sched_context *sched, struct io_context *io, int callbackmode)
846 struct in_addr ia;
847 memset(&ia, 0, sizeof(ia));
848 return ast_udptl_new_with_bindaddr(sched, io, callbackmode, ia);
851 int ast_udptl_settos(struct ast_udptl *udptl, int tos)
853 int res;
855 if ((res = setsockopt(udptl->fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
856 ast_log(LOG_WARNING, "UDPTL unable to set TOS to %d\n", tos);
857 return res;
860 void ast_udptl_set_peer(struct ast_udptl *udptl, struct sockaddr_in *them)
862 udptl->them.sin_port = them->sin_port;
863 udptl->them.sin_addr = them->sin_addr;
866 void ast_udptl_get_peer(struct ast_udptl *udptl, struct sockaddr_in *them)
868 them->sin_family = AF_INET;
869 them->sin_port = udptl->them.sin_port;
870 them->sin_addr = udptl->them.sin_addr;
873 void ast_udptl_get_us(struct ast_udptl *udptl, struct sockaddr_in *us)
875 memcpy(us, &udptl->us, sizeof(udptl->us));
878 void ast_udptl_stop(struct ast_udptl *udptl)
880 memset(&udptl->them.sin_addr, 0, sizeof(udptl->them.sin_addr));
881 memset(&udptl->them.sin_port, 0, sizeof(udptl->them.sin_port));
884 void ast_udptl_destroy(struct ast_udptl *udptl)
886 if (udptl->ioid)
887 ast_io_remove(udptl->io, udptl->ioid);
888 if (udptl->fd > -1)
889 close(udptl->fd);
890 free(udptl);
893 int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
895 int len;
896 int res;
897 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
898 char iabuf[INET_ADDRSTRLEN];
900 /* If we have no peer, return immediately */
901 if (s->them.sin_addr.s_addr == INADDR_ANY)
902 return 0;
904 /* If there is no data length, return immediately */
905 if (f->datalen == 0)
906 return 0;
908 if (f->frametype != AST_FRAME_MODEM) {
909 ast_log(LOG_WARNING, "UDPTL can only send T.38 data\n");
910 return -1;
913 /* Cook up the UDPTL packet, with the relevant EC info. */
914 len = udptl_build_packet(s, buf, f->data, f->datalen);
916 if (len > 0 && s->them.sin_port && s->them.sin_addr.s_addr) {
917 if ((res = sendto(s->fd, buf, len, 0, (struct sockaddr *) &s->them, sizeof(s->them))) < 0)
918 ast_log(LOG_NOTICE, "UDPTL Transmission error to %s:%d: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->them.sin_addr), ntohs(s->them.sin_port), strerror(errno));
919 #if 0
920 printf("Sent %d bytes of UDPTL data to %s:%d\n", res, ast_inet_ntoa(iabuf, sizeof(iabuf), udptl->them.sin_addr), ntohs(udptl->them.sin_port));
921 #endif
922 if (udptl_debug_test_addr(&s->them))
923 ast_verbose("Sent UDPTL packet to %s:%d (type %d, seq %d, len %d)\n",
924 ast_inet_ntoa(iabuf, sizeof(iabuf), s->them.sin_addr),
925 ntohs(s->them.sin_port), 0, s->seqno, len);
928 return 0;
931 void ast_udptl_proto_unregister(struct ast_udptl_protocol *proto)
933 struct ast_udptl_protocol *cur;
934 struct ast_udptl_protocol *prev;
936 cur = protos;
937 prev = NULL;
938 while(cur) {
939 if (cur == proto) {
940 if (prev)
941 prev->next = proto->next;
942 else
943 protos = proto->next;
944 return;
946 prev = cur;
947 cur = cur->next;
951 int ast_udptl_proto_register(struct ast_udptl_protocol *proto)
953 struct ast_udptl_protocol *cur;
955 cur = protos;
956 while(cur) {
957 if (cur->type == proto->type) {
958 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
959 return -1;
961 cur = cur->next;
963 proto->next = protos;
964 protos = proto;
965 return 0;
968 static struct ast_udptl_protocol *get_proto(struct ast_channel *chan)
970 struct ast_udptl_protocol *cur;
972 cur = protos;
973 while (cur) {
974 if (cur->type == chan->tech->type)
975 return cur;
976 cur = cur->next;
978 return NULL;
981 int ast_udptl_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
983 struct ast_frame *f;
984 struct ast_channel *who;
985 struct ast_channel *cs[3];
986 struct ast_udptl *p0;
987 struct ast_udptl *p1;
988 struct ast_udptl_protocol *pr0;
989 struct ast_udptl_protocol *pr1;
990 struct sockaddr_in ac0;
991 struct sockaddr_in ac1;
992 struct sockaddr_in t0;
993 struct sockaddr_in t1;
994 char iabuf[INET_ADDRSTRLEN];
995 void *pvt0;
996 void *pvt1;
997 int to;
999 ast_channel_lock(c0);
1000 while (ast_channel_trylock(c1)) {
1001 ast_channel_unlock(c0);
1002 usleep(1);
1003 ast_channel_lock(c0);
1005 pr0 = get_proto(c0);
1006 pr1 = get_proto(c1);
1007 if (!pr0) {
1008 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
1009 ast_channel_unlock(c0);
1010 ast_channel_unlock(c1);
1011 return -1;
1013 if (!pr1) {
1014 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
1015 ast_channel_unlock(c0);
1016 ast_channel_unlock(c1);
1017 return -1;
1019 pvt0 = c0->tech_pvt;
1020 pvt1 = c1->tech_pvt;
1021 p0 = pr0->get_udptl_info(c0);
1022 p1 = pr1->get_udptl_info(c1);
1023 if (!p0 || !p1) {
1024 /* Somebody doesn't want to play... */
1025 ast_channel_unlock(c0);
1026 ast_channel_unlock(c1);
1027 return -2;
1029 if (pr0->set_udptl_peer(c0, p1)) {
1030 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
1031 } else {
1032 /* Store UDPTL peer */
1033 ast_udptl_get_peer(p1, &ac1);
1035 if (pr1->set_udptl_peer(c1, p0))
1036 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
1037 else {
1038 /* Store UDPTL peer */
1039 ast_udptl_get_peer(p0, &ac0);
1041 ast_channel_unlock(c0);
1042 ast_channel_unlock(c1);
1043 cs[0] = c0;
1044 cs[1] = c1;
1045 cs[2] = NULL;
1046 for (;;) {
1047 if ((c0->tech_pvt != pvt0) ||
1048 (c1->tech_pvt != pvt1) ||
1049 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
1050 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
1051 /* Tell it to try again later */
1052 return -3;
1054 to = -1;
1055 ast_udptl_get_peer(p1, &t1);
1056 ast_udptl_get_peer(p0, &t0);
1057 if (inaddrcmp(&t1, &ac1)) {
1058 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d\n",
1059 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t1.sin_addr), ntohs(t1.sin_port));
1060 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d\n",
1061 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac1.sin_addr), ntohs(ac1.sin_port));
1062 memcpy(&ac1, &t1, sizeof(ac1));
1064 if (inaddrcmp(&t0, &ac0)) {
1065 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d\n",
1066 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t0.sin_addr), ntohs(t0.sin_port));
1067 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d\n",
1068 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac0.sin_addr), ntohs(ac0.sin_port));
1069 memcpy(&ac0, &t0, sizeof(ac0));
1071 who = ast_waitfor_n(cs, 2, &to);
1072 if (!who) {
1073 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
1074 /* check for hangup / whentohangup */
1075 if (ast_check_hangup(c0) || ast_check_hangup(c1))
1076 break;
1077 continue;
1079 f = ast_read(who);
1080 if (!f) {
1081 *fo = f;
1082 *rc = who;
1083 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
1084 /* That's all we needed */
1085 return 0;
1086 } else {
1087 if (f->frametype == AST_FRAME_MODEM) {
1088 /* Forward T.38 frames if they happen upon us */
1089 if (who == c0) {
1090 ast_write(c1, f);
1091 } else if (who == c1) {
1092 ast_write(c0, f);
1095 ast_frfree(f);
1097 /* Swap priority. Not that it's a big deal at this point */
1098 cs[2] = cs[0];
1099 cs[0] = cs[1];
1100 cs[1] = cs[2];
1102 return -1;
1105 static int udptl_do_debug_ip(int fd, int argc, char *argv[])
1107 struct hostent *hp;
1108 struct ast_hostent ahp;
1109 char iabuf[INET_ADDRSTRLEN];
1110 int port;
1111 char *p;
1112 char *arg;
1114 port = 0;
1115 if (argc != 4)
1116 return RESULT_SHOWUSAGE;
1117 arg = argv[3];
1118 p = strstr(arg, ":");
1119 if (p) {
1120 *p = '\0';
1121 p++;
1122 port = atoi(p);
1124 hp = ast_gethostbyname(arg, &ahp);
1125 if (hp == NULL)
1126 return RESULT_SHOWUSAGE;
1127 udptldebugaddr.sin_family = AF_INET;
1128 memcpy(&udptldebugaddr.sin_addr, hp->h_addr, sizeof(udptldebugaddr.sin_addr));
1129 udptldebugaddr.sin_port = htons(port);
1130 if (port == 0)
1131 ast_cli(fd, "UDPTL Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), udptldebugaddr.sin_addr));
1132 else
1133 ast_cli(fd, "UDPTL Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), udptldebugaddr.sin_addr), port);
1134 udptldebug = 1;
1135 return RESULT_SUCCESS;
1138 static int udptl_do_debug(int fd, int argc, char *argv[])
1140 if (argc != 2) {
1141 if (argc != 4)
1142 return RESULT_SHOWUSAGE;
1143 return udptl_do_debug_ip(fd, argc, argv);
1145 udptldebug = 1;
1146 memset(&udptldebugaddr,0,sizeof(udptldebugaddr));
1147 ast_cli(fd, "UDPTL Debugging Enabled\n");
1148 return RESULT_SUCCESS;
1151 static int udptl_no_debug(int fd, int argc, char *argv[])
1153 if (argc !=3)
1154 return RESULT_SHOWUSAGE;
1155 udptldebug = 0;
1156 ast_cli(fd,"UDPTL Debugging Disabled\n");
1157 return RESULT_SUCCESS;
1160 static char debug_usage[] =
1161 "Usage: udptl debug [ip host[:port]]\n"
1162 " Enable dumping of all UDPTL packets to and from host.\n";
1164 static char no_debug_usage[] =
1165 "Usage: udptl no debug\n"
1166 " Disable all UDPTL debugging\n";
1168 static struct ast_cli_entry cli_debug_ip =
1169 {{ "udptl", "debug", "ip", NULL } , udptl_do_debug, "Enable UDPTL debugging on IP", debug_usage };
1171 static struct ast_cli_entry cli_debug =
1172 {{ "udptl", "debug", NULL } , udptl_do_debug, "Enable UDPTL debugging", debug_usage };
1174 static struct ast_cli_entry cli_no_debug =
1175 {{ "udptl", "no", "debug", NULL } , udptl_no_debug, "Disable UDPTL debugging", no_debug_usage };
1177 void ast_udptl_reload(void)
1179 struct ast_config *cfg;
1180 char *s;
1182 udptlstart = 4500;
1183 udptlend = 4999;
1184 udptlfectype = 0;
1185 udptlfecentries = 0;
1186 udptlfecspan = 0;
1187 udptlmaxdatagram = 0;
1189 if ((cfg = ast_config_load("udptl.conf"))) {
1190 if ((s = ast_variable_retrieve(cfg, "general", "udptlstart"))) {
1191 udptlstart = atoi(s);
1192 if (udptlstart < 1024)
1193 udptlstart = 1024;
1194 if (udptlstart > 65535)
1195 udptlstart = 65535;
1197 if ((s = ast_variable_retrieve(cfg, "general", "udptlend"))) {
1198 udptlend = atoi(s);
1199 if (udptlend < 1024)
1200 udptlend = 1024;
1201 if (udptlend > 65535)
1202 udptlend = 65535;
1204 if ((s = ast_variable_retrieve(cfg, "general", "udptlchecksums"))) {
1205 #ifdef SO_NO_CHECK
1206 if (ast_false(s))
1207 nochecksums = 1;
1208 else
1209 nochecksums = 0;
1210 #else
1211 if (ast_false(s))
1212 ast_log(LOG_WARNING, "Disabling UDPTL checksums is not supported on this operating system!\n");
1213 #endif
1215 if ((s = ast_variable_retrieve(cfg, "general", "T38FaxUdpEC"))) {
1216 if (strcmp(s, "t38UDPFEC") == 0)
1217 udptlfectype = 2;
1218 else if (strcmp(s, "t38UDPRedundancy") == 0)
1219 udptlfectype = 1;
1221 if ((s = ast_variable_retrieve(cfg, "general", "T38FaxMaxDatagram"))) {
1222 udptlmaxdatagram = atoi(s);
1223 if (udptlmaxdatagram < 0)
1224 udptlmaxdatagram = 0;
1225 if (udptlmaxdatagram > LOCAL_FAX_MAX_DATAGRAM)
1226 udptlmaxdatagram = LOCAL_FAX_MAX_DATAGRAM;
1228 if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECentries"))) {
1229 udptlfecentries = atoi(s);
1230 if (udptlfecentries < 0)
1231 udptlfecentries = 0;
1232 if (udptlfecentries > MAX_FEC_ENTRIES)
1233 udptlfecentries = MAX_FEC_ENTRIES;
1235 if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECspan"))) {
1236 udptlfecspan = atoi(s);
1237 if (udptlfecspan < 0)
1238 udptlfecspan = 0;
1239 if (udptlfecspan > MAX_FEC_SPAN)
1240 udptlfecspan = MAX_FEC_SPAN;
1242 ast_config_destroy(cfg);
1244 if (udptlstart >= udptlend) {
1245 ast_log(LOG_WARNING, "Unreasonable values for UDPTL start/end\n");
1246 udptlstart = 4500;
1247 udptlend = 4999;
1249 if (option_verbose > 1)
1250 ast_verbose(VERBOSE_PREFIX_2 "UDPTL allocating from port range %d -> %d\n", udptlstart, udptlend);
1253 void ast_udptl_init(void)
1255 ast_cli_register(&cli_debug);
1256 ast_cli_register(&cli_debug_ip);
1257 ast_cli_register(&cli_no_debug);
1258 ast_udptl_reload();