Version 0.1.3 from FTP
[asterisk/asterisk.git] / channels / chan_phone.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Generic Linux Telephony Interface driver
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 <sys/time.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <stdlib.h>
29 #include <arpa/inet.h>
30 #include <fcntl.h>
31 #include <sys/ioctl.h>
32 #include <linux/telephony.h>
33 /* Still use some IXJ specific stuff */
34 #include <linux/ixjuser.h>
35 #include "DialTone.h"
36
37 #define phone_MAX_BUF 480
38
39 static char *desc = "Linux Telephony API Support";
40 static char *type = "Phone";
41 static char *tdesc = "Standard Linux Telephony API Driver";
42 static char *config = "phone.conf";
43
44 /* Default context for dialtone mode */
45 static char context[AST_MAX_EXTENSION] = "default";
46
47 /* Default language */
48 static char language[MAX_LANGUAGE] = "";
49 static int usecnt =0;
50
51 static int echocancel = AEC_OFF;
52
53 static int silencesupression = 0;
54
55 static int prefformat = AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR;
56
57 static pthread_mutex_t usecnt_lock = PTHREAD_MUTEX_INITIALIZER;
58
59 /* Protect the interface list (of phone_pvt's) */
60 static pthread_mutex_t iflock = PTHREAD_MUTEX_INITIALIZER;
61
62 /* Protect the monitoring thread, so only one process can kill or start it, and not
63    when it's doing something critical. */
64 static pthread_mutex_t monlock = PTHREAD_MUTEX_INITIALIZER;
65
66 /* This is the thread for the monitor which checks for input on the channels
67    which are not currently in use.  */
68 static pthread_t monitor_thread = -1;
69
70 static int restart_monitor(void);
71
72 /* The private structures of the Phone Jack channels are linked for
73    selecting outgoing channels */
74    
75 #define MODE_DIALTONE   1
76 #define MODE_IMMEDIATE  2
77    
78 static struct phone_pvt {
79         int fd;                                                 /* Raw file descriptor for this device */
80         struct ast_channel *owner;              /* Channel we belong to, possibly NULL */
81         int mode;                                               /* Is this in the  */
82         int lastformat;                                 /* Last output format */
83         int lastinput;                                  /* Last input format */
84         int ministate;                                  /* Miniature state, for dialtone mode */
85         char dev[256];                                  /* Device name */
86         struct phone_pvt *next;                 /* Next channel in list */
87         struct ast_frame fr;                    /* Frame */
88         char offset[AST_FRIENDLY_OFFSET];
89         char buf[phone_MAX_BUF];                                        /* Static buffer for reading frames */
90         int obuflen;
91         int dialtone;
92         int silencesupression;
93         char context[AST_MAX_EXTENSION];
94         char obuf[phone_MAX_BUF * 2];
95         char ext[AST_MAX_EXTENSION];
96         char language[MAX_LANGUAGE];
97 } *iflist = NULL;
98
99 static int phone_digit(struct ast_channel *ast, char digit)
100 {
101         struct phone_pvt *p;
102         int outdigit;
103         p = ast->pvt->pvt;
104         switch(digit) {
105         case '0':
106         case '1':
107         case '2':
108         case '3':
109         case '4':
110         case '5':
111         case '6':
112         case '7':
113         case '8':
114         case '9':
115                 outdigit = digit - '0' + 1;
116                 break;
117         case '*':
118                 outdigit = 11;
119                 break;
120         case '#':
121                 outdigit = 12;
122                 break;
123         default:
124                 ast_log(LOG_WARNING, "Unknown digit '%c'\n", digit);
125                 return -1;
126         }
127         ioctl(p->fd, PHONE_PLAY_TONE, digit);
128         return 0;
129 }
130
131 static int phone_call(struct ast_channel *ast, char *dest, int timeout)
132 {
133         struct phone_pvt *p;
134         p = ast->pvt->pvt;
135         if ((ast->state != AST_STATE_DOWN) && (ast->state != AST_STATE_RESERVED)) {
136                 ast_log(LOG_WARNING, "phone_call called on %s, neither down nor reserved\n", ast->name);
137                 return -1;
138         }
139         /* When we call, it just works, really, there's no destination...  Just
140            ring the phone and wait for someone to answer */
141         if (option_debug)
142                 ast_log(LOG_DEBUG, "Ringing %s on %s (%d)\n", dest, ast->name, ast->fd);
143         ioctl(p->fd, PHONE_RING_START);
144         ast->state = AST_STATE_RINGING;
145         return 0;
146 }
147
148 static int phone_hangup(struct ast_channel *ast)
149 {
150         struct phone_pvt *p;
151         p = ast->pvt->pvt;
152         if (option_debug)
153                 ast_log(LOG_DEBUG, "phone_hangup(%s)\n", ast->name);
154         if (!ast->pvt->pvt) {
155                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
156                 return 0;
157         }
158         /* XXX Is there anything we can do to really hang up except stop recording? */
159         ast->state = AST_STATE_DOWN;
160         if (ioctl(p->fd, PHONE_REC_STOP))
161                 ast_log(LOG_WARNING, "Failed to stop recording\n");
162         if (ioctl(p->fd, PHONE_PLAY_STOP))
163                 ast_log(LOG_WARNING, "Failed to stop playing\n");
164         if (ioctl(p->fd, PHONE_RING_STOP))
165                 ast_log(LOG_WARNING, "Failed to stop ringing\n");
166         if (ioctl(p->fd, PHONE_CPT_STOP))
167                 ast_log(LOG_WARNING, "Failed to stop sounds\n");
168         /* If they're off hook, give a busy signal */
169         if (ioctl(p->fd, PHONE_HOOKSTATE)) {
170                 if (option_debug)
171                         ast_log(LOG_DEBUG, "Got hunghup, giving busy signal\n");
172                 ioctl(p->fd, PHONE_BUSY);
173         }
174         p->lastformat = -1;
175         p->lastinput = -1;
176         p->ministate = 0;
177         p->obuflen = 0;
178         p->dialtone = 0;
179         memset(p->ext, 0, sizeof(p->ext));
180         ((struct phone_pvt *)(ast->pvt->pvt))->owner = NULL;
181         pthread_mutex_lock(&usecnt_lock);
182         usecnt--;
183         if (usecnt < 0) 
184                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
185         pthread_mutex_unlock(&usecnt_lock);
186         ast_update_use_count();
187         if (option_verbose > 2) 
188                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
189         ast->pvt->pvt = NULL;
190         ast->state = AST_STATE_DOWN;
191         restart_monitor();
192         return 0;
193 }
194
195 static int phone_setup(struct ast_channel *ast)
196 {
197         struct phone_pvt *p;
198         p = ast->pvt->pvt;
199         ioctl(p->fd, PHONE_CPT_STOP);
200         /* Nothing to answering really, just start recording */
201         if (ast->format & AST_FORMAT_G723_1) {
202                 /* Prefer g723 */
203                 ioctl(p->fd, PHONE_REC_STOP);
204                 if (p->lastinput != AST_FORMAT_G723_1) {
205                         p->lastinput = AST_FORMAT_G723_1;
206                         if (ioctl(p->fd, PHONE_REC_CODEC, G723_63)) {
207                                 ast_log(LOG_WARNING, "Failed to set codec to g723.1\n");
208                                 return -1;
209                         }
210                 }
211         } else if (ast->format & AST_FORMAT_SLINEAR) {
212                 ioctl(p->fd, PHONE_REC_STOP);
213                 if (p->lastinput != AST_FORMAT_SLINEAR) {
214                         p->lastinput = AST_FORMAT_SLINEAR;
215                         if (ioctl(p->fd, PHONE_REC_CODEC, LINEAR16)) {
216                                 ast_log(LOG_WARNING, "Failed to set codec to signed linear 16\n");
217                                 return -1;
218                         }
219                 }
220         } else {
221                 ast_log(LOG_WARNING, "Can't do format %d\n", ast->format);
222                 return -1;
223         }
224         if (ioctl(p->fd, PHONE_REC_START)) {
225                 ast_log(LOG_WARNING, "Failed to start recording\n");
226                 return -1;
227         }
228         return 0;
229 }
230
231 static int phone_answer(struct ast_channel *ast)
232 {
233         phone_setup(ast);
234         if (option_debug)
235                 ast_log(LOG_DEBUG, "phone_answer(%s)\n", ast->name);
236         ast->rings = 0;
237         ast->state = AST_STATE_UP;
238         return 0;
239 }
240
241 static char phone_2digit(char c)
242 {
243         if (c == 12)
244                 return '#';
245         else if (c == 11)
246                 return '*';
247         else if ((c < 10) && (c >= 0))
248                 return '0' + c - 1;
249         else
250                 return '?';
251 }
252
253 static struct ast_frame  *phone_read(struct ast_channel *ast)
254 {
255         int res;
256         union telephony_exception phonee;
257         struct phone_pvt *p = ast->pvt->pvt;
258         char digit;
259
260         /* Some nice norms */
261         p->fr.datalen = 0;
262         p->fr.timelen = 0;
263         p->fr.data =  NULL;
264         p->fr.src = type;
265         p->fr.offset = 0;
266         p->fr.mallocd=0;
267
268         phonee.bytes = ioctl(p->fd, PHONE_EXCEPTION);
269         if (phonee.bits.dtmf_ready)  {
270                 /* We've got a digit -- Just handle this nicely and easily */
271                 digit =  ioctl(p->fd, PHONE_GET_DTMF_ASCII);
272                 p->fr.subclass = digit;
273                 p->fr.frametype = AST_FRAME_DTMF;
274                 return &p->fr;
275         }
276         if (phonee.bits.hookstate) {
277                 res = ioctl(p->fd, PHONE_HOOKSTATE);
278                 /* See if we've gone on hook, if so, notify by returning NULL */
279                 if (!res)
280                         return NULL;
281                 else {
282                         if (ast->state == AST_STATE_RINGING) {
283                                 /* They've picked up the phone */
284                                 p->fr.frametype = AST_FRAME_CONTROL;
285                                 p->fr.subclass = AST_CONTROL_ANSWER;
286                                 phone_setup(ast);
287                                 ast->state = AST_STATE_UP;
288                                 return &p->fr;
289                         }  else 
290                                 ast_log(LOG_WARNING, "Got off hook in weird state %d\n", ast->state);
291                 }
292         }
293 #if 0
294         if (phonee.bits.pstn_ring)
295                 ast_verbose("Unit is ringing\n");
296         if (phonee.bits.caller_id) {
297                 ast_verbose("We have caller ID: %s\n");
298         }
299 #endif
300         /* Try to read some data... */
301         CHECK_BLOCKING(ast);
302         res = read(p->fd, p->buf, phone_MAX_BUF);
303         ast->blocking = 0;
304         if (res < 0) {
305 #if 0
306                 if (errno == EAGAIN) {
307                         ast_log(LOG_WARNING, "Null frame received\n");
308                         p->fr.frametype = AST_FRAME_NULL;
309                         p->fr.subclass = 0;
310                         return &p->fr;
311                 }
312 #endif
313                 ast_log(LOG_WARNING, "Error reading: %s\n", strerror(errno));
314                 return NULL;
315         }
316         p->fr.data = p->buf;
317         switch(p->buf[0] & 0x3) {
318         case '0':
319         case '1':
320                 /* Normal */
321                 break;
322         case '2':
323         case '3':
324                 /* VAD/CNG, only send two words */
325                 res = 4;
326                 break;
327         }
328         p->fr.datalen = res;
329         p->fr.frametype = AST_FRAME_VOICE;
330         p->fr.subclass = p->lastinput;
331         p->fr.offset = AST_FRIENDLY_OFFSET;
332         return &p->fr;
333 }
334
335 static int phone_write_buf(struct phone_pvt *p, char *buf, int len, int frlen)
336 {
337         int res;
338         /* Store as much of the buffer as we can, then write fixed frames */
339         int space = sizeof(p->obuf) - p->obuflen;
340         /* Make sure we have enough buffer space to store the frame */
341         if (space < len)
342                 len = space;
343         memcpy(p->obuf + p->obuflen, buf, len);
344         p->obuflen += len;
345         while(p->obuflen > frlen) {
346 #if 0
347                 res = frlen;
348                 ast_log(LOG_DEBUG, "Wrote %d bytes\n", res);
349 #else
350                 res = write(p->fd, p->obuf, frlen);
351 #endif
352                 if (res != frlen) {
353                         if (res < 1) {
354                                 ast_log(LOG_WARNING, "Write failed: %s\n", strerror(errno));
355                                 return -1;
356                         } else {
357                                 ast_log(LOG_WARNING, "Only wrote %d of %d bytes\n", res, frlen);
358                         }
359                 }
360                 p->obuflen -= frlen;
361                 /* Move memory if necessary */
362                 if (p->obuflen) 
363                         memmove(p->obuf, p->obuf + frlen, p->obuflen);
364         }
365         return len;
366 }
367
368 static int phone_write(struct ast_channel *ast, struct ast_frame *frame)
369 {
370         struct phone_pvt *p = ast->pvt->pvt;
371         int res;
372         int maxfr=0;
373         char *pos;
374         int sofar;
375         int expected;
376         char tmpbuf[4];
377         /* Write a frame of (presumably voice) data */
378         if (frame->frametype != AST_FRAME_VOICE) {
379                 ast_log(LOG_WARNING, "Don't know what to do with  frame type '%d'\n", frame->frametype);
380                 ast_frfree(frame);
381                 return -1;
382         }
383         if (!(frame->subclass & (AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR))) {
384                 ast_log(LOG_WARNING, "Cannot handle frames in %d format\n", frame->subclass);
385                 ast_frfree(frame);
386                 return -1;
387         }
388         /* If we're not in up mode, go into up mode now */
389         if (ast->state != AST_STATE_UP) {
390                 ast->state = AST_STATE_UP;
391                 phone_setup(ast);
392         }
393         if (frame->subclass == AST_FORMAT_G723_1) {
394                 if (p->lastformat != AST_FORMAT_G723_1) {
395                         ioctl(p->fd, PHONE_PLAY_STOP);
396                         ioctl(p->fd, PHONE_REC_STOP);
397                         if (ioctl(p->fd, PHONE_PLAY_CODEC, G723_63)) {
398                                 ast_log(LOG_WARNING, "Unable to set G723.1 mode\n");
399                                 return -1;
400                         }
401                         if (ioctl(p->fd, PHONE_REC_CODEC, G723_63)) {
402                                 ast_log(LOG_WARNING, "Unable to set G723.1 mode\n");
403                                 return -1;
404                         }
405                         p->lastformat = AST_FORMAT_G723_1;
406                         p->lastinput = AST_FORMAT_G723_1;
407                         /* Reset output buffer */
408                         p->obuflen = 0;
409                 }
410                 if (frame->datalen > 24) {
411                         ast_log(LOG_WARNING, "Frame size too large for G.723.1 (%d bytes)\n", frame->datalen);
412                         return -1;
413                 }
414                 maxfr = 24;
415         } else if (frame->subclass == AST_FORMAT_SLINEAR) {
416                 if (p->lastformat != AST_FORMAT_SLINEAR) {
417                         ioctl(p->fd, PHONE_PLAY_STOP);
418                         ioctl(p->fd, PHONE_REC_STOP);
419                         if (ioctl(p->fd, PHONE_PLAY_CODEC, LINEAR16)) {
420                                 ast_log(LOG_WARNING, "Unable to set 16-bit linear mode\n");
421                                 return -1;
422                         }
423                         if (ioctl(p->fd, PHONE_REC_CODEC, LINEAR16)) {
424                                 ast_log(LOG_WARNING, "Unable to set 16-bit linear mode\n");
425                                 return -1;
426                         }
427                         p->lastformat = AST_FORMAT_SLINEAR;
428                         p->lastinput = AST_FORMAT_SLINEAR;
429                         /* Reset output buffer */
430                         p->obuflen = 0;
431                 }
432                 maxfr = 480;
433         }
434         ioctl(p->fd, PHONE_REC_DEPTH, 3);
435         ioctl(p->fd, PHONE_PLAY_DEPTH, 3);
436         if (ioctl(p->fd, PHONE_PLAY_START)) {
437                 ast_log(LOG_WARNING, "Failed to start playback\n");
438                 return -1;
439         }
440         if (ioctl(p->fd, PHONE_REC_START)) {
441                 ast_log(LOG_WARNING, "Failed to start recording\n");
442                 return -1;
443         }
444         /* If we get here, we have a voice frame of Appropriate data */
445         sofar = 0;
446         pos = frame->data;
447         while(sofar < frame->datalen) {
448                 /* Write in no more than maxfr sized frames */
449                 expected = frame->datalen - sofar;
450                 if (maxfr < expected)
451                         expected = maxfr;
452                 /* XXX Internet Phone Jack does not handle the 4-byte VAD frame properly! XXX 
453                    we have to pad it to 24 bytes still.  */
454                 if (frame->datalen == 4) {
455                         if (p->silencesupression) {
456                                 memset(tmpbuf + 4, 0, sizeof(tmpbuf) - 4);
457                                 memcpy(tmpbuf, frame->data, 4);
458                                 expected = 24;
459                                 res = phone_write_buf(p, tmpbuf, expected, maxfr);
460                         }
461                         res = 4;
462                         expected=4;
463                 } else {
464                         res = phone_write_buf(p, pos, expected, maxfr);
465                 }
466                 if (res != expected) {
467                         if (res < 0) 
468                                 ast_log(LOG_WARNING, "Write returned error (%s)\n", strerror(errno));
469                         else
470                                 ast_log(LOG_WARNING, "Only wrote %d of %d bytes\n", res, frame->datalen);
471                         return -1;
472                 }
473                 sofar += res;
474                 pos += res;
475         }
476         return 0;
477 }
478
479 static struct ast_channel *phone_new(struct phone_pvt *i, int state, char *context)
480 {
481         struct ast_channel *tmp;
482         tmp = ast_channel_alloc();
483         if (tmp) {
484                 snprintf(tmp->name, sizeof(tmp->name), "Phone/%s", i->dev + 5);
485                 tmp->type = type;
486                 tmp->fd = i->fd;
487                 /* XXX Switching formats silently causes kernel panics XXX */
488                 tmp->format = prefformat;
489                 tmp->state = state;
490                 if (state == AST_STATE_RING)
491                         tmp->rings = 1;
492                 tmp->pvt->pvt = i;
493                 tmp->pvt->send_digit = phone_digit;
494                 tmp->pvt->call = phone_call;
495                 tmp->pvt->hangup = phone_hangup;
496                 tmp->pvt->answer = phone_answer;
497                 tmp->pvt->read = phone_read;
498                 tmp->pvt->write = phone_write;
499                 strncpy(tmp->context, context, sizeof(tmp->context));
500                 if (strlen(i->ext))
501                         strncpy(tmp->exten, i->ext, sizeof(tmp->exten));
502                 if (strlen(i->language))
503                         strncpy(tmp->language, i->language, sizeof(tmp->language));
504                 i->owner = tmp;
505                 pthread_mutex_lock(&usecnt_lock);
506                 usecnt++;
507                 pthread_mutex_unlock(&usecnt_lock);
508                 ast_update_use_count();
509                 if (state != AST_STATE_DOWN) {
510                         if (state == AST_STATE_RING) {
511                                 ioctl(tmp->fd, PHONE_RINGBACK);
512                         }
513                         if (ast_pbx_start(tmp)) {
514                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
515                                 ast_hangup(tmp);
516                         }
517                 }
518         } else
519                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
520         return tmp;
521 }
522
523 static void phone_mini_packet(struct phone_pvt *i)
524 {
525         int res;
526         char buf[1024];
527         /* Ignore stuff we read... */
528         res = read(i->fd, buf, sizeof(buf));
529         if (res < 1) {
530                 ast_log(LOG_WARNING, "Read returned %d\n", res);
531                 return;
532         }
533 }
534
535 static void phone_check_exception(struct phone_pvt *i)
536 {
537         int offhook=0;
538         char digit[2] = {0 , 0};
539         union telephony_exception phonee;
540         /* XXX Do something XXX */
541 #if 0
542         ast_log(LOG_DEBUG, "Exception!\n");
543 #endif
544         phonee.bytes = ioctl(i->fd, PHONE_EXCEPTION);
545         if (phonee.bits.dtmf_ready)  {
546                 digit[0] = ioctl(i->fd, PHONE_GET_DTMF_ASCII);
547                 if (i->mode == MODE_DIALTONE) {
548                         ioctl(i->fd, PHONE_PLAY_STOP);
549                         ioctl(i->fd, PHONE_REC_STOP);
550                         ioctl(i->fd, PHONE_CPT_STOP);
551                         i->dialtone = 0;
552                         if (strlen(i->ext) < AST_MAX_EXTENSION - 1)
553                                 strcat(i->ext, digit);
554                         if (ast_exists_extension(NULL, i->context, i->ext, 1)) {
555                                 /* It's a valid extension in its context, get moving! */
556                                 phone_new(i, AST_STATE_RING, i->context);
557                                 /* No need to restart monitor, we are the monitor */
558                                 if (i->owner) {
559                                         pthread_mutex_lock(&usecnt_lock);
560                                         usecnt--;
561                                         pthread_mutex_unlock(&usecnt_lock);
562                                         ast_update_use_count();
563                                 }
564                         } else if (!ast_canmatch_extension(NULL, i->context, i->ext, 1)) {
565                                 /* There is nothing in the specified extension that can match anymore.
566                                    Try the default */
567                                 if (ast_exists_extension(NULL, "default", i->ext, 1)) {
568                                         /* Check the default, too... */
569                                         phone_new(i, AST_STATE_RING, "default");
570                                         if (i->owner) {
571                                                 pthread_mutex_lock(&usecnt_lock);
572                                                 usecnt--;
573                                                 pthread_mutex_unlock(&usecnt_lock);
574                                                 ast_update_use_count();
575                                         }
576                                         /* XXX This should probably be justified better XXX */
577                                 }  else if (!ast_canmatch_extension(NULL, "default", i->ext, 1)) {
578                                         /* It's not a valid extension, give a busy signal */
579                                         if (option_debug)
580                                                 ast_log(LOG_DEBUG, "%s can't match anything in %s or default\n", i->ext, i->context);
581                                         ioctl(i->fd, PHONE_BUSY);
582                                 }
583                         }
584 #if 0
585                         ast_verbose("Extension is %s\n", i->ext);
586 #endif
587                 }
588         }
589         if (phonee.bits.hookstate) {
590                 offhook = ioctl(i->fd, PHONE_HOOKSTATE);
591                 if (offhook) {
592                         if (i->mode == MODE_IMMEDIATE) {
593                                 phone_new(i, AST_STATE_RING, i->context);
594                         } else if (i->mode == MODE_DIALTONE) {
595                                 pthread_mutex_lock(&usecnt_lock);
596                                 usecnt++;
597                                 pthread_mutex_unlock(&usecnt_lock);
598                                 ast_update_use_count();
599                                 /* Reset the extension */
600                                 i->ext[0] = '\0';
601                                 /* Play the dialtone */
602                                 i->dialtone++;
603                                 ioctl(i->fd, PHONE_PLAY_STOP);
604                                 ioctl(i->fd, PHONE_PLAY_CODEC, ULAW);
605                                 ioctl(i->fd, PHONE_PLAY_START);
606                         }
607                 } else {
608                         if (i->dialtone) {
609                                 pthread_mutex_lock(&usecnt_lock);
610                                 usecnt--;
611                                 pthread_mutex_unlock(&usecnt_lock);
612                                 ast_update_use_count();
613                         }
614                         memset(i->ext, 0, sizeof(i->ext));
615                         ioctl(i->fd, PHONE_CPT_STOP);
616                         ioctl(i->fd, PHONE_PLAY_STOP);
617                         ioctl(i->fd, PHONE_REC_STOP);
618                         i->dialtone = 0;
619                 }
620         }
621         if (phonee.bits.pstn_ring)
622                 ast_verbose("Unit is ringing\n");
623         if (phonee.bits.caller_id)
624                 ast_verbose("We have caller ID\n");
625         
626         
627 }
628
629 static void *do_monitor(void *data)
630 {
631         fd_set rfds, efds;
632         int n, res;
633         struct phone_pvt *i;
634         int tonepos = 0;
635         /* The tone we're playing this round */
636         struct timeval tv = {0,0};
637         int dotone;
638         /* This thread monitors all the frame relay interfaces which are not yet in use
639            (and thus do not have a separate thread) indefinitely */
640         /* From here on out, we die whenever asked */
641         if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
642                 ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
643                 return NULL;
644         }
645         for(;;) {
646                 /* Don't let anybody kill us right away.  Nobody should lock the interface list
647                    and wait for the monitor list, but the other way around is okay. */
648                 if (pthread_mutex_lock(&monlock)) {
649                         ast_log(LOG_ERROR, "Unable to grab monitor lock\n");
650                         return NULL;
651                 }
652                 /* Lock the interface list */
653                 if (pthread_mutex_lock(&iflock)) {
654                         ast_log(LOG_ERROR, "Unable to grab interface lock\n");
655                         pthread_mutex_unlock(&monlock);
656                         return NULL;
657                 }
658                 /* Build the stuff we're going to select on, that is the socket of every
659                    phone_pvt that does not have an associated owner channel */
660                 n = -1;
661                 FD_ZERO(&rfds);
662                 FD_ZERO(&efds);
663                 i = iflist;
664                 dotone = 0;
665                 while(i) {
666                         if (FD_ISSET(i->fd, &rfds)) 
667                                 ast_log(LOG_WARNING, "Descriptor %d appears twice (%s)?\n", i->fd, i->dev);
668                         if (!i->owner) {
669                                 /* This needs to be watched, as it lacks an owner */
670                                 FD_SET(i->fd, &rfds);
671                                 FD_SET(i->fd, &efds);
672                                 if (i->fd > n)
673                                         n = i->fd;
674                                 if (i->dialtone) {
675                                         /* Remember we're going to have to come back and play
676                                            more dialtones */
677                                         if (!tv.tv_usec && !tv.tv_sec) {
678                                                 /* If we're due for a dialtone, play one */
679                                                 if (write(i->fd, DialTone + tonepos, 240) != 240)
680                                                         ast_log(LOG_WARNING, "Dial tone write error\n");
681                                         }
682                                         dotone++;
683                                 }
684                         }
685                         
686                         i = i->next;
687                 }
688                 /* Okay, now that we know what to do, release the interface lock */
689                 pthread_mutex_unlock(&iflock);
690                 
691                 /* And from now on, we're okay to be killed, so release the monitor lock as well */
692                 pthread_mutex_unlock(&monlock);
693                 /* Wait indefinitely for something to happen */
694                 if (dotone) {
695                         /* If we're ready to recycle the time, set it to 30 ms */
696                         tonepos += 240;
697                         if (tonepos >= sizeof(DialTone))
698                                         tonepos = 0;
699                         if (!tv.tv_usec && !tv.tv_sec) {
700                                 tv.tv_usec = 30000;
701                                 tv.tv_sec = 0;
702                         }
703                         res = select(n + 1, &rfds, NULL, &efds, &tv);
704                 } else {
705                         res = select(n + 1, &rfds, NULL, &efds, NULL);
706                         tv.tv_usec = 0;
707                         tv.tv_sec = 0;
708                         tonepos = 0;
709                 }
710                 /* Okay, select has finished.  Let's see what happened.  */
711                 if (res < 0) {
712                         ast_log(LOG_WARNING, "select return %d: %s\n", res, strerror(errno));
713                         continue;
714                 }
715                 /* If there are no fd's changed, just continue, it's probably time
716                    to play some more dialtones */
717                 if (!res)
718                         continue;
719                 /* Alright, lock the interface list again, and let's look and see what has
720                    happened */
721                 if (pthread_mutex_lock(&iflock)) {
722                         ast_log(LOG_WARNING, "Unable to lock the interface list\n");
723                         continue;
724                 }
725                 i = iflist;
726                 while(i) {
727                         if (FD_ISSET(i->fd, &rfds)) {
728                                 if (i->owner) {
729                                         ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d, %s)...\n", i->fd, i->dev);
730                                         continue;
731                                 }
732                                 phone_mini_packet(i);
733                         }
734                         if (FD_ISSET(i->fd, &efds)) {
735                                 if (i->owner) {
736                                         ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d, %s)...\n", i->fd, i->dev);
737                                         continue;
738                                 }
739                                 phone_check_exception(i);
740                         }
741                         i=i->next;
742                 }
743                 pthread_mutex_unlock(&iflock);
744         }
745         /* Never reached */
746         return NULL;
747         
748 }
749
750 static int restart_monitor()
751 {
752         /* If we're supposed to be stopped -- stay stopped */
753         if (monitor_thread == -2)
754                 return 0;
755         if (pthread_mutex_lock(&monlock)) {
756                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
757                 return -1;
758         }
759         if (monitor_thread == pthread_self()) {
760                 pthread_mutex_unlock(&monlock);
761                 ast_log(LOG_WARNING, "Cannot kill myself\n");
762                 return -1;
763         }
764         if (monitor_thread != -1) {
765                 pthread_cancel(monitor_thread);
766 #if 0
767                 pthread_join(monitor_thread, NULL);
768 #endif
769         }
770         /* Start a new monitor */
771         if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
772                 pthread_mutex_unlock(&monlock);
773                 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
774                 return -1;
775         }
776         pthread_mutex_unlock(&monlock);
777         return 0;
778 }
779
780 static struct phone_pvt *mkif(char *iface, int mode)
781 {
782         /* Make a phone_pvt structure for this interface */
783         struct phone_pvt *tmp;
784 #if 0
785         int flags;      
786 #endif
787         
788         tmp = malloc(sizeof(struct phone_pvt));
789         if (tmp) {
790                 tmp->fd = open(iface, O_RDWR);
791                 if (tmp->fd < 0) {
792                         ast_log(LOG_WARNING, "Unable to open '%s'\n", iface);
793                         free(tmp);
794                         return NULL;
795                 }
796                 ioctl(tmp->fd, PHONE_PLAY_STOP);
797                 ioctl(tmp->fd, PHONE_REC_STOP);
798                 ioctl(tmp->fd, PHONE_RING_STOP);
799                 ioctl(tmp->fd, PHONE_CPT_STOP);
800                 if (echocancel != AEC_OFF)
801                         ioctl(tmp->fd, IXJCTL_AEC_START, echocancel);
802                 if (silencesupression) 
803                         tmp->silencesupression = 1;
804 #ifdef PHONE_VAD
805                 ioctl(tmp->fd, PHONE_VAD, tmp->silencesupression);
806 #endif
807                 tmp->mode = mode;
808 #if 0
809                 flags = fcntl(tmp->fd, F_GETFL);
810                 fcntl(tmp->fd, F_SETFL, flags | O_NONBLOCK);
811 #endif
812                 tmp->owner = NULL;
813                 tmp->lastformat = -1;
814                 tmp->lastinput = -1;
815                 tmp->ministate = 0;
816                 memset(tmp->ext, 0, sizeof(tmp->ext));
817                 strncpy(tmp->language, language, sizeof(tmp->language));
818                 strncpy(tmp->dev, iface, sizeof(tmp->dev));
819                 strncpy(tmp->context, context, sizeof(tmp->context));
820                 tmp->next = NULL;
821                 tmp->obuflen = 0;
822                 tmp->dialtone = 0;
823         }
824         return tmp;
825 }
826
827 static struct ast_channel *phone_request(char *type, int format, void *data)
828 {
829         int oldformat;
830         struct phone_pvt *p;
831         struct ast_channel *tmp = NULL;
832         char *name = data;
833         
834         oldformat = format;
835         format &= (AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR);
836         if (!format) {
837                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", oldformat);
838                 return NULL;
839         }
840         /* Search for an unowned channel */
841         if (pthread_mutex_lock(&iflock)) {
842                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
843                 return NULL;
844         }
845         p = iflist;
846         while(p) {
847                 if (!strcmp(name, p->dev + 5)) {
848                         if (!p->owner) {
849                                 tmp = phone_new(p, AST_STATE_DOWN, p->context);
850                                 break;
851                         }
852                 }
853                 p = p->next;
854         }
855         pthread_mutex_unlock(&iflock);
856         restart_monitor();
857         return tmp;
858 }
859
860 int load_module()
861 {
862         struct ast_config *cfg;
863         struct ast_variable *v;
864         struct phone_pvt *tmp;
865         int mode = MODE_IMMEDIATE;
866         cfg = ast_load(config);
867
868         /* We *must* have a config file otherwise stop immediately */
869         if (!cfg) {
870                 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
871                 return -1;
872         }
873         if (pthread_mutex_lock(&iflock)) {
874                 /* It's a little silly to lock it, but we mind as well just to be sure */
875                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
876                 return -1;
877         }
878         v = ast_variable_browse(cfg, "interfaces");
879         while(v) {
880                 /* Create the interface list */
881                 if (!strcasecmp(v->name, "device")) {
882                                 tmp = mkif(v->value, mode);
883                                 if (tmp) {
884                                         tmp->next = iflist;
885                                         iflist = tmp;
886                                         
887                                 } else {
888                                         ast_log(LOG_ERROR, "Unable to register channel '%s'\n", v->value);
889                                         ast_destroy(cfg);
890                                         pthread_mutex_unlock(&iflock);
891                                         unload_module();
892                                         return -1;
893                                 }
894                 } else if (!strcasecmp(v->name, "silencesupression")) {
895                         silencesupression = ast_true(v->value);
896                 } else if (!strcasecmp(v->name, "language")) {
897                         strncpy(language, v->value, sizeof(language));
898                 } else if (!strcasecmp(v->name, "mode")) {
899                         if (!strncasecmp(v->value, "di", 2)) 
900                                 mode = MODE_DIALTONE;
901                         else if (!strncasecmp(v->value, "im", 2))
902                                 mode = MODE_IMMEDIATE;
903                         else
904                                 ast_log(LOG_WARNING, "Unknown mode: %s\n", v->value);
905                 } else if (!strcasecmp(v->name, "context")) {
906                         strncpy(context, v->value, sizeof(context));
907                 } else if (!strcasecmp(v->name, "format")) {
908                         if (!strcasecmp(v->value, "g723.1")) {
909                                 prefformat = AST_FORMAT_G723_1;
910                         } else if (!strcasecmp(v->value, "slinear")) {
911                                 prefformat = AST_FORMAT_SLINEAR;
912                         } else 
913                                 ast_log(LOG_WARNING, "Unknown format '%s'\n", v->value);
914                 } else if (!strcasecmp(v->name, "echocancel")) {
915                         if (!strcasecmp(v->value, "off")) {
916                                 echocancel = AEC_OFF;
917                         } else if (!strcasecmp(v->value, "low")) {
918                                 echocancel = AEC_LOW;
919                         } else if (!strcasecmp(v->value, "medium")) {
920                                 echocancel = AEC_MED;
921                         } else if (!strcasecmp(v->value, "high")) {
922                                 echocancel = AEC_HIGH;
923                         } else 
924                                 ast_log(LOG_WARNING, "Unknown echo cancellation '%s'\n", v->value);
925                 }
926                 v = v->next;
927         }
928         pthread_mutex_unlock(&iflock);
929         /* Make sure we can register our Adtranphone channel type */
930         if (ast_channel_register(type, tdesc, AST_FORMAT_G723_1, phone_request)) {
931                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
932                 ast_destroy(cfg);
933                 unload_module();
934                 return -1;
935         }
936         ast_destroy(cfg);
937         /* And start the monitor for the first time */
938         restart_monitor();
939         return 0;
940 }
941
942
943
944 int unload_module()
945 {
946         struct phone_pvt *p, *pl;
947         /* First, take us out of the channel loop */
948         ast_channel_unregister(type);
949         if (!pthread_mutex_lock(&iflock)) {
950                 /* Hangup all interfaces if they have an owner */
951                 p = iflist;
952                 while(p) {
953                         if (p->owner)
954                                 ast_softhangup(p->owner);
955                         p = p->next;
956                 }
957                 iflist = NULL;
958                 pthread_mutex_unlock(&iflock);
959         } else {
960                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
961                 return -1;
962         }
963         if (!pthread_mutex_lock(&monlock)) {
964                 if (monitor_thread > -1) {
965                         pthread_cancel(monitor_thread);
966                         pthread_join(monitor_thread, NULL);
967                 }
968                 monitor_thread = -2;
969                 pthread_mutex_unlock(&monlock);
970         } else {
971                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
972                 return -1;
973         }
974
975         if (!pthread_mutex_lock(&iflock)) {
976                 /* Destroy all the interfaces and free their memory */
977                 p = iflist;
978                 while(p) {
979                         /* Close the socket, assuming it's real */
980                         if (p->fd > -1)
981                                 close(p->fd);
982                         pl = p;
983                         p = p->next;
984                         /* Free associated memory */
985                         free(pl);
986                 }
987                 iflist = NULL;
988                 pthread_mutex_unlock(&iflock);
989         } else {
990                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
991                 return -1;
992         }
993                 
994         return 0;
995 }
996
997 int usecount()
998 {
999         int res;
1000         pthread_mutex_lock(&usecnt_lock);
1001         res = usecnt;
1002         pthread_mutex_unlock(&usecnt_lock);
1003         return res;
1004 }
1005
1006 char *description()
1007 {
1008         return desc;
1009 }
1010