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