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