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