Debian Codegraph @

3rdparty/iaxclient/lib/libiax2/src/iax.c

raw symbols SCIP
1 /*
2 * libiax: An implementation of Inter-Asterisk eXchange
3 *
4 * Copyright (C) 2001, Linux Support Services, Inc.
5 *
6 * Mark Spencer <[email protected]>
7 * Frik Strecker <[email protected]>
8 *
9 * This program is free software, distributed under the terms of
10 * the GNU Lesser (Library) General Public License
11 */
12
13 #ifdef HAVE_CONFIG_H
14 #include "config.h"
15 #endif
16
17 #if defined(WIN32) || defined(_WIN32_WCE)
18 #undef __STRICT_ANSI__ //for strdup with ms
19 #include "winpoop.h"
20 #if defined(_WIN32_WCE)
21 #define strdup _strdup
22 #else
23 #include <process.h>
24 #include <fcntl.h>
25 #include <io.h>
26 #include <errno.h>
27 #endif
28 #include <string.h>
29 #include <time.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <limits.h>
34
35 #if !defined(_WIN32_WCE)
36 #include <sys/timeb.h>
37 #endif
38
39 #define snprintf _snprintf
40
41 #if defined(_MSC_VER)
42 #define close closesocket
43 #if !defined(_WIN32_WCE)
44 #define inline __inline
45 #endif
46 #endif
47
48 #else // !#if defined(WIN32) || defined(_WIN32_WCE)
49 #include <netdb.h>
50 #include <sys/socket.h>
51 #include <netinet/in.h>
52 #include <sys/time.h> // gettimeofday
53 #ifndef HAVE_GETTIMEOFDAY
54 #define HAVE_GETTIMEOFDAY 1
55 #endif
56 #include <stdlib.h>
57
58 #ifdef __GNUC__
59 #ifndef __USE_SVID
60 #define __USE_SVID
61 #endif
62 #endif
63
64 #include <string.h>
65 #include <stdarg.h>
66 #include <stdio.h>
67 #include <unistd.h>
68 #include <fcntl.h>
69 #include <errno.h>
70 #include <sys/select.h>
71 #include <netinet/in.h>
72 #include <arpa/inet.h>
73 #include <time.h>
74
75 // FlightGear: Modified to include FreeBSD
76 #if !defined(MACOSX) && !defined(__OpenBSD__) && !defined(__FreeBSD__)
77 #include <malloc.h>
78 #if !defined(SOLARIS)
79 #include <error.h>
80 #endif
81 #endif
82
83 #endif // #if defined(WIN32) || defined(_WIN32_WCE) yes or no
84
85 #ifndef _MSC_VER
86 #endif
87
88 #include "jitterbuf.h"
89 #include "iax-client.h"
90 #include "md5.h"
91
92 /* Define socket options for IAX2 sockets, based on platform
93 * availability of flags */
94 #if defined(WIN32) || defined(_WIN32_WCE)
95 #define IAX_SOCKOPTS 0
96 #else
97 #ifdef MACOSX
98 #define IAX_SOCKOPTS MSG_DONTWAIT
99 #else
100 #if defined(SOLARIS) || defined(__OpenBSD__)
101 #define IAX_SOCKOPTS MSG_DONTWAIT
102 #else /* Linux and others */
103 #define IAX_SOCKOPTS MSG_DONTWAIT | MSG_NOSIGNAL
104 #endif
105 #endif
106 #endif
107
108
109 #ifdef SNOM_HACK
110 /* The snom phone seems to improperly execute memset in some cases */
111 #include "../../snom_phonecore2/include/snom_memset.h"
112 #endif
113
114 /* Voice TS Prediction causes libiax2 to clean up the timestamps on
115 * outgoing frames. It works best with either continuous voice, or
116 * callers who call iax_send_cng to indicate DTX for silence */
117 #define USE_VOICE_TS_PREDICTION
118
119 #define MIN_RETRY_TIME 10
120 #define MAX_RETRY_TIME 4000
121 #define MEMORY_SIZE 1000
122
123 #define TRANSFER_NONE 0
124 #define TRANSFER_BEGIN 1
125 #define TRANSFER_READY 2
126 #define TRANSFER_REL 3
127
128 /* Video frames bypass jitterbuffer */
129 static int video_bypass_jitterbuffer = 0;
130
131 /* To use or not to use the jitterbuffer */
132 static int iax_use_jitterbuffer = 1;
133
134 /* UDP Socket (file descriptor) */
135 static int netfd = -1;
136
137 /* Max timeouts */
138 static const int maxretries = 10;
139
140 /* configurable jitterbuffer options */
141 static long jb_target_extra = -1;
142
143 /* external global networking replacements */
144 static iax_sendto_t iax_sendto = (iax_sendto_t) sendto;
145 static iax_recvfrom_t iax_recvfrom = (iax_recvfrom_t) recvfrom;
146
147 /* ping interval (seconds) */
148 static int ping_time = 10;
149 static void send_ping(void *session);
150
151 struct iax_session {
152 /* Private data */
153 void *pvt;
154 /* session-local Sendto function */
155 iax_sendto_t sendto;
156 /* Is voice quelched (e.g. hold) */
157 int quelch;
158 /* Codec Pref Order */
159 char codec_order[32];
160 /* Codec Pref Order Index*/
161 int codec_order_len;
162 /* Last received voice format */
163 int voiceformat;
164 /* Last transmitted voice format */
165 int svoiceformat;
166 /* Last received video format */
167 int videoformat;
168 /* Last transmitted video format */
169 int svideoformat;
170 /* Per session capability */
171 int capability;
172 /* Last received timestamp */
173 unsigned int last_ts;
174 /* Last transmitted timestamp */
175 unsigned int lastsent;
176 /* Timestamp of the last transmitted video frame */
177 unsigned int lastvsent;
178 #ifdef USE_VOICE_TS_PREDICTION
179 /* Next predicted voice ts */
180 unsigned int nextpred;
181 /* True if the last voice we transmitted was not silence/CNG */
182 int notsilenttx;
183 #endif
184 /* Our last measured ping time */
185 unsigned int pingtime;
186 /* Address of peer */
187 struct sockaddr_in peeraddr;
188 /* Our call number */
189 int callno;
190 /* Peer's call number */
191 int peercallno;
192 /* Our next outgoing sequence number */
193 unsigned char oseqno;
194 /* Next sequence number they have not yet acknowledged */
195 unsigned char rseqno;
196 /* Our last received incoming sequence number */
197 unsigned char iseqno;
198 /* Last acknowledged sequence number */
199 unsigned char aseqno;
200 /* Last sequence number we VNAKd */
201 unsigned char lastvnak;
202 /* Time value that we base our transmission on */
203 struct timeval offset;
204 /* Time value we base our delivery on */
205 struct timeval rxcore;
206 /* Current link state */
207 int state;
208 /* Unregister reason */
209 char unregreason[MAXSTRLEN];
210 /* Expected Username */
211 char username[MAXSTRLEN];
212 /* Expected Secret */
213 char secret[MAXSTRLEN];
214 /* Refresh if applicable */
215 int refresh;
216
217 /* ping scheduler id */
218 int pingid;
219
220 /* Transfer stuff */
221 struct sockaddr_in transfer;
222 int transferring;
223 int transfercallno;
224 int transferid;
225 int transferpeer; /* for attended transfer */
226 int transfer_moh; /* for music on hold while performing attended transfer */
227
228 jitterbuf *jb;
229
230 struct iax_netstat remote_netstats;
231
232 /* For linking if there are multiple connections */
233 struct iax_session *next;
234 };
235
236 char iax_errstr[256];
237
238
239 #define IAXERROR snprintf(iax_errstr, sizeof(iax_errstr),
240
241 #ifdef DEBUG_SUPPORT
242
243 #ifdef DEBUG_DEFAULT
244 static int debug = 1;
245 #else
246 static int debug = 0;
247 #endif
248
249 void iax_enable_debug(void)
250 {
251 debug = 1;
252 }
253
254 void iax_disable_debug(void)
255 {
256 debug = 0;
257 }
258
259 void iax_enable_jitterbuffer(void)
260 {
261 iax_use_jitterbuffer = 1;
262 }
263
264 void iax_disable_jitterbuffer(void)
265 {
266 iax_use_jitterbuffer = 0;
267 }
268
269 void iax_set_private(struct iax_session *s, void *ptr)
270 {
271 s->pvt = ptr;
272 }
273
274 void *iax_get_private(struct iax_session *s)
275 {
276 return s->pvt;
277 }
278
279 void iax_set_sendto(struct iax_session *s, iax_sendto_t ptr)
280 {
281 s->sendto = ptr;
282 }
283
284 /* This is a little strange, but to debug you call DEBU(G "Hello World!\n"); */
285 #if defined(WIN32) || defined(_WIN32_WCE)
286 #define G __FILE__, __LINE__,
287 #else
288 #define G __FILE__, __LINE__, __PRETTY_FUNCTION__,
289 #endif
290
291 #define DEBU __debug
292 #if defined(WIN32) || defined(_WIN32_WCE)
293 static int __debug(const char *file, int lineno, const char *fmt, ...)
294 {
295 va_list args;
296 va_start(args, fmt);
297 if (debug) {
298 fprintf(stderr, "%s line %d: ", file, lineno);
299 vfprintf(stderr, fmt, args);
300 }
301 va_end(args);
302 return 0;
303 }
304 #else
305 static int __debug(const char *file, int lineno, const char *func, const char *fmt, ...)
306 {
307 va_list args;
308 va_start(args, fmt);
309 if (debug) {
310 fprintf(stderr, "%s line %d in %s: ", file, lineno, func);
311 vfprintf(stderr, fmt, args);
312 }
313 va_end(args);
314 return 0;
315 }
316 #endif
317 #else /* No debug support */
318
319 #if defined(WIN32) || defined(_WIN32_WCE)
320 #define DEBU
321 #else
322 #define DEBU(fmt...) \
323 do {} while(0)
324 #endif
325 #define G
326 #endif
327
328 void iax_seed_random()
329 {
330 #if defined(HAVE_SRANDOMDEV)
331 srandomdev();
332 #elif defined(HAVE_SRANDOM)
333 srandom((unsigned int)time(0));
334 #elif defined(HAVE_SRAND48)
335 srand48((long int)time(0));
336 #else
337 srand((unsigned int)time(0));
338 #endif
339 }
340
341 int iax_random()
342 {
343 #if defined(HAVE_RANDOM)
344 return (int)random();
345 #elif defined(HAVE_LRAND48)
346 return (int)lrand48();
347 #else
348 return rand();
349 #endif
350 }
351
352 typedef void (*sched_func)(void *);
353
354 struct iax_sched {
355 /* These are scheduled things to be delivered */
356 struct timeval when;
357 /* If event is non-NULL then we're delivering an event */
358 struct iax_event *event;
359 /* If frame is non-NULL then we're transmitting a frame */
360 struct iax_frame *frame;
361 /* If func is non-NULL then we should call it */
362 sched_func func;
363 /* and pass it this argument */
364 void *arg;
365 /* Easy linking */
366 struct iax_sched *next;
367 };
368
369 static struct iax_sched *schedq = NULL;
370 static struct iax_session *sessions = NULL;
371 static int callnums = 1;
372
373 unsigned int iax_session_get_capability(struct iax_session *s)
374 {
375 return s->capability;
376 }
377
378 static int inaddrcmp(struct sockaddr_in *sin1, struct sockaddr_in *sin2)
379 {
380 return (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr) || (sin1->sin_port != sin2->sin_port);
381 }
382
383 static int iax_sched_add(struct iax_event *event, struct iax_frame *frame, sched_func func, void *arg, int ms)
384 {
385
386 /* Schedule event to be delivered to the client
387 in ms milliseconds from now, or a reliable frame to be retransmitted */
388 struct iax_sched *sched, *cur, *prev = NULL;
389
390 if (!event && !frame && !func) {
391 DEBU(G "No event, no frame, no func? what are we scheduling?\n");
392 return -1;
393 }
394
395 //fprintf(stderr, "scheduling event %d ms from now\n", ms);
396 sched = (struct iax_sched*)malloc(sizeof(struct iax_sched));
397 if (sched) {
398 memset(sched, 0, sizeof(struct iax_sched));
399 sched->when = iax_tvnow();
400 sched->when.tv_sec += (ms / 1000);
401 ms = ms % 1000;
402 sched->when.tv_usec += (ms * 1000);
403 if (sched->when.tv_usec > 1000000) {
404 sched->when.tv_usec -= 1000000;
405 sched->when.tv_sec++;
406 }
407 sched->event = event;
408 sched->frame = frame;
409 sched->func = func;
410 sched->arg = arg;
411 /* Put it in the list, in order */
412 cur = schedq;
413 while(cur && ((cur->when.tv_sec < sched->when.tv_sec) ||
414 ((cur->when.tv_usec <= sched->when.tv_usec) &&
415 (cur->when.tv_sec == sched->when.tv_sec)))) {
416 prev = cur;
417 cur = cur->next;
418 }
419 sched->next = cur;
420 if (prev) {
421 prev->next = sched;
422 } else {
423 schedq = sched;
424 }
425 return 0;
426 } else {
427 DEBU(G "Out of memory!\n");
428 return -1;
429 }
430 }
431
432 static int iax_sched_del(struct iax_event *event, struct iax_frame *frame, sched_func func, void *arg, int all)
433 {
434 struct iax_sched *cur, *tmp, *prev = NULL;
435
436 cur = schedq;
437 while (cur) {
438 if (cur->event == event && cur->frame == frame && cur->func == func && cur->arg == arg) {
439 if (prev)
440 prev->next = cur->next;
441 else
442 schedq = cur->next;
443 tmp = cur;
444 cur = cur->next;
445 free(tmp);
446 if (!all)
447 return -1;
448 } else {
449 prev = cur;
450 cur = cur->next;
451 }
452 }
453 return 0;
454 }
455
456
457 int iax_time_to_next_event(void)
458 {
459 struct timeval tv;
460 struct iax_sched *cur = schedq;
461 int ms, min = 999999999;
462
463 /* If there are no pending events, we don't need to timeout */
464 if (!cur)
465 return -1;
466 tv = iax_tvnow();
467 while(cur) {
468 ms = (cur->when.tv_sec - tv.tv_sec) * 1000 +
469 (cur->when.tv_usec - tv.tv_usec) / 1000;
470 if (ms < min)
471 min = ms;
472 cur = cur->next;
473 }
474 if (min < 0)
475 min = 0;
476 return min;
477 }
478
479 struct iax_session *iax_session_new(void)
480 {
481 struct iax_session *s;
482 s = calloc(1, sizeof(struct iax_session));
483 if (s) {
484 jb_conf jbconf;
485
486 /* Initialize important fields */
487 s->voiceformat = -1;
488 s->svoiceformat = -1;
489 s->videoformat = -1;
490 /* Default pingtime to 100 ms -- should cover most decent net connections */
491 s->pingtime = 100;
492 /* XXX Not quite right -- make sure it's not in use, but that won't matter
493 unless you've had at least 65k calls. XXX */
494 s->callno = callnums++;
495 if (callnums > 32767)
496 callnums = 1;
497 s->peercallno = 0;
498 s->lastvnak = -1;
499 s->transferpeer = 0; /* for attended transfer */
500 s->next = sessions;
501 s->sendto = iax_sendto;
502 s->pingid = -1;
503
504 #ifdef USE_VOICE_TS_PREDICTION
505 s->nextpred = 0;
506 #endif
507
508 s->jb = jb_new();
509 if ( !s->jb )
510 {
511 free(s);
512 return 0;
513 }
514 jbconf.max_jitterbuf = 0;
515 jbconf.resync_threshold = 1000;
516 jbconf.max_contig_interp = 0;
517 jbconf.target_extra = jb_target_extra;
518 jb_setconf(s->jb, &jbconf);
519
520 sessions = s;
521 }
522 return s;
523 }
524
525 static int iax_session_valid(struct iax_session *session)
526 {
527 /* Return -1 on a valid iax session pointer, 0 on a failure */
528 struct iax_session *cur = sessions;
529 while(cur) {
530 if (session == cur)
531 return -1;
532 cur = cur->next;
533 }
534 return 0;
535 }
536
537 int iax_get_netstats(struct iax_session *session, int *rtt, struct iax_netstat *local, struct iax_netstat *remote)
538 {
539 jb_info stats;
540
541 if(!iax_session_valid(session)) return -1;
542
543 *rtt = session->pingtime;
544
545 *remote = session->remote_netstats;
546
547 jb_getinfo(session->jb, &stats);
548
549 local->jitter = stats.jitter;
550 /* XXX: should be short-term loss pct.. */
551 if(stats.frames_in == 0) stats.frames_in = 1;
552 local->losspct = stats.losspct/1000;
553 local->losscnt = stats.frames_lost;
554 local->packets = stats.frames_in;
555 local->delay = stats.current - stats.min;
556 local->dropped = stats.frames_dropped;
557 local->ooo = stats.frames_ooo;
558
559 return 0;
560 }
561
562 #ifdef USE_VOICE_TS_PREDICTION
563 static void add_ms(struct timeval *tv, int ms)
564 {
565 tv->tv_usec += ms * 1000;
566 if (tv->tv_usec > 999999) {
567 tv->tv_sec += tv->tv_usec / 1000000;
568 tv->tv_usec %= 1000000;
569 }
570
571 if (tv->tv_usec < 0) {
572 tv->tv_sec += (tv->tv_usec / 1000000 - 1);
573 tv->tv_usec = (tv->tv_usec % 1000000) + 1000000;
574 }
575 }
576 #endif
577
578 static int calc_timestamp(struct iax_session *session, unsigned int ts, struct ast_frame *f)
579 {
580 int ms;
581 struct timeval tv;
582 int voice = 0;
583 int video = 0;
584 int genuine = 0;
585
586 if ( f && f->frametype == AST_FRAME_VOICE )
587 {
588 voice = 1;
589 } else if ( f && f->frametype == AST_FRAME_VIDEO )
590 {
591 video = 1;
592 } else if (!f || f->frametype == AST_FRAME_IAX)
593 {
594 genuine = 1;
595 }
596
597 /* If this is the first packet we're sending, get our
598 offset now. */
599 if (!session->offset.tv_sec && !session->offset.tv_usec)
600 session->offset = iax_tvnow();
601
602 /* If the timestamp is specified, just use their specified
603 timestamp no matter what. Usually this is done for
604 special cases. */
605 if (ts)
606 {
607 if ( f && session )
608 session->lastsent = ts;
609 return ts;
610 }
611
612 /* Otherwise calculate the timestamp from the current time */
613 tv = iax_tvnow();
614
615 /* Calculate the number of milliseconds since we sent the first packet */
616 ms = (tv.tv_sec - session->offset.tv_sec) * 1000 +
617 (tv.tv_usec - session->offset.tv_usec) / 1000;
618
619 if (ms < 0)
620 ms = 0;
621
622 if(voice) {
623 #ifdef USE_VOICE_TS_PREDICTION
624 /* If we haven't most recently sent silence, and we're
625 * close in time, use predicted time */
626 if(session->notsilenttx && (ms - session->nextpred) <= 240) {
627 /* Adjust our txcore, keeping voice and non-voice
628 * synchronized */
629 add_ms(&session->offset, (int)(ms - session->nextpred)/10);
630
631 if(!session->nextpred)
632 session->nextpred = ms;
633 ms = session->nextpred;
634 } else {
635 /* in this case, just use the actual time, since
636 * we're either way off (shouldn't happen), or we're
637 * ending a silent period -- and seed the next predicted
638 * time. Also, round ms to the next multiple of
639 * frame size (so our silent periods are multiples
640 * of frame size too) */
641 int diff = ms % (f->samples / 8);
642 if(diff)
643 ms += f->samples/8 - diff;
644 session->nextpred = ms;
645 }
646 session->notsilenttx = 1;
647 #else
648 if(ms <= session->lastsent)
649 ms = session->lastsent + 3;
650 #endif
651 } else if ( video ) {
652 /*
653 * IAX2 draft 03 says that timestamps MUST be in order.
654 * It does not say anything about several frames having the same timestamp
655 * When transporting video, we can have a frame that spans multiple iax packets
656 * (so called slices), so it would make sense to use the same timestamp for all of
657 * them
658 * We do want to make sure that frames don't go backwards though
659 */
660 if ( (unsigned int)ms < session->lastsent )
661 ms = session->lastsent;
662 } else {
663 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking)
664 if appropriate unless it's a genuine frame */
665 if (genuine) {
666 if ((unsigned int)ms <= session->lastsent)
667 ms = session->lastsent + 3;
668 } else if ((ms - session->lastsent) <= 240) {
669 ms = session->lastsent + 3;
670 }
671
672 }
673
674 /* Record the last sent packet for future reference */
675 /* unless an AST_FRAME_IAX */
676 if (!genuine)
677 session->lastsent = ms;
678
679 #ifdef USE_VOICE_TS_PREDICTION
680 /* set next predicted ts based on 8khz samples */
681 if(voice)
682 session->nextpred += f->samples / 8;
683 #endif
684
685 return ms;
686 }
687
688 static unsigned char get_n_bits_at(unsigned char *data, int n, int bit)
689 {
690 int byte = bit / 8; /* byte containing first bit */
691 int rem = 8 - (bit % 8); /* remaining bits in first byte */
692 unsigned char ret = 0;
693
694 if (n <= 0 || n > 8)
695 return 0;
696
697 if (rem < n) {
698 ret = (data[byte] << (n - rem));
699 ret |= (data[byte + 1] >> (8 - n + rem));
700 } else {
701 ret = (data[byte] >> (rem - n));
702 }
703
704 return (ret & (0xff >> (8 - n)));
705 }
706
707 static int speex_get_wb_sz_at(unsigned char *data, int len, int bit)
708 {
709 static int SpeexWBSubModeSz[] = {
710 0, 36, 112, 192,
711 352, 0, 0, 0 };
712 int off = bit;
713 unsigned char c;
714
715 /* skip up to two wideband frames */
716 if (((len * 8 - off) >= 5) &&
717 get_n_bits_at(data, 1, off)) {
718 c = get_n_bits_at(data, 3, off + 1);
719 off += SpeexWBSubModeSz[c];
720
721 if (((len * 8 - off) >= 5) &&
722 get_n_bits_at(data, 1, off)) {
723 c = get_n_bits_at(data, 3, off + 1);
724 off += SpeexWBSubModeSz[c];
725
726 if (((len * 8 - off) >= 5) &&
727 get_n_bits_at(data, 1, off)) {
728 /* too many in a row */
729 DEBU(G "\tCORRUPT too many wideband streams in a row\n");
730 return -1;
731 }
732 }
733
734 }
735 return off - bit;
736 }
737
738 static int speex_get_samples(unsigned char *data, int len)
739 {
740 static int SpeexSubModeSz[] = {
741 0, 43, 119, 160,
742 220, 300, 364, 492,
743 79, 0, 0, 0,
744 0, 0, 0, 0 };
745 static int SpeexInBandSz[] = {
746 1, 1, 4, 4,
747 4, 4, 4, 4,
748 8, 8, 16, 16,
749 32, 32, 64, 64 };
750 int bit = 0;
751 int cnt = 0;
752 int off = 0;
753 unsigned char c;
754
755 DEBU(G "speex_get_samples(%d)\n", len);
756 while ((len * 8 - bit) >= 5) {
757 /* skip wideband frames */
758 off = speex_get_wb_sz_at(data, len, bit);
759 if (off < 0) {
760 DEBU(G "\tERROR reading wideband frames\n");
761 break;
762 }
763 bit += off;
764
765 if ((len * 8 - bit) < 5) {
766 DEBU(G "\tERROR not enough bits left after wb\n");
767 break;
768 }
769
770 /* get control bits */
771 c = get_n_bits_at(data, 5, bit);
772 DEBU(G "\tCONTROL: %d at %d\n", c, bit);
773 bit += 5;
774
775 if (c == 15) {
776 DEBU(G "\tTERMINATOR\n");
777 break;
778 } else if (c == 14) {
779 /* in-band signal; next 4 bits contain signal id */
780 c = get_n_bits_at(data, 4, bit);
781 bit += 4;
782 DEBU(G "\tIN-BAND %d bits\n", SpeexInBandSz[c]);
783 bit += SpeexInBandSz[c];
784 } else if (c == 13) {
785 /* user in-band; next 5 bits contain msg len */
786 c = get_n_bits_at(data, 5, bit);
787 bit += 5;
788 DEBU(G "\tUSER-BAND %d bytes\n", c);
789 bit += c * 8;
790 } else if (c > 8) {
791 DEBU(G "\tUNKNOWN sub-mode %d\n", c);
792 break;
793 } else {
794 /* skip number bits for submode (less the 5 control bits) */
795 DEBU(G "\tSUBMODE %d %d bits\n", c, SpeexSubModeSz[c]);
796 bit += SpeexSubModeSz[c] - 5;
797
798 cnt += 160; /* new frame */
799 }
800 }
801 DEBU(G "\tSAMPLES: %d\n", cnt);
802 return cnt;
803 }
804
805 static inline int get_interp_len(int format)
806 {
807 return (format == AST_FORMAT_ILBC) ? 30 : 20;
808 }
809
810 static int get_sample_cnt(struct iax_event *e)
811 {
812 int cnt = 0;
813
814 /*
815 * In the case of zero length frames, do not return a cnt of 0
816 */
817 if ( e->datalen == 0 ) {
818 return get_interp_len( e->subclass ) * 8;
819 }
820
821 switch (e->subclass) {
822 case AST_FORMAT_SPEEX:
823 cnt = speex_get_samples(e->data, e->datalen);
824 break;
825 case AST_FORMAT_G723_1:
826 cnt = 240; /* FIXME Not always the case */
827 break;
828 case AST_FORMAT_ILBC:
829 cnt = 240 * (e->datalen / 50);
830 break;
831 case AST_FORMAT_GSM:
832 cnt = 160 * (e->datalen / 33);
833 break;
834 case AST_FORMAT_G729A:
835 cnt = 160 * (e->datalen / 20);
836 break;
837 case AST_FORMAT_SLINEAR:
838 cnt = e->datalen / 2;
839 break;
840 case AST_FORMAT_LPC10:
841 cnt = 22 * 8 + (((char *)(e->data))[7] & 0x1) * 8;
842 break;
843 case AST_FORMAT_ULAW:
844 case AST_FORMAT_ALAW:
845 cnt = e->datalen;
846 break;
847 case AST_FORMAT_ADPCM:
848 case AST_FORMAT_G726:
849 cnt = e->datalen * 2;
850 break;
851 default:
852 return 0;
853 }
854 return cnt;
855 }
856
857 static int iax_xmit_frame(struct iax_frame *f)
858 {
859 int res;
860 #ifdef DEBUG_SUPPORT
861 if (debug) {
862 struct ast_iax2_full_hdr *h = (struct ast_iax2_full_hdr *)f->data;
863
864 if (ntohs(h->scallno) & IAX_FLAG_FULL)
865 iax_showframe(f, NULL, 0, f->transfer ?
866 &(f->session->transfer) :
867 &(f->session->peeraddr),
868 f->datalen - sizeof(struct ast_iax2_full_hdr));
869 }
870 #endif
871 if (!f->session) {
872 IAXERROR "No session in iax_xmit_frame");
873 return -1;
874 }
875
876 /* Send the frame raw */
877 res = f->session->sendto(netfd, (const char *) f->data, f->datalen,
878 IAX_SOCKOPTS, f->transfer ?
879 (struct sockaddr *)&(f->session->transfer) :
880 (struct sockaddr *)&(f->session->peeraddr),
881 sizeof(f->session->peeraddr));
882 return res;
883 }
884
885 static int iax_reliable_xmit(struct iax_frame *f)
886 {
887 struct iax_frame *fc;
888 struct ast_iax2_full_hdr *fh;
889 fh = (struct ast_iax2_full_hdr *) f->data;
890 if (!fh->type) {
891 return -2;
892 }
893 fc = (struct iax_frame *)malloc(sizeof(struct iax_frame));
894 if (fc) {
895 /* Make a copy of the frame */
896 memcpy(fc, f, sizeof(struct iax_frame));
897 /* And a copy of the data if applicable */
898 if (!fc->data || !fc->datalen) {
899 IAXERROR "No frame data?");
900 DEBU(G "No frame data?\n");
901 return -1;
902 } else {
903 fc->data = (char *)malloc(fc->datalen);
904 if (!fc->data) {
905 DEBU(G "Out of memory\n");
906 IAXERROR "Out of memory\n");
907 return -1;
908 }
909 memcpy(fc->data, f->data, f->datalen);
910 iax_sched_add(NULL, fc, NULL, NULL, fc->retrytime);
911 return iax_xmit_frame(fc);
912 }
913 } else
914 return -1;
915 }
916
917 void iax_set_networking(iax_sendto_t st, iax_recvfrom_t rf)
918 {
919 iax_sendto = st;
920 iax_recvfrom = rf;
921 }
922
923 void iax_set_jb_target_extra( long value )
924 {
925 /* store in jb_target_extra, a static global */
926 jb_target_extra = value ;
927 }
928
929 int iax_init(int preferredportno)
930 {
931 int portno = preferredportno;
932 #ifndef _MSC_VER // avoid compare of address of imported function
933 /* MSVC only - In certain circumstances the addresses placed in iax_sendto and iax_recvfrom
934 can be an offset to a jump table, making a compare of the current address to the address
935 of the actual imported function fail. */
936 if (iax_recvfrom == (iax_recvfrom_t)recvfrom)
937 #endif // !_MSC_VER
938 {
939 struct sockaddr_in sin;
940 socklen_t sinlen;
941 int flags;
942 int bufsize = 128 * 1024;
943
944 if (netfd > -1)
945 {
946 /* Okay, just don't do anything */
947 DEBU(G "Already initialized.");
948 return 0;
949 }
950 netfd = (int)socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
951 if (netfd < 0)
952 {
953 DEBU(G "Unable to allocate UDP socket\n");
954 IAXERROR "Unable to allocate UDP socket\n");
955 return -1;
956 }
957
958 if (preferredportno == 0)
959 preferredportno = IAX_DEFAULT_PORTNO;
960
961 if (preferredportno < 0)
962 preferredportno = 0;
963
964 sin.sin_family = AF_INET;
965 sin.sin_addr.s_addr = 0;
966 sin.sin_port = htons((short)preferredportno);
967 if (bind(netfd, (struct sockaddr *) &sin, sizeof(sin)) < 0)
968 {
969 #if defined(WIN32) || defined(_WIN32_WCE)
970 if (WSAGetLastError() == WSAEADDRINUSE)
971 #else
972 if (errno == EADDRINUSE)
973 #endif
974 {
975 /*the port is already in use, so bind to a free port chosen by the IP stack*/
976 DEBU(G "Unable to bind to preferred port - port is in use. Trying to bind to a free one");
977 sin.sin_port = htons((short)0);
978 if (bind(netfd, (struct sockaddr *) &sin, sizeof(sin)) < 0)
979 {
980 IAXERROR "Unable to bind UDP socket\n");
981 return -1;
982 }
983 } else
984 {
985 IAXERROR "Unable to bind UDP socket\n");
986 return -1;
987 }
988 }
989
990 sinlen = sizeof(sin);
991 if (getsockname(netfd, (struct sockaddr *) &sin, &sinlen) < 0)
992 {
993 close(netfd);
994 netfd = -1;
995 DEBU(G "Unable to figure out what I'm bound to.");
996 IAXERROR "Unable to determine bound port number.");
997 return -1;
998 }
999 #if defined(WIN32) || defined(_WIN32_WCE)
1000 flags = 1;
1001 if (ioctlsocket(netfd,FIONBIO,(unsigned long *) &flags))
1002 {
1003 closesocket(netfd);
1004 netfd = -1;
1005 DEBU(G "Unable to set non-blocking mode.");
1006 IAXERROR "Unable to set non-blocking mode.");
1007 return -1;
1008 }
1009
1010 #else
1011 if ((flags = fcntl(netfd, F_GETFL)) < 0)
1012 {
1013 close(netfd);
1014 netfd = -1;
1015 DEBU(G "Unable to retrieve socket flags.");
1016 IAXERROR "Unable to retrieve socket flags.");
1017 return -1;
1018 }
1019 if (fcntl(netfd, F_SETFL, flags | O_NONBLOCK) < 0)
1020 {
1021 close(netfd);
1022 netfd = -1;
1023 DEBU(G "Unable to set non-blocking mode.");
1024 IAXERROR "Unable to set non-blocking mode.");
1025 return -1;
1026 }
1027 #endif
1028 /* Mihai: increase UDP socket buffers to avoid packet loss. */
1029 if (setsockopt(netfd, SOL_SOCKET, SO_RCVBUF, (char *)&bufsize,
1030 sizeof(bufsize)) < 0)
1031 {
1032 DEBU(G "Unable to set receive buffer size.");
1033 IAXERROR "Unable to set receive buffer size.");
1034 }
1035
1036 /* set send buffer size too */
1037 if (setsockopt(netfd, SOL_SOCKET, SO_SNDBUF, (char *)&bufsize,
1038 sizeof(bufsize)) < 0)
1039 {
1040 DEBU(G "Unable to set send buffer size.");
1041 IAXERROR "Unable to set send buffer size.");
1042 }
1043
1044 portno = ntohs(sin.sin_port);
1045 DEBU(G "Started on port %d\n", portno);
1046 }
1047
1048 iax_seed_random();
1049 callnums = 1 + (int)(32767.0 * (iax_random() / (RAND_MAX + 1.0)));
1050
1051 return portno;
1052 }
1053
1054 static void destroy_session(struct iax_session *session);
1055
1056 static void convert_reply(char *out, unsigned char *in)
1057 {
1058 int x;
1059 for (x=0;x<16;x++)
1060 sprintf(out + (x << 1), "%2.2x", (int)in[x]);
1061 }
1062
1063 static unsigned char compress_subclass(int subclass)
1064 {
1065 int x;
1066 int power=-1;
1067 /* If it's 128 or smaller, just return it */
1068 if (subclass < IAX_FLAG_SC_LOG)
1069 return subclass;
1070 /* Otherwise find its power */
1071 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1072 if (subclass & (1 << x)) {
1073 if (power > -1) {
1074 DEBU(G "Can't compress subclass %d\n", subclass);
1075 return 0;
1076 } else
1077 power = x;
1078 }
1079 }
1080 return power | IAX_FLAG_SC_LOG;
1081 }
1082
1083 static int iax_send(struct iax_session *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final, int fullframe)
1084 {
1085 /* Queue a packet for delivery on a given private structure. Use "ts" for
1086 timestamp, or calculate if ts is 0. Send immediately without retransmission
1087 or delayed, with retransmission */
1088 struct ast_iax2_full_hdr *fh;
1089 struct ast_iax2_mini_hdr *mh;
1090 struct ast_iax2_video_hdr *vh;
1091 //unsigned char buf[5120]; //fd: changed max packet size[5120];
1092 unsigned char buf[32 * 1024]; //Mihai: let's see if this is where it crashes
1093
1094 struct iax_frame *fr;
1095 int res;
1096 int sendmini=0;
1097 unsigned int lastsent;
1098 unsigned int fts;
1099
1100 if (!pvt)
1101 {
1102 IAXERROR "No private structure for packet?\n");
1103 return -1;
1104 }
1105
1106 /* this must come before the next call to calc_timestamp() since
1107 calc_timestamp() will change lastsent to the returned value */
1108 lastsent = pvt->lastsent;
1109
1110 /* Calculate actual timestamp */
1111 fts = calc_timestamp(pvt, ts, f);
1112
1113 if (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L))
1114 /* High two bits are the same on timestamp, or sending on a trunk */ &&
1115 (f->frametype == AST_FRAME_VOICE)
1116 /* is a voice frame */ &&
1117 (f->subclass == pvt->svoiceformat)
1118 /* is the same type */ )
1119 {
1120 /* Force immediate rather than delayed transmission */
1121 now = 1;
1122 /* Mark that mini-style frame is appropriate */
1123 sendmini = 1;
1124 }
1125
1126 /* Bitmask taken from chan_iax2.c... I must ask Mark Spencer for this? I think not... */
1127 if ( f->frametype == AST_FRAME_VIDEO )
1128 {
1129 /* Check if the timestamp has rolled over or if the video codec has changed */
1130 if ( ((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
1131 (f->subclass == pvt->svideoformat)
1132 )
1133 {
1134 /* send a mini video frame immediately */
1135 now = 1;
1136 sendmini = 1;
1137 } else
1138 {
1139 /* we want to send a fullframe and be able to retransmit it */
1140 now = 0;
1141 sendmini = 0;
1142 }
1143 pvt->lastvsent = fts;
1144 }
1145
1146 /* if requested, force a full frame */
1147 if ( fullframe )
1148 {
1149 now = 0;
1150 sendmini = 0;
1151 }
1152
1153 /* Allocate an iax_frame */
1154 if (now)
1155 {
1156 fr = (struct iax_frame *) buf;
1157 } else
1158 {
1159 fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
1160 if ( fr == NULL )
1161 {
1162 IAXERROR "Out of memory\n");
1163 return -1;
1164 }
1165 }
1166
1167 /* Copy our prospective frame into our immediate or retransmitted wrapper */
1168 iax_frame_wrap(fr, f);
1169
1170 fr->ts = fts;
1171 if (!fr->ts)
1172 {
1173 IAXERROR "timestamp is 0?\n");
1174 if (!now)
1175 iax_frame_free(fr);
1176 return -1;
1177 }
1178
1179 fr->callno = pvt->callno;
1180 fr->transfer = transfer;
1181 fr->final = final;
1182 fr->session = pvt;
1183 if (!sendmini)
1184 {
1185 /* We need a full frame */
1186 if (seqno > -1)
1187 fr->oseqno = seqno;
1188 else
1189 fr->oseqno = pvt->oseqno++;
1190 fr->iseqno = pvt->iseqno;
1191 fh = (struct ast_iax2_full_hdr *)(((char *)fr->af.data) - sizeof(struct ast_iax2_full_hdr));
1192 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
1193 fh->ts = htonl(fr->ts);
1194 fh->oseqno = fr->oseqno;
1195 if (transfer)
1196 {
1197 fh->iseqno = 0;
1198 } else
1199 fh->iseqno = fr->iseqno;
1200 /* Keep track of the last thing we've acknowledged */
1201 pvt->aseqno = fr->iseqno;
1202 fh->type = fr->af.frametype & 0xFF;
1203 if (f->frametype == AST_FRAME_VIDEO)
1204 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
1205 else
1206 fh->csub = compress_subclass(fr->af.subclass);
1207 if (transfer)
1208 {
1209 fr->dcallno = pvt->transfercallno;
1210 } else
1211 fr->dcallno = pvt->peercallno;
1212 fh->dcallno = htons(fr->dcallno);
1213 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
1214 fr->data = fh;
1215 fr->retries = maxretries;
1216 /* Retry after 2x the ping time has passed */
1217 fr->retrytime = pvt->pingtime * 2;
1218 if (fr->retrytime < MIN_RETRY_TIME)
1219 fr->retrytime = MIN_RETRY_TIME;
1220 if (fr->retrytime > MAX_RETRY_TIME)
1221 fr->retrytime = MAX_RETRY_TIME;
1222 /* Acks' don't get retried */
1223 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
1224 fr->retries = -1;
1225 if (f->frametype == AST_FRAME_VOICE)
1226 {
1227 pvt->svoiceformat = f->subclass;
1228 }
1229 else if (f->frametype == AST_FRAME_VIDEO)
1230 {
1231 pvt->svideoformat = f->subclass & ~0x1;
1232 }
1233 if (now)
1234 {
1235 res = iax_xmit_frame(fr);
1236 } else
1237 res = iax_reliable_xmit(fr);
1238 } else
1239 {
1240 if (fr->af.frametype == AST_FRAME_VIDEO)
1241 {
1242 /* Video frame have no sequence number */
1243 fr->oseqno = -1;
1244 fr->iseqno = -1;
1245 vh = (struct ast_iax2_video_hdr *)(((char* )fr->af.data) - sizeof(struct ast_iax2_video_hdr));
1246 vh->zeros = 0;
1247 vh->callno = htons(0x8000 | fr->callno);
1248 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
1249 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
1250 fr->data = vh;
1251 fr->retries = -1;
1252 res = iax_xmit_frame(fr);
1253 } else
1254 {
1255 /* Mini-frames have no sequence number */
1256 fr->oseqno = -1;
1257 fr->iseqno = -1;
1258 /* Mini frame will do */
1259 mh = (struct ast_iax2_mini_hdr *)(((char *)fr->af.data) - sizeof(struct ast_iax2_mini_hdr));
1260 mh->callno = htons(fr->callno);
1261 mh->ts = htons(fr->ts & 0xFFFF);
1262 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
1263 fr->data = mh;
1264 fr->retries = -1;
1265 res = iax_xmit_frame(fr);
1266 }
1267 }
1268 if( !now && fr!=NULL )
1269 iax_frame_free( fr );
1270 return res;
1271 }
1272
1273 #if 0
1274 static int iax_predestroy(struct iax_session *pvt)
1275 {
1276 if (!pvt) {
1277 return -1;
1278 }
1279 if (!pvt->alreadygone) {
1280 /* No more pings or lagrq's */
1281 if (pvt->pingid > -1)
1282 ast_sched_del(sched, pvt->pingid);
1283 if (pvt->lagid > -1)
1284 ast_sched_del(sched, pvt->lagid);
1285 if (pvt->autoid > -1)
1286 ast_sched_del(sched, pvt->autoid);
1287 if (pvt->initid > -1)
1288 ast_sched_del(sched, pvt->initid);
1289 pvt->pingid = -1;
1290 pvt->lagid = -1;
1291 pvt->autoid = -1;
1292 pvt->initid = -1;
1293 pvt->alreadygone = 1;
1294 }
1295 return 0;
1296 }
1297 #endif
1298
1299 static int __send_command(struct iax_session *i, char type, int command,
1300 unsigned int ts, unsigned char *data, int datalen, int seqno,
1301 int now, int transfer, int final, int fullframe, int samples)
1302 {
1303 struct ast_frame f;
1304 f.frametype = type;
1305 f.subclass = command;
1306 f.datalen = datalen;
1307 f.samples = samples;
1308 f.mallocd = 0;
1309 f.offset = 0;
1310 #ifdef __GNUC__
1311 f.src = (char *) __FUNCTION__;
1312 #else
1313 f.src = (char *) __FILE__;
1314 #endif
1315 f.data = data;
1316 return iax_send(i, &f, ts, seqno, now, transfer, final, fullframe);
1317 }
1318
1319 static int send_command(struct iax_session *i, char type, int command, unsigned int ts, unsigned char *data, int datalen, int seqno)
1320 {
1321 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0, 0, 0);
1322 }
1323
1324 static int send_command_video(struct iax_session *i, char type, int command, unsigned int ts, unsigned char *data, int datalen, int seqno, int fullframe)
1325 {
1326 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0, fullframe, 0);
1327 }
1328
1329 static int send_command_final(struct iax_session *i, char type, int command, unsigned int ts, unsigned char *data, int datalen, int seqno)
1330 {
1331 #if 0
1332 /* It is assumed that the callno has already been locked */
1333 iax_predestroy(i);
1334 #endif
1335 int r;
1336 r = __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1, 0, 0);
1337 if (r >= 0) destroy_session(i);
1338 return r;
1339 }
1340
1341 static int send_command_immediate(struct iax_session *i, char type, int command, unsigned int ts, unsigned char *data, int datalen, int seqno)
1342 {
1343 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0, 0, 0);
1344 }
1345
1346 static int send_command_transfer(struct iax_session *i, char type, int command, unsigned int ts, unsigned char *data, int datalen)
1347 {
1348 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0, 0, 0);
1349 }
1350
1351 static int send_command_samples(struct iax_session *i, char type, int command, unsigned int ts, unsigned char *data, int datalen, int seqno, int samples)
1352 {
1353 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0, 0, samples);
1354 }
1355
1356 int iax_transfer(struct iax_session *session, const char *number)
1357 {
1358 struct iax_ie_data ied; //IE Data Structure (Stuff To Send)
1359
1360 // Clear The Memory Used For IE Buffer
1361 memset(&ied, 0, sizeof(ied));
1362
1363 // Copy The Transfer Destination Into The IE Structure
1364 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, number);
1365
1366 // Send The Transfer Command - Asterisk Will Handle The Rest!
1367 send_command(session, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
1368
1369 // Return Success
1370 return 0;
1371 }
1372
1373 static void stop_transfer(struct iax_session *session)
1374 {
1375 struct iax_sched *sch;
1376
1377 sch = schedq;
1378 while(sch) {
1379 if (sch->frame && (sch->frame->session == session))
1380 sch->frame->retries = -1;
1381 sch = sch->next;
1382 }
1383 } /* stop_transfer */
1384
1385 static void complete_transfer(struct iax_session *session, int peercallno, int xfr2peer, int preserveSeq)
1386 {
1387 jb_frame frame;
1388
1389 session->peercallno = peercallno;
1390 /* Change from transfer to session now */
1391 if (xfr2peer) {
1392 memcpy(&session->peeraddr, &session->transfer, sizeof(session->peeraddr));
1393 memset(&session->transfer, 0, sizeof(session->transfer));
1394 session->transferring = TRANSFER_NONE;
1395 session->transferpeer = 0;
1396 session->transfer_moh = 0;
1397 /* Force retransmission of a real voice packet, and reset all timing */
1398 session->svoiceformat = -1;
1399 session->voiceformat = 0;
1400 session->svideoformat = -1;
1401 session->videoformat = 0;
1402 }
1403
1404 memset(&session->rxcore, 0, sizeof(session->rxcore));
1405 memset(&session->offset, 0, sizeof(session->offset));
1406
1407 /* Reset jitterbuffer */
1408 while(jb_getall(session->jb,&frame) == JB_OK)
1409 iax_event_free((struct iax_event *)frame.data);
1410
1411 jb_reset(session->jb);
1412
1413 if (! preserveSeq)
1414 {
1415 /* Reset sequence numbers */
1416 session->aseqno = 0;
1417 session->oseqno = 0;
1418 session->iseqno = 0;
1419 }
1420
1421 session->lastsent = 0;
1422 session->last_ts = 0;
1423 session->pingtime = 30;
1424 /* We have to dump anything we were going to (re)transmit now that we've been
1425 transferred since they're all invalid and for the old host. */
1426 stop_transfer(session);
1427 } /* complete_transfer */
1428
1429 int iax_setup_transfer(struct iax_session *org_session, struct iax_session *new_session)
1430 {
1431 int res;
1432 struct iax_ie_data ied0;
1433 struct iax_ie_data ied1;
1434
1435 struct iax_session *s0 = org_session;
1436 struct iax_session *s1 = new_session;
1437
1438 int transfer_id = 1 + (int)(32767.0 * (iax_random() / (RAND_MAX + 1.0)));
1439
1440 memset(&ied0, 0, sizeof(ied0));
1441
1442 memset(&ied1, 0, sizeof(ied1));
1443
1444 /* reversed setup */
1445 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &s1->peeraddr);
1446 iax_ie_append_short(&ied0, IAX_IE_CALLNO, s1->peercallno);
1447 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transfer_id);
1448
1449 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &s0->peeraddr);
1450 iax_ie_append_short(&ied1, IAX_IE_CALLNO, s0->peercallno);
1451 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transfer_id);
1452
1453 s0->transfer = s1->peeraddr;
1454 s1->transfer = s0->peeraddr;
1455
1456 s0->transferid = transfer_id;
1457 s1->transferid = transfer_id;
1458
1459 s0->transfercallno = s0->peercallno;
1460 s1->transfercallno = s1->peercallno;
1461
1462 s0->transferring = TRANSFER_BEGIN;
1463 s1->transferring = TRANSFER_BEGIN;
1464
1465 s0->transferpeer = s1->callno;
1466 s1->transferpeer = s0->callno;
1467 #ifdef DEBUG_SUPPORT
1468 if (debug) {
1469 DEBU(G "iax_setup_transfer(%d, %d) transfer_id=%d\n", s0->callno, s1->callno, transfer_id);
1470 DEBU(G "\torg: callno=%d peercallno=%d peeraddr=%s peerport=%d\n", s0->callno, s0->peercallno, inet_ntoa(s0->peeraddr.sin_addr), ntohs(s0->peeraddr.sin_port));
1471 DEBU(G "\tnew: callno=%d peercallno=%d peeraddr=%s peerport=%d\n", s1->callno, s1->peercallno, inet_ntoa(s1->peeraddr.sin_addr), ntohs(s1->peeraddr.sin_port));
1472 }
1473 #endif
1474
1475 res = send_command(s0, AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
1476 if (res < 0) {
1477 return -1;
1478 }
1479
1480 res = send_command(s1, AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
1481 if (res < 0) {
1482 return -1;
1483 }
1484
1485 return 0;
1486 }
1487
1488 static int iax_finish_transfer(struct iax_session *s, short new_peer)
1489 {
1490 int res;
1491 struct iax_ie_data ied;
1492
1493 memset(&ied, 0, sizeof(ied));
1494
1495 iax_ie_append_short(&ied, IAX_IE_CALLNO, new_peer);
1496
1497 res = send_command(s, AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied.buf, ied.pos, -1);
1498
1499 complete_transfer(s, new_peer, 0, 1);
1500
1501 return res;
1502
1503 }
1504
1505 static struct iax_session *iax_find_session2(short callno)
1506 {
1507 struct iax_session *cur = sessions;
1508
1509 while(cur) {
1510 if (callno == cur->callno && callno != 0) {
1511 return cur;
1512 }
1513 cur = cur->next;
1514 }
1515
1516 return NULL;
1517 }
1518
1519 static int iax_handle_txready(struct iax_session *s)
1520 {
1521 struct iax_session *s0, *s1;
1522 short s0_org_peer, s1_org_peer;
1523
1524 if (s->transfer_moh) {
1525 s->transfer_moh = 0;
1526 iax_unquelch(s);
1527 }
1528
1529 complete_transfer(s, s->peercallno, 0, 1);
1530
1531 s->transferring = TRANSFER_REL;
1532
1533 s0 = s;
1534 s1 = iax_find_session2(s0->transferpeer);
1535
1536 if (s1 != NULL &&
1537 s1->callno == s0->transferpeer &&
1538 s0->transferring == TRANSFER_REL &&
1539 s1->transferring == TRANSFER_REL) {
1540
1541 s0_org_peer = s0->peercallno;
1542 s1_org_peer = s1->peercallno;
1543
1544 iax_finish_transfer(s0, s1_org_peer);
1545 iax_finish_transfer(s1, s0_org_peer);
1546 return 1;
1547 }
1548
1549 return 0;
1550 }
1551
1552 static void iax_handle_txreject(struct iax_session *s)
1553 {
1554 struct iax_session *s0, *s1;
1555
1556 s0 = s;
1557 s1 = iax_find_session2(s0->transferpeer);
1558 if (s1 != NULL &&
1559 s0->transferpeer == s1->callno &&
1560 s1->transferring) {
1561 if (s1->transfer_moh) {
1562 s1->transfer_moh = 0;
1563 send_command_immediate(s1, AST_FRAME_IAX, IAX_COMMAND_UNQUELCH, 0, NULL, 0, s1->iseqno);
1564 }
1565 }
1566 if (s0->transfer_moh) {
1567 s0->transfer_moh = 0;
1568 send_command_immediate(s0, AST_FRAME_IAX, IAX_COMMAND_UNQUELCH, 0, NULL, 0, s0->iseqno);
1569 }
1570
1571 memset(&s->transfer, 0, sizeof(s->transfer));
1572 s->transferring = TRANSFER_NONE;
1573 s->transferpeer = 0;
1574 s->transfer_moh = 0;
1575 }
1576
1577 static void destroy_session(struct iax_session *session)
1578 {
1579 struct iax_session *cur, *prev=NULL;
1580 struct iax_sched *curs, *prevs=NULL, *nexts=NULL;
1581 int loop_cnt=0;
1582 curs = schedq;
1583 while(curs) {
1584 nexts = curs->next;
1585 if (curs->frame && curs->frame->session == session) {
1586 /* Just mark these frames as if they've been sent */
1587 curs->frame->retries = -1;
1588 } else if (curs->event && curs->event->session == session) {
1589 if (prevs)
1590 prevs->next = nexts;
1591 else
1592 schedq = nexts;
1593 if (curs->event)
1594 iax_event_free(curs->event);
1595 free(curs);
1596 } else {
1597 prevs = curs;
1598 }
1599 curs = nexts;
1600 loop_cnt++;
1601 }
1602
1603 cur = sessions;
1604 while(cur) {
1605 if (cur == session) {
1606 jb_frame frame;
1607
1608 if (prev)
1609 prev->next = session->next;
1610 else
1611 sessions = session->next;
1612
1613 while(jb_getall(session->jb,&frame) == JB_OK)
1614 iax_event_free((struct iax_event *)frame.data);
1615
1616 jb_destroy(session->jb);
1617
1618 free(session);
1619 return;
1620 }
1621 prev = cur;
1622 cur = cur->next;
1623 }
1624 }
1625
1626 static int iax_send_lagrp(struct iax_session *session, unsigned int ts);
1627 static int iax_send_pong(struct iax_session *session, unsigned int ts);
1628
1629 static struct iax_event *handle_event(struct iax_event *event)
1630 {
1631 /* We have a candidate event to be delievered. Be sure
1632 the session still exists. */
1633 if (event)
1634 {
1635 if ( event->etype == IAX_EVENT_NULL ) return event;
1636 if (iax_session_valid(event->session))
1637 {
1638 /* Lag requests are never actually sent to the client, but
1639 other than that are handled as normal packets */
1640 switch(event->etype)
1641 {
1642 /* the user on the outside may need to look at the session so we will not free
1643 it here anymore we will test for hangup event in iax_event_free and do it
1644 there.
1645 */
1646 case IAX_EVENT_REJECT:
1647 case IAX_EVENT_HANGUP:
1648 /* Destroy this session -- it's no longer valid */
1649 destroy_session(event->session);
1650 return event;
1651 case IAX_EVENT_LAGRQ:
1652 event->etype = IAX_EVENT_LAGRP;
1653 iax_send_lagrp(event->session, event->ts);
1654 iax_event_free(event);
1655 break;
1656 case IAX_EVENT_PING:
1657 event->etype = IAX_EVENT_PONG;
1658 iax_send_pong(event->session, event->ts);
1659 iax_event_free(event);
1660 break;
1661 case IAX_EVENT_POKE:
1662 event->etype = IAX_EVENT_PONG;
1663 iax_send_pong(event->session, event->ts);
1664 destroy_session(event->session);
1665 iax_event_free(event);
1666 break;
1667 default:
1668 return event;
1669 }
1670 } else
1671 iax_event_free(event);
1672 }
1673 return NULL;
1674 }
1675
1676 static int iax2_vnak(struct iax_session *session)
1677 {
1678 /* send vnak just once for a given sequence number */
1679 if ( (unsigned char)(session->lastvnak - session->iseqno) < 128 )
1680 {
1681 return 0;
1682 }
1683
1684 session->lastvnak = session->iseqno;
1685 return send_command_immediate(session, AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, session->iseqno);
1686 }
1687
1688 int iax_send_dtmf(struct iax_session *session, char digit)
1689 {
1690 return send_command(session, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1691 }
1692
1693 int iax_send_voice(struct iax_session *session, int format, unsigned char *data, int datalen, int samples)
1694 {
1695 /* Send a (possibly compressed) voice frame */
1696 if (!session->quelch)
1697 return send_command_samples(session, AST_FRAME_VOICE, format, 0, data, datalen, -1, samples);
1698 return 0;
1699 }
1700
1701 int iax_send_cng(struct iax_session *session, int level, unsigned char *data,
1702 int datalen)
1703 {
1704 #ifdef USE_VOICE_TS_PREDICTION
1705 session->notsilenttx = 0;
1706 #endif
1707 return send_command(session, AST_FRAME_CNG, level, 0, data, datalen, -1);
1708 }
1709
1710 int iax_send_image(struct iax_session *session, int format, unsigned char *data,
1711 int datalen)
1712 {
1713 /* Send an image frame */
1714 return send_command(session, AST_FRAME_IMAGE, format, 0, data, datalen, -1);
1715 }
1716
1717 int iax_send_video(struct iax_session *session, int format, unsigned char *data,
1718 int datalen, int fullframe)
1719 {
1720 if (!session->quelch)
1721 {
1722 int res = send_command_video(session, AST_FRAME_VIDEO, format,
1723 0, data, datalen, -1, fullframe);
1724 return res;
1725 }
1726 return 0;
1727 }
1728
1729 int iax_send_video_trunk(struct iax_session *session, int format,
1730 char *data, int datalen, int fullframe, int ntrunk)
1731 {
1732 static int my_lastts = 0;
1733
1734 if ( ntrunk == 0 )
1735 my_lastts = calc_timestamp(session, 0, NULL);
1736
1737 if ( !session->quelch )
1738 {
1739 return send_command_video(session, AST_FRAME_VIDEO, format,
1740 my_lastts, (unsigned char *)data, datalen, -1,
1741 fullframe);
1742 }
1743 return 0;
1744 }
1745
1746 int iax_video_bypass_jitter(struct iax_session *s, int mode)
1747 {
1748 video_bypass_jitterbuffer = mode;
1749 return 0;
1750 }
1751
1752 int iax_register(struct iax_session *session, const char *server, const char *peer, const char *secret, int refresh)
1753 {
1754 /* Send a registration request */
1755 char tmp[200];
1756 char *p;
1757 int res;
1758 int portno = IAX_DEFAULT_PORTNO;
1759 struct iax_ie_data ied;
1760 struct hostent *hp;
1761
1762 tmp[199] = '\0';
1763 strncpy(tmp, server, sizeof(tmp) - 1);
1764 p = strchr(tmp, ':');
1765 if (p) {
1766 *p = '\0';
1767 portno = atoi(p+1);
1768 }
1769
1770 memset(&ied, 0, sizeof(ied));
1771 if (secret)
1772 strncpy(session->secret, secret, sizeof(session->secret) - 1);
1773 else
1774 strcpy(session->secret, "");
1775
1776 memset(&session->unregreason, 0, sizeof(session->unregreason));
1777
1778 /* Connect first */
1779 hp = gethostbyname(tmp);
1780 if (!hp) {
1781 snprintf(iax_errstr, sizeof(iax_errstr) - 1, "Invalid hostname: %s", tmp);
1782 iax_errstr[255] = '\0';
1783 return -1;
1784 }
1785
1786 memcpy(&session->peeraddr.sin_addr, hp->h_addr, sizeof(session->peeraddr.sin_addr));
1787 session->peeraddr.sin_port = htons(portno);
1788 session->peeraddr.sin_family = AF_INET;
1789 strncpy(session->username, peer, sizeof(session->username) - 1);
1790 session->refresh = refresh;
1791 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer);
1792 iax_ie_append_short(&ied, IAX_IE_REFRESH, refresh);
1793 res = send_command(session, AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
1794 return res;
1795 }
1796
1797 int iax_unregister(struct iax_session *session, const char *server, const char *peer, const char *secret, const char *reason)
1798 {
1799 /* Send an unregistration request */
1800 char tmp[200];
1801 char *p;
1802 int portno = IAX_DEFAULT_PORTNO;
1803 struct iax_ie_data ied;
1804 struct hostent *hp;
1805
1806 tmp[199] = '\0';
1807 strncpy(tmp, server, sizeof(tmp) - 1);
1808 p = strchr(tmp, ':');
1809 if (p) {
1810 *p = '\0';
1811 portno = atoi(p+1);
1812 }
1813
1814 memset(&ied, 0, sizeof(ied));
1815 if (secret)
1816 strncpy(session->secret, secret, sizeof(session->secret) - 1);
1817 else
1818 strcpy(session->secret, "");
1819
1820 if (reason && strlen(reason))
1821 strncpy(session->unregreason, reason, sizeof(session->unregreason) - 1);
1822 else
1823 strcpy(session->unregreason, "Unspecified");
1824
1825 /* Connect first */
1826 hp = gethostbyname(tmp);
1827 if (!hp) {
1828 snprintf(iax_errstr, sizeof(iax_errstr) - 1, "Invalid hostname: %s", tmp);
1829 iax_errstr[255] = '\0';
1830 return -1;
1831 }
1832
1833 memcpy(&session->peeraddr.sin_addr, hp->h_addr, sizeof(session->peeraddr.sin_addr));
1834 session->peeraddr.sin_port = htons(portno);
1835 session->peeraddr.sin_family = AF_INET;
1836 strncpy(session->username, peer, sizeof(session->username) - 1);
1837 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer);
1838 iax_ie_append_str(&ied, IAX_IE_CAUSE, session->unregreason);
1839 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_REGREL, 0, ied.buf, ied.pos, -1);
1840 }
1841
1842 int iax_reject(struct iax_session *session, char *reason)
1843 {
1844 struct iax_ie_data ied;
1845 memset(&ied, 0, sizeof(ied));
1846 iax_ie_append_str(&ied, IAX_IE_CAUSE, reason ? reason : "Unspecified");
1847 return send_command_final(session, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
1848 }
1849
1850 int iax_hangup(struct iax_session *session, char *byemsg)
1851 {
1852 struct iax_ie_data ied;
1853 iax_sched_del(NULL, NULL, send_ping, (void *) session, 1);
1854 memset(&ied, 0, sizeof(ied));
1855 iax_ie_append_str(&ied, IAX_IE_CAUSE, byemsg ? byemsg : "Normal clearing");
1856 return send_command_final(session, AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
1857 }
1858
1859 int iax_sendurl(struct iax_session *session, char *url)
1860 {
1861 return send_command(session, AST_FRAME_HTML, AST_HTML_URL, 0,
1862 (unsigned char *)url, (int)strlen(url), -1);
1863 }
1864
1865 int iax_ring_announce(struct iax_session *session)
1866 {
1867 return send_command(session, AST_FRAME_CONTROL, AST_CONTROL_RINGING, 0, NULL, 0, -1);
1868 }
1869
1870 int iax_lag_request(struct iax_session *session)
1871 {
1872 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1873 }
1874
1875 int iax_busy(struct iax_session *session)
1876 {
1877 return send_command(session, AST_FRAME_CONTROL, AST_CONTROL_BUSY, 0, NULL, 0, -1);
1878 }
1879
1880 int iax_congestion(struct iax_session *session)
1881 {
1882 return send_command(session, AST_FRAME_CONTROL, AST_CONTROL_CONGESTION, 0, NULL, 0, -1);
1883 }
1884
1885
1886 int iax_accept(struct iax_session *session, int format)
1887 {
1888 struct iax_ie_data ied;
1889 memset(&ied, 0, sizeof(ied));
1890 iax_ie_append_int(&ied, IAX_IE_FORMAT, format);
1891 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied.buf, ied.pos, -1);
1892 }
1893
1894 int iax_answer(struct iax_session *session)
1895 {
1896 return send_command(session, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
1897 }
1898
1899 int iax_load_complete(struct iax_session *session)
1900 {
1901 return send_command(session, AST_FRAME_HTML, AST_HTML_LDCOMPLETE, 0, NULL, 0, -1);
1902 }
1903
1904 int iax_send_url(struct iax_session *session, const char *url, int link)
1905 {
1906 return send_command(session, AST_FRAME_HTML,
1907 link ? AST_HTML_LINKURL : AST_HTML_URL, 0,
1908 (unsigned char *)url, (int)strlen(url), -1);
1909 }
1910
1911 int iax_send_text(struct iax_session *session, const char *text)
1912 {
1913 return send_command(session, AST_FRAME_TEXT, 0, 0,
1914 (unsigned char *)text, (int)strlen(text) + 1, -1);
1915 }
1916
1917 int iax_send_unlink(struct iax_session *session)
1918 {
1919 return send_command(session, AST_FRAME_HTML, AST_HTML_UNLINK, 0, NULL, 0, -1);
1920 }
1921
1922 int iax_send_link_reject(struct iax_session *session)
1923 {
1924 return send_command(session, AST_FRAME_HTML, AST_HTML_LINKREJECT, 0, NULL, 0, -1);
1925 }
1926
1927 static int iax_send_pong(struct iax_session *session, unsigned int ts)
1928 {
1929 struct iax_ie_data ied;
1930 jb_info stats;
1931
1932 memset(&ied, 0, sizeof(ied));
1933
1934 jb_getinfo(session->jb, &stats);
1935
1936 iax_ie_append_int(&ied,IAX_IE_RR_JITTER, stats.jitter);
1937 /* XXX: should be short-term loss pct.. */
1938 if(stats.frames_in == 0) stats.frames_in = 1;
1939 iax_ie_append_int(&ied,IAX_IE_RR_LOSS,
1940 ((0xff & (stats.losspct/1000)) << 24 |
1941 (stats.frames_lost & 0x00ffffff)));
1942 iax_ie_append_int(&ied,IAX_IE_RR_PKTS, stats.frames_in);
1943 iax_ie_append_short(&ied,IAX_IE_RR_DELAY,
1944 (unsigned short)(stats.current - stats.min));
1945 iax_ie_append_int(&ied,IAX_IE_RR_DROPPED, stats.frames_dropped);
1946 iax_ie_append_int(&ied,IAX_IE_RR_OOO, stats.frames_ooo);
1947
1948 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_PONG, ts, ied.buf, ied.pos, -1);
1949 }
1950
1951 /* external API; deprecated since we send pings ourselves now (finally) */
1952 int iax_send_ping(struct iax_session *session)
1953 {
1954 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1955 }
1956
1957 /* scheduled ping sender; sends ping, then reschedules */
1958 static void send_ping(void *s)
1959 {
1960 struct iax_session *session = (struct iax_session *)s;
1961
1962 /* important, eh? */
1963 if(!iax_session_valid(session)) return;
1964
1965 send_command(session, AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1966 session->pingid = iax_sched_add(NULL,NULL, send_ping, (void *)session, ping_time * 1000);
1967 return;
1968 }
1969
1970 static int iax_send_lagrp(struct iax_session *session, unsigned int ts)
1971 {
1972 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_LAGRP, ts, NULL, 0, -1);
1973 }
1974
1975 static int iax_send_txcnt(struct iax_session *session)
1976 {
1977 struct iax_ie_data ied;
1978 memset(&ied, 0, sizeof(ied));
1979 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, session->transferid);
1980 return send_command_transfer(session, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
1981 }
1982
1983 static int iax_send_txrej(struct iax_session *session)
1984 {
1985 struct iax_ie_data ied;
1986 memset(&ied, 0, sizeof(ied));
1987 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, session->transferid);
1988 return send_command_transfer(session, AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, ied.buf, ied.pos);
1989 }
1990
1991 static int iax_send_txaccept(struct iax_session *session)
1992 {
1993 struct iax_ie_data ied;
1994 memset(&ied, 0, sizeof(ied));
1995 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, session->transferid);
1996 return send_command_transfer(session, AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, ied.buf, ied.pos);
1997 }
1998
1999 static int iax_send_txready(struct iax_session *session)
2000 {
2001 struct iax_ie_data ied;
2002 memset(&ied, 0, sizeof(ied));
2003 /* see asterisk chan_iax2.c */
2004 iax_ie_append_short(&ied, IAX_IE_CALLNO, session->callno);
2005 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied.buf, ied.pos, -1);
2006 }
2007
2008 int iax_auth_reply(struct iax_session *session, char *password, char *challenge, int methods)
2009 {
2010 char reply[16];
2011 struct MD5Context md5;
2012 char realreply[256];
2013 struct iax_ie_data ied;
2014 memset(&ied, 0, sizeof(ied));
2015 if ((methods & IAX_AUTH_MD5) && challenge) {
2016 MD5Init(&md5);
2017 MD5Update(&md5, (const unsigned char *) challenge,
2018 (unsigned int)strlen(challenge));
2019 MD5Update(&md5, (const unsigned char *) password,
2020 (unsigned int)strlen(password));
2021 MD5Final((unsigned char *) reply, &md5);
2022 memset(realreply, 0, sizeof(realreply));
2023 convert_reply(realreply, (unsigned char *) reply);
2024 iax_ie_append_str(&ied, IAX_IE_MD5_RESULT, realreply);
2025 } else {
2026 iax_ie_append_str(&ied, IAX_IE_PASSWORD, password);
2027 }
2028 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
2029 }
2030
2031 static int iax_regauth_reply(struct iax_session *session, char *password, char *challenge, int methods)
2032 {
2033 char reply[16];
2034 struct MD5Context md5;
2035 char realreply[256];
2036 struct iax_ie_data ied;
2037 memset(&ied, 0, sizeof(ied));
2038 iax_ie_append_str(&ied, IAX_IE_USERNAME, session->username);
2039 if ((methods & IAX_AUTHMETHOD_MD5) && challenge) {
2040 MD5Init(&md5);
2041 MD5Update(&md5, (const unsigned char *) challenge,
2042 (unsigned int)strlen(challenge));
2043 MD5Update(&md5, (const unsigned char *) password,
2044 (unsigned int)strlen(password));
2045 MD5Final((unsigned char *) reply, &md5);
2046 memset(realreply, 0, sizeof(realreply));
2047 convert_reply(realreply, (unsigned char *) reply);
2048 iax_ie_append_str(&ied, IAX_IE_MD5_RESULT, realreply);
2049 } else {
2050 iax_ie_append_str(&ied, IAX_IE_PASSWORD, password);
2051 }
2052 if (strlen(session->unregreason)) { /* Non-zero unregreason length indicates REGREL */
2053 iax_ie_append_str(&ied, IAX_IE_CAUSE, session->unregreason);
2054 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_REGREL, 0, ied.buf, ied.pos, -1);
2055 } else {
2056 iax_ie_append_short(&ied, IAX_IE_REFRESH, session->refresh);
2057 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
2058 }
2059 }
2060
2061
2062 int iax_dial(struct iax_session *session, char *number)
2063 {
2064 struct iax_ie_data ied;
2065 memset(&ied, 0, sizeof(ied));
2066 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, number);
2067 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_DIAL, 0, ied.buf, ied.pos, -1);
2068 }
2069
2070 int iax_quelch(struct iax_session *session)
2071 {
2072 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_QUELCH, 0, NULL, 0, -1);
2073 }
2074
2075 int iax_unquelch(struct iax_session *session)
2076 {
2077 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_UNQUELCH, 0, NULL, 0, -1);
2078 }
2079
2080 int iax_dialplan_request(struct iax_session *session, char *number)
2081 {
2082 struct iax_ie_data ied;
2083 memset(&ied, 0, sizeof(ied));
2084 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, number);
2085 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
2086 }
2087
2088 static inline int which_bit(unsigned int i)
2089 {
2090 char x;
2091 for(x = 0; x < 32; x++) {
2092 if ((1U << x) == i) {
2093 return x + 1;
2094 }
2095 }
2096 return 0;
2097 }
2098
2099 char iax_pref_codec_add(struct iax_session *session, unsigned int format)
2100 {
2101 int diff = (int) 'A';
2102 session->codec_order[session->codec_order_len++] = (which_bit(format)) + diff;
2103 session->codec_order[session->codec_order_len] = '\0';
2104 return session->codec_order[session->codec_order_len-1];
2105 }
2106
2107
2108 void iax_pref_codec_del(struct iax_session *session, unsigned int format)
2109 {
2110 int diff = (int) 'A';
2111 int x;
2112 char old[32];
2113 char remove = which_bit(format) + diff;
2114
2115 strncpy(old, session->codec_order, sizeof(old));
2116 session->codec_order_len = 0;
2117
2118 for (x = 0; x < (int) strlen(old); x++) {
2119 if (old[x] != remove) {
2120 session->codec_order[session->codec_order_len++] = old[x];
2121 }
2122 }
2123 session->codec_order[session->codec_order_len] = '\0';
2124 }
2125
2126 int iax_pref_codec_get(struct iax_session *session, unsigned int *array, int len)
2127 {
2128 int diff = (int) 'A';
2129 int x;
2130
2131 for (x = 0; x < session->codec_order_len && x < len; x++) {
2132 array[x] = (1 << (session->codec_order[x] - diff - 1));
2133 }
2134
2135 return x;
2136 }
2137
2138 int iax_call(struct iax_session *session, const char *cidnum, const char *cidname, const char *ich, const char *lang, int wait, int formats, int capabilities)
2139 {
2140 char tmp[256]="";
2141 char *part1, *part2;
2142 int res;
2143 int portno;
2144 char *username, *hostname, *secret, *context, *exten, *dnid;
2145 struct iax_ie_data ied;
2146 struct hostent *hp;
2147 /* We start by parsing up the temporary variable which is of the form of:
2148 [user@]peer[:portno][/exten[@context]] */
2149 if (!ich) {
2150 IAXERROR "Invalid IAX Call Handle\n");
2151 DEBU(G "Invalid IAX Call Handle\n");
2152 return -1;
2153 }
2154 memset(&ied, 0, sizeof(ied));
2155 strncpy(tmp, ich, sizeof(tmp) - 1);
2156 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2157 if (cidnum)
2158 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, cidnum);
2159 if (cidname)
2160 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, cidname);
2161
2162 if (session->codec_order_len) {
2163 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, session->codec_order);
2164 }
2165
2166 session->capability = capabilities;
2167 session->pingid = iax_sched_add(NULL,NULL, send_ping, (void *)session, 2 * 1000);
2168
2169 /* XXX We should have a preferred format XXX */
2170 iax_ie_append_int(&ied, IAX_IE_FORMAT, formats);
2171 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, capabilities);
2172 if (lang)
2173 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, lang);
2174
2175 /* Part 1 is [user[:password]@]peer[:port] */
2176 part1 = strtok(tmp, "/");
2177
2178 /* Part 2 is exten[@context] if it is anything all */
2179 part2 = strtok(NULL, "/");
2180
2181 if (strchr(part1, '@')) {
2182 username = strtok(part1, "@");
2183 hostname = strtok(NULL, "@");
2184 } else {
2185 username = NULL;
2186 hostname = part1;
2187 }
2188
2189 if (username && strchr(username, ':')) {
2190 username = strtok(username, ":");
2191 secret = strtok(NULL, ":");
2192 } else
2193 secret = NULL;
2194
2195 if(username)
2196 strncpy(session->username, username, sizeof(session->username) - 1);
2197
2198 if(secret)
2199 strncpy(session->secret, secret, sizeof(session->secret) - 1);
2200
2201 if (strchr(hostname, ':')) {
2202 strtok(hostname, ":");
2203 portno = atoi(strtok(NULL, ":"));
2204 } else {
2205 portno = IAX_DEFAULT_PORTNO;
2206 }
2207 if (part2) {
2208 exten = strtok(part2, "@");
2209 dnid = exten;
2210 context = strtok(NULL, "@");
2211 } else {
2212 exten = NULL;
2213 dnid = NULL;
2214 context = NULL;
2215 }
2216 if (username)
2217 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2218 if (exten && strlen(exten))
2219 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, exten);
2220 if (dnid && strlen(dnid))
2221 iax_ie_append_str(&ied, IAX_IE_DNID, dnid);
2222 if (context && strlen(context))
2223 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2224
2225 /* Setup host connection */
2226 hp = gethostbyname(hostname);
2227 if (!hp) {
2228 snprintf(iax_errstr, sizeof(iax_errstr), "Invalid hostname: %s", hostname);
2229 return -1;
2230 }
2231 memcpy(&session->peeraddr.sin_addr, hp->h_addr, sizeof(session->peeraddr.sin_addr));
2232 session->peeraddr.sin_port = htons(portno);
2233 session->peeraddr.sin_family = AF_INET;
2234 res = send_command(session, AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2235 if (res < 0)
2236 return res;
2237 if (wait) {
2238 DEBU(G "Waiting not yet implemented\n");
2239 return -1;
2240 }
2241 return res;
2242 }
2243
2244 static int calc_rxstamp(struct iax_session *session)
2245 {
2246 struct timeval tv;
2247 int ms;
2248
2249 if (!session->rxcore.tv_sec && !session->rxcore.tv_usec) {
2250 session->rxcore = iax_tvnow();
2251 }
2252 tv = iax_tvnow();
2253
2254 ms = (tv.tv_sec - session->rxcore.tv_sec) * 1000 +
2255 (tv.tv_usec - session->rxcore.tv_usec) / 1000;
2256 return ms;
2257 }
2258
2259 #ifdef notdef_cruft
2260 static int match(struct sockaddr_in *sin, short callno, short dcallno, struct iax_session *cur)
2261 {
2262 if ((cur->peeraddr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2263 (cur->peeraddr.sin_port == sin->sin_port)) {
2264 /* This is the main host */
2265 if ((cur->peercallno == callno) ||
2266 ((dcallno == cur->callno) && !cur->peercallno)) {
2267 /* That's us. Be sure we keep track of the peer call number */
2268 cur->peercallno = callno;
2269 return 1;
2270 }
2271 }
2272 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2273 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2274 /* We're transferring */
2275 if (dcallno == cur->callno)
2276 return 1;
2277 }
2278 return 0;
2279 }
2280 #endif
2281
2282 /* splitted match into 2 passes otherwise causing problem of matching
2283 up the wrong session using the dcallno and the peercallno because
2284 during a transfer (2 IAX channels on the same client/system) the
2285 same peercallno (from two different asterisks) exist in more than
2286 one session.
2287 */
2288 static int forward_match(struct sockaddr_in *sin, short callno, short dcallno, struct iax_session *cur)
2289 {
2290 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2291 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2292 /* We're transferring */
2293 if (dcallno == cur->callno)
2294 {
2295 return 1;
2296 }
2297 }
2298
2299 if ((cur->peeraddr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2300 (cur->peeraddr.sin_port == sin->sin_port)) {
2301 if (dcallno == cur->callno && dcallno != 0) {
2302 /* That's us. Be sure we keep track of the peer call number */
2303 if (cur->peercallno == 0) {
2304 cur->peercallno = callno;
2305 }
2306 else if ( cur->peercallno != callno )
2307 {
2308 // print a warning when the callno's don't match
2309 fprintf( stderr, "WARNING: peercallno does not match callno"
2310 ", peercallno => %d, callno => %d, dcallno => %d",
2311 cur->peercallno, callno, dcallno ) ;
2312 return 0 ;
2313 }
2314 return 1;
2315 }
2316 }
2317
2318 return 0;
2319 }
2320
2321 static int reverse_match(struct sockaddr_in *sin, short callno, struct iax_session *cur)
2322 {
2323 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2324 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2325 /* We're transferring */
2326 if (callno == cur->peercallno) {
2327 return 1;
2328 }
2329 }
2330 if ((cur->peeraddr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2331 (cur->peeraddr.sin_port == sin->sin_port)) {
2332 if (callno == cur->peercallno) {
2333 return 1;
2334 }
2335 }
2336
2337 return 0;
2338 }
2339
2340 static struct iax_session *iax_find_session(struct sockaddr_in *sin,
2341 short callno,
2342 short dcallno,
2343 int makenew)
2344 {
2345 struct iax_session *cur = sessions;
2346 while(cur) {
2347 if (forward_match(sin, callno, dcallno, cur)) {
2348 return cur;
2349 }
2350 cur = cur->next;
2351 }
2352
2353 cur = sessions;
2354 while(cur) {
2355 if (reverse_match(sin, callno, cur)) {
2356 return cur;
2357 }
2358 cur = cur->next;
2359 }
2360
2361 if (makenew && !dcallno) {
2362 cur = iax_session_new();
2363 cur->peercallno = callno;
2364 cur->peeraddr.sin_addr.s_addr = sin->sin_addr.s_addr;
2365 cur->peeraddr.sin_port = sin->sin_port;
2366 cur->peeraddr.sin_family = AF_INET;
2367 cur->pingid = iax_sched_add(NULL,NULL, send_ping, (void *)cur, 2 * 1000);
2368 DEBU(G "Making new session, peer callno %d, our callno %d\n", callno, cur->callno);
2369 } else {
2370 DEBU(G "No session, peer = %d, us = %d\n", callno, dcallno);
2371 }
2372 return cur;
2373 }
2374
2375 #ifdef EXTREME_DEBUG
2376 static int display_time(int ms)
2377 {
2378 static int oldms = -1;
2379 if (oldms < 0) {
2380 DEBU(G "First measure\n");
2381 oldms = ms;
2382 return 0;
2383 }
2384 DEBU(G "Time from last frame is %d ms\n", ms - oldms);
2385 oldms = ms;
2386 return 0;
2387 }
2388 #endif
2389
2390 /* From chan_iax2/steve davies: need to get permission from steve or digium, I guess */
2391 static long unwrap_timestamp(long ts, long last)
2392 {
2393 int x;
2394
2395 if ( (ts & 0xFFFF0000) == (last & 0xFFFF0000) ) {
2396 x = ts - last;
2397 if (x < -50000) {
2398 /* Sudden big jump backwards in timestamp:
2399 What likely happened here is that miniframe
2400 timestamp has circled but we haven't gotten the
2401 update from the main packet. We'll just pretend
2402 that we did, and update the timestamp
2403 appropriately. */
2404 ts = ( (last & 0xFFFF0000) + 0x10000) | (ts & 0xFFFF);
2405 DEBU(G "schedule_delivery: pushed forward timestamp\n");
2406 }
2407 if (x > 50000) {
2408 /* Sudden apparent big jump forwards in timestamp:
2409 What's likely happened is this is an old miniframe
2410 belonging to the previous top-16-bit timestamp that
2411 has turned up out of order. Adjust the timestamp
2412 appropriately. */
2413 ts = ( (last & 0xFFFF0000) - 0x10000) | (ts & 0xFFFF);
2414 DEBU(G "schedule_delivery: pushed back timestamp\n");
2415 }
2416 }
2417 else if ( (ts & 0xFFFF8000L) == (last & 0xFFFF8000L) ) {
2418 x = ts - last;
2419 if (x < -50000) {
2420 /* Sudden big jump backwards in timestamp:
2421 What likely happened here is that miniframe
2422 timestamp has circled but we haven't gotten the
2423 update from the main packet. We'll just pretend
2424 that we did, and update the timestamp
2425 appropriately. */
2426 ts = ( (last & 0xFFFF8000L) + 0x10000) | (ts & 0xFFFF);
2427 DEBU(G "schedule_delivery: pushed forward timestamp\n");
2428 }
2429 if (x > 50000) {
2430 /* Sudden apparent big jump forwards in timestamp:
2431 * What's likely happened is this is an old miniframe
2432 * belonging to the previous top-16-bit timestamp that
2433 * has turned up out of order. Adjust the timestamp
2434 * appropriately. */
2435 ts = ( (last & 0xFFFF8000L) - 0x10000) | (ts & 0xFFFF);
2436 DEBU(G "schedule_delivery: pushed back timestamp\n");
2437 }
2438 }
2439 return ts;
2440 }
2441
2442
2443 static struct iax_event *schedule_delivery(struct iax_event *e, unsigned int ts, int updatehistory)
2444 {
2445 /*
2446 * This is the core of the IAX jitterbuffer delivery mechanism:
2447 * Dynamically adjust the jitterbuffer and decide how long to wait
2448 * before delivering the packet.
2449 */
2450
2451 #ifdef EXTREME_DEBUG
2452 DEBU(G "[%p] We are at %d, packet is for %d\n", e->session, calc_rxstamp(e->session), ts);
2453 #endif
2454
2455 /* insert into jitterbuffer */
2456 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2457 if ( !iax_use_jitterbuffer ||
2458 (e->etype == IAX_EVENT_VIDEO &&
2459 video_bypass_jitterbuffer) )
2460 {
2461 iax_sched_add(e, NULL, NULL, NULL, 0);
2462 return NULL;
2463 } else
2464 {
2465 int type = JB_TYPE_CONTROL;
2466 int len = 0;
2467
2468 if(e->etype == IAX_EVENT_VOICE)
2469 {
2470 type = JB_TYPE_VOICE;
2471 /* The frame time only has an effect for voice */
2472 len = get_sample_cnt(e) / 8;
2473 } else if(e->etype == IAX_EVENT_VIDEO)
2474 {
2475 type = JB_TYPE_VIDEO;
2476 } else if(e->etype == IAX_EVENT_CNG)
2477 {
2478 type = JB_TYPE_SILENCE;
2479 }
2480
2481 /* unwrap timestamp */
2482 ts = unwrap_timestamp(ts,e->session->last_ts);
2483
2484 /* move forward last_ts if it's greater. We do this _after_
2485 * unwrapping, because asterisk _still_ has cases where it
2486 * doesn't send full frames when it ought to */
2487 if(ts > e->session->last_ts)
2488 {
2489 e->session->last_ts = ts;
2490 }
2491
2492 if(jb_put(e->session->jb, e, type, len, ts,
2493 calc_rxstamp(e->session)) == JB_DROP)
2494 {
2495 iax_event_free(e);
2496 }
2497 }
2498
2499 return NULL;
2500 }
2501
2502 static int uncompress_subclass(unsigned char csub)
2503 {
2504 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
2505 if (csub & IAX_FLAG_SC_LOG)
2506 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
2507 else
2508 return csub;
2509 }
2510
2511 static void iax_handle_vnak(struct iax_session *session, struct ast_iax2_full_hdr *fh)
2512 {
2513 struct iax_sched *sch, *list, *l, *tmp;
2514
2515 /*
2516 * According to the IAX2 02 draft, we MUST immediately retransmit all frames
2517 * with higher sequence number than the VNAK's iseqno
2518 * However, it seems that the right thing to do would be to retransmit
2519 * frames with sequence numbers higher OR EQUAL to VNAK's iseqno.
2520 */
2521 sch = schedq;
2522 list = NULL;
2523 while ( sch != NULL )
2524 {
2525 if ( sch->frame != NULL &&
2526 sch->frame->session == session
2527 )
2528 {
2529 /*
2530 * We want to check if our frame's oseqno is greater or equal than
2531 * the VNAK's iseqno, but we need to take into account sequence
2532 * number wrap-arounds
2533 * session->rseqno is our last acknowledged sequence number, so
2534 * we use that as a base
2535 */
2536 if ( (unsigned char)(fh->iseqno - session->rseqno) <= (unsigned char)(sch->frame->oseqno - session->rseqno) )
2537 {
2538 /*
2539 * We cannot retransmit immediately, since the frames are ordered by retransmit time
2540 * We need to collect them and arrange them in ascending order of their oseqno
2541 */
2542 tmp = (struct iax_sched *)calloc(1, sizeof(struct iax_sched));
2543 tmp->frame = sch->frame;
2544
2545 if ( list == NULL ||
2546 (list->frame->oseqno - session->rseqno) > (tmp->frame->oseqno - session->rseqno)
2547 )
2548 {
2549 tmp->next = list;
2550 list = tmp;
2551 } else
2552 {
2553 l = list;
2554 while ( l != NULL )
2555 {
2556 if ( l->next == NULL ||
2557 (l->next->frame->oseqno - session->rseqno) > (tmp->frame->oseqno - session->rseqno)
2558 )
2559 {
2560 tmp->next = l->next;
2561 l->next = tmp;
2562 break;
2563 }
2564 l = l->next;
2565 }
2566 }
2567 }
2568 }
2569 sch = sch->next;
2570 }
2571
2572 /* Transmit collected frames and free the space */
2573 while ( list != NULL )
2574 {
2575 tmp = list;
2576 iax_xmit_frame(tmp->frame);
2577 list = list->next;
2578 free(tmp);
2579 }
2580 }
2581
2582 static struct iax_event *iax_header_to_event(struct iax_session *session, struct ast_iax2_full_hdr *fh, int datalen, struct sockaddr_in *sin)
2583 {
2584 struct iax_event *e;
2585 struct iax_sched *sch;
2586 unsigned int ts;
2587 int subclass;
2588 int nowts;
2589 int updatehistory = 1;
2590 ts = ntohl(fh->ts);
2591
2592 if (fh->type==AST_FRAME_VIDEO)
2593 subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
2594 else
2595 subclass = uncompress_subclass(fh->csub);
2596
2597 /* don't run last_ts backwards; i.e. for retransmits and the like */
2598 if (ts > session->last_ts &&
2599 (fh->type == AST_FRAME_IAX &&
2600 subclass != IAX_COMMAND_ACK &&
2601 subclass != IAX_COMMAND_PONG &&
2602 subclass != IAX_COMMAND_LAGRP))
2603 {
2604 session->last_ts = ts;
2605 }
2606
2607 #ifdef DEBUG_SUPPORT
2608 if (debug)
2609 iax_showframe(NULL, fh, 1, sin, datalen);
2610 #endif
2611
2612 /* Get things going with it, timestamp wise, if we
2613 haven't already. */
2614
2615 /* Handle implicit ACKing unless this is an INVAL, and only if this is
2616 from the real peer, not the transfer peer */
2617 if ( !inaddrcmp(sin, &session->peeraddr) &&
2618 ( subclass != IAX_COMMAND_INVAL ||
2619 fh->type != AST_FRAME_IAX
2620 )
2621 )
2622 {
2623 unsigned char x;
2624 /* XXX This code is not very efficient. Surely there is a better way which still
2625 properly handles boundary conditions? XXX */
2626 /* First we have to qualify that the ACKed value is within our window */
2627 for (x=session->rseqno; x != session->oseqno; x++)
2628 if (fh->iseqno == x)
2629 break;
2630 if ((x != session->oseqno) || (session->oseqno == fh->iseqno))
2631 {
2632 /* The acknowledgement is within our window. Time to acknowledge everything
2633 that it says to */
2634 for (x=session->rseqno; x != fh->iseqno; x++)
2635 {
2636 /* Ack the packet with the given timestamp */
2637 DEBU(G "Cancelling transmission of packet %d\n", x);
2638 sch = schedq;
2639 while(sch)
2640 {
2641 if ( sch->frame &&
2642 sch->frame->session == session &&
2643 sch->frame->oseqno == x
2644 )
2645 sch->frame->retries = -1;
2646 sch = sch->next;
2647 }
2648 }
2649 /* Note how much we've received acknowledgement for */
2650 session->rseqno = fh->iseqno;
2651 } else
2652 DEBU(G "Received iseqno %d not within window %d->%d\n", fh->iseqno, session->rseqno, session->oseqno);
2653 }
2654
2655 /* Check where we are */
2656 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
2657 ((fh->type != AST_FRAME_VOICE) && (fh->type != AST_FRAME_VIDEO)))
2658 updatehistory = 0;
2659 if ((session->iseqno != fh->oseqno) &&
2660 (session->iseqno ||
2661 ((subclass != IAX_COMMAND_TXREADY) &&
2662 (subclass != IAX_COMMAND_TXREL) &&
2663 (subclass != IAX_COMMAND_TXCNT) &&
2664 (subclass != IAX_COMMAND_TXACC)) ||
2665 (fh->type != AST_FRAME_IAX)))
2666 {
2667 if (
2668 ((subclass != IAX_COMMAND_ACK) &&
2669 (subclass != IAX_COMMAND_INVAL) &&
2670 (subclass != IAX_COMMAND_TXREADY) &&
2671 (subclass != IAX_COMMAND_TXREL) &&
2672 (subclass != IAX_COMMAND_TXCNT) &&
2673 (subclass != IAX_COMMAND_TXACC) &&
2674 (subclass != IAX_COMMAND_VNAK)) ||
2675 (fh->type != AST_FRAME_IAX))
2676 {
2677 /* If it's not an ACK packet, it's out of order. */
2678 DEBU(G "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
2679 session->iseqno, fh->oseqno, fh->type, subclass);
2680
2681 /*
2682 * Check if session->iseqno > fh->oseqno, accounting for possible wrap around
2683 * This is correct if the two values are not equal (which, in this case, is guaranteed)
2684 */
2685 if ( (unsigned char)(session->iseqno - fh->oseqno) < 128 )
2686 {
2687 /* If we've already seen it, ack it XXX There's a border condition here XXX */
2688 if ((fh->type != AST_FRAME_IAX) ||
2689 ((subclass != IAX_COMMAND_ACK) && (subclass != IAX_COMMAND_INVAL)))
2690 {
2691 DEBU(G "Acking anyway\n");
2692 /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
2693 we have anything to send, we'll retransmit and get an ACK back anyway XXX */
2694 send_command_immediate(session, AST_FRAME_IAX, IAX_COMMAND_ACK, ts, NULL, 0,fh->iseqno);
2695 }
2696 } else
2697 {
2698 /* Send a VNAK requesting retransmission */
2699 iax2_vnak(session);
2700 }
2701 return NULL;
2702 }
2703 } else
2704 {
2705 /* Increment unless it's an ACK or VNAK */
2706 if (((subclass != IAX_COMMAND_ACK) &&
2707 (subclass != IAX_COMMAND_INVAL) &&
2708 (subclass != IAX_COMMAND_TXCNT) &&
2709 (subclass != IAX_COMMAND_TXACC) &&
2710 (subclass != IAX_COMMAND_VNAK)) ||
2711 (fh->type != AST_FRAME_IAX))
2712 session->iseqno++;
2713 }
2714
2715 e = (struct iax_event *)malloc(sizeof(struct iax_event) + datalen + 1);
2716
2717 if (e) {
2718 memset(e, 0, sizeof(struct iax_event) + datalen);
2719 /* Set etype to some unknown value so do not inavertently
2720 sending IAX_EVENT_CONNECT event, which is 0 to application.
2721 */
2722 e->etype = -1;
2723 e->session = session;
2724 switch(fh->type) {
2725 case AST_FRAME_DTMF:
2726 e->etype = IAX_EVENT_DTMF;
2727 e->subclass = subclass;
2728 /*
2729 We want the DTMF event deliver immediately so all I/O can be
2730 terminate quickly in an IVR system.
2731 e = schedule_delivery(e, ts, updatehistory); */
2732 break;
2733 case AST_FRAME_VOICE:
2734 e->etype = IAX_EVENT_VOICE;
2735 e->subclass = subclass;
2736 e->ts = ts;
2737 session->voiceformat = subclass;
2738 if (datalen) {
2739 memcpy(e->data, fh->iedata, datalen);
2740 e->datalen = datalen;
2741 }
2742 e = schedule_delivery(e, ts, updatehistory);
2743 break;
2744 case AST_FRAME_CNG:
2745 e->etype = IAX_EVENT_CNG;
2746 e->subclass = subclass;
2747 if (datalen) {
2748 memcpy(e->data, fh->iedata, datalen);
2749 e->datalen = datalen;
2750 }
2751 e = schedule_delivery(e, ts, updatehistory);
2752 break;
2753 case AST_FRAME_IAX:
2754 /* Parse IE's */
2755 if (datalen) {
2756 memcpy(e->data, fh->iedata, datalen);
2757 e->datalen = datalen;
2758 }
2759 if (iax_parse_ies(&e->ies, e->data, e->datalen)) {
2760 IAXERROR "Unable to parse IE's");
2761 free(e);
2762 e = NULL;
2763 break;
2764 }
2765 switch(subclass) {
2766 case IAX_COMMAND_NEW:
2767 /* This is a new, incoming call */
2768 /* save the capability for validation */
2769 session->capability = e->ies.capability;
2770 if (e->ies.codec_prefs) {
2771 strncpy(session->codec_order,
2772 e->ies.codec_prefs,
2773 sizeof(session->codec_order) - 1);
2774 session->codec_order[31] = '\0';
2775 session->codec_order_len =
2776 (int)strlen(session->codec_order);
2777 }
2778 e->etype = IAX_EVENT_CONNECT;
2779 e = schedule_delivery(e, ts, updatehistory);
2780 break;
2781 case IAX_COMMAND_AUTHREQ:
2782 /* This is a request for a call */
2783 e->etype = IAX_EVENT_AUTHRQ;
2784 if (strlen(session->username) && !strcmp(e->ies.username, session->username) &&
2785 strlen(session->secret)) {
2786 /* Hey, we already know this one */
2787 iax_auth_reply(session, session->secret, e->ies.challenge, e->ies.authmethods);
2788 free(e);
2789 e = NULL;
2790 break;
2791 }
2792 e = schedule_delivery(e, ts, updatehistory);
2793 break;
2794 case IAX_COMMAND_HANGUP:
2795 e->etype = IAX_EVENT_HANGUP;
2796 e = schedule_delivery(e, ts, updatehistory);
2797 break;
2798 case IAX_COMMAND_INVAL:
2799 e->etype = IAX_EVENT_HANGUP;
2800 e = schedule_delivery(e, ts, updatehistory);
2801 break;
2802 case IAX_COMMAND_REJECT:
2803 e->etype = IAX_EVENT_REJECT;
2804 e = schedule_delivery(e, ts, updatehistory);
2805 break;
2806 case IAX_COMMAND_ACK:
2807 free(e);
2808 e = NULL;
2809 break;
2810 case IAX_COMMAND_VNAK:
2811 iax_handle_vnak(session, fh);
2812 free(e);
2813 e = NULL;
2814 break;
2815 case IAX_COMMAND_LAGRQ:
2816 /* Pass this along for later handling */
2817 e->etype = IAX_EVENT_LAGRQ;
2818 e->ts = ts;
2819 e = schedule_delivery(e, ts, updatehistory);
2820 break;
2821 case IAX_COMMAND_POKE:
2822 e->etype = IAX_EVENT_POKE;
2823 e->ts = ts;
2824 break;
2825 case IAX_COMMAND_PING:
2826 /* PINGS and PONGS don't get scheduled; */
2827 e->etype = IAX_EVENT_PING;
2828 e->ts = ts;
2829 break;
2830 case IAX_COMMAND_PONG:
2831 e->etype = IAX_EVENT_PONG;
2832 /* track weighted average of ping time */
2833 session->pingtime = ((2 * session->pingtime) + (calc_timestamp(session,0,NULL) - ts)) / 3;
2834 session->remote_netstats.jitter = e->ies.rr_jitter;
2835 session->remote_netstats.losspct = e->ies.rr_loss >> 24;;
2836 session->remote_netstats.losscnt = e->ies.rr_loss & 0xffffff;
2837 session->remote_netstats.packets = e->ies.rr_pkts;
2838 session->remote_netstats.delay = e->ies.rr_delay;
2839 session->remote_netstats.dropped = e->ies.rr_dropped;
2840 session->remote_netstats.ooo = e->ies.rr_ooo;
2841 break;
2842 case IAX_COMMAND_ACCEPT:
2843 if (e->ies.format & session->capability) {
2844 e->etype = IAX_EVENT_ACCEPT;
2845 }
2846 else {
2847 struct iax_ie_data ied;
2848 /* Although this should not happen, we
2849 * added this to make sure the
2850 * negotiation protocol is enforced.
2851 * For lack of event to notify the
2852 * application we use the defined
2853 * REJECT event.
2854 */
2855 memset(&ied, 0, sizeof(ied));
2856 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unable to negotiate codec");
2857 send_command_final(session, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
2858 e->etype = IAX_EVENT_REJECT;
2859 }
2860 e = schedule_delivery(e, ts, updatehistory);
2861 break;
2862 case IAX_COMMAND_REGACK:
2863 e->etype = IAX_EVENT_REGACK;
2864 e = schedule_delivery(e, ts, updatehistory);
2865 break;
2866 case IAX_COMMAND_REGAUTH:
2867 iax_regauth_reply(session, session->secret, e->ies.challenge, e->ies.authmethods);
2868 free(e);
2869 e = NULL;
2870 break;
2871 case IAX_COMMAND_REGREJ:
2872 e->etype = IAX_EVENT_REGREJ;
2873 e = schedule_delivery(e, ts, updatehistory);
2874 break;
2875 case IAX_COMMAND_LAGRP:
2876 e->etype = IAX_EVENT_LAGRP;
2877 nowts = calc_timestamp(session, 0, NULL);
2878 e->ts = nowts - ts;
2879 /* Can't call schedule_delivery since timestamp is non-normal */
2880 break;;
2881 case IAX_COMMAND_TXREQ:
2882 /* added check for defensive programming
2883 * - in case the asterisk server
2884 * or another client does not send the
2885 * apparent transfer address
2886 */
2887 if (e->ies.apparent_addr != NULL) {
2888 /* so a full voice frame is sent on the
2889 next voice output */
2890 session->svoiceformat = -1;
2891 session->transfer = *e->ies.apparent_addr;
2892 session->transfer.sin_family = AF_INET;
2893 session->transfercallno = e->ies.callno;
2894 session->transferring = TRANSFER_BEGIN;
2895 session->transferid = e->ies.transferid;
2896 iax_send_txcnt(session);
2897 }
2898 free(e);
2899 e = NULL;
2900 break;
2901 case IAX_COMMAND_DPREP:
2902 /* Received dialplan reply */
2903 e->etype = IAX_EVENT_DPREP;
2904 /* Return immediately, makes no sense to schedule */
2905 break;
2906 case IAX_COMMAND_TXCNT:
2907 if (session->transferring) {
2908 session->transfer = *sin;
2909 iax_send_txaccept(session);
2910 }
2911 free(e);
2912 e = NULL;
2913 break;
2914 case IAX_COMMAND_TXACC:
2915 if (session->transferring) {
2916 stop_transfer(session);
2917 session->transferring = TRANSFER_READY;
2918 iax_send_txready(session);
2919 }
2920 free(e);
2921 e = NULL;
2922 break;
2923 case IAX_COMMAND_TXREL:
2924 /* Release the transfer */
2925 send_command_immediate(session, AST_FRAME_IAX, IAX_COMMAND_ACK, ts, NULL, 0, fh->iseqno);
2926 if (session->transferring) {
2927 complete_transfer(session, e->ies.callno, 1, 0);
2928 }
2929 else {
2930 complete_transfer(session, session->peercallno, 0, 1);
2931 }
2932 e->etype = IAX_EVENT_TRANSFER;
2933 /* notify that asterisk no longer sitting between peers */
2934 e = schedule_delivery(e, ts, updatehistory);
2935 break;
2936 case IAX_COMMAND_QUELCH:
2937 e->etype = IAX_EVENT_QUELCH;
2938 session->quelch = 1;
2939 break;
2940 case IAX_COMMAND_UNQUELCH:
2941 e->etype = IAX_EVENT_UNQUELCH;
2942 session->quelch = 0;
2943 break;
2944 case IAX_COMMAND_TXREJ:
2945 e->etype = IAX_EVENT_TXREJECT;
2946 iax_handle_txreject(session);
2947 break;
2948
2949 case IAX_COMMAND_TXREADY:
2950 send_command_immediate(session, AST_FRAME_IAX, IAX_COMMAND_ACK, ts, NULL, 0, fh->iseqno);
2951 if (iax_handle_txready(session)) {
2952 e->etype = IAX_EVENT_TXREADY;
2953 }
2954 else {
2955 free(e);
2956 e = NULL;
2957 }
2958 break;
2959 default:
2960 DEBU(G "Don't know what to do with IAX command %d\n", subclass);
2961 free(e);
2962 e = NULL;
2963 }
2964 break;
2965 case AST_FRAME_CONTROL:
2966 switch(subclass) {
2967 case AST_CONTROL_ANSWER:
2968 e->etype = IAX_EVENT_ANSWER;
2969 e = schedule_delivery(e, ts, updatehistory);
2970 break;
2971 case AST_CONTROL_CONGESTION:
2972 case AST_CONTROL_BUSY:
2973 e->etype = IAX_EVENT_BUSY;
2974 e = schedule_delivery(e, ts, updatehistory);
2975 break;
2976 case AST_CONTROL_RINGING:
2977 e->etype = IAX_EVENT_RINGA;
2978 e = schedule_delivery(e, ts, updatehistory);
2979 break;
2980 default:
2981 DEBU(G "Don't know what to do with AST control %d\n", subclass);
2982 free(e);
2983 return NULL;
2984 }
2985 break;
2986 case AST_FRAME_IMAGE:
2987 e->etype = IAX_EVENT_IMAGE;
2988 e->subclass = subclass;
2989 if (datalen) {
2990 memcpy(e->data, fh->iedata, datalen);
2991 }
2992 e = schedule_delivery(e, ts, updatehistory);
2993 break;
2994 case AST_FRAME_VIDEO:
2995 e->etype = IAX_EVENT_VIDEO;
2996 e->subclass = subclass;
2997 e->ts = ts;
2998 session->videoformat = e->subclass;
2999 memcpy(e->data, fh->iedata, datalen);
3000 e->datalen = datalen;
3001 e = schedule_delivery(e, ts, updatehistory);
3002 break;
3003 case AST_FRAME_TEXT:
3004 e->etype = IAX_EVENT_TEXT;
3005 if (datalen) {
3006 memcpy(e->data, fh->iedata, datalen);
3007 e->datalen = datalen;
3008 }
3009 e = schedule_delivery(e, ts, updatehistory);
3010 break;
3011
3012 case AST_FRAME_HTML:
3013 switch(fh->csub) {
3014 case AST_HTML_LINKURL:
3015 e->etype = IAX_EVENT_LINKURL;
3016 /* Fall through */
3017 case AST_HTML_URL:
3018 if (e->etype == -1)
3019 e->etype = IAX_EVENT_URL;
3020 e->subclass = fh->csub;
3021 e->datalen = datalen;
3022 if (datalen) {
3023 memcpy(e->data, fh->iedata, datalen);
3024 }
3025 e = schedule_delivery(e, ts, updatehistory);
3026 break;
3027 case AST_HTML_LDCOMPLETE:
3028 e->etype = IAX_EVENT_LDCOMPLETE;
3029 e = schedule_delivery(e, ts, updatehistory);
3030 break;
3031 case AST_HTML_UNLINK:
3032 e->etype = IAX_EVENT_UNLINK;
3033 e = schedule_delivery(e, ts, updatehistory);
3034 break;
3035 case AST_HTML_LINKREJECT:
3036 e->etype = IAX_EVENT_LINKREJECT;
3037 e = schedule_delivery(e, ts, updatehistory);
3038 break;
3039 default:
3040 DEBU(G "Don't know how to handle HTML type %d frames\n", fh->csub);
3041 free(e);
3042 return NULL;
3043 }
3044 break;
3045 default:
3046 DEBU(G "Don't know what to do with frame type %d\n", fh->type);
3047 free(e);
3048 return NULL;
3049 }
3050 } else
3051 DEBU(G "Out of memory\n");
3052
3053 /* Already ack'd iax frames */
3054 if (session->aseqno != session->iseqno) {
3055 send_command_immediate(session, AST_FRAME_IAX, IAX_COMMAND_ACK, ts, NULL, 0, fh->iseqno);
3056 }
3057 return e;
3058 }
3059
3060 /* Some parts taken from iax_miniheader_to_event and from from chan_iax2.c. We must inform Mark Spencer? */
3061 static struct iax_event *iax_videoheader_to_event(struct iax_session *session,
3062 struct ast_iax2_video_hdr *vh, int datalen)
3063 {
3064 struct iax_event * e;
3065
3066 if ( session->videoformat <= 0 )
3067 {
3068 DEBU(G "No last video format received on session %d\n",
3069 session->callno);
3070 return 0;
3071 }
3072
3073 e = (struct iax_event *)malloc(sizeof(struct iax_event) + datalen);
3074
3075 if ( !e )
3076 {
3077 DEBU(G "Out of memory\n");
3078 return 0;
3079 }
3080
3081 e->etype = IAX_EVENT_VIDEO;
3082 e->session = session;
3083 e->subclass = session->videoformat | (ntohs(vh->ts) & 0x8000 ? 1 : 0);
3084 e->datalen = datalen;
3085 memcpy(e->data, vh->data, e->datalen);
3086 e->ts = (session->last_ts & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
3087
3088 return schedule_delivery(e, e->ts, 1);
3089 }
3090
3091 static struct iax_event *iax_miniheader_to_event(struct iax_session *session,
3092 struct ast_iax2_mini_hdr *mh, int datalen)
3093 {
3094 struct iax_event * e;
3095
3096 if ( session->voiceformat <= 0 )
3097 {
3098 DEBU(G "No last format received on session %d\n", session->callno);
3099 return 0;
3100 }
3101
3102 e = (struct iax_event *)malloc(sizeof(struct iax_event) + datalen);
3103
3104 if ( !e )
3105 {
3106 DEBU(G "Out of memory\n");
3107 return 0;
3108 }
3109
3110 e->etype = IAX_EVENT_VOICE;
3111 e->session = session;
3112 e->subclass = session->voiceformat;
3113 e->datalen = datalen;
3114 memcpy(e->data, mh->data, datalen);
3115 e->ts = (session->last_ts & 0xFFFF0000) | ntohs(mh->ts);
3116
3117 return schedule_delivery(e, e->ts, 1);
3118 }
3119
3120 void iax_destroy(struct iax_session *session)
3121 {
3122 destroy_session(session);
3123 }
3124
3125 static struct iax_event *iax_net_read(void)
3126 {
3127 unsigned char buf[65536];
3128 int res;
3129 struct sockaddr_in sin;
3130 socklen_t sinlen;
3131 struct iax_event *event;
3132
3133 sinlen = sizeof(sin);
3134 res = iax_recvfrom(netfd, (char *)buf, sizeof(buf), 0, (struct sockaddr *) &sin, &sinlen);
3135 if (res < 0) {
3136 #if defined(_WIN32_WCE)
3137 if (WSAGetLastError() != WSAEWOULDBLOCK) {
3138 DEBU(G "Error on read: %d\n", WSAGetLastError());
3139 IAXERROR "Read error on network socket: ???");
3140 }
3141 #elif defined(WIN32) || defined(_WIN32_WCE)
3142 if (WSAGetLastError() != WSAEWOULDBLOCK) {
3143 DEBU(G "Error on read: %d\n", WSAGetLastError());
3144 IAXERROR "Read error on network socket: %s", strerror(errno));
3145 }
3146 #else
3147 if (errno != EAGAIN) {
3148 DEBU(G "Error on read: %s\n", strerror(errno));
3149 IAXERROR "Read error on network socket: %s", strerror(errno));
3150 }
3151 #endif
3152 return NULL;
3153 }
3154 event = iax_net_process(buf, res, &sin);
3155 if ( event == NULL )
3156 {
3157 // We have received a frame. The corresponding event is queued
3158 // We need to motify the entire stack of calling functions so they
3159 // don't go to sleep thinking there are no more frames to process
3160 // TODO: this is buttugly from a design point of view. Basically we
3161 // change libiax2 behavior to accomodate iaxclient.
3162 // There must be a way to do it better.
3163 event = (struct iax_event *)malloc(sizeof(struct iax_event));
3164 if ( event != NULL ) event->etype = IAX_EVENT_NULL;
3165 }
3166 return event;
3167 }
3168
3169 static struct iax_session *iax_txcnt_session(struct ast_iax2_full_hdr *fh, int datalen,
3170 struct sockaddr_in *sin, short callno, short dcallno)
3171 {
3172 int subclass = uncompress_subclass(fh->csub);
3173 unsigned char buf[ 65536 ]; /* allocated on stack with same size as iax_net_read() */
3174 struct iax_ies ies;
3175 struct iax_session *cur;
3176
3177 if ((fh->type != AST_FRAME_IAX) || (subclass != IAX_COMMAND_TXCNT) || (!datalen)) {
3178 return NULL; /* special handling for TXCNT only */
3179 }
3180 memcpy(buf, fh->iedata, datalen); /* prepare local buf for iax_parse_ies() */
3181
3182 if (iax_parse_ies(&ies, buf, datalen)) {
3183 return NULL; /* Unable to parse IE's */
3184 }
3185 if (!ies.transferid) {
3186 return NULL; /* TXCNT without proper IAX_IE_TRANSFERID */
3187 }
3188 for( cur=sessions; cur; cur=cur->next ) {
3189 if ((cur->transferring) && (cur->transferid == (int) ies.transferid) &&
3190 (cur->callno == dcallno) && (cur->transfercallno == callno)) {
3191 /* We're transferring ---
3192 * skip address/port checking which would fail while
3193 * remote peer behind symmetric NAT, verify
3194 * transferid instead
3195 */
3196 cur->transfer.sin_addr.s_addr = sin->sin_addr.s_addr; /* setup for further handling */
3197 cur->transfer.sin_port = sin->sin_port;
3198 break;
3199 }
3200 }
3201 return cur;
3202 }
3203
3204 struct iax_event *iax_net_process(unsigned char *buf, int len, struct sockaddr_in *sin)
3205 {
3206 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)buf;
3207 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)buf;
3208 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)buf;
3209 struct iax_session *session;
3210
3211 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
3212 /* Full size header */
3213 if ((size_t)len < sizeof(struct ast_iax2_full_hdr)) {
3214 DEBU(G "Short header received from %s\n", inet_ntoa(sin->sin_addr));
3215 IAXERROR "Short header received from %s\n", inet_ntoa(sin->sin_addr));
3216 return NULL;
3217 }
3218 /* We have a full header, process appropriately */
3219 session = iax_find_session(sin,
3220 ntohs(fh->scallno) & ~IAX_FLAG_FULL,
3221 ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, 1);
3222 if (!session)
3223 session = iax_txcnt_session(fh,
3224 len - sizeof(struct ast_iax2_full_hdr),
3225 sin, ntohs(fh->scallno) & ~IAX_FLAG_FULL,
3226 ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS);
3227 if (session)
3228 return iax_header_to_event(session, fh, len - sizeof(struct ast_iax2_full_hdr), sin);
3229 DEBU(G "No session?\n");
3230 return NULL;
3231 } else {
3232 if ((size_t)len < sizeof(struct ast_iax2_mini_hdr)) {
3233 DEBU(G "Short header received from %s\n", inet_ntoa(sin->sin_addr));
3234 IAXERROR "Short header received from %s\n", inet_ntoa(sin->sin_addr));
3235 return NULL;
3236 }
3237 /* Miniature, voice frame */
3238 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000))
3239 {
3240 session = iax_find_session(sin, ntohs(vh->callno) & ~0x8000, 0, 0);
3241
3242 if (session)
3243 return iax_videoheader_to_event(session, vh,
3244 len - sizeof(struct ast_iax2_video_hdr));
3245 } else {
3246 /* audio frame */
3247 session = iax_find_session(sin, ntohs(fh->scallno), 0, 0);
3248 if (session)
3249 return iax_miniheader_to_event(session, mh,
3250 len - sizeof(struct ast_iax2_mini_hdr));
3251 }
3252 DEBU(G "No session?\n");
3253 return NULL;
3254 }
3255 }
3256
3257 static struct iax_sched *iax_get_sched(struct timeval tv)
3258 {
3259 struct iax_sched *cur, *prev=NULL;
3260 cur = schedq;
3261 /* Check the event schedule first. */
3262 while(cur) {
3263 if ((tv.tv_sec > cur->when.tv_sec) ||
3264 ((tv.tv_sec == cur->when.tv_sec) &&
3265 (tv.tv_usec >= cur->when.tv_usec))) {
3266 /* Take it out of the event queue */
3267 if (prev) {
3268 prev->next = cur->next;
3269 } else {
3270 schedq = cur->next;
3271 }
3272 return cur;
3273 }
3274 cur = cur->next;
3275 }
3276 return NULL;
3277 }
3278
3279 struct iax_event *iax_get_event(int blocking)
3280 {
3281 struct iax_event *event;
3282 struct iax_frame *frame;
3283 struct timeval tv;
3284 struct iax_sched *cur;
3285 struct iax_session *session;
3286
3287 tv = iax_tvnow();
3288
3289 while((cur = iax_get_sched(tv)))
3290 {
3291 event = cur->event;
3292 frame = cur->frame;
3293 if (event)
3294 {
3295 /* See if this is an event we need to handle */
3296 event = handle_event(event);
3297 if (event)
3298 {
3299 free(cur);
3300 return event;
3301 }
3302 } else if(frame)
3303 {
3304 /* It's a frame, transmit it and schedule a retry */
3305 if (frame->retries < 0)
3306 {
3307 /* It's been acked. No need to send it. Destroy the old
3308 frame. If final, destroy the session. */
3309 if (frame->final)
3310 destroy_session(frame->session);
3311 if (frame->data)
3312 free(frame->data);
3313 free(frame);
3314 } else if (frame->retries == 0)
3315 {
3316 if (frame->transfer)
3317 {
3318 /* Send a transfer reject since we weren't able to connect */
3319 iax_send_txrej(frame->session);
3320 if (frame->data)
3321 free(frame->data);
3322 free(frame);
3323 free(cur);
3324 break;
3325 } else
3326 {
3327 /* We haven't been able to get an ACK on this packet. If a
3328 final frame, destroy the session, otherwise, pass up timeout */
3329 if (frame->final)
3330 {
3331 destroy_session(frame->session);
3332 if (frame->data)
3333 free(frame->data);
3334 free(frame);
3335 } else
3336 {
3337 event = (struct iax_event *)malloc(sizeof(struct iax_event));
3338 if (event)
3339 {
3340 event->etype = IAX_EVENT_TIMEOUT;
3341 event->session = frame->session;
3342 if (frame->data)
3343 free(frame->data);
3344 free(frame);
3345 free(cur);
3346 return handle_event(event);
3347 }
3348 }
3349 }
3350 } else
3351 {
3352 struct ast_iax2_full_hdr *fh;
3353 /* Decrement remaining retries */
3354 frame->retries--;
3355 /* Multiply next retry time by 4, not above MAX_RETRY_TIME though */
3356 frame->retrytime *= 4;
3357 /* Keep under 1000 ms if this is a transfer packet */
3358 if (!frame->transfer)
3359 {
3360 if (frame->retrytime > MAX_RETRY_TIME)
3361 frame->retrytime = MAX_RETRY_TIME;
3362 } else if (frame->retrytime > 1000)
3363 frame->retrytime = 1000;
3364 fh = (struct ast_iax2_full_hdr *)(frame->data);
3365 fh->dcallno = htons(IAX_FLAG_RETRANS | frame->dcallno);
3366 iax_xmit_frame(frame);
3367 /* Schedule another retransmission */
3368 DEBU(G "Scheduling retransmission %d\n", frame->retries);
3369 iax_sched_add(NULL, frame, NULL, NULL, frame->retrytime);
3370 }
3371 } else if (cur->func)
3372 {
3373 cur->func(cur->arg);
3374 }
3375 free(cur);
3376 }
3377
3378 /* get jitterbuffer-scheduled events */
3379 for ( session = sessions; session; session = session->next )
3380 {
3381 int ret;
3382 long now;
3383 long next;
3384 jb_frame frame;
3385
3386 now = (tv.tv_sec - session->rxcore.tv_sec) * 1000 +
3387 (tv.tv_usec - session->rxcore.tv_usec) / 1000;
3388
3389 if ( now <= (next = jb_next(session->jb)) )
3390 continue;
3391
3392 /* interp len no longer hardcoded, now determined by get_interp_len */
3393 ret = jb_get(session->jb,&frame,now,get_interp_len(session->voiceformat));
3394
3395 switch(ret) {
3396 case JB_OK:
3397 event = (struct iax_event *)frame.data;
3398 event = handle_event(event);
3399 if (event) {
3400 return event;
3401 }
3402 break;
3403 case JB_INTERP:
3404 /* create an interpolation frame */
3405 //fprintf(stderr, "Making Interpolation frame\n");
3406 event = (struct iax_event *)malloc(sizeof(struct iax_event));
3407 if (event) {
3408 event->etype = IAX_EVENT_VOICE;
3409 event->subclass = session->voiceformat;
3410 /* XXX: ??? applications probably ignore this anyway */
3411 event->ts = now;
3412 event->session = session;
3413 event->datalen = 0;
3414 event = handle_event(event);
3415 if(event)
3416 return event;
3417 }
3418 break;
3419 case JB_DROP:
3420 iax_event_free((struct iax_event *)frame.data);
3421 break;
3422 case JB_NOFRAME:
3423 case JB_EMPTY:
3424 /* do nothing */
3425 break;
3426 default:
3427 /* shouldn't happen */
3428 break;
3429 }
3430 }
3431
3432 /* Now look for networking events */
3433 if (blocking) {
3434 /* Block until there is data if desired */
3435 fd_set fds;
3436 int nextEventTime;
3437
3438 FD_ZERO(&fds);
3439 FD_SET(netfd, &fds);
3440
3441 nextEventTime = iax_time_to_next_event();
3442
3443 if(nextEventTime < 0) select(netfd + 1, &fds, NULL, NULL, NULL);
3444 else
3445 {
3446 struct timeval nextEvent;
3447
3448 nextEvent.tv_sec = nextEventTime / 1000;
3449 nextEvent.tv_usec = (nextEventTime % 1000) * 1000;
3450
3451 select(netfd + 1, &fds, NULL, NULL, &nextEvent);
3452 }
3453
3454 }
3455 event = iax_net_read();
3456
3457 return handle_event(event);
3458 }
3459
3460 struct sockaddr_in iax_get_peer_addr(struct iax_session *session)
3461 {
3462 return session->peeraddr;
3463 }
3464
3465 void iax_session_destroy(struct iax_session **session)
3466 {
3467 destroy_session(*session);
3468 *session = NULL;
3469 }
3470
3471 void iax_event_free(struct iax_event *event)
3472 {
3473 /* We gave the user a chance to play with the session now we need to
3474 * destroy it if you are not calling this function on every event you
3475 * read you are now going to leak sessions as well as events!
3476 */
3477 switch(event->etype) {
3478 case IAX_EVENT_REJECT:
3479 case IAX_EVENT_HANGUP:
3480 /* Destroy this session -- it's no longer valid */
3481 if (event->session) { /* maybe the user did it already */
3482 destroy_session(event->session);
3483 }
3484 break;
3485 }
3486 free(event);
3487 }
3488
3489 int iax_get_fd(void)
3490 {
3491 /* Return our network file descriptor. The client can select on this
3492 * (probably with other things, or can add it to a network add sort
3493 * of gtk_input_add for example */
3494 return netfd;
3495 }
3496
3497 int iax_quelch_moh(struct iax_session *session, int MOH)
3498 {
3499 struct iax_ie_data ied; //IE Data Structure (Stuff To Send)
3500 memset(&ied, 0, sizeof(ied));
3501
3502 // You can't quelch the quelched
3503 if (session->quelch == 1)
3504 return -1;
3505
3506 if (MOH) {
3507 iax_ie_append(&ied, IAX_IE_MUSICONHOLD);
3508 session->transfer_moh = 1;
3509 }
3510
3511 return send_command(session, AST_FRAME_IAX, IAX_COMMAND_QUELCH, 0, ied.buf, ied.pos, -1);
3512 }
3513
3514 struct timeval iax_tvnow(void)
3515 {
3516 struct timeval tv;
3517
3518 #ifdef HAVE_GETTIMEOFDAY
3519 gettimeofday(&tv, 0);
3520 #elif defined(_MSC_VER)
3521 struct _timeb curSysTime;
3522
3523 _ftime(&curSysTime);
3524 tv.tv_sec = (long)curSysTime.time;
3525 tv.tv_usec = curSysTime.millitm * 1000;
3526 #else
3527 #error no gettimeofday or equivalent available
3528 #endif
3529 return tv;
3530 }