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