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