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