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