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