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