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