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