Make it build with the bristuffed libpri
[asterisk-bristuff.git] / main / udptl.c
bloba9386ac099bb734c38f4f74be761ea4ad244ac80
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 * A license has been granted to Digium (via disclaimer) for the use of
15 * this code.
18 #include "asterisk.h"
20 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/time.h>
26 #include <signal.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <netinet/in.h>
30 #include <sys/time.h>
31 #include <sys/socket.h>
32 #include <arpa/inet.h>
33 #include <fcntl.h>
35 #include "asterisk/udptl.h"
36 #include "asterisk/frame.h"
37 #include "asterisk/logger.h"
38 #include "asterisk/options.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/acl.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/config.h"
43 #include "asterisk/lock.h"
44 #include "asterisk/utils.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/unaligned.h"
47 #include "asterisk/utils.h"
49 #define UDPTL_MTU 1200
51 #if !defined(FALSE)
52 #define FALSE 0
53 #endif
54 #if !defined(TRUE)
55 #define TRUE (!FALSE)
56 #endif
58 static int udptlstart;
59 static int udptlend;
60 static int udptldebug; /* Are we debugging? */
61 static struct sockaddr_in udptldebugaddr; /* Debug packets to/from this host */
62 #ifdef SO_NO_CHECK
63 static int nochecksums;
64 #endif
65 static int udptlfectype;
66 static int udptlfecentries;
67 static int udptlfecspan;
68 static int udptlmaxdatagram;
70 #define LOCAL_FAX_MAX_DATAGRAM 400
71 #define MAX_FEC_ENTRIES 5
72 #define MAX_FEC_SPAN 5
74 #define UDPTL_BUF_MASK 15
76 typedef struct {
77 int buf_len;
78 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
79 } udptl_fec_tx_buffer_t;
81 typedef struct {
82 int buf_len;
83 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
84 int fec_len[MAX_FEC_ENTRIES];
85 uint8_t fec[MAX_FEC_ENTRIES][LOCAL_FAX_MAX_DATAGRAM];
86 int fec_span;
87 int fec_entries;
88 } udptl_fec_rx_buffer_t;
90 struct ast_udptl {
91 int fd;
92 char resp;
93 struct ast_frame f[16];
94 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
95 unsigned int lasteventseqn;
96 int nat;
97 int flags;
98 struct sockaddr_in us;
99 struct sockaddr_in them;
100 int *ioid;
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;
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 memset(&s->f[0], 0, sizeof(s->f[0]));
300 /* Decode seq_number */
301 if (ptr + 2 > len)
302 return -1;
303 seq_no = (buf[0] << 8) | buf[1];
304 ptr += 2;
306 /* Break out the primary packet */
307 if ((stat = decode_open_type(buf, len, &ptr, &ifp, &ifp_len)) != 0)
308 return -1;
309 /* Decode error_recovery */
310 if (ptr + 1 > len)
311 return -1;
312 if ((buf[ptr++] & 0x80) == 0) {
313 /* Secondary packet mode for error recovery */
314 if (seq_no > s->rx_seq_no) {
315 /* We received a later packet than we expected, so we need to check if we can fill in the gap from the
316 secondary packets. */
317 total_count = 0;
318 do {
319 if ((stat2 = decode_length(buf, len, &ptr, &count)) < 0)
320 return -1;
321 for (i = 0; i < count; i++) {
322 if ((stat = decode_open_type(buf, len, &ptr, &bufs[total_count + i], &lengths[total_count + i])) != 0)
323 return -1;
325 total_count += count;
327 while (stat2 > 0);
328 /* Step through in reverse order, so we go oldest to newest */
329 for (i = total_count; i > 0; i--) {
330 if (seq_no - i >= s->rx_seq_no) {
331 /* This one wasn't seen before */
332 /* Decode the secondary IFP packet */
333 //fprintf(stderr, "Secondary %d, len %d\n", seq_no - i, lengths[i - 1]);
334 s->f[ifp_no].frametype = AST_FRAME_MODEM;
335 s->f[ifp_no].subclass = AST_MODEM_T38;
337 s->f[ifp_no].mallocd = 0;
338 s->f[ifp_no].seqno = seq_no - i;
339 s->f[ifp_no].datalen = lengths[i - 1];
340 s->f[ifp_no].data = (uint8_t *) bufs[i - 1];
341 s->f[ifp_no].offset = 0;
342 s->f[ifp_no].src = "UDPTL";
343 if (ifp_no > 0)
344 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
345 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
346 ifp_no++;
351 else
353 /* FEC mode for error recovery */
354 /* Our buffers cannot tolerate overlength IFP packets in FEC mode */
355 if (ifp_len > LOCAL_FAX_MAX_DATAGRAM)
356 return -1;
357 /* Update any missed slots in the buffer */
358 for ( ; seq_no > s->rx_seq_no; s->rx_seq_no++) {
359 x = s->rx_seq_no & UDPTL_BUF_MASK;
360 s->rx[x].buf_len = -1;
361 s->rx[x].fec_len[0] = 0;
362 s->rx[x].fec_span = 0;
363 s->rx[x].fec_entries = 0;
366 x = seq_no & UDPTL_BUF_MASK;
368 memset(repaired, 0, sizeof(repaired));
370 /* Save the new IFP packet */
371 memcpy(s->rx[x].buf, ifp, ifp_len);
372 s->rx[x].buf_len = ifp_len;
373 repaired[x] = TRUE;
375 /* Decode the FEC packets */
376 /* The span is defined as an unconstrained integer, but will never be more
377 than a small value. */
378 if (ptr + 2 > len)
379 return -1;
380 if (buf[ptr++] != 1)
381 return -1;
382 span = buf[ptr++];
383 s->rx[x].fec_span = span;
385 /* The number of entries is defined as a length, but will only ever be a small
386 value. Treat it as such. */
387 if (ptr + 1 > len)
388 return -1;
389 entries = buf[ptr++];
390 s->rx[x].fec_entries = entries;
392 /* Decode the elements */
393 for (i = 0; i < entries; i++) {
394 if ((stat = decode_open_type(buf, len, &ptr, &data, &s->rx[x].fec_len[i])) != 0)
395 return -1;
396 if (s->rx[x].fec_len[i] > LOCAL_FAX_MAX_DATAGRAM)
397 return -1;
399 /* Save the new FEC data */
400 memcpy(s->rx[x].fec[i], data, s->rx[x].fec_len[i]);
401 #if 0
402 fprintf(stderr, "FEC: ");
403 for (j = 0; j < s->rx[x].fec_len[i]; j++)
404 fprintf(stderr, "%02X ", data[j]);
405 fprintf(stderr, "\n");
406 #endif
409 /* See if we can reconstruct anything which is missing */
410 /* TODO: this does not comprehensively hunt back and repair everything that is possible */
411 for (l = x; l != ((x - (16 - span*entries)) & UDPTL_BUF_MASK); l = (l - 1) & UDPTL_BUF_MASK) {
412 if (s->rx[l].fec_len[0] <= 0)
413 continue;
414 for (m = 0; m < s->rx[l].fec_entries; m++) {
415 limit = (l + m) & UDPTL_BUF_MASK;
416 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) {
417 if (s->rx[k].buf_len <= 0)
418 which = (which == -1) ? k : -2;
420 if (which >= 0) {
421 /* Repairable */
422 for (j = 0; j < s->rx[l].fec_len[m]; j++) {
423 s->rx[which].buf[j] = s->rx[l].fec[m][j];
424 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)
425 s->rx[which].buf[j] ^= (s->rx[k].buf_len > j) ? s->rx[k].buf[j] : 0;
427 s->rx[which].buf_len = s->rx[l].fec_len[m];
428 repaired[which] = TRUE;
432 /* Now play any new packets forwards in time */
433 for (l = (x + 1) & UDPTL_BUF_MASK, j = seq_no - UDPTL_BUF_MASK; l != x; l = (l + 1) & UDPTL_BUF_MASK, j++) {
434 if (repaired[l]) {
435 //fprintf(stderr, "Fixed packet %d, len %d\n", j, l);
436 s->f[ifp_no].frametype = AST_FRAME_MODEM;
437 s->f[ifp_no].subclass = AST_MODEM_T38;
439 s->f[ifp_no].mallocd = 0;
440 s->f[ifp_no].seqno = j;
441 s->f[ifp_no].datalen = s->rx[l].buf_len;
442 s->f[ifp_no].data = s->rx[l].buf;
443 s->f[ifp_no].offset = 0;
444 s->f[ifp_no].src = "UDPTL";
445 if (ifp_no > 0)
446 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
447 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
448 ifp_no++;
453 /* If packets are received out of sequence, we may have already processed this packet from the error
454 recovery information in a packet already received. */
455 if (seq_no >= s->rx_seq_no) {
456 /* Decode the primary IFP packet */
457 s->f[ifp_no].frametype = AST_FRAME_MODEM;
458 s->f[ifp_no].subclass = AST_MODEM_T38;
460 s->f[ifp_no].mallocd = 0;
461 s->f[ifp_no].seqno = seq_no;
462 s->f[ifp_no].datalen = ifp_len;
463 s->f[ifp_no].data = (uint8_t *) ifp;
464 s->f[ifp_no].offset = 0;
465 s->f[ifp_no].src = "UDPTL";
466 if (ifp_no > 0)
467 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
468 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
470 ifp_no++;
473 s->rx_seq_no = seq_no + 1;
474 return ifp_no;
476 /*- End of function --------------------------------------------------------*/
478 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, uint8_t *ifp, int ifp_len)
480 uint8_t fec[LOCAL_FAX_MAX_DATAGRAM];
481 int i;
482 int j;
483 int seq;
484 int entry;
485 int entries;
486 int span;
487 int m;
488 int len;
489 int limit;
490 int high_tide;
492 seq = s->tx_seq_no & 0xFFFF;
494 /* Map the sequence number to an entry in the circular buffer */
495 entry = seq & UDPTL_BUF_MASK;
497 /* We save the message in a circular buffer, for generating FEC or
498 redundancy sets later on. */
499 s->tx[entry].buf_len = ifp_len;
500 memcpy(s->tx[entry].buf, ifp, ifp_len);
502 /* Build the UDPTLPacket */
504 len = 0;
505 /* Encode the sequence number */
506 buf[len++] = (seq >> 8) & 0xFF;
507 buf[len++] = seq & 0xFF;
509 /* Encode the primary IFP packet */
510 if (encode_open_type(buf, &len, ifp, ifp_len) < 0)
511 return -1;
513 /* Encode the appropriate type of error recovery information */
514 switch (s->error_correction_scheme)
516 case UDPTL_ERROR_CORRECTION_NONE:
517 /* Encode the error recovery type */
518 buf[len++] = 0x00;
519 /* The number of entries will always be zero, so it is pointless allowing
520 for the fragmented case here. */
521 if (encode_length(buf, &len, 0) < 0)
522 return -1;
523 break;
524 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
525 /* Encode the error recovery type */
526 buf[len++] = 0x00;
527 if (s->tx_seq_no > s->error_correction_entries)
528 entries = s->error_correction_entries;
529 else
530 entries = s->tx_seq_no;
531 /* The number of entries will always be small, so it is pointless allowing
532 for the fragmented case here. */
533 if (encode_length(buf, &len, entries) < 0)
534 return -1;
535 /* Encode the elements */
536 for (i = 0; i < entries; i++) {
537 j = (entry - i - 1) & UDPTL_BUF_MASK;
538 if (encode_open_type(buf, &len, s->tx[j].buf, s->tx[j].buf_len) < 0)
539 return -1;
541 break;
542 case UDPTL_ERROR_CORRECTION_FEC:
543 span = s->error_correction_span;
544 entries = s->error_correction_entries;
545 if (seq < s->error_correction_span*s->error_correction_entries) {
546 /* In the initial stages, wind up the FEC smoothly */
547 entries = seq/s->error_correction_span;
548 if (seq < s->error_correction_span)
549 span = 0;
551 /* Encode the error recovery type */
552 buf[len++] = 0x80;
553 /* Span is defined as an inconstrained integer, which it dumb. It will only
554 ever be a small value. Treat it as such. */
555 buf[len++] = 1;
556 buf[len++] = span;
557 /* The number of entries is defined as a length, but will only ever be a small
558 value. Treat it as such. */
559 buf[len++] = entries;
560 for (m = 0; m < entries; m++) {
561 /* Make an XOR'ed entry the maximum length */
562 limit = (entry + m) & UDPTL_BUF_MASK;
563 high_tide = 0;
564 for (i = (limit - span*entries) & UDPTL_BUF_MASK; i != limit; i = (i + entries) & UDPTL_BUF_MASK) {
565 if (high_tide < s->tx[i].buf_len) {
566 for (j = 0; j < high_tide; j++)
567 fec[j] ^= s->tx[i].buf[j];
568 for ( ; j < s->tx[i].buf_len; j++)
569 fec[j] = s->tx[i].buf[j];
570 high_tide = s->tx[i].buf_len;
571 } else {
572 for (j = 0; j < s->tx[i].buf_len; j++)
573 fec[j] ^= s->tx[i].buf[j];
576 if (encode_open_type(buf, &len, fec, high_tide) < 0)
577 return -1;
579 break;
582 if (s->verbose)
583 fprintf(stderr, "\n");
585 s->tx_seq_no++;
586 return len;
589 int ast_udptl_fd(struct ast_udptl *udptl)
591 return udptl->fd;
594 void ast_udptl_set_data(struct ast_udptl *udptl, void *data)
596 udptl->data = data;
599 void ast_udptl_set_callback(struct ast_udptl *udptl, ast_udptl_callback callback)
601 udptl->callback = callback;
604 void ast_udptl_setnat(struct ast_udptl *udptl, int nat)
606 udptl->nat = nat;
609 static int udptlread(int *id, int fd, short events, void *cbdata)
611 struct ast_udptl *udptl = cbdata;
612 struct ast_frame *f;
614 if ((f = ast_udptl_read(udptl))) {
615 if (udptl->callback)
616 udptl->callback(udptl, f, udptl->data);
618 return 1;
621 struct ast_frame *ast_udptl_read(struct ast_udptl *udptl)
623 int res;
624 struct sockaddr_in sin;
625 socklen_t len;
626 uint16_t seqno = 0;
627 uint16_t *udptlheader;
629 len = sizeof(sin);
631 /* Cache where the header will go */
632 res = recvfrom(udptl->fd,
633 udptl->rawdata + AST_FRIENDLY_OFFSET,
634 sizeof(udptl->rawdata) - AST_FRIENDLY_OFFSET,
636 (struct sockaddr *) &sin,
637 &len);
638 udptlheader = (uint16_t *)(udptl->rawdata + AST_FRIENDLY_OFFSET);
639 if (res < 0) {
640 if (errno != EAGAIN)
641 ast_log(LOG_WARNING, "UDPTL read error: %s\n", strerror(errno));
642 ast_assert(errno != EBADF);
643 return &ast_null_frame;
646 /* Ignore if the other side hasn't been given an address yet. */
647 if (!udptl->them.sin_addr.s_addr || !udptl->them.sin_port)
648 return &ast_null_frame;
650 if (udptl->nat) {
651 /* Send to whoever sent to us */
652 if ((udptl->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
653 (udptl->them.sin_port != sin.sin_port)) {
654 memcpy(&udptl->them, &sin, sizeof(udptl->them));
655 ast_log(LOG_DEBUG, "UDPTL NAT: Using address %s:%d\n", ast_inet_ntoa(udptl->them.sin_addr), ntohs(udptl->them.sin_port));
659 if (udptl_debug_test_addr(&sin)) {
660 ast_verbose("Got UDPTL packet from %s:%d (type %d, seq %d, len %d)\n",
661 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), 0, seqno, res);
663 #if 0
664 printf("Got UDPTL packet from %s:%d (seq %d, len = %d)\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), seqno, res);
665 #endif
666 if (udptl_rx_packet(udptl, udptl->rawdata + AST_FRIENDLY_OFFSET, res) < 1)
667 return &ast_null_frame;
669 return &udptl->f[0];
672 void ast_udptl_offered_from_local(struct ast_udptl* udptl, int local)
674 if (udptl)
675 udptl->udptl_offered_from_local = local;
676 else
677 ast_log(LOG_WARNING, "udptl structure is null\n");
680 int ast_udptl_get_error_correction_scheme(struct ast_udptl* udptl)
682 if (udptl)
683 return udptl->error_correction_scheme;
684 else {
685 ast_log(LOG_WARNING, "udptl structure is null\n");
686 return -1;
690 void ast_udptl_set_error_correction_scheme(struct ast_udptl* udptl, int ec)
692 if (udptl) {
693 switch (ec) {
694 case UDPTL_ERROR_CORRECTION_FEC:
695 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
696 break;
697 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
698 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
699 break;
700 case UDPTL_ERROR_CORRECTION_NONE:
701 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_NONE;
702 break;
703 default:
704 ast_log(LOG_WARNING, "error correction parameter invalid\n");
706 } else
707 ast_log(LOG_WARNING, "udptl structure is null\n");
710 int ast_udptl_get_local_max_datagram(struct ast_udptl* udptl)
712 if (udptl)
713 return udptl->local_max_datagram_size;
714 else {
715 ast_log(LOG_WARNING, "udptl structure is null\n");
716 return -1;
720 int ast_udptl_get_far_max_datagram(struct ast_udptl* udptl)
722 if (udptl)
723 return udptl->far_max_datagram_size;
724 else {
725 ast_log(LOG_WARNING, "udptl structure is null\n");
726 return -1;
730 void ast_udptl_set_local_max_datagram(struct ast_udptl* udptl, int max_datagram)
732 if (udptl)
733 udptl->local_max_datagram_size = max_datagram;
734 else
735 ast_log(LOG_WARNING, "udptl structure is null\n");
738 void ast_udptl_set_far_max_datagram(struct ast_udptl* udptl, int max_datagram)
740 if (udptl)
741 udptl->far_max_datagram_size = max_datagram;
742 else
743 ast_log(LOG_WARNING, "udptl structure is null\n");
746 struct ast_udptl *ast_udptl_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int callbackmode, struct in_addr addr)
748 struct ast_udptl *udptl;
749 int x;
750 int startplace;
751 int i;
752 long int flags;
754 if (!(udptl = ast_calloc(1, sizeof(*udptl))))
755 return NULL;
757 if (udptlfectype == 2)
758 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
759 else if (udptlfectype == 1)
760 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
761 else
762 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_NONE;
763 udptl->error_correction_span = udptlfecspan;
764 udptl->error_correction_entries = udptlfecentries;
766 udptl->far_max_datagram_size = udptlmaxdatagram;
767 udptl->local_max_datagram_size = udptlmaxdatagram;
769 memset(&udptl->rx, 0, sizeof(udptl->rx));
770 memset(&udptl->tx, 0, sizeof(udptl->tx));
771 for (i = 0; i <= UDPTL_BUF_MASK; i++) {
772 udptl->rx[i].buf_len = -1;
773 udptl->tx[i].buf_len = -1;
776 udptl->them.sin_family = AF_INET;
777 udptl->us.sin_family = AF_INET;
779 if ((udptl->fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
780 free(udptl);
781 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
782 return NULL;
784 flags = fcntl(udptl->fd, F_GETFL);
785 fcntl(udptl->fd, F_SETFL, flags | O_NONBLOCK);
786 #ifdef SO_NO_CHECK
787 if (nochecksums)
788 setsockopt(udptl->fd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
789 #endif
790 /* Find us a place */
791 x = (ast_random() % (udptlend - udptlstart)) + udptlstart;
792 startplace = x;
793 for (;;) {
794 udptl->us.sin_port = htons(x);
795 udptl->us.sin_addr = addr;
796 if (bind(udptl->fd, (struct sockaddr *) &udptl->us, sizeof(udptl->us)) == 0)
797 break;
798 if (errno != EADDRINUSE) {
799 ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
800 close(udptl->fd);
801 free(udptl);
802 return NULL;
804 if (++x > udptlend)
805 x = udptlstart;
806 if (x == startplace) {
807 ast_log(LOG_WARNING, "No UDPTL ports remaining\n");
808 close(udptl->fd);
809 free(udptl);
810 return NULL;
813 if (io && sched && callbackmode) {
814 /* Operate this one in a callback mode */
815 udptl->sched = sched;
816 udptl->io = io;
817 udptl->ioid = ast_io_add(udptl->io, udptl->fd, udptlread, AST_IO_IN, udptl);
819 return udptl;
822 struct ast_udptl *ast_udptl_new(struct sched_context *sched, struct io_context *io, int callbackmode)
824 struct in_addr ia;
825 memset(&ia, 0, sizeof(ia));
826 return ast_udptl_new_with_bindaddr(sched, io, callbackmode, ia);
829 int ast_udptl_settos(struct ast_udptl *udptl, int tos)
831 int res;
833 if ((res = setsockopt(udptl->fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
834 ast_log(LOG_WARNING, "UDPTL unable to set TOS to %d\n", tos);
835 return res;
838 void ast_udptl_set_peer(struct ast_udptl *udptl, struct sockaddr_in *them)
840 udptl->them.sin_port = them->sin_port;
841 udptl->them.sin_addr = them->sin_addr;
844 void ast_udptl_get_peer(struct ast_udptl *udptl, struct sockaddr_in *them)
846 memset(them, 0, sizeof(*them));
847 them->sin_family = AF_INET;
848 them->sin_port = udptl->them.sin_port;
849 them->sin_addr = udptl->them.sin_addr;
852 void ast_udptl_get_us(struct ast_udptl *udptl, struct sockaddr_in *us)
854 memcpy(us, &udptl->us, sizeof(udptl->us));
857 void ast_udptl_stop(struct ast_udptl *udptl)
859 memset(&udptl->them.sin_addr, 0, sizeof(udptl->them.sin_addr));
860 memset(&udptl->them.sin_port, 0, sizeof(udptl->them.sin_port));
863 void ast_udptl_destroy(struct ast_udptl *udptl)
865 if (udptl->ioid)
866 ast_io_remove(udptl->io, udptl->ioid);
867 if (udptl->fd > -1)
868 close(udptl->fd);
869 free(udptl);
872 int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
874 int seq;
875 int len;
876 int res;
877 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
879 /* If we have no peer, return immediately */
880 if (s->them.sin_addr.s_addr == INADDR_ANY)
881 return 0;
883 /* If there is no data length, return immediately */
884 if (f->datalen == 0)
885 return 0;
887 if (f->frametype != AST_FRAME_MODEM) {
888 ast_log(LOG_WARNING, "UDPTL can only send T.38 data\n");
889 return -1;
892 /* Save seq_no for debug output because udptl_build_packet increments it */
893 seq = s->tx_seq_no & 0xFFFF;
895 /* Cook up the UDPTL packet, with the relevant EC info. */
896 len = udptl_build_packet(s, buf, f->data, f->datalen);
898 if (len > 0 && s->them.sin_port && s->them.sin_addr.s_addr) {
899 if ((res = sendto(s->fd, buf, len, 0, (struct sockaddr *) &s->them, sizeof(s->them))) < 0)
900 ast_log(LOG_NOTICE, "UDPTL Transmission error to %s:%d: %s\n", ast_inet_ntoa(s->them.sin_addr), ntohs(s->them.sin_port), strerror(errno));
901 #if 0
902 printf("Sent %d bytes of UDPTL data to %s:%d\n", res, ast_inet_ntoa(udptl->them.sin_addr), ntohs(udptl->them.sin_port));
903 #endif
904 if (udptl_debug_test_addr(&s->them))
905 ast_verbose("Sent UDPTL packet to %s:%d (type %d, seq %d, len %d)\n",
906 ast_inet_ntoa(s->them.sin_addr),
907 ntohs(s->them.sin_port), 0, seq, len);
910 return 0;
913 void ast_udptl_proto_unregister(struct ast_udptl_protocol *proto)
915 struct ast_udptl_protocol *cur;
916 struct ast_udptl_protocol *prev;
918 cur = protos;
919 prev = NULL;
920 while (cur) {
921 if (cur == proto) {
922 if (prev)
923 prev->next = proto->next;
924 else
925 protos = proto->next;
926 return;
928 prev = cur;
929 cur = cur->next;
933 int ast_udptl_proto_register(struct ast_udptl_protocol *proto)
935 struct ast_udptl_protocol *cur;
937 cur = protos;
938 while (cur) {
939 if (cur->type == proto->type) {
940 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
941 return -1;
943 cur = cur->next;
945 proto->next = protos;
946 protos = proto;
947 return 0;
950 static struct ast_udptl_protocol *get_proto(struct ast_channel *chan)
952 struct ast_udptl_protocol *cur;
954 cur = protos;
955 while (cur) {
956 if (cur->type == chan->tech->type)
957 return cur;
958 cur = cur->next;
960 return NULL;
963 int ast_udptl_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
965 struct ast_frame *f;
966 struct ast_channel *who;
967 struct ast_channel *cs[3];
968 struct ast_udptl *p0;
969 struct ast_udptl *p1;
970 struct ast_udptl_protocol *pr0;
971 struct ast_udptl_protocol *pr1;
972 struct sockaddr_in ac0;
973 struct sockaddr_in ac1;
974 struct sockaddr_in t0;
975 struct sockaddr_in t1;
976 void *pvt0;
977 void *pvt1;
978 int to;
980 ast_channel_lock(c0);
981 while (ast_channel_trylock(c1)) {
982 ast_channel_unlock(c0);
983 usleep(1);
984 ast_channel_lock(c0);
986 pr0 = get_proto(c0);
987 pr1 = get_proto(c1);
988 if (!pr0) {
989 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
990 ast_channel_unlock(c0);
991 ast_channel_unlock(c1);
992 return -1;
994 if (!pr1) {
995 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
996 ast_channel_unlock(c0);
997 ast_channel_unlock(c1);
998 return -1;
1000 pvt0 = c0->tech_pvt;
1001 pvt1 = c1->tech_pvt;
1002 p0 = pr0->get_udptl_info(c0);
1003 p1 = pr1->get_udptl_info(c1);
1004 if (!p0 || !p1) {
1005 /* Somebody doesn't want to play... */
1006 ast_channel_unlock(c0);
1007 ast_channel_unlock(c1);
1008 return -2;
1010 if (pr0->set_udptl_peer(c0, p1)) {
1011 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
1012 memset(&ac1, 0, sizeof(ac1));
1013 } else {
1014 /* Store UDPTL peer */
1015 ast_udptl_get_peer(p1, &ac1);
1017 if (pr1->set_udptl_peer(c1, p0)) {
1018 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
1019 memset(&ac0, 0, sizeof(ac0));
1020 } else {
1021 /* Store UDPTL peer */
1022 ast_udptl_get_peer(p0, &ac0);
1024 ast_channel_unlock(c0);
1025 ast_channel_unlock(c1);
1026 cs[0] = c0;
1027 cs[1] = c1;
1028 cs[2] = NULL;
1029 for (;;) {
1030 if ((c0->tech_pvt != pvt0) ||
1031 (c1->tech_pvt != pvt1) ||
1032 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
1033 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
1034 /* Tell it to try again later */
1035 return -3;
1037 to = -1;
1038 ast_udptl_get_peer(p1, &t1);
1039 ast_udptl_get_peer(p0, &t0);
1040 if (inaddrcmp(&t1, &ac1)) {
1041 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d\n",
1042 c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port));
1043 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d\n",
1044 c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port));
1045 memcpy(&ac1, &t1, sizeof(ac1));
1047 if (inaddrcmp(&t0, &ac0)) {
1048 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d\n",
1049 c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port));
1050 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d\n",
1051 c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port));
1052 memcpy(&ac0, &t0, sizeof(ac0));
1054 who = ast_waitfor_n(cs, 2, &to);
1055 if (!who) {
1056 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
1057 /* check for hangup / whentohangup */
1058 if (ast_check_hangup(c0) || ast_check_hangup(c1))
1059 break;
1060 continue;
1062 f = ast_read(who);
1063 if (!f) {
1064 *fo = f;
1065 *rc = who;
1066 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
1067 /* That's all we needed */
1068 return 0;
1069 } else {
1070 if (f->frametype == AST_FRAME_MODEM) {
1071 /* Forward T.38 frames if they happen upon us */
1072 if (who == c0) {
1073 ast_write(c1, f);
1074 } else if (who == c1) {
1075 ast_write(c0, f);
1078 ast_frfree(f);
1080 /* Swap priority. Not that it's a big deal at this point */
1081 cs[2] = cs[0];
1082 cs[0] = cs[1];
1083 cs[1] = cs[2];
1085 return -1;
1088 static int udptl_do_debug_ip(int fd, int argc, char *argv[])
1090 struct hostent *hp;
1091 struct ast_hostent ahp;
1092 int port;
1093 char *p;
1094 char *arg;
1096 port = 0;
1097 if (argc != 4)
1098 return RESULT_SHOWUSAGE;
1099 arg = argv[3];
1100 p = strstr(arg, ":");
1101 if (p) {
1102 *p = '\0';
1103 p++;
1104 port = atoi(p);
1106 hp = ast_gethostbyname(arg, &ahp);
1107 if (hp == NULL)
1108 return RESULT_SHOWUSAGE;
1109 udptldebugaddr.sin_family = AF_INET;
1110 memcpy(&udptldebugaddr.sin_addr, hp->h_addr, sizeof(udptldebugaddr.sin_addr));
1111 udptldebugaddr.sin_port = htons(port);
1112 if (port == 0)
1113 ast_cli(fd, "UDPTL Debugging Enabled for IP: %s\n", ast_inet_ntoa(udptldebugaddr.sin_addr));
1114 else
1115 ast_cli(fd, "UDPTL Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(udptldebugaddr.sin_addr), port);
1116 udptldebug = 1;
1117 return RESULT_SUCCESS;
1120 static int udptl_do_debug(int fd, int argc, char *argv[])
1122 if (argc != 2) {
1123 if (argc != 4)
1124 return RESULT_SHOWUSAGE;
1125 return udptl_do_debug_ip(fd, argc, argv);
1127 udptldebug = 1;
1128 memset(&udptldebugaddr,0,sizeof(udptldebugaddr));
1129 ast_cli(fd, "UDPTL Debugging Enabled\n");
1130 return RESULT_SUCCESS;
1133 static int udptl_nodebug(int fd, int argc, char *argv[])
1135 if (argc != 3)
1136 return RESULT_SHOWUSAGE;
1137 udptldebug = 0;
1138 ast_cli(fd,"UDPTL Debugging Disabled\n");
1139 return RESULT_SUCCESS;
1142 static char debug_usage[] =
1143 "Usage: udptl debug [ip host[:port]]\n"
1144 " Enable dumping of all UDPTL packets to and from host.\n";
1146 static char nodebug_usage[] =
1147 "Usage: udptl debug off\n"
1148 " Disable all UDPTL debugging\n";
1150 static struct ast_cli_entry cli_udptl_no_debug = {
1151 { "udptl", "no", "debug", NULL },
1152 udptl_nodebug, NULL,
1153 NULL };
1155 static struct ast_cli_entry cli_udptl[] = {
1156 { { "udptl", "debug", NULL },
1157 udptl_do_debug, "Enable UDPTL debugging",
1158 debug_usage },
1160 { { "udptl", "debug", "ip", NULL },
1161 udptl_do_debug, "Enable UDPTL debugging on IP",
1162 debug_usage },
1164 { { "udptl", "debug", "off", NULL },
1165 udptl_nodebug, "Disable UDPTL debugging",
1166 nodebug_usage, NULL, &cli_udptl_no_debug },
1169 void ast_udptl_reload(void)
1171 struct ast_config *cfg;
1172 const char *s;
1174 udptlstart = 4500;
1175 udptlend = 4999;
1176 udptlfectype = 0;
1177 udptlfecentries = 0;
1178 udptlfecspan = 0;
1179 udptlmaxdatagram = 0;
1181 if ((cfg = ast_config_load("udptl.conf"))) {
1182 if ((s = ast_variable_retrieve(cfg, "general", "udptlstart"))) {
1183 udptlstart = atoi(s);
1184 if (udptlstart < 1024)
1185 udptlstart = 1024;
1186 if (udptlstart > 65535)
1187 udptlstart = 65535;
1189 if ((s = ast_variable_retrieve(cfg, "general", "udptlend"))) {
1190 udptlend = atoi(s);
1191 if (udptlend < 1024)
1192 udptlend = 1024;
1193 if (udptlend > 65535)
1194 udptlend = 65535;
1196 if ((s = ast_variable_retrieve(cfg, "general", "udptlchecksums"))) {
1197 #ifdef SO_NO_CHECK
1198 if (ast_false(s))
1199 nochecksums = 1;
1200 else
1201 nochecksums = 0;
1202 #else
1203 if (ast_false(s))
1204 ast_log(LOG_WARNING, "Disabling UDPTL checksums is not supported on this operating system!\n");
1205 #endif
1207 if ((s = ast_variable_retrieve(cfg, "general", "T38FaxUdpEC"))) {
1208 if (strcmp(s, "t38UDPFEC") == 0)
1209 udptlfectype = 2;
1210 else if (strcmp(s, "t38UDPRedundancy") == 0)
1211 udptlfectype = 1;
1213 if ((s = ast_variable_retrieve(cfg, "general", "T38FaxMaxDatagram"))) {
1214 udptlmaxdatagram = atoi(s);
1215 if (udptlmaxdatagram < 0)
1216 udptlmaxdatagram = 0;
1217 if (udptlmaxdatagram > LOCAL_FAX_MAX_DATAGRAM)
1218 udptlmaxdatagram = LOCAL_FAX_MAX_DATAGRAM;
1220 if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECentries"))) {
1221 udptlfecentries = atoi(s);
1222 if (udptlfecentries < 0)
1223 udptlfecentries = 0;
1224 if (udptlfecentries > MAX_FEC_ENTRIES)
1225 udptlfecentries = MAX_FEC_ENTRIES;
1227 if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECspan"))) {
1228 udptlfecspan = atoi(s);
1229 if (udptlfecspan < 0)
1230 udptlfecspan = 0;
1231 if (udptlfecspan > MAX_FEC_SPAN)
1232 udptlfecspan = MAX_FEC_SPAN;
1234 ast_config_destroy(cfg);
1236 if (udptlstart >= udptlend) {
1237 ast_log(LOG_WARNING, "Unreasonable values for UDPTL start/end\n");
1238 udptlstart = 4500;
1239 udptlend = 4999;
1241 if (option_verbose > 1)
1242 ast_verbose(VERBOSE_PREFIX_2 "UDPTL allocating from port range %d -> %d\n", udptlstart, udptlend);
1245 void ast_udptl_init(void)
1247 ast_cli_register_multiple(cli_udptl, sizeof(cli_udptl) / sizeof(struct ast_cli_entry));
1248 ast_udptl_reload();