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