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