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