Version 0.1.0 from FTP
[asterisk/asterisk.git] / channels / chan_vofr.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Implementation of Voice over Frame Relay, Adtran Style
5  * 
6  * Copyright (C) 1999, Adtran Inc. and Linux Support Services, LLC
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <pthread.h>
16 #include <string.h>
17 #include <asterisk/channel.h>
18 #include <asterisk/channel_pvt.h>
19 #include <asterisk/config.h>
20 #include <asterisk/logger.h>
21 #include <asterisk/module.h>
22 #include <asterisk/pbx.h>
23 #include <asterisk/options.h>
24 #include <sys/socket.h>
25 #include <errno.h>
26 #include <unistd.h>
27 #include <stdlib.h>
28 #include <arpa/inet.h>
29 #include <linux/if_packet.h>
30 #include <linux/if_ether.h>
31 #include "adtranvofr.h"
32
33 #define G723_MAX_BUF 2048
34
35 #define FR_API_MESS 16
36
37 static char *desc = "Adtran Voice over Frame Relay";
38 static char *type = "AdtranVoFR";
39 static char *tdesc = "Voice over Frame Relay/Adtran style";
40 static char *config = "adtranvofr.conf";
41
42 static char context[AST_MAX_EXTENSION] = "default";
43
44 static int usecnt =0;
45 static pthread_mutex_t usecnt_lock = PTHREAD_MUTEX_INITIALIZER;
46
47 /* Protect the interface list (of vofr_pvt's) */
48 static pthread_mutex_t iflock = PTHREAD_MUTEX_INITIALIZER;
49
50 /* Protect the monitoring thread, so only one process can kill or start it, and not
51    when it's doing something critical. */
52 static pthread_mutex_t monlock = PTHREAD_MUTEX_INITIALIZER;
53
54 /* This is the thread for the monitor which checks for input on the channels
55    which are not currently in use.  */
56 static pthread_t monitor_thread = -1;
57
58 static int restart_monitor();
59
60 /* The private structures of the Adtran VoFR channels are linked for
61    selecting outgoing channels */
62    
63 static struct vofr_pvt {
64         int s;                                                  /* Raw socket for this DLCI */
65         struct sockaddr_pkt sa;                 /* Sockaddr needed for sending, also has iface name */
66         struct ast_channel *owner;              /* Channel we belong to, possibly NULL */
67         int outgoing;                                   /* Does this channel support outgoing calls? */
68         struct vofr_pvt *next;                  /* Next channel in list */
69         struct vofr_hdr *hdr;                           /* VOFR header version of buf */
70         struct vofr_hdr *ohdr;
71         u_int8_t dlcih;                                 /* High two bits of DLCI */
72         u_int8_t dlcil;                                 /* Bottom two bits of DLCI */
73         u_int8_t cid;                                   /* Call ID */
74         char buf[G723_MAX_BUF];                                 /* Static buffer for reading frames */
75         char obuf[G723_MAX_BUF];                                /* Output buffer */
76         char context[AST_MAX_EXTENSION];
77 } *iflist = NULL;
78
79 #ifdef VOFRDUMPER
80
81 /* Some useful debugging routines */
82
83 static char *set(int val)
84 {
85         return (val ? "Set  " : "Unset");
86 }
87
88 static char *controlstr(int control)
89 {
90         switch(control) {
91         case VOFR_CONTROL_ADTRAN:
92                 return "Adtran Proprietary";
93         case VOFR_CONTROL_VOICE:
94                 return "Voice";
95         case VOFR_CONTROL_RFC1490:
96                 return "RFC 1490";
97         }
98         return "Unknown";
99 }
100
101 static char *dtypestr(int control)
102 {
103         switch(control) {
104         case VOFR_TYPE_SIGNAL:
105                 return "Signal Frame";
106         case VOFR_TYPE_VOICE:
107                 return "Voice Frame";
108         case VOFR_TYPE_ANSWER:
109                 return "Answer Tone";
110         case VOFR_TYPE_FAX:     
111                 return "FAX";
112         case VOFR_TYPE_DTMF:
113                 return "DTMF Digit";
114         }
115         return "Unknown";
116 }
117
118 static char *vflagsstr(int flags)
119 {
120         static char buf[80];
121         buf[0] = '\0';
122         if (!flags)
123                 return "(None)";
124         if (flags & VOFR_ROUTE_LOCAL)
125                 strcat(buf, "Local ");
126         if (flags & VOFR_ROUTE_VOICE)
127                 strcat(buf, "Voice ");
128         if (flags & VOFR_ROUTE_DTE)
129                 strcat(buf, "DTE ");
130         else if (flags & VOFR_ROUTE_DTE1)
131                 strcat(buf, "DTE1 ");
132         else if (flags & VOFR_ROUTE_DTE2)       
133                 strcat(buf, "DTE2 ");
134         return buf;
135 }
136
137 static char *remidstr(int remid)
138 {
139         switch(remid) {
140         case VOFR_CARD_TYPE_UNSPEC:
141                 return "Unspecified";
142         case VOFR_CARD_TYPE_FXS:
143                 return "FXS";
144         case VOFR_CARD_TYPE_FXO:
145                 return "FXO";
146         case VOFR_CARD_TYPE_ENM:        
147                 return "E&M";
148         case VOFR_CARD_TYPE_VCOM:       
149                 return "Atlas/VCOM";
150         }
151         return "Unknown";
152 }
153
154 static char *modulationstr(int modulation)
155 {
156         switch(modulation) {
157         case VOFR_MODULATION_SINGLE:
158                 return "Single Frequency";
159         case VOFR_MODULATION_V21:
160                 return "V.21";
161         case VOFR_MODULATION_V27ter_2:
162                 return "V.27 (2400bps)";
163         case VOFR_MODULATION_V27ter_4:
164                 return "V.27 (4800bps)";
165         case VOFR_MODULATION_V29_7:
166                 return "V.29 (7200bps)";
167         case VOFR_MODULATION_V29_9:
168                 return "V.29 (9600bps)";
169         case VOFR_MODULATION_V33_12:
170                 return "V.33 (12000bps)";
171         case VOFR_MODULATION_V33_14:
172                 return "V.33 (14400BPS)";
173         }
174         return "Unknown";
175 }
176
177 static char *signalstr(int signal)
178 {
179         switch(signal) {
180         case VOFR_SIGNAL_ON_HOOK:
181                 return "On Hook";
182         case VOFR_SIGNAL_OFF_HOOK:
183                 return "Off Hook";
184         case VOFR_SIGNAL_RING:
185                 return "Ring";
186         case VOFR_SIGNAL_SWITCHED_DIAL:
187                 return "Switched Dial";
188         case VOFR_SIGNAL_BUSY:
189                 return "Busy";
190         case VOFR_SIGNAL_TRUNK_BUSY:
191                 return "Trunk Busy";
192         }
193         return "Unknown";
194 }
195
196 static char *vofr_digitstr(int val)
197 {
198         static char num[5];
199         if (val < 10) {
200                 snprintf(num, sizeof(num), "%d", val);
201                 return num;
202         }
203         switch(val) {
204         case 10:
205                 return "*";
206         case 11:
207                 return "#";
208         }
209         return "Unknown";
210 }
211
212
213 static void vofr_dump_packet(struct vofr_hdr *vh, int len)
214 {
215         printf("VoFR Packet Dump\n");
216         printf("================\n");
217         printf("EI: %s ", set(vh->control & VOFR_MASK_EI));
218         printf("LI: %s\n", set(vh->control & VOFR_MASK_LI));
219         printf("Control: %s (0x%02x)\n", 
220                 controlstr(vh->control & VOFR_MASK_CONTROL), vh->control & VOFR_MASK_CONTROL);
221         printf("Data Type: %s (0x%02x)\n", dtypestr(vh->dtype), vh->dtype);
222         if (vh->dtype == VOFR_TYPE_SIGNAL) {
223                 printf(" \\--Signal: %s (0x%02x)\n", signalstr(vh->data[0]), vh->data[0]);
224         }
225         if (vh->dtype == VOFR_TYPE_DTMF) {
226                 printf(" \\--Digit: %s (0x%02x)\n", vofr_digitstr(vh->data[0]), vh->data[0]);
227         }
228         printf("Connect Tag: 0x%02x\n", vh->ctag);
229         printf("Voice Rt Flags: %s\n", vflagsstr(vh->vflags));
230         printf("DLCI X-Ref: %d\n", (vh->dlcih << 8) | (vh->dlcil));
231         printf("Channel ID: %d\n", vh->cid);
232         printf("Remote ID: %s (0x%02x)\n", remidstr(vh->remid), vh->remid);
233         printf("Modulation: %s (0x%02x)\n", modulationstr(vh->mod), vh->mod);
234         printf("\n");
235         fflush(stdout);
236 }
237
238 #endif
239
240 static int vofr_xmit(struct vofr_pvt *p, char *data, int len)
241 {
242         int res;
243     res=sendto(p->s, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_pkt));
244         if (res != len) {
245                 ast_log(LOG_WARNING, "vofr_xmit returned %d\n", res);
246         }
247         return res;
248 }
249
250 static int vofr_digit(struct ast_channel *ast, char digit)
251 {
252         /*
253          * T H I S   I S   T O T A L L Y   U N D O C U M E N T E D
254          *     A N D   D O E S   N O T   S O U N D   R I G H T
255          *   XXX Figure out how to really send a decent digit XXX
256          */
257         struct vofr_pvt *p;
258         struct vofr_hdr *vh;
259         p = ast->pvt->pvt;
260         vh = p->ohdr;
261         vh->control = VOFR_CONTROL_VOICE;
262         vh->dtype = VOFR_TYPE_DTMF;
263         vh->vflags = VOFR_ROUTE_NONE;
264         vh->dlcih = p->dlcih;
265         vh->dlcil = p->dlcil;
266         vh->cid = p->cid;
267         vh->remid = VOFR_CARD_TYPE_ASTERISK;
268         vh->mod = VOFR_MODULATION_SINGLE;
269         if ((digit >= '0') && (digit <= '9'))
270                 vh->data[0] = digit - '0';
271         else if (digit == '*')
272                 vh->data[0] = 10;
273         else if (digit == '#')
274                 vh->data[0] = 11;
275         else {
276                 ast_log(LOG_WARNING, "%s: tried to dial a non digit '%c'\n", ast->name, digit);
277                 return -1;
278         }
279         vh->data[1] = 0x14;
280         vh->data[2] = 0x1f;
281         vh->data[3] = 0x70;
282                 /* We sorta start the digit */
283         vofr_xmit(p, p->obuf, VOFR_HDR_SIZE + 4 + FR_API_MESS);
284         usleep(30000);
285                 /* And terminate with an empty voice frame */
286         vh->control = VOFR_CONTROL_VOICE;
287         vh->dtype = VOFR_TYPE_VOICE;
288         vh->vflags = VOFR_ROUTE_NONE;
289         vh->dlcih = p->dlcih;
290         vh->dlcil = p->dlcil;
291         vh->cid = p->cid;
292         vh->remid = VOFR_CARD_TYPE_ASTERISK;
293         vh->mod = VOFR_MODULATION_SINGLE;
294         vofr_xmit(p, p->obuf, VOFR_HDR_SIZE + FR_API_MESS);
295         return 0;
296 }
297
298 static int vofr_xmit_signal(struct vofr_pvt *p, int signal, int pad)
299 {
300         /* Prepare and transmit outgoing buffer with given signal and
301            pad the end with *pad* bytes of data presumed to already
302            be in the buffer (like DTMF tones, etc) */
303         struct vofr_hdr *vh = p->ohdr;
304         int res;
305     vh->control = VOFR_CONTROL_VOICE;
306     vh->dtype = VOFR_TYPE_SIGNAL;
307     vh->vflags = VOFR_ROUTE_NONE;
308     vh->dlcih = p->dlcih;
309     vh->dlcil = p->dlcil;
310     vh->cid = p->cid;
311     vh->remid = VOFR_CARD_TYPE_ASTERISK;
312     vh->mod = VOFR_MODULATION_SINGLE;
313     vh->data[0] = signal;
314         if (FR_API_MESS)
315                 memset(p->obuf, 0, FR_API_MESS);
316         res = vofr_xmit(p, p->obuf,  VOFR_HDR_SIZE + pad + 1 + FR_API_MESS);
317         return res;
318
319 }
320
321 static int vofr_call(struct ast_channel *ast, char *dest, int timeout)
322 {
323         int res;
324         int otimeout;
325         struct ast_frame *f;
326         struct vofr_pvt *p;
327         p = ast->pvt->pvt;
328         if ((ast->state != AST_STATE_DOWN) && (ast->state != AST_STATE_RESERVED)) {
329                 ast_log(LOG_WARNING, "vofr_call called on %s, neither down nor reserved\n", ast->name);
330                 return -1;
331         }
332         /* Take the system off hook */
333         vofr_xmit_signal(p, VOFR_SIGNAL_OFFHOOK, 0);
334         /* Wait for an acknowledgement */
335         otimeout = 1000;
336         while(otimeout) {
337                 otimeout = ast_waitfor(ast, 1000);
338                 if (otimeout < 1) {
339                         ast_log(LOG_WARNING, "Unable to take line off hook\n");
340                         /* Musta gotten hung up, or no ack on off hook */
341                         return -1;      
342                 }
343                 f = ast_read(ast);
344                 if (!f)
345                         return -1;
346                 if ((f->frametype == AST_FRAME_CONTROL) &&
347                     (f->subclass == AST_CONTROL_OFFHOOK)) 
348                         /* Off hook */
349                                 break;
350         }
351         if (!otimeout) {
352                 ast_log(LOG_WARNING, "Unable to take line off hook\n");
353                 return -1;
354         }
355         /* Send the digits */
356         while(*dest) {
357                 ast->state = AST_STATE_DIALING;
358                 vofr_digit(ast, *dest);
359                 /* Wait .1 seconds before dialing next digit */
360                 usleep(100000);
361                 dest++;
362         }
363         if (timeout) {
364                 /* Wait for the ack that it's ringing */
365                 otimeout = 1000;
366                 while(otimeout) {
367                         otimeout = ast_waitfor(ast, 1000);
368                         if (otimeout < 1) {
369                                 ast_log(LOG_WARNING, "No acknowledgement for ringing\n");
370                                 /* Musta gotten hung up, or no ack on off hook */
371                                 return -1;      
372                         }
373                         f = ast_read(ast);
374                         if (!f) 
375                                 return -1;
376                         
377                         if (f->frametype == AST_FRAME_CONTROL) {
378                             if (f->subclass == AST_CONTROL_RINGING) {
379                                         ast->state = AST_STATE_RINGING;
380                                         /* We're ringing -- good enough */
381                                         break;
382                                 }
383                                 if (f->subclass == AST_CONTROL_BUSY)
384                                 /* It's busy */
385                                         return -1;
386                         }
387                         ast_frfree(f);
388                 }               
389         }
390         otimeout = timeout;
391         while(timeout) {
392                 /* Wait for an answer, up to timeout... */
393                 res = ast_waitfor(ast, timeout);
394                 if (res < 0)
395                         /* Musta gotten hung up */
396                         return -1;
397                 else
398                         timeout = res;
399                 if (res) {
400                         /* Ooh, read what's there. */
401                         f = ast_read(ast);
402                         if (!f)
403                                 return -1;
404                         if ((f->frametype == AST_FRAME_CONTROL) && 
405                             (f->subclass == AST_CONTROL_ANSWER)) 
406                                 /* Got an answer -- return the # of ms it took */
407                                 return otimeout - res;
408                                 
409                 }
410         }
411         return 0;
412 }
413
414 static int send_hangup(struct vofr_pvt *p)
415 {
416         /* Just send the hangup sequence */
417         return vofr_xmit_signal(p, 0x80, 0);
418 }
419
420 static int vofr_hangup(struct ast_channel *ast)
421 {
422         int res;
423         if (option_debug)
424                 ast_log(LOG_DEBUG, "vofr_hangup(%s)\n", ast->name);
425         if (!ast->pvt->pvt) {
426                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
427                 return 0;
428         }
429         res = send_hangup(ast->pvt->pvt);
430         if (res < 0) {
431                 ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
432                 return -1;
433         }
434         ast->state = AST_STATE_DOWN;
435         ((struct vofr_pvt *)(ast->pvt->pvt))->owner = NULL;
436         pthread_mutex_lock(&usecnt_lock);
437         usecnt--;
438         if (usecnt < 0) 
439                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
440         pthread_mutex_unlock(&usecnt_lock);
441         ast_update_use_count();
442         if (option_verbose > 2) 
443                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
444         ast->pvt->pvt = NULL;
445         ast->state = AST_STATE_DOWN;
446         restart_monitor();
447         return 0;
448 }
449
450 static int vofr_answer(struct ast_channel *ast)
451 {
452         int res;
453         int cnt = 1000;
454         char buf[2048];
455         struct vofr_hdr *vh;
456         ast->rings = 0;
457         if (option_debug)
458                 ast_log(LOG_DEBUG, "vofr_answer(%s)\n", ast->name);
459         res = vofr_xmit_signal(ast->pvt->pvt, VOFR_SIGNAL_OFFHOOK, 0);
460         if (res < 0)
461                 ast_log(LOG_WARNING, "Unable to anaswer line %s\n", ast->name);
462         ast->state = AST_STATE_UP;
463         while(cnt > 0) {
464                 cnt = ast_waitfor(ast, cnt);
465                 if (cnt > 0) {
466                         res = read(ast->fd, buf, sizeof(buf));
467                         res -= FR_API_MESS;
468                         if (res < 0)
469                                 ast_log(LOG_WARNING, "Warning:  read failed (%s) on %s\n", strerror(errno), ast->name);
470                         else {
471                                 /* We're looking for an answer */
472                                 vh = (struct vofr_hdr *)(buf + FR_API_MESS);
473                                 switch(vh->dtype) {
474                                 case VOFR_TYPE_SIGNAL:
475                                         switch(vh->data[0]) {
476                                         case VOFR_SIGNAL_UNKNOWN:
477                                                 switch(vh->data[1]) {
478                                                 case 0x1:
479                                                         if (option_debug) 
480                                                                 ast_log(LOG_DEBUG, "Answered '%s'\n", ast->name);
481                                                         else if (option_verbose > 2) 
482                                                                 ast_verbose( VERBOSE_PREFIX_3 "Answered '%s'\n", ast->name);
483                                                         ast->state = AST_STATE_UP;
484                                                         return 0;
485                                                         break;
486                                                 default:
487                                                         ast_log(LOG_WARNING, "Unexpected 'unknown' frame type %d\n", vh->data[1]);
488                                                 }
489                                                 break;
490                                         case VOFR_SIGNAL_ON_HOOK:
491                                                 /* Ignore onhooks.  */
492                                                 break;
493                                         default:
494                                                 ast_log(LOG_WARNING, "Unexpected signal type %d\n", vh->data[0]);
495                                         }
496                                         break;
497                                 default:
498                                         ast_log(LOG_WARNING, "Unexpected data type %d\n", vh->dtype);
499                                 }
500                         }
501                 }
502         }
503         ast_log(LOG_WARNING, "Did not get acknowledged answer\n");
504         return -1;
505 }
506
507 static char vofr_2digit(char c)
508 {
509         if (c == 11)
510                 return '#';
511         else if (c == 10)
512                 return '*';
513         else if ((c < 10) && (c >= 0))
514                 return '0' + c;
515         else
516                 return '?';
517 }
518
519 static struct ast_frame  *vofr_read(struct ast_channel *ast)
520 {
521         int res;
522         char tone;
523         int timeout,x;
524         struct vofr_pvt *p = ast->pvt->pvt;
525         short *swapping;
526         struct ast_frame *fr = (struct ast_frame *)(p->buf);
527         struct vofr_hdr *vh = (struct vofr_hdr *)(p->buf + sizeof(struct ast_frame) + AST_FRIENDLY_OFFSET - sizeof(struct vofr_hdr));
528         /* Read into the right place in the buffer, in case we send this
529            as a voice frame. */
530         CHECK_BLOCKING(ast);
531         res = read(p->s, ((char *)vh)  - FR_API_MESS, 
532                                 G723_MAX_BUF - AST_FRIENDLY_OFFSET - sizeof(struct ast_frame) + sizeof(struct vofr_hdr) + FR_API_MESS);
533         ast->blocking = 0;
534         res -= FR_API_MESS;             
535         if (res < sizeof(struct vofr_hdr *)) {
536                 ast_log(LOG_WARNING, "Nonsense frame on %s\n", ast->name);
537                 return NULL;
538         }
539
540         /* Some nice norms */
541         fr->datalen = 0;
542         fr->timelen = 0;
543         fr->data =  NULL;
544         fr->src = type;
545         fr->offset = 0;
546         fr->mallocd=0;
547         
548         /* Now, what we do depends on what we read */
549         switch(vh->dtype) {
550         case VOFR_TYPE_SIGNAL:
551                 switch(vh->data[0]) {
552                 case VOFR_SIGNAL_ON_HOOK:
553                         /* Hang up this line */
554                         if (ast->state == AST_STATE_UP)
555                                 return NULL;
556                         else {
557                                 fr->frametype = AST_FRAME_NULL;
558                                 fr->subclass = 0;
559                                 break;
560                         }
561                 case VOFR_SIGNAL_UNKNOWN:
562                         switch(vh->data[1]) {
563                         case 0x1:
564                                 /* This is a little tricky, because it depends
565                                    on the context of what state we're in */
566                                 switch(ast->state) {
567                                 case AST_STATE_RINGING:
568                                         fr->frametype = AST_FRAME_CONTROL;
569                                         fr->subclass = AST_CONTROL_ANSWER;
570                                         ast->state = AST_STATE_UP;
571                                         break;
572                                 case AST_STATE_DOWN:
573                                 case AST_STATE_UP:
574                                         fr->frametype = AST_FRAME_NULL;
575                                         fr->subclass = 0;
576                                         break;
577                                 }
578                                 break;
579                         case 0x2:
580                                 /* Remote acknowledged off hook */
581                                 fr->frametype = AST_FRAME_CONTROL;
582                                 fr->subclass = AST_CONTROL_OFFHOOK;
583                                 ast->state = AST_STATE_OFFHOOK;
584                                 break;
585                         case 0x3:
586                                 /* Busy signal */
587                                 fr->frametype = AST_FRAME_CONTROL;
588                                 fr->subclass = AST_CONTROL_BUSY;
589                                 ast->state = AST_STATE_BUSY;
590                                 break;
591                         case 0x5:
592                                 /* Ringing -- acknowledged */
593                                 fr->frametype = AST_FRAME_CONTROL;
594                                 fr->subclass = AST_CONTROL_RINGING;
595                                 ast->state = AST_STATE_RINGING;
596                                 break;
597                         case 0x6:
598                                 /* Hang up detected.  Return NULL */
599                                 return NULL;
600                         default:
601                                 ast_log(LOG_WARNING, "Don't know what to do with 'unknown' signal '%d'\n", vh->data[1]);
602                                 fr->frametype = AST_FRAME_NULL;
603                                 fr->subclass = 0;
604                         }
605                         return fr;
606                         break;
607                 default:
608                         ast_log(LOG_WARNING, "Don't know what to do with signal '%d'\n", vh->data[0]);
609                 }
610                 break;
611         case VOFR_TYPE_DTMF:
612                 /* If it's a DTMF tone, then we want to wait until we don't get any more dtmf tones or
613                    the DTMF tone changes.  
614                        XXX Note: We will drop at least one frame here though XXX */
615                 
616                 tone = vofr_2digit(vh->data[0]);
617                 timeout = 50;
618                 do {
619                         if ((timeout = ast_waitfor(ast, timeout)) < 1)
620                                 break;
621                         CHECK_BLOCKING(ast);
622                         res = read(p->s, ((char *)vh)  - FR_API_MESS, 
623                                         G723_MAX_BUF - AST_FRIENDLY_OFFSET - sizeof(struct ast_frame) + sizeof(struct vofr_hdr) + FR_API_MESS);
624                         ast->blocking = 0;
625                         res -= FR_API_MESS;             
626                         if (res < sizeof(struct vofr_hdr *)) {
627                                 ast_log(LOG_WARNING, "Nonsense frame on %s\n", ast->name);
628                                 return NULL;
629                         }
630                         if (vh->dtype == VOFR_TYPE_DTMF) {
631                                 /* Reset the timeout */
632                                 timeout = 50;
633                                 if ((tone != vofr_2digit(vh->data[0])) )
634                                         /* Or not...  Something else now.. Just send our first frame */
635                                         break;
636                         }
637                         
638                 } while (timeout);
639                 fr->frametype = AST_FRAME_DTMF;
640                 fr->subclass = tone;
641                 fr->datalen = 0;
642                 fr->data = NULL;
643                 fr->offset = 0;
644                 return fr;
645         case VOFR_TYPE_VOICE:
646                 /* XXX Bug in the Adtran: Sometimes we don't know when calls are picked up, so if we
647                        get voice frames, go ahead and consider it answered even though it probably has
648                            not been answered XXX */
649                 if ((ast->state == AST_STATE_RINGING) || (ast->state == AST_STATE_DIALING))  {
650                         ast_log(LOG_DEBUG, "Adtran bug! (state = %d)\n", ast->state);
651                         fr->frametype = AST_FRAME_CONTROL;
652                         fr->subclass = AST_CONTROL_ANSWER;
653                         ast->state = AST_STATE_UP;
654                         return fr;
655                 } else if (ast->state !=  AST_STATE_UP) {
656                         ast_log(LOG_WARNING, "Voice in weird state %d\n", ast->state);
657                 }
658                 fr->frametype = AST_FRAME_VOICE;
659                 fr->subclass = AST_FORMAT_G723_1;
660                 fr->datalen = res - sizeof(struct vofr_hdr);
661                 fr->data = ((char *)vh) + sizeof(struct vofr_hdr);
662                 fr->src = type;
663                 /* XXX Byte swapping is a bug XXX */
664                 swapping = fr->data;
665                 for (x=0;x<fr->datalen/2;x++)
666                         swapping[x] = ntohs(swapping[x]);
667                 fr->offset = AST_FRIENDLY_OFFSET;
668                 /* Thirty ms of sound per frame */
669                 fr->timelen = 30;
670                 return fr;
671         default:
672                 ast_log(LOG_WARNING, "Don't know what to do with data type %d frames\n", vh->dtype);
673         }
674         /* If we don't know what it is, send a NULL frame */
675         fr->frametype = AST_FRAME_NULL;
676         fr->subclass = 0;
677         return fr;
678 }
679
680 static int vofr_write(struct ast_channel *ast, struct ast_frame *frame)
681 {
682         struct vofr_hdr *vh;
683         struct vofr_pvt *p = ast->pvt->pvt;
684         short *swapping;
685     int x;
686         char *start;
687         int res;
688         /* Write a frame of (presumably voice) data */
689         if (frame->frametype != AST_FRAME_VOICE) {
690                 ast_log(LOG_WARNING, "Don't know what to do with  frame type '%d'\n", frame->frametype);
691                 return -1;
692         }
693         if (frame->subclass != AST_FORMAT_G723_1) {
694                 ast_log(LOG_WARNING, "Cannot handle frames in %d format\n", frame->subclass);
695                 return -1;
696         }
697         /* If we get here, we have a voice frame of G.723.1 data.  First check to be
698            sure we have enough headroom for the vofr header.  If there isn't enough
699            headroom, we're lazy and just error out rather than copying it into the
700            output buffer, because applications should always leave AST_FRIENDLY_OFFSET
701            bytes just for this reason. */
702         if (frame->offset < sizeof(struct vofr_hdr) + FR_API_MESS) {
703                 ast_log(LOG_WARNING, "Frame source '%s' didn't provide a friendly enough offset\n", (frame->src ? frame->src : "**Unknown**"));
704                 return -1;
705         }
706         /* XXX Byte swapping is a bug XXX */
707         swapping = frame->data;
708         for (x=0;x<frame->datalen/2;x++)
709                 swapping[x] = ntohs(swapping[x]);
710         vh = (struct vofr_hdr *)(frame->data - sizeof(struct vofr_hdr));
711         /* Some versions of the API have some header mess that needs to be
712            zero'd out and acounted for..  */
713         start = ((void *)vh) - FR_API_MESS;
714         if (start)
715                 memset(start, 0, FR_API_MESS);
716         /* Now we fill in the vofr header */
717         vh->control = VOFR_CONTROL_VOICE;
718         vh->dtype = VOFR_TYPE_VOICE;
719         vh->vflags = VOFR_ROUTE_NONE;
720         vh->dlcih = p->dlcih;
721         vh->dlcil = p->dlcil;
722         vh->cid = p->cid;
723         vh->remid = VOFR_CARD_TYPE_ASTERISK;
724         vh->mod = VOFR_MODULATION_SINGLE;
725         res = vofr_xmit(p, start, 
726                                 VOFR_HDR_SIZE + frame->datalen + FR_API_MESS);
727         res -= FR_API_MESS;
728         /* XXX Byte swapping is a bug, but get it back to the right format XXX */
729         swapping = frame->data;
730         for (x=0;x<frame->datalen/2;x++)
731                 swapping[x] = htons(swapping[x]);
732         if (res != VOFR_HDR_SIZE + frame->datalen) {
733                 ast_log(LOG_WARNING, "Unable to write frame correctly\n");
734                 return -1;
735         }
736         return 0;
737 }
738
739 static struct ast_channel *vofr_new(struct vofr_pvt *i, int state)
740 {
741         struct ast_channel *tmp;
742         tmp = ast_channel_alloc();
743         if (tmp) {
744                 snprintf(tmp->name, sizeof(tmp->name), "AdtranVoFR/%s", i->sa.spkt_device);
745                 tmp->type = type;
746                 tmp->fd = i->s;
747                 /* Adtran VoFR supports only G723.1 format data.  G711 (ulaw) would be nice too */
748                 tmp->format = AST_FORMAT_G723_1;
749                 tmp->state = state;
750                 if (state == AST_STATE_RING)
751                         tmp->rings = 1;
752                 tmp->pvt->pvt = i;
753                 tmp->pvt->send_digit = vofr_digit;
754                 tmp->pvt->call = vofr_call;
755                 tmp->pvt->hangup = vofr_hangup;
756                 tmp->pvt->answer = vofr_answer;
757                 tmp->pvt->read = vofr_read;
758                 tmp->pvt->write = vofr_write;
759                 i->owner = tmp;
760                 pthread_mutex_lock(&usecnt_lock);
761                 usecnt++;
762                 pthread_mutex_unlock(&usecnt_lock);
763                 ast_update_use_count();
764                 strncpy(tmp->context, i->context, sizeof(tmp->context));
765                 if (state != AST_STATE_DOWN) {
766                         if (ast_pbx_start(tmp)) {
767                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
768                                 ast_hangup(tmp);
769                         }
770                 }
771         } else
772                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
773         return tmp;
774 }
775
776 static int vofr_mini_packet(struct vofr_pvt *i, struct vofr_hdr *pkt, int len)
777 {
778         /* Here, we're looking for rings or off hooks -- signals that
779            something is about to happen and we need to start the 
780            PBX thread */
781         switch(pkt->dtype) {
782         case VOFR_TYPE_SIGNAL:
783                 switch(pkt->data[0]) {
784                 case VOFR_SIGNAL_RING:
785                         /* If we get a RING, we definitely want to start a new thread */
786                         vofr_new(i, AST_STATE_RING);
787                         break;
788                 case VOFR_SIGNAL_ON_HOOK:
789                         break;
790                 case VOFR_SIGNAL_UNKNOWN:
791                         switch(pkt->data[1]) {
792                         case 0x1:
793                                 /* ignore */
794                                 break;
795                         case 0x6:
796                                 /* A remote hangup request */
797                                 if (option_debug)
798                                         ast_log(LOG_DEBUG, "Sending hangup reply\n");
799                                 send_hangup(i);
800                                 break;
801                         default:
802                                 ast_log(LOG_WARNING, "Unexected 'unknown' signal '%d'\n", pkt->data[1]);
803                         }
804                         break;
805                 default:
806                         ast_log(LOG_DEBUG, "Unknown signal type '%d'\n", pkt->data[0]);
807                 }                       
808                 break;
809         case VOFR_TYPE_VOICE:
810                 break;
811         default:
812                 ast_log(LOG_DEBUG, "Unknown packet type '%d'\n", pkt->dtype);
813         }
814         return 0;
815 }
816
817 static void *do_monitor(void *data)
818 {
819         fd_set rfds;
820         int n, res;
821         struct vofr_pvt *i;
822         /* This thread monitors all the frame relay interfaces which are not yet in use
823            (and thus do not have a separate thread) indefinitely */
824         /* From here on out, we die whenever asked */
825         if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
826                 ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
827                 return NULL;
828         }
829         for(;;) {
830                 /* Don't let anybody kill us right away.  Nobody should lock the interface list
831                    and wait for the monitor list, but the other way around is okay. */
832                 if (pthread_mutex_lock(&monlock)) {
833                         ast_log(LOG_ERROR, "Unable to grab monitor lock\n");
834                         return NULL;
835                 }
836                 /* Lock the interface list */
837                 if (pthread_mutex_lock(&iflock)) {
838                         ast_log(LOG_ERROR, "Unable to grab interface lock\n");
839                         pthread_mutex_unlock(&monlock);
840                         return NULL;
841                 }
842                 /* Build the stuff we're going to select on, that is the socket of every
843                    vofr_pvt that does not have an associated owner channel */
844                 n = -1;
845                 FD_ZERO(&rfds);
846                 i = iflist;
847                 while(i) {
848                         if (FD_ISSET(i->s, &rfds)) 
849                                 ast_log(LOG_WARNING, "Descriptor %d appears twice (%s)?\n", i->s, i->sa.spkt_device);
850                         if (!i->owner) {
851                                 /* This needs to be watched, as it lacks an owner */
852                                 FD_SET(i->s, &rfds);
853                                 if (i->s > n)
854                                         n = i->s;
855                         }
856                         i = i->next;
857                 }
858                 /* Okay, now that we know what to do, release the interface lock */
859                 pthread_mutex_unlock(&iflock);
860                 
861                 /* And from now on, we're okay to be killed, so release the monitor lock as well */
862                 pthread_mutex_unlock(&monlock);
863                 /* Wait indefinitely for something to happen */
864                 res = select(n + 1, &rfds, NULL, NULL, NULL);
865                 /* Okay, select has finished.  Let's see what happened.  */
866                 if (res < 0) {
867                         ast_log(LOG_WARNING, "select return %d: %s\n", res, strerror(errno));
868                         continue;
869                 }
870                 /* Alright, lock the interface list again, and let's look and see what has
871                    happened */
872                 if (pthread_mutex_lock(&iflock)) {
873                         ast_log(LOG_WARNING, "Unable to lock the interface list\n");
874                         continue;
875                 }
876                 i = iflist;
877                 while(i) {
878                         if (FD_ISSET(i->s, &rfds)) {
879                                 if (i->owner) {
880                                         ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d, %s)...\n", i->s, i->sa.spkt_device);
881                                         continue;
882                                 }
883                                 res = read(i->s, i->buf, sizeof(i->buf));
884                                 res -= FR_API_MESS;
885 #ifdef VOFRDUMPER
886                                 vofr_dump_packet(i->hdr, res);
887 #endif
888                                 vofr_mini_packet(i, i->hdr, res);
889                         }
890                         i=i->next;
891                 }
892                 pthread_mutex_unlock(&iflock);
893         }
894         /* Never reached */
895         return NULL;
896         
897 }
898
899 static int restart_monitor()
900 {
901         /* If we're supposed to be stopped -- stay stopped */
902         if (monitor_thread == -2)
903                 return 0;
904         if (pthread_mutex_lock(&monlock)) {
905                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
906                 return -1;
907         }
908         if (monitor_thread == pthread_self()) {
909                 pthread_mutex_unlock(&monlock);
910                 ast_log(LOG_WARNING, "Cannot kill myself\n");
911                 return -1;
912         }
913         if (monitor_thread != -1) {
914                 pthread_cancel(monitor_thread);
915 #if 0
916                 pthread_join(monitor_thread, NULL);
917 #endif
918         }
919         /* Start a new monitor */
920         if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
921                 pthread_mutex_unlock(&monlock);
922                 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
923                 return -1;
924         }
925         pthread_mutex_unlock(&monlock);
926         return 0;
927 }
928
929 struct vofr_pvt *mkif(char *type, char *iface)
930 {
931         /* Make a vofr_pvt structure for this interface */
932         struct vofr_pvt *tmp;
933         int sndbuf = 4096;
934         
935         tmp = malloc(sizeof(struct vofr_pvt));
936         if (tmp) {
937
938                 /* Allocate a packet socket */
939                 tmp->s = socket(AF_INET, SOCK_PACKET, htons(ETH_P_ALL));
940                 if (tmp->s < 0) {
941                         ast_log(LOG_ERROR, "Unable to create socket: %s\n", strerror(errno));
942                         free(tmp);
943                         return NULL;
944                 }
945
946                 /* Prepare sockaddr for binding */
947                 memset(&tmp->sa, 0, sizeof(tmp->sa));
948                 strncpy(tmp->sa.spkt_device, iface, sizeof(tmp->sa.spkt_device));
949                 tmp->sa.spkt_protocol = htons(0x16);
950                 tmp->sa.spkt_family = AF_PACKET;
951                 
952                 /* Bind socket to specific interface */
953                 if (bind(tmp->s, (struct sockaddr *)&tmp->sa, sizeof(struct sockaddr))) {
954                         ast_log(LOG_ERROR, "Unable to bind to '%s': %s\n", tmp->sa.spkt_device, 
955                                                                                 strerror(errno));
956                         free(tmp);
957                         return NULL;
958                 }
959                 
960                 /* Set magic send buffer size */
961                 if (setsockopt(tmp->s, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf))) {
962                         ast_log(LOG_ERROR, "Unable to set send buffer size to %d: %s\n", sndbuf, strerror(errno));
963                         free(tmp);
964                         return NULL;
965                 }
966                 tmp->owner =  NULL;
967                 tmp->hdr = (struct vofr_hdr *)(tmp->buf + FR_API_MESS);
968                 tmp->ohdr = (struct vofr_hdr *)(tmp->obuf + FR_API_MESS);
969                 tmp->dlcil = 0;
970                 tmp->dlcih = 0;
971                 tmp->cid = 1;
972                 strncpy(tmp->context, context, sizeof(tmp->context));
973                 /* User terminations are game for outgoing connections */
974                 if (!strcasecmp(type, "user")) 
975                         tmp->outgoing = 1;
976                 else
977                         tmp->outgoing = 0;
978                 tmp->next = NULL;
979                 /* Hang it up to be sure it's good */
980                 send_hangup(tmp);
981                 
982         }
983         return tmp;
984 }
985
986 static struct ast_channel *vofr_request(char *type, int format, void *data)
987 {
988         int oldformat;
989         struct vofr_pvt *p;
990         struct ast_channel *tmp = NULL;
991         /* We can only support G.723.1 formatted frames, but we should never
992            be asked to support anything else anyway, since we've published
993            our capabilities when we registered. */
994         oldformat = format;
995         format &= AST_FORMAT_G723_1;
996         if (!format) {
997                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
998                 return NULL;
999         }
1000         /* Search for an unowned channel */
1001         if (pthread_mutex_lock(&iflock)) {
1002                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
1003                 return NULL;
1004         }
1005         p = iflist;
1006         while(p) {
1007                 if (!p->owner) {
1008                         tmp = vofr_new(p, AST_STATE_DOWN);
1009                         break;
1010                 }
1011                 p = p->next;
1012         }
1013         pthread_mutex_unlock(&iflock);
1014         restart_monitor();
1015         return tmp;
1016 }
1017
1018 int load_module()
1019 {
1020         struct ast_config *cfg;
1021         struct ast_variable *v;
1022         struct vofr_pvt *tmp;
1023         cfg = ast_load(config);
1024
1025         /* We *must* have a config file otherwise stop immediately */
1026         if (!cfg) {
1027                 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
1028                 return -1;
1029         }
1030         if (pthread_mutex_lock(&iflock)) {
1031                 /* It's a little silly to lock it, but we mind as well just to be sure */
1032                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
1033                 return -1;
1034         }
1035         v = ast_variable_browse(cfg, "interfaces");
1036         while(v) {
1037                 /* Create the interface list */
1038                 if (!strcasecmp(v->name, "user") ||
1039                         !strcasecmp(v->name, "network")) {
1040                                 tmp = mkif(v->name, v->value);
1041                                 if (tmp) {
1042                                         tmp->next = iflist;
1043                                         iflist = tmp;
1044                                 } else {
1045                                         ast_log(LOG_ERROR, "Unable to register channel '%s'\n", v->value);
1046                                         ast_destroy(cfg);
1047                                         pthread_mutex_unlock(&iflock);
1048                                         unload_module();
1049                                         return -1;
1050                                 }
1051                 } else if (!strcasecmp(v->name, "context")) {
1052                         strncpy(context, v->value, sizeof(context));
1053                 }
1054                 v = v->next;
1055         }
1056         pthread_mutex_unlock(&iflock);
1057         /* Make sure we can register our AdtranVoFR channel type */
1058         if (ast_channel_register(type, tdesc, AST_FORMAT_G723_1, vofr_request)) {
1059                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1060                 ast_destroy(cfg);
1061                 unload_module();
1062                 return -1;
1063         }
1064         ast_destroy(cfg);
1065         /* And start the monitor for the first time */
1066         restart_monitor();
1067         return 0;
1068 }
1069
1070
1071
1072 int unload_module()
1073 {
1074         struct vofr_pvt *p, *pl;
1075         /* First, take us out of the channel loop */
1076         ast_channel_unregister(type);
1077         if (!pthread_mutex_lock(&iflock)) {
1078                 /* Hangup all interfaces if they have an owner */
1079                 p = iflist;
1080                 while(p) {
1081                         if (p->owner)
1082                                 ast_softhangup(p->owner);
1083                         p = p->next;
1084                 }
1085                 iflist = NULL;
1086                 pthread_mutex_unlock(&iflock);
1087         } else {
1088                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1089                 return -1;
1090         }
1091         if (!pthread_mutex_lock(&monlock)) {
1092                 if (monitor_thread > -1) {
1093                         pthread_cancel(monitor_thread);
1094                         pthread_join(monitor_thread, NULL);
1095                 }
1096                 monitor_thread = -2;
1097                 pthread_mutex_unlock(&monlock);
1098         } else {
1099                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1100                 return -1;
1101         }
1102
1103         if (!pthread_mutex_lock(&iflock)) {
1104                 /* Destroy all the interfaces and free their memory */
1105                 p = iflist;
1106                 while(p) {
1107                         /* Close the socket, assuming it's real */
1108                         if (p->s > -1)
1109                                 close(p->s);
1110                         pl = p;
1111                         p = p->next;
1112                         /* Free associated memory */
1113                         free(pl);
1114                 }
1115                 iflist = NULL;
1116                 pthread_mutex_unlock(&iflock);
1117         } else {
1118                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1119                 return -1;
1120         }
1121                 
1122         return 0;
1123 }
1124
1125 int usecount()
1126 {
1127         int res;
1128         pthread_mutex_lock(&usecnt_lock);
1129         res = usecnt;
1130         pthread_mutex_unlock(&usecnt_lock);
1131         return res;
1132 }
1133
1134 char *description()
1135 {
1136         return desc;
1137 }
1138