ast_func_read() needs a writable copy of the function name to be passed
[asterisk-bristuff.git] / main / udptl.c
blob6d5c82a2d9067f19aface16b9224233448a1207d
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 uint16_t seqno;
102 struct sched_context *sched;
103 struct io_context *io;
104 void *data;
105 ast_udptl_callback callback;
106 int udptl_offered_from_local;
108 /*! This option indicates the error correction scheme used in transmitted UDPTL
109 packets. */
110 int error_correction_scheme;
112 /*! This option indicates the number of error correction entries transmitted in
113 UDPTL packets. */
114 int error_correction_entries;
116 /*! This option indicates the span of the error correction entries in transmitted
117 UDPTL packets (FEC only). */
118 int error_correction_span;
120 /*! This option indicates the maximum size of a UDPTL packet that can be accepted by
121 the remote device. */
122 int far_max_datagram_size;
124 /*! This option indicates the maximum size of a UDPTL packet that we are prepared to
125 accept. */
126 int local_max_datagram_size;
128 int verbose;
130 struct sockaddr_in far;
132 int tx_seq_no;
133 int rx_seq_no;
134 int rx_expected_seq_no;
136 udptl_fec_tx_buffer_t tx[UDPTL_BUF_MASK + 1];
137 udptl_fec_rx_buffer_t rx[UDPTL_BUF_MASK + 1];
140 static struct ast_udptl_protocol *protos;
142 static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, int len);
143 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, uint8_t *ifp, int ifp_len);
145 static inline int udptl_debug_test_addr(struct sockaddr_in *addr)
147 if (udptldebug == 0)
148 return 0;
149 if (udptldebugaddr.sin_addr.s_addr) {
150 if (((ntohs(udptldebugaddr.sin_port) != 0)
151 && (udptldebugaddr.sin_port != addr->sin_port))
152 || (udptldebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
153 return 0;
155 return 1;
158 static int decode_length(uint8_t *buf, int limit, int *len, int *pvalue)
160 if ((buf[*len] & 0x80) == 0) {
161 if (*len >= limit)
162 return -1;
163 *pvalue = buf[*len];
164 (*len)++;
165 return 0;
167 if ((buf[*len] & 0x40) == 0) {
168 if (*len >= limit - 1)
169 return -1;
170 *pvalue = (buf[*len] & 0x3F) << 8;
171 (*len)++;
172 *pvalue |= buf[*len];
173 (*len)++;
174 return 0;
176 if (*len >= limit)
177 return -1;
178 *pvalue = (buf[*len] & 0x3F) << 14;
179 (*len)++;
180 /* Indicate we have a fragment */
181 return 1;
183 /*- End of function --------------------------------------------------------*/
185 static int decode_open_type(uint8_t *buf, int limit, int *len, const uint8_t **p_object, int *p_num_octets)
187 int octet_cnt;
188 int octet_idx;
189 int stat;
190 int i;
191 const uint8_t **pbuf;
193 for (octet_idx = 0, *p_num_octets = 0; ; octet_idx += octet_cnt) {
194 if ((stat = decode_length(buf, limit, len, &octet_cnt)) < 0)
195 return -1;
196 if (octet_cnt > 0) {
197 *p_num_octets += octet_cnt;
199 pbuf = &p_object[octet_idx];
200 i = 0;
201 /* Make sure the buffer contains at least the number of bits requested */
202 if ((*len + octet_cnt) > limit)
203 return -1;
205 *pbuf = &buf[*len];
206 *len += octet_cnt;
208 if (stat == 0)
209 break;
211 return 0;
213 /*- End of function --------------------------------------------------------*/
215 static int encode_length(uint8_t *buf, int *len, int value)
217 int multiplier;
219 if (value < 0x80) {
220 /* 1 octet */
221 buf[*len] = value;
222 (*len)++;
223 return value;
225 if (value < 0x4000) {
226 /* 2 octets */
227 /* Set the first bit of the first octet */
228 buf[*len] = ((0x8000 | value) >> 8) & 0xFF;
229 (*len)++;
230 buf[*len] = value & 0xFF;
231 (*len)++;
232 return value;
234 /* Fragmentation */
235 multiplier = (value < 0x10000) ? (value >> 14) : 4;
236 /* Set the first 2 bits of the octet */
237 buf[*len] = 0xC0 | multiplier;
238 (*len)++;
239 return multiplier << 14;
241 /*- End of function --------------------------------------------------------*/
243 static int encode_open_type(uint8_t *buf, int *len, const uint8_t *data, int num_octets)
245 int enclen;
246 int octet_idx;
247 uint8_t zero_byte;
249 /* If open type is of zero length, add a single zero byte (10.1) */
250 if (num_octets == 0) {
251 zero_byte = 0;
252 data = &zero_byte;
253 num_octets = 1;
255 /* Encode the open type */
256 for (octet_idx = 0; ; num_octets -= enclen, octet_idx += enclen) {
257 if ((enclen = encode_length(buf, len, num_octets)) < 0)
258 return -1;
259 if (enclen > 0) {
260 memcpy(&buf[*len], &data[octet_idx], enclen);
261 *len += enclen;
263 if (enclen >= num_octets)
264 break;
267 return 0;
269 /*- End of function --------------------------------------------------------*/
271 static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, int len)
273 int stat;
274 int stat2;
275 int i;
276 int j;
277 int k;
278 int l;
279 int m;
280 int x;
281 int limit;
282 int which;
283 int ptr;
284 int count;
285 int total_count;
286 int seq_no;
287 const uint8_t *ifp;
288 const uint8_t *data;
289 int ifp_len;
290 int repaired[16];
291 const uint8_t *bufs[16];
292 int lengths[16];
293 int span;
294 int entries;
295 int ifp_no;
297 ptr = 0;
298 ifp_no = 0;
299 memset(&s->f[0], 0, sizeof(s->f[0]));
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 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
346 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
347 ifp_no++;
351 /* If packets are received out of sequence, we may have already processed this packet from the error
352 recovery information in a packet already received. */
353 if (seq_no >= s->rx_seq_no) {
354 /* Decode the primary IFP packet */
355 s->f[ifp_no].frametype = AST_FRAME_MODEM;
356 s->f[ifp_no].subclass = AST_MODEM_T38;
358 s->f[ifp_no].mallocd = 0;
359 //s->f[ifp_no].???seq_no = seq_no;
360 s->f[ifp_no].datalen = ifp_len;
361 s->f[ifp_no].data = (uint8_t *) ifp;
362 s->f[ifp_no].offset = 0;
363 s->f[ifp_no].src = "UDPTL";
364 if (ifp_no > 0)
365 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
366 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
369 else
371 /* FEC mode for error recovery */
372 /* Our buffers cannot tolerate overlength IFP packets in FEC mode */
373 if (ifp_len > LOCAL_FAX_MAX_DATAGRAM)
374 return -1;
375 /* Update any missed slots in the buffer */
376 for ( ; seq_no > s->rx_seq_no; s->rx_seq_no++) {
377 x = s->rx_seq_no & UDPTL_BUF_MASK;
378 s->rx[x].buf_len = -1;
379 s->rx[x].fec_len[0] = 0;
380 s->rx[x].fec_span = 0;
381 s->rx[x].fec_entries = 0;
384 x = seq_no & UDPTL_BUF_MASK;
386 memset(repaired, 0, sizeof(repaired));
388 /* Save the new IFP packet */
389 memcpy(s->rx[x].buf, ifp, ifp_len);
390 s->rx[x].buf_len = ifp_len;
391 repaired[x] = TRUE;
393 /* Decode the FEC packets */
394 /* The span is defined as an unconstrained integer, but will never be more
395 than a small value. */
396 if (ptr + 2 > len)
397 return -1;
398 if (buf[ptr++] != 1)
399 return -1;
400 span = buf[ptr++];
401 s->rx[x].fec_span = span;
403 /* The number of entries is defined as a length, but will only ever be a small
404 value. Treat it as such. */
405 if (ptr + 1 > len)
406 return -1;
407 entries = buf[ptr++];
408 s->rx[x].fec_entries = entries;
410 /* Decode the elements */
411 for (i = 0; i < entries; i++) {
412 if ((stat = decode_open_type(buf, len, &ptr, &data, &s->rx[x].fec_len[i])) != 0)
413 return -1;
414 if (s->rx[x].fec_len[i] > LOCAL_FAX_MAX_DATAGRAM)
415 return -1;
417 /* Save the new FEC data */
418 memcpy(s->rx[x].fec[i], data, s->rx[x].fec_len[i]);
419 #if 0
420 fprintf(stderr, "FEC: ");
421 for (j = 0; j < s->rx[x].fec_len[i]; j++)
422 fprintf(stderr, "%02X ", data[j]);
423 fprintf(stderr, "\n");
424 #endif
427 /* See if we can reconstruct anything which is missing */
428 /* TODO: this does not comprehensively hunt back and repair everything that is possible */
429 for (l = x; l != ((x - (16 - span*entries)) & UDPTL_BUF_MASK); l = (l - 1) & UDPTL_BUF_MASK) {
430 if (s->rx[l].fec_len[0] <= 0)
431 continue;
432 for (m = 0; m < s->rx[l].fec_entries; m++) {
433 limit = (l + m) & UDPTL_BUF_MASK;
434 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) {
435 if (s->rx[k].buf_len <= 0)
436 which = (which == -1) ? k : -2;
438 if (which >= 0) {
439 /* Repairable */
440 for (j = 0; j < s->rx[l].fec_len[m]; j++) {
441 s->rx[which].buf[j] = s->rx[l].fec[m][j];
442 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)
443 s->rx[which].buf[j] ^= (s->rx[k].buf_len > j) ? s->rx[k].buf[j] : 0;
445 s->rx[which].buf_len = s->rx[l].fec_len[m];
446 repaired[which] = TRUE;
450 /* Now play any new packets forwards in time */
451 for (l = (x + 1) & UDPTL_BUF_MASK, j = seq_no - UDPTL_BUF_MASK; l != x; l = (l + 1) & UDPTL_BUF_MASK, j++) {
452 if (repaired[l]) {
453 //fprintf(stderr, "Fixed packet %d, len %d\n", j, l);
454 s->f[ifp_no].frametype = AST_FRAME_MODEM;
455 s->f[ifp_no].subclass = AST_MODEM_T38;
457 s->f[ifp_no].mallocd = 0;
458 //s->f[ifp_no].???seq_no = j;
459 s->f[ifp_no].datalen = s->rx[l].buf_len;
460 s->f[ifp_no].data = s->rx[l].buf;
461 s->f[ifp_no].offset = 0;
462 s->f[ifp_no].src = "UDPTL";
463 if (ifp_no > 0)
464 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
465 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
466 ifp_no++;
469 /* Decode the primary IFP packet */
470 s->f[ifp_no].frametype = AST_FRAME_MODEM;
471 s->f[ifp_no].subclass = AST_MODEM_T38;
473 s->f[ifp_no].mallocd = 0;
474 //s->f[ifp_no].???seq_no = j;
475 s->f[ifp_no].datalen = ifp_len;
476 s->f[ifp_no].data = (uint8_t *) ifp;
477 s->f[ifp_no].offset = 0;
478 s->f[ifp_no].src = "UDPTL";
479 if (ifp_no > 0)
480 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
481 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
484 s->rx_seq_no = seq_no + 1;
485 return 0;
487 /*- End of function --------------------------------------------------------*/
489 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, uint8_t *ifp, int ifp_len)
491 uint8_t fec[LOCAL_FAX_MAX_DATAGRAM];
492 int i;
493 int j;
494 int seq;
495 int entry;
496 int entries;
497 int span;
498 int m;
499 int len;
500 int limit;
501 int high_tide;
503 seq = s->tx_seq_no & 0xFFFF;
505 /* Map the sequence number to an entry in the circular buffer */
506 entry = seq & UDPTL_BUF_MASK;
508 /* We save the message in a circular buffer, for generating FEC or
509 redundancy sets later on. */
510 s->tx[entry].buf_len = ifp_len;
511 memcpy(s->tx[entry].buf, ifp, ifp_len);
513 /* Build the UDPTLPacket */
515 len = 0;
516 /* Encode the sequence number */
517 buf[len++] = (seq >> 8) & 0xFF;
518 buf[len++] = seq & 0xFF;
520 /* Encode the primary IFP packet */
521 if (encode_open_type(buf, &len, ifp, ifp_len) < 0)
522 return -1;
524 /* Encode the appropriate type of error recovery information */
525 switch (s->error_correction_scheme)
527 case UDPTL_ERROR_CORRECTION_NONE:
528 /* Encode the error recovery type */
529 buf[len++] = 0x00;
530 /* The number of entries will always be zero, so it is pointless allowing
531 for the fragmented case here. */
532 if (encode_length(buf, &len, 0) < 0)
533 return -1;
534 break;
535 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
536 /* Encode the error recovery type */
537 buf[len++] = 0x00;
538 if (s->tx_seq_no > s->error_correction_entries)
539 entries = s->error_correction_entries;
540 else
541 entries = s->tx_seq_no;
542 /* The number of entries will always be small, so it is pointless allowing
543 for the fragmented case here. */
544 if (encode_length(buf, &len, entries) < 0)
545 return -1;
546 /* Encode the elements */
547 for (i = 0; i < entries; i++) {
548 j = (entry - i - 1) & UDPTL_BUF_MASK;
549 if (encode_open_type(buf, &len, s->tx[j].buf, s->tx[j].buf_len) < 0)
550 return -1;
552 break;
553 case UDPTL_ERROR_CORRECTION_FEC:
554 span = s->error_correction_span;
555 entries = s->error_correction_entries;
556 if (seq < s->error_correction_span*s->error_correction_entries) {
557 /* In the initial stages, wind up the FEC smoothly */
558 entries = seq/s->error_correction_span;
559 if (seq < s->error_correction_span)
560 span = 0;
562 /* Encode the error recovery type */
563 buf[len++] = 0x80;
564 /* Span is defined as an inconstrained integer, which it dumb. It will only
565 ever be a small value. Treat it as such. */
566 buf[len++] = 1;
567 buf[len++] = span;
568 /* The number of entries is defined as a length, but will only ever be a small
569 value. Treat it as such. */
570 buf[len++] = entries;
571 for (m = 0; m < entries; m++) {
572 /* Make an XOR'ed entry the maximum length */
573 limit = (entry + m) & UDPTL_BUF_MASK;
574 high_tide = 0;
575 for (i = (limit - span*entries) & UDPTL_BUF_MASK; i != limit; i = (i + entries) & UDPTL_BUF_MASK) {
576 if (high_tide < s->tx[i].buf_len) {
577 for (j = 0; j < high_tide; j++)
578 fec[j] ^= s->tx[i].buf[j];
579 for ( ; j < s->tx[i].buf_len; j++)
580 fec[j] = s->tx[i].buf[j];
581 high_tide = s->tx[i].buf_len;
582 } else {
583 for (j = 0; j < s->tx[i].buf_len; j++)
584 fec[j] ^= s->tx[i].buf[j];
587 if (encode_open_type(buf, &len, fec, high_tide) < 0)
588 return -1;
590 break;
593 if (s->verbose)
594 fprintf(stderr, "\n");
596 s->tx_seq_no++;
597 return len;
600 int ast_udptl_fd(struct ast_udptl *udptl)
602 return udptl->fd;
605 void ast_udptl_set_data(struct ast_udptl *udptl, void *data)
607 udptl->data = data;
610 void ast_udptl_set_callback(struct ast_udptl *udptl, ast_udptl_callback callback)
612 udptl->callback = callback;
615 void ast_udptl_setnat(struct ast_udptl *udptl, int nat)
617 udptl->nat = nat;
620 static int udptlread(int *id, int fd, short events, void *cbdata)
622 struct ast_udptl *udptl = cbdata;
623 struct ast_frame *f;
625 if ((f = ast_udptl_read(udptl))) {
626 if (udptl->callback)
627 udptl->callback(udptl, f, udptl->data);
629 return 1;
632 struct ast_frame *ast_udptl_read(struct ast_udptl *udptl)
634 int res;
635 struct sockaddr_in sin;
636 socklen_t len;
637 uint16_t seqno = 0;
638 uint16_t *udptlheader;
640 len = sizeof(sin);
642 /* Cache where the header will go */
643 res = recvfrom(udptl->fd,
644 udptl->rawdata + AST_FRIENDLY_OFFSET,
645 sizeof(udptl->rawdata) - AST_FRIENDLY_OFFSET,
647 (struct sockaddr *) &sin,
648 &len);
649 udptlheader = (uint16_t *)(udptl->rawdata + AST_FRIENDLY_OFFSET);
650 if (res < 0) {
651 if (errno != EAGAIN)
652 ast_log(LOG_WARNING, "UDPTL read error: %s\n", strerror(errno));
653 if (errno == EBADF)
654 CRASH;
655 return &ast_null_frame;
658 /* Ignore if the other side hasn't been given an address yet. */
659 if (!udptl->them.sin_addr.s_addr || !udptl->them.sin_port)
660 return &ast_null_frame;
662 if (udptl->nat) {
663 /* Send to whoever sent to us */
664 if ((udptl->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
665 (udptl->them.sin_port != sin.sin_port)) {
666 memcpy(&udptl->them, &sin, sizeof(udptl->them));
667 ast_log(LOG_DEBUG, "UDPTL NAT: Using address %s:%d\n", ast_inet_ntoa(udptl->them.sin_addr), ntohs(udptl->them.sin_port));
671 if (udptl_debug_test_addr(&sin)) {
672 ast_verbose("Got UDPTL packet from %s:%d (type %d, seq %d, len %d)\n",
673 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), 0, seqno, res);
675 #if 0
676 printf("Got UDPTL packet from %s:%d (seq %d, len = %d)\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), seqno, res);
677 #endif
678 udptl_rx_packet(udptl, udptl->rawdata + AST_FRIENDLY_OFFSET, res);
680 return &udptl->f[0];
683 void ast_udptl_offered_from_local(struct ast_udptl* udptl, int local)
685 if (udptl)
686 udptl->udptl_offered_from_local = local;
687 else
688 ast_log(LOG_WARNING, "udptl structure is null\n");
691 int ast_udptl_get_error_correction_scheme(struct ast_udptl* udptl)
693 if (udptl)
694 return udptl->error_correction_scheme;
695 else {
696 ast_log(LOG_WARNING, "udptl structure is null\n");
697 return -1;
701 void ast_udptl_set_error_correction_scheme(struct ast_udptl* udptl, int ec)
703 if (udptl) {
704 switch (ec) {
705 case UDPTL_ERROR_CORRECTION_FEC:
706 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
707 break;
708 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
709 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
710 break;
711 case UDPTL_ERROR_CORRECTION_NONE:
712 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_NONE;
713 break;
714 default:
715 ast_log(LOG_WARNING, "error correction parameter invalid\n");
717 } else
718 ast_log(LOG_WARNING, "udptl structure is null\n");
721 int ast_udptl_get_local_max_datagram(struct ast_udptl* udptl)
723 if (udptl)
724 return udptl->local_max_datagram_size;
725 else {
726 ast_log(LOG_WARNING, "udptl structure is null\n");
727 return -1;
731 int ast_udptl_get_far_max_datagram(struct ast_udptl* udptl)
733 if (udptl)
734 return udptl->far_max_datagram_size;
735 else {
736 ast_log(LOG_WARNING, "udptl structure is null\n");
737 return -1;
741 void ast_udptl_set_local_max_datagram(struct ast_udptl* udptl, int max_datagram)
743 if (udptl)
744 udptl->local_max_datagram_size = max_datagram;
745 else
746 ast_log(LOG_WARNING, "udptl structure is null\n");
749 void ast_udptl_set_far_max_datagram(struct ast_udptl* udptl, int max_datagram)
751 if (udptl)
752 udptl->far_max_datagram_size = max_datagram;
753 else
754 ast_log(LOG_WARNING, "udptl structure is null\n");
757 struct ast_udptl *ast_udptl_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int callbackmode, struct in_addr addr)
759 struct ast_udptl *udptl;
760 int x;
761 int startplace;
762 int i;
763 long int flags;
765 if (!(udptl = ast_calloc(1, sizeof(*udptl))))
766 return NULL;
768 if (udptlfectype == 2)
769 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
770 else if (udptlfectype == 1)
771 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
772 else
773 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_NONE;
774 udptl->error_correction_span = udptlfecspan;
775 udptl->error_correction_entries = udptlfecentries;
777 udptl->far_max_datagram_size = udptlmaxdatagram;
778 udptl->local_max_datagram_size = udptlmaxdatagram;
780 memset(&udptl->rx, 0, sizeof(udptl->rx));
781 memset(&udptl->tx, 0, sizeof(udptl->tx));
782 for (i = 0; i <= UDPTL_BUF_MASK; i++) {
783 udptl->rx[i].buf_len = -1;
784 udptl->tx[i].buf_len = -1;
787 udptl->seqno = ast_random() & 0xffff;
788 udptl->them.sin_family = AF_INET;
789 udptl->us.sin_family = AF_INET;
791 if ((udptl->fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
792 free(udptl);
793 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
794 return NULL;
796 flags = fcntl(udptl->fd, F_GETFL);
797 fcntl(udptl->fd, F_SETFL, flags | O_NONBLOCK);
798 #ifdef SO_NO_CHECK
799 if (nochecksums)
800 setsockopt(udptl->fd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
801 #endif
802 /* Find us a place */
803 x = (ast_random() % (udptlend - udptlstart)) + udptlstart;
804 startplace = x;
805 for (;;) {
806 udptl->us.sin_port = htons(x);
807 udptl->us.sin_addr = addr;
808 if (bind(udptl->fd, (struct sockaddr *) &udptl->us, sizeof(udptl->us)) == 0)
809 break;
810 if (errno != EADDRINUSE) {
811 ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
812 close(udptl->fd);
813 free(udptl);
814 return NULL;
816 if (++x > udptlend)
817 x = udptlstart;
818 if (x == startplace) {
819 ast_log(LOG_WARNING, "No UDPTL ports remaining\n");
820 close(udptl->fd);
821 free(udptl);
822 return NULL;
825 if (io && sched && callbackmode) {
826 /* Operate this one in a callback mode */
827 udptl->sched = sched;
828 udptl->io = io;
829 udptl->ioid = ast_io_add(udptl->io, udptl->fd, udptlread, AST_IO_IN, udptl);
831 return udptl;
834 struct ast_udptl *ast_udptl_new(struct sched_context *sched, struct io_context *io, int callbackmode)
836 struct in_addr ia;
837 memset(&ia, 0, sizeof(ia));
838 return ast_udptl_new_with_bindaddr(sched, io, callbackmode, ia);
841 int ast_udptl_settos(struct ast_udptl *udptl, int tos)
843 int res;
845 if ((res = setsockopt(udptl->fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
846 ast_log(LOG_WARNING, "UDPTL unable to set TOS to %d\n", tos);
847 return res;
850 void ast_udptl_set_peer(struct ast_udptl *udptl, struct sockaddr_in *them)
852 udptl->them.sin_port = them->sin_port;
853 udptl->them.sin_addr = them->sin_addr;
856 void ast_udptl_get_peer(struct ast_udptl *udptl, struct sockaddr_in *them)
858 them->sin_family = AF_INET;
859 them->sin_port = udptl->them.sin_port;
860 them->sin_addr = udptl->them.sin_addr;
863 void ast_udptl_get_us(struct ast_udptl *udptl, struct sockaddr_in *us)
865 memcpy(us, &udptl->us, sizeof(udptl->us));
868 void ast_udptl_stop(struct ast_udptl *udptl)
870 memset(&udptl->them.sin_addr, 0, sizeof(udptl->them.sin_addr));
871 memset(&udptl->them.sin_port, 0, sizeof(udptl->them.sin_port));
874 void ast_udptl_destroy(struct ast_udptl *udptl)
876 if (udptl->ioid)
877 ast_io_remove(udptl->io, udptl->ioid);
878 if (udptl->fd > -1)
879 close(udptl->fd);
880 free(udptl);
883 int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
885 int len;
886 int res;
887 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
889 /* If we have no peer, return immediately */
890 if (s->them.sin_addr.s_addr == INADDR_ANY)
891 return 0;
893 /* If there is no data length, return immediately */
894 if (f->datalen == 0)
895 return 0;
897 if (f->frametype != AST_FRAME_MODEM) {
898 ast_log(LOG_WARNING, "UDPTL can only send T.38 data\n");
899 return -1;
902 /* Cook up the UDPTL packet, with the relevant EC info. */
903 len = udptl_build_packet(s, buf, f->data, f->datalen);
905 if (len > 0 && s->them.sin_port && s->them.sin_addr.s_addr) {
906 if ((res = sendto(s->fd, buf, len, 0, (struct sockaddr *) &s->them, sizeof(s->them))) < 0)
907 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));
908 #if 0
909 printf("Sent %d bytes of UDPTL data to %s:%d\n", res, ast_inet_ntoa(udptl->them.sin_addr), ntohs(udptl->them.sin_port));
910 #endif
911 if (udptl_debug_test_addr(&s->them))
912 ast_verbose("Sent UDPTL packet to %s:%d (type %d, seq %d, len %d)\n",
913 ast_inet_ntoa(s->them.sin_addr),
914 ntohs(s->them.sin_port), 0, s->seqno, len);
917 return 0;
920 void ast_udptl_proto_unregister(struct ast_udptl_protocol *proto)
922 struct ast_udptl_protocol *cur;
923 struct ast_udptl_protocol *prev;
925 cur = protos;
926 prev = NULL;
927 while (cur) {
928 if (cur == proto) {
929 if (prev)
930 prev->next = proto->next;
931 else
932 protos = proto->next;
933 return;
935 prev = cur;
936 cur = cur->next;
940 int ast_udptl_proto_register(struct ast_udptl_protocol *proto)
942 struct ast_udptl_protocol *cur;
944 cur = protos;
945 while (cur) {
946 if (cur->type == proto->type) {
947 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
948 return -1;
950 cur = cur->next;
952 proto->next = protos;
953 protos = proto;
954 return 0;
957 static struct ast_udptl_protocol *get_proto(struct ast_channel *chan)
959 struct ast_udptl_protocol *cur;
961 cur = protos;
962 while (cur) {
963 if (cur->type == chan->tech->type)
964 return cur;
965 cur = cur->next;
967 return NULL;
970 int ast_udptl_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
972 struct ast_frame *f;
973 struct ast_channel *who;
974 struct ast_channel *cs[3];
975 struct ast_udptl *p0;
976 struct ast_udptl *p1;
977 struct ast_udptl_protocol *pr0;
978 struct ast_udptl_protocol *pr1;
979 struct sockaddr_in ac0;
980 struct sockaddr_in ac1;
981 struct sockaddr_in t0;
982 struct sockaddr_in t1;
983 void *pvt0;
984 void *pvt1;
985 int to;
987 ast_channel_lock(c0);
988 while (ast_channel_trylock(c1)) {
989 ast_channel_unlock(c0);
990 usleep(1);
991 ast_channel_lock(c0);
993 pr0 = get_proto(c0);
994 pr1 = get_proto(c1);
995 if (!pr0) {
996 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
997 ast_channel_unlock(c0);
998 ast_channel_unlock(c1);
999 return -1;
1001 if (!pr1) {
1002 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
1003 ast_channel_unlock(c0);
1004 ast_channel_unlock(c1);
1005 return -1;
1007 pvt0 = c0->tech_pvt;
1008 pvt1 = c1->tech_pvt;
1009 p0 = pr0->get_udptl_info(c0);
1010 p1 = pr1->get_udptl_info(c1);
1011 if (!p0 || !p1) {
1012 /* Somebody doesn't want to play... */
1013 ast_channel_unlock(c0);
1014 ast_channel_unlock(c1);
1015 return -2;
1017 if (pr0->set_udptl_peer(c0, p1)) {
1018 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
1019 } else {
1020 /* Store UDPTL peer */
1021 ast_udptl_get_peer(p1, &ac1);
1023 if (pr1->set_udptl_peer(c1, p0))
1024 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
1025 else {
1026 /* Store UDPTL peer */
1027 ast_udptl_get_peer(p0, &ac0);
1029 ast_channel_unlock(c0);
1030 ast_channel_unlock(c1);
1031 cs[0] = c0;
1032 cs[1] = c1;
1033 cs[2] = NULL;
1034 for (;;) {
1035 if ((c0->tech_pvt != pvt0) ||
1036 (c1->tech_pvt != pvt1) ||
1037 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
1038 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
1039 /* Tell it to try again later */
1040 return -3;
1042 to = -1;
1043 ast_udptl_get_peer(p1, &t1);
1044 ast_udptl_get_peer(p0, &t0);
1045 if (inaddrcmp(&t1, &ac1)) {
1046 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d\n",
1047 c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port));
1048 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d\n",
1049 c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port));
1050 memcpy(&ac1, &t1, sizeof(ac1));
1052 if (inaddrcmp(&t0, &ac0)) {
1053 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d\n",
1054 c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port));
1055 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d\n",
1056 c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port));
1057 memcpy(&ac0, &t0, sizeof(ac0));
1059 who = ast_waitfor_n(cs, 2, &to);
1060 if (!who) {
1061 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
1062 /* check for hangup / whentohangup */
1063 if (ast_check_hangup(c0) || ast_check_hangup(c1))
1064 break;
1065 continue;
1067 f = ast_read(who);
1068 if (!f) {
1069 *fo = f;
1070 *rc = who;
1071 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
1072 /* That's all we needed */
1073 return 0;
1074 } else {
1075 if (f->frametype == AST_FRAME_MODEM) {
1076 /* Forward T.38 frames if they happen upon us */
1077 if (who == c0) {
1078 ast_write(c1, f);
1079 } else if (who == c1) {
1080 ast_write(c0, f);
1083 ast_frfree(f);
1085 /* Swap priority. Not that it's a big deal at this point */
1086 cs[2] = cs[0];
1087 cs[0] = cs[1];
1088 cs[1] = cs[2];
1090 return -1;
1093 static int udptl_do_debug_ip(int fd, int argc, char *argv[])
1095 struct hostent *hp;
1096 struct ast_hostent ahp;
1097 int port;
1098 char *p;
1099 char *arg;
1101 port = 0;
1102 if (argc != 4)
1103 return RESULT_SHOWUSAGE;
1104 arg = argv[3];
1105 p = strstr(arg, ":");
1106 if (p) {
1107 *p = '\0';
1108 p++;
1109 port = atoi(p);
1111 hp = ast_gethostbyname(arg, &ahp);
1112 if (hp == NULL)
1113 return RESULT_SHOWUSAGE;
1114 udptldebugaddr.sin_family = AF_INET;
1115 memcpy(&udptldebugaddr.sin_addr, hp->h_addr, sizeof(udptldebugaddr.sin_addr));
1116 udptldebugaddr.sin_port = htons(port);
1117 if (port == 0)
1118 ast_cli(fd, "UDPTL Debugging Enabled for IP: %s\n", ast_inet_ntoa(udptldebugaddr.sin_addr));
1119 else
1120 ast_cli(fd, "UDPTL Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(udptldebugaddr.sin_addr), port);
1121 udptldebug = 1;
1122 return RESULT_SUCCESS;
1125 static int udptl_do_debug(int fd, int argc, char *argv[])
1127 if (argc != 2) {
1128 if (argc != 4)
1129 return RESULT_SHOWUSAGE;
1130 return udptl_do_debug_ip(fd, argc, argv);
1132 udptldebug = 1;
1133 memset(&udptldebugaddr,0,sizeof(udptldebugaddr));
1134 ast_cli(fd, "UDPTL Debugging Enabled\n");
1135 return RESULT_SUCCESS;
1138 static int udptl_nodebug(int fd, int argc, char *argv[])
1140 if (argc != 3)
1141 return RESULT_SHOWUSAGE;
1142 udptldebug = 0;
1143 ast_cli(fd,"UDPTL Debugging Disabled\n");
1144 return RESULT_SUCCESS;
1147 static char debug_usage[] =
1148 "Usage: udptl debug [ip host[:port]]\n"
1149 " Enable dumping of all UDPTL packets to and from host.\n";
1151 static char nodebug_usage[] =
1152 "Usage: udptl debug off\n"
1153 " Disable all UDPTL debugging\n";
1155 static struct ast_cli_entry cli_udptl_no_debug = {
1156 { "udptl", "no", "debug", NULL },
1157 udptl_nodebug, NULL,
1158 NULL };
1160 static struct ast_cli_entry cli_udptl[] = {
1161 { { "udptl", "debug", NULL },
1162 udptl_do_debug, "Enable UDPTL debugging",
1163 debug_usage },
1165 { { "udptl", "debug", "ip", NULL },
1166 udptl_do_debug, "Enable UDPTL debugging on IP",
1167 debug_usage },
1169 { { "udptl", "debug", "off", NULL },
1170 udptl_nodebug, "Disable UDPTL debugging",
1171 nodebug_usage, NULL, &cli_udptl_no_debug },
1174 void ast_udptl_reload(void)
1176 struct ast_config *cfg;
1177 const char *s;
1179 udptlstart = 4500;
1180 udptlend = 4999;
1181 udptlfectype = 0;
1182 udptlfecentries = 0;
1183 udptlfecspan = 0;
1184 udptlmaxdatagram = 0;
1186 if ((cfg = ast_config_load("udptl.conf"))) {
1187 if ((s = ast_variable_retrieve(cfg, "general", "udptlstart"))) {
1188 udptlstart = atoi(s);
1189 if (udptlstart < 1024)
1190 udptlstart = 1024;
1191 if (udptlstart > 65535)
1192 udptlstart = 65535;
1194 if ((s = ast_variable_retrieve(cfg, "general", "udptlend"))) {
1195 udptlend = atoi(s);
1196 if (udptlend < 1024)
1197 udptlend = 1024;
1198 if (udptlend > 65535)
1199 udptlend = 65535;
1201 if ((s = ast_variable_retrieve(cfg, "general", "udptlchecksums"))) {
1202 #ifdef SO_NO_CHECK
1203 if (ast_false(s))
1204 nochecksums = 1;
1205 else
1206 nochecksums = 0;
1207 #else
1208 if (ast_false(s))
1209 ast_log(LOG_WARNING, "Disabling UDPTL checksums is not supported on this operating system!\n");
1210 #endif
1212 if ((s = ast_variable_retrieve(cfg, "general", "T38FaxUdpEC"))) {
1213 if (strcmp(s, "t38UDPFEC") == 0)
1214 udptlfectype = 2;
1215 else if (strcmp(s, "t38UDPRedundancy") == 0)
1216 udptlfectype = 1;
1218 if ((s = ast_variable_retrieve(cfg, "general", "T38FaxMaxDatagram"))) {
1219 udptlmaxdatagram = atoi(s);
1220 if (udptlmaxdatagram < 0)
1221 udptlmaxdatagram = 0;
1222 if (udptlmaxdatagram > LOCAL_FAX_MAX_DATAGRAM)
1223 udptlmaxdatagram = LOCAL_FAX_MAX_DATAGRAM;
1225 if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECentries"))) {
1226 udptlfecentries = atoi(s);
1227 if (udptlfecentries < 0)
1228 udptlfecentries = 0;
1229 if (udptlfecentries > MAX_FEC_ENTRIES)
1230 udptlfecentries = MAX_FEC_ENTRIES;
1232 if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECspan"))) {
1233 udptlfecspan = atoi(s);
1234 if (udptlfecspan < 0)
1235 udptlfecspan = 0;
1236 if (udptlfecspan > MAX_FEC_SPAN)
1237 udptlfecspan = MAX_FEC_SPAN;
1239 ast_config_destroy(cfg);
1241 if (udptlstart >= udptlend) {
1242 ast_log(LOG_WARNING, "Unreasonable values for UDPTL start/end\n");
1243 udptlstart = 4500;
1244 udptlend = 4999;
1246 if (option_verbose > 1)
1247 ast_verbose(VERBOSE_PREFIX_2 "UDPTL allocating from port range %d -> %d\n", udptlstart, udptlend);
1250 void ast_udptl_init(void)
1252 ast_cli_register_multiple(cli_udptl, sizeof(cli_udptl) / sizeof(struct ast_cli_entry));
1253 ast_udptl_reload();