Version 0.1.1 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, Mark Spencer
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(void);
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_RING:
562                         ast->rings++;
563                         break;
564                 case VOFR_SIGNAL_UNKNOWN:
565                         switch(vh->data[1]) {
566                         case 0x1:
567                                 /* This is a little tricky, because it depends
568                                    on the context of what state we're in */
569                                 switch(ast->state) {
570                                 case AST_STATE_RINGING:
571                                         fr->frametype = AST_FRAME_CONTROL;
572                                         fr->subclass = AST_CONTROL_ANSWER;
573                                         ast->state = AST_STATE_UP;
574                                         break;
575                                 case AST_STATE_DOWN:
576                                 case AST_STATE_UP:
577                                         fr->frametype = AST_FRAME_NULL;
578                                         fr->subclass = 0;
579                                         break;
580                                 }
581                                 break;
582                         case 0x2:
583                                 /* Remote acknowledged off hook */
584                                 fr->frametype = AST_FRAME_CONTROL;
585                                 fr->subclass = AST_CONTROL_OFFHOOK;
586                                 ast->state = AST_STATE_OFFHOOK;
587                                 break;
588                         case 0x3:
589                                 /* Busy signal */
590                                 fr->frametype = AST_FRAME_CONTROL;
591                                 fr->subclass = AST_CONTROL_BUSY;
592                                 ast->state = AST_STATE_BUSY;
593                                 break;
594                         case 0x5:
595                                 /* Ringing -- acknowledged */
596                                 fr->frametype = AST_FRAME_CONTROL;
597                                 fr->subclass = AST_CONTROL_RINGING;
598                                 ast->state = AST_STATE_RINGING;
599                                 break;
600                         case 0x6:
601                                 /* Hang up detected.  Return NULL */
602                                 return NULL;
603                         default:
604                                 ast_log(LOG_WARNING, "Don't know what to do with 'unknown' signal '%d'\n", vh->data[1]);
605                                 fr->frametype = AST_FRAME_NULL;
606                                 fr->subclass = 0;
607                         }
608                         return fr;
609                         break;
610                 default:
611                         ast_log(LOG_WARNING, "Don't know what to do with signal '%d'\n", vh->data[0]);
612                 }
613                 break;
614         case VOFR_TYPE_DTMF:
615                 /* If it's a DTMF tone, then we want to wait until we don't get any more dtmf tones or
616                    the DTMF tone changes.  
617                        XXX Note: We will drop at least one frame here though XXX */
618                 
619                 tone = vofr_2digit(vh->data[0]);
620                 timeout = 50;
621                 do {
622                         if ((timeout = ast_waitfor(ast, timeout)) < 1)
623                                 break;
624                         CHECK_BLOCKING(ast);
625                         res = read(p->s, ((char *)vh)  - FR_API_MESS, 
626                                         G723_MAX_BUF - AST_FRIENDLY_OFFSET - sizeof(struct ast_frame) + sizeof(struct vofr_hdr) + FR_API_MESS);
627                         ast->blocking = 0;
628                         res -= FR_API_MESS;             
629                         if (res < sizeof(struct vofr_hdr *)) {
630                                 ast_log(LOG_WARNING, "Nonsense frame on %s\n", ast->name);
631                                 return NULL;
632                         }
633                         if (vh->dtype == VOFR_TYPE_DTMF) {
634                                 /* Reset the timeout */
635                                 timeout = 50;
636                                 if ((tone != vofr_2digit(vh->data[0])) )
637                                         /* Or not...  Something else now.. Just send our first frame */
638                                         break;
639                         }
640                         
641                 } while (timeout);
642                 fr->frametype = AST_FRAME_DTMF;
643                 fr->subclass = tone;
644                 fr->datalen = 0;
645                 fr->data = NULL;
646                 fr->offset = 0;
647                 return fr;
648         case VOFR_TYPE_VOICE:
649                 /* XXX Bug in the Adtran: Sometimes we don't know when calls are picked up, so if we
650                        get voice frames, go ahead and consider it answered even though it probably has
651                            not been answered XXX */
652                 if ((ast->state == AST_STATE_RINGING) || (ast->state == AST_STATE_DIALING))  {
653                         ast_log(LOG_DEBUG, "Adtran bug! (state = %d)\n", ast->state);
654                         fr->frametype = AST_FRAME_CONTROL;
655                         fr->subclass = AST_CONTROL_ANSWER;
656                         ast->state = AST_STATE_UP;
657                         return fr;
658                 } else if (ast->state !=  AST_STATE_UP) {
659                         ast_log(LOG_WARNING, "Voice in weird state %d\n", ast->state);
660                 }
661                 fr->frametype = AST_FRAME_VOICE;
662                 fr->subclass = AST_FORMAT_G723_1;
663                 fr->datalen = res - sizeof(struct vofr_hdr);
664                 fr->data = ((char *)vh) + sizeof(struct vofr_hdr);
665                 fr->src = type;
666                 /* XXX Byte swapping is a bug XXX */
667                 swapping = fr->data;
668                 for (x=0;x<fr->datalen/2;x++)
669                         swapping[x] = ntohs(swapping[x]);
670                 fr->offset = AST_FRIENDLY_OFFSET;
671                 /* Thirty ms of sound per frame */
672                 fr->timelen = 30;
673                 return fr;
674         default:
675                 ast_log(LOG_WARNING, "Don't know what to do with data type %d frames\n", vh->dtype);
676         }
677         /* If we don't know what it is, send a NULL frame */
678         fr->frametype = AST_FRAME_NULL;
679         fr->subclass = 0;
680         return fr;
681 }
682
683 static int vofr_write(struct ast_channel *ast, struct ast_frame *frame)
684 {
685         struct vofr_hdr *vh;
686         struct vofr_pvt *p = ast->pvt->pvt;
687         short *swapping;
688     int x;
689         char *start;
690         int res;
691         /* Write a frame of (presumably voice) data */
692         if (frame->frametype != AST_FRAME_VOICE) {
693                 ast_log(LOG_WARNING, "Don't know what to do with  frame type '%d'\n", frame->frametype);
694                 return -1;
695         }
696         if (frame->subclass != AST_FORMAT_G723_1) {
697                 ast_log(LOG_WARNING, "Cannot handle frames in %d format\n", frame->subclass);
698                 return -1;
699         }
700         /* If we get here, we have a voice frame of G.723.1 data.  First check to be
701            sure we have enough headroom for the vofr header.  If there isn't enough
702            headroom, we're lazy and just error out rather than copying it into the
703            output buffer, because applications should always leave AST_FRIENDLY_OFFSET
704            bytes just for this reason. */
705         if (frame->offset < sizeof(struct vofr_hdr) + FR_API_MESS) {
706                 ast_log(LOG_WARNING, "Frame source '%s' didn't provide a friendly enough offset\n", (frame->src ? frame->src : "**Unknown**"));
707                 return -1;
708         }
709         /* XXX Byte swapping is a bug XXX */
710         swapping = frame->data;
711         for (x=0;x<frame->datalen/2;x++)
712                 swapping[x] = ntohs(swapping[x]);
713         vh = (struct vofr_hdr *)(frame->data - sizeof(struct vofr_hdr));
714         /* Some versions of the API have some header mess that needs to be
715            zero'd out and acounted for..  */
716         start = ((void *)vh) - FR_API_MESS;
717         if (start)
718                 memset(start, 0, FR_API_MESS);
719         /* Now we fill in the vofr header */
720         vh->control = VOFR_CONTROL_VOICE;
721         vh->dtype = VOFR_TYPE_VOICE;
722         vh->vflags = VOFR_ROUTE_NONE;
723         vh->dlcih = p->dlcih;
724         vh->dlcil = p->dlcil;
725         vh->cid = p->cid;
726         vh->remid = VOFR_CARD_TYPE_ASTERISK;
727         vh->mod = VOFR_MODULATION_SINGLE;
728         res = vofr_xmit(p, start, 
729                                 VOFR_HDR_SIZE + frame->datalen + FR_API_MESS);
730         res -= FR_API_MESS;
731         /* XXX Byte swapping is a bug, but get it back to the right format XXX */
732         swapping = frame->data;
733         for (x=0;x<frame->datalen/2;x++)
734                 swapping[x] = htons(swapping[x]);
735         if (res != VOFR_HDR_SIZE + frame->datalen) {
736                 ast_log(LOG_WARNING, "Unable to write frame correctly\n");
737                 return -1;
738         }
739         return 0;
740 }
741
742 static struct ast_channel *vofr_new(struct vofr_pvt *i, int state)
743 {
744         struct ast_channel *tmp;
745         tmp = ast_channel_alloc();
746         if (tmp) {
747                 snprintf(tmp->name, sizeof(tmp->name), "AdtranVoFR/%s", i->sa.spkt_device);
748                 tmp->type = type;
749                 tmp->fd = i->s;
750                 /* Adtran VoFR supports only G723.1 format data.  G711 (ulaw) would be nice too */
751                 tmp->format = AST_FORMAT_G723_1;
752                 tmp->state = state;
753                 if (state == AST_STATE_RING)
754                         tmp->rings = 1;
755                 tmp->pvt->pvt = i;
756                 tmp->pvt->send_digit = vofr_digit;
757                 tmp->pvt->call = vofr_call;
758                 tmp->pvt->hangup = vofr_hangup;
759                 tmp->pvt->answer = vofr_answer;
760                 tmp->pvt->read = vofr_read;
761                 tmp->pvt->write = vofr_write;
762                 i->owner = tmp;
763                 pthread_mutex_lock(&usecnt_lock);
764                 usecnt++;
765                 pthread_mutex_unlock(&usecnt_lock);
766                 ast_update_use_count();
767                 strncpy(tmp->context, i->context, sizeof(tmp->context));
768                 if (state != AST_STATE_DOWN) {
769                         if (ast_pbx_start(tmp)) {
770                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
771                                 ast_hangup(tmp);
772                         }
773                 }
774         } else
775                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
776         return tmp;
777 }
778
779 static int vofr_mini_packet(struct vofr_pvt *i, struct vofr_hdr *pkt, int len)
780 {
781         /* Here, we're looking for rings or off hooks -- signals that
782            something is about to happen and we need to start the 
783            PBX thread */
784         switch(pkt->dtype) {
785         case VOFR_TYPE_SIGNAL:
786                 switch(pkt->data[0]) {
787                 case VOFR_SIGNAL_RING:
788                         /* If we get a RING, we definitely want to start a new thread */
789                         if (!i->owner)
790                                 vofr_new(i, AST_STATE_RING);
791                         else
792                                 ast_log(LOG_WARNING, "Got a ring, but there's an owner?\n");
793                         break;
794                 case VOFR_SIGNAL_OFF_HOOK:
795                         /* Network termination, go off hook */
796 #if 0
797                         ast_log(LOG_DEBUG, "Off hook\n");
798 #endif
799                         vofr_xmit_signal(i, 0x10, 2);
800                         if (!i->owner)
801                                 vofr_new(i, AST_STATE_UP);
802                         else
803                                 ast_log(LOG_WARNING, "Got an offhook, but there's an owner?\n");
804                         break;
805                 case VOFR_SIGNAL_ON_HOOK:
806                         break;
807                 case VOFR_SIGNAL_UNKNOWN:
808                         switch(pkt->data[1]) {
809                         case 0x1:
810                                 /* ignore */
811                                 break;
812                         case 0x6:
813                                 /* A remote hangup request */
814                                 if (option_debug)
815                                         ast_log(LOG_DEBUG, "Sending hangup reply\n");
816                                 send_hangup(i);
817                                 break;
818                         default:
819                                 ast_log(LOG_WARNING, "Unexected 'unknown' signal '%d'\n", pkt->data[1]);
820                         }
821                         break;
822                 default:
823                         ast_log(LOG_DEBUG, "Unknown signal type '%d'\n", pkt->data[0]);
824                 }                       
825                 break;
826         case VOFR_TYPE_VOICE:
827                 break;
828         default:
829                 ast_log(LOG_DEBUG, "Unknown packet type '%d'\n", pkt->dtype);
830         }
831         return 0;
832 }
833
834 static void *do_monitor(void *data)
835 {
836         fd_set rfds;
837         int n, res;
838         struct vofr_pvt *i;
839         /* This thread monitors all the frame relay interfaces which are not yet in use
840            (and thus do not have a separate thread) indefinitely */
841         /* From here on out, we die whenever asked */
842         if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
843                 ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
844                 return NULL;
845         }
846         for(;;) {
847                 /* Don't let anybody kill us right away.  Nobody should lock the interface list
848                    and wait for the monitor list, but the other way around is okay. */
849                 if (pthread_mutex_lock(&monlock)) {
850                         ast_log(LOG_ERROR, "Unable to grab monitor lock\n");
851                         return NULL;
852                 }
853                 /* Lock the interface list */
854                 if (pthread_mutex_lock(&iflock)) {
855                         ast_log(LOG_ERROR, "Unable to grab interface lock\n");
856                         pthread_mutex_unlock(&monlock);
857                         return NULL;
858                 }
859                 /* Build the stuff we're going to select on, that is the socket of every
860                    vofr_pvt that does not have an associated owner channel */
861                 n = -1;
862                 FD_ZERO(&rfds);
863                 i = iflist;
864                 while(i) {
865                         if (FD_ISSET(i->s, &rfds)) 
866                                 ast_log(LOG_WARNING, "Descriptor %d appears twice (%s)?\n", i->s, i->sa.spkt_device);
867                         if (!i->owner) {
868                                 /* This needs to be watched, as it lacks an owner */
869                                 FD_SET(i->s, &rfds);
870                                 if (i->s > n)
871                                         n = i->s;
872                         }
873                         i = i->next;
874                 }
875                 /* Okay, now that we know what to do, release the interface lock */
876                 pthread_mutex_unlock(&iflock);
877                 
878                 /* And from now on, we're okay to be killed, so release the monitor lock as well */
879                 pthread_mutex_unlock(&monlock);
880                 /* Wait indefinitely for something to happen */
881                 res = select(n + 1, &rfds, NULL, NULL, NULL);
882                 /* Okay, select has finished.  Let's see what happened.  */
883                 if (res < 0) {
884                         ast_log(LOG_WARNING, "select return %d: %s\n", res, strerror(errno));
885                         continue;
886                 }
887                 /* Alright, lock the interface list again, and let's look and see what has
888                    happened */
889                 if (pthread_mutex_lock(&iflock)) {
890                         ast_log(LOG_WARNING, "Unable to lock the interface list\n");
891                         continue;
892                 }
893                 i = iflist;
894                 while(i) {
895                         if (FD_ISSET(i->s, &rfds)) {
896                                 if (i->owner) {
897                                         ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d, %s)...\n", i->s, i->sa.spkt_device);
898                                         continue;
899                                 }
900                                 res = read(i->s, i->buf, sizeof(i->buf));
901                                 res -= FR_API_MESS;
902 #ifdef VOFRDUMPER
903                                 vofr_dump_packet(i->hdr, res);
904 #endif
905                                 vofr_mini_packet(i, i->hdr, res);
906                         }
907                         i=i->next;
908                 }
909                 pthread_mutex_unlock(&iflock);
910         }
911         /* Never reached */
912         return NULL;
913         
914 }
915
916 static int restart_monitor(void)
917 {
918         /* If we're supposed to be stopped -- stay stopped */
919         if (monitor_thread == -2)
920                 return 0;
921         if (pthread_mutex_lock(&monlock)) {
922                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
923                 return -1;
924         }
925         if (monitor_thread == pthread_self()) {
926                 pthread_mutex_unlock(&monlock);
927                 ast_log(LOG_WARNING, "Cannot kill myself\n");
928                 return -1;
929         }
930         if (monitor_thread != -1) {
931                 pthread_cancel(monitor_thread);
932 #if 0
933                 pthread_join(monitor_thread, NULL);
934 #endif
935         }
936         /* Start a new monitor */
937         if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
938                 pthread_mutex_unlock(&monlock);
939                 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
940                 return -1;
941         }
942         pthread_mutex_unlock(&monlock);
943         return 0;
944 }
945
946 static struct vofr_pvt *mkif(char *type, char *iface)
947 {
948         /* Make a vofr_pvt structure for this interface */
949         struct vofr_pvt *tmp;
950         int sndbuf = 4096;
951         
952         tmp = malloc(sizeof(struct vofr_pvt));
953         if (tmp) {
954
955                 /* Allocate a packet socket */
956                 tmp->s = socket(AF_INET, SOCK_PACKET, htons(ETH_P_ALL));
957                 if (tmp->s < 0) {
958                         ast_log(LOG_ERROR, "Unable to create socket: %s\n", strerror(errno));
959                         free(tmp);
960                         return NULL;
961                 }
962
963                 /* Prepare sockaddr for binding */
964                 memset(&tmp->sa, 0, sizeof(tmp->sa));
965                 strncpy(tmp->sa.spkt_device, iface, sizeof(tmp->sa.spkt_device));
966                 tmp->sa.spkt_protocol = htons(0x16);
967                 tmp->sa.spkt_family = AF_PACKET;
968                 
969                 /* Bind socket to specific interface */
970                 if (bind(tmp->s, (struct sockaddr *)&tmp->sa, sizeof(struct sockaddr))) {
971                         ast_log(LOG_ERROR, "Unable to bind to '%s': %s\n", tmp->sa.spkt_device, 
972                                                                                 strerror(errno));
973                         free(tmp);
974                         return NULL;
975                 }
976                 
977                 /* Set magic send buffer size */
978                 if (setsockopt(tmp->s, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf))) {
979                         ast_log(LOG_ERROR, "Unable to set send buffer size to %d: %s\n", sndbuf, strerror(errno));
980                         free(tmp);
981                         return NULL;
982                 }
983                 tmp->owner =  NULL;
984                 tmp->hdr = (struct vofr_hdr *)(tmp->buf + FR_API_MESS);
985                 tmp->ohdr = (struct vofr_hdr *)(tmp->obuf + FR_API_MESS);
986                 tmp->dlcil = 0;
987                 tmp->dlcih = 0;
988                 tmp->cid = 1;
989                 strncpy(tmp->context, context, sizeof(tmp->context));
990                 /* User terminations are game for outgoing connections */
991                 if (!strcasecmp(type, "user")) 
992                         tmp->outgoing = 1;
993                 else
994                         tmp->outgoing = 0;
995                 tmp->next = NULL;
996                 /* Hang it up to be sure it's good */
997                 send_hangup(tmp);
998                 
999         }
1000         return tmp;
1001 }
1002
1003 static struct ast_channel *vofr_request(char *type, int format, void *data)
1004 {
1005         int oldformat;
1006         struct vofr_pvt *p;
1007         struct ast_channel *tmp = NULL;
1008         /* We can only support G.723.1 formatted frames, but we should never
1009            be asked to support anything else anyway, since we've published
1010            our capabilities when we registered. */
1011         oldformat = format;
1012         format &= AST_FORMAT_G723_1;
1013         if (!format) {
1014                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
1015                 return NULL;
1016         }
1017         /* Search for an unowned channel */
1018         if (pthread_mutex_lock(&iflock)) {
1019                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
1020                 return NULL;
1021         }
1022         p = iflist;
1023         while(p) {
1024                 if (!p->owner) {
1025                         tmp = vofr_new(p, AST_STATE_DOWN);
1026                         break;
1027                 }
1028                 p = p->next;
1029         }
1030         pthread_mutex_unlock(&iflock);
1031         restart_monitor();
1032         return tmp;
1033 }
1034
1035 int load_module()
1036 {
1037         struct ast_config *cfg;
1038         struct ast_variable *v;
1039         struct vofr_pvt *tmp;
1040         cfg = ast_load(config);
1041
1042         /* We *must* have a config file otherwise stop immediately */
1043         if (!cfg) {
1044                 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
1045                 return -1;
1046         }
1047         if (pthread_mutex_lock(&iflock)) {
1048                 /* It's a little silly to lock it, but we mind as well just to be sure */
1049                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
1050                 return -1;
1051         }
1052         v = ast_variable_browse(cfg, "interfaces");
1053         while(v) {
1054                 /* Create the interface list */
1055                 if (!strcasecmp(v->name, "user") ||
1056                         !strcasecmp(v->name, "network")) {
1057                                 tmp = mkif(v->name, v->value);
1058                                 if (tmp) {
1059                                         tmp->next = iflist;
1060                                         iflist = tmp;
1061                                 } else {
1062                                         ast_log(LOG_ERROR, "Unable to register channel '%s'\n", v->value);
1063                                         ast_destroy(cfg);
1064                                         pthread_mutex_unlock(&iflock);
1065                                         unload_module();
1066                                         return -1;
1067                                 }
1068                 } else if (!strcasecmp(v->name, "context")) {
1069                         strncpy(context, v->value, sizeof(context));
1070                 }
1071                 v = v->next;
1072         }
1073         pthread_mutex_unlock(&iflock);
1074         /* Make sure we can register our AdtranVoFR channel type */
1075         if (ast_channel_register(type, tdesc, AST_FORMAT_G723_1, vofr_request)) {
1076                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1077                 ast_destroy(cfg);
1078                 unload_module();
1079                 return -1;
1080         }
1081         ast_destroy(cfg);
1082         /* And start the monitor for the first time */
1083         restart_monitor();
1084         return 0;
1085 }
1086
1087
1088
1089 int unload_module()
1090 {
1091         struct vofr_pvt *p, *pl;
1092         /* First, take us out of the channel loop */
1093         ast_channel_unregister(type);
1094         if (!pthread_mutex_lock(&iflock)) {
1095                 /* Hangup all interfaces if they have an owner */
1096                 p = iflist;
1097                 while(p) {
1098                         if (p->owner)
1099                                 ast_softhangup(p->owner);
1100                         p = p->next;
1101                 }
1102                 iflist = NULL;
1103                 pthread_mutex_unlock(&iflock);
1104         } else {
1105                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1106                 return -1;
1107         }
1108         if (!pthread_mutex_lock(&monlock)) {
1109                 if (monitor_thread > -1) {
1110                         pthread_cancel(monitor_thread);
1111                         pthread_join(monitor_thread, NULL);
1112                 }
1113                 monitor_thread = -2;
1114                 pthread_mutex_unlock(&monlock);
1115         } else {
1116                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1117                 return -1;
1118         }
1119
1120         if (!pthread_mutex_lock(&iflock)) {
1121                 /* Destroy all the interfaces and free their memory */
1122                 p = iflist;
1123                 while(p) {
1124                         /* Close the socket, assuming it's real */
1125                         if (p->s > -1)
1126                                 close(p->s);
1127                         pl = p;
1128                         p = p->next;
1129                         /* Free associated memory */
1130                         free(pl);
1131                 }
1132                 iflist = NULL;
1133                 pthread_mutex_unlock(&iflock);
1134         } else {
1135                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1136                 return -1;
1137         }
1138                 
1139         return 0;
1140 }
1141
1142 int usecount()
1143 {
1144         int res;
1145         pthread_mutex_lock(&usecnt_lock);
1146         res = usecnt;
1147         pthread_mutex_unlock(&usecnt_lock);
1148         return res;
1149 }
1150
1151 char *description()
1152 {
1153         return desc;
1154 }
1155