Fix chan_phone error code (bug #3692)
[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            length ? 0 : -1;
535 }
536
537 static int phone_write(struct ast_channel *ast, struct ast_frame *frame)
538 {
539         struct phone_pvt *p = ast->pvt->pvt;
540         int res;
541         int maxfr=0;
542         char *pos;
543         int sofar;
544         int expected;
545         int codecset = 0;
546         char tmpbuf[4];
547         /* Write a frame of (presumably voice) data */
548         if (frame->frametype != AST_FRAME_VOICE && p->mode != MODE_FXS) {
549                 if (frame->frametype != AST_FRAME_IMAGE)
550                         ast_log(LOG_WARNING, "Don't know what to do with  frame type '%d'\n", frame->frametype);
551                 return 0;
552         }
553         if (!(frame->subclass &
554                 (AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW)) && 
555             p->mode != MODE_FXS) {
556                 ast_log(LOG_WARNING, "Cannot handle frames in %d format\n", frame->subclass);
557                 return -1;
558         }
559 #if 0
560         /* If we're not in up mode, go into up mode now */
561         if (ast->_state != AST_STATE_UP) {
562                 ast_setstate(ast, AST_STATE_UP);
563                 phone_setup(ast);
564         }
565 #else
566         if (ast->_state != AST_STATE_UP) {
567                 /* Don't try tos end audio on-hook */
568                 return 0;
569         }
570 #endif  
571         if (frame->subclass == AST_FORMAT_G723_1) {
572                 if (p->lastformat != AST_FORMAT_G723_1) {
573                         ioctl(p->fd, PHONE_PLAY_STOP);
574                         ioctl(p->fd, PHONE_REC_STOP);
575                         if (ioctl(p->fd, PHONE_PLAY_CODEC, G723_63)) {
576                                 ast_log(LOG_WARNING, "Unable to set G723.1 mode\n");
577                                 return -1;
578                         }
579                         if (ioctl(p->fd, PHONE_REC_CODEC, G723_63)) {
580                                 ast_log(LOG_WARNING, "Unable to set G723.1 mode\n");
581                                 return -1;
582                         }
583                         p->lastformat = AST_FORMAT_G723_1;
584                         p->lastinput = AST_FORMAT_G723_1;
585                         /* Reset output buffer */
586                         p->obuflen = 0;
587                         codecset = 1;
588                 }
589                 if (frame->datalen > 24) {
590                         ast_log(LOG_WARNING, "Frame size too large for G.723.1 (%d bytes)\n", frame->datalen);
591                         return -1;
592                 }
593                 maxfr = 24;
594         } else if (frame->subclass == AST_FORMAT_SLINEAR) {
595                 if (p->lastformat != AST_FORMAT_SLINEAR) {
596                         ioctl(p->fd, PHONE_PLAY_STOP);
597                         ioctl(p->fd, PHONE_REC_STOP);
598                         if (ioctl(p->fd, PHONE_PLAY_CODEC, LINEAR16)) {
599                                 ast_log(LOG_WARNING, "Unable to set 16-bit linear mode\n");
600                                 return -1;
601                         }
602                         if (ioctl(p->fd, PHONE_REC_CODEC, LINEAR16)) {
603                                 ast_log(LOG_WARNING, "Unable to set 16-bit linear mode\n");
604                                 return -1;
605                         }
606                         p->lastformat = AST_FORMAT_SLINEAR;
607                         p->lastinput = AST_FORMAT_SLINEAR;
608                         codecset = 1;
609                         /* Reset output buffer */
610                         p->obuflen = 0;
611                 }
612                 maxfr = 480;
613         } else if (frame->subclass == AST_FORMAT_ULAW) {
614                 if (p->lastformat != AST_FORMAT_ULAW) {
615                         ioctl(p->fd, PHONE_PLAY_STOP);
616                         ioctl(p->fd, PHONE_REC_STOP);
617                         if (ioctl(p->fd, PHONE_PLAY_CODEC, ULAW)) {
618                                 ast_log(LOG_WARNING, "Unable to set uLaw mode\n");
619                                 return -1;
620                         }
621                         if (ioctl(p->fd, PHONE_REC_CODEC, ULAW)) {
622                                 ast_log(LOG_WARNING, "Unable to set uLaw mode\n");
623                                 return -1;
624                         }
625                         p->lastformat = AST_FORMAT_ULAW;
626                         p->lastinput = AST_FORMAT_ULAW;
627                         codecset = 1;
628                         /* Reset output buffer */
629                         p->obuflen = 0;
630                 }
631                 maxfr = 240;
632         } else {
633                 if (p->lastformat != frame->subclass) {
634                         ioctl(p->fd, PHONE_PLAY_STOP);
635                         ioctl(p->fd, PHONE_REC_STOP);
636                         if (ioctl(p->fd, PHONE_PLAY_CODEC, frame->subclass)) {
637                                 ast_log(LOG_WARNING, "Unable to set %d mode\n",
638                                         frame->subclass);
639                                 return -1;
640                         }
641                         if (ioctl(p->fd, PHONE_REC_CODEC, frame->subclass)) {
642                                 ast_log(LOG_WARNING, "Unable to set %d mode\n",
643                                         frame->subclass);
644                                 return -1;
645                         }
646                         p->lastformat = frame->subclass;
647                         p->lastinput = frame->subclass;
648                         codecset = 1;
649                         /* Reset output buffer */
650                         p->obuflen = 0;
651                 }
652                 maxfr = 480;
653         }
654         if (codecset) {
655                 ioctl(p->fd, PHONE_REC_DEPTH, 3);
656                 ioctl(p->fd, PHONE_PLAY_DEPTH, 3);
657                 if (ioctl(p->fd, PHONE_PLAY_START)) {
658                         ast_log(LOG_WARNING, "Failed to start playback\n");
659                         return -1;
660                 }
661                 if (ioctl(p->fd, PHONE_REC_START)) {
662                         ast_log(LOG_WARNING, "Failed to start recording\n");
663                         return -1;
664                 }
665         }
666         /* If we get here, we have a frame of Appropriate data */
667         sofar = 0;
668         pos = frame->data;
669         while(sofar < frame->datalen) {
670                 /* Write in no more than maxfr sized frames */
671                 expected = frame->datalen - sofar;
672                 if (maxfr < expected)
673                         expected = maxfr;
674                 /* XXX Internet Phone Jack does not handle the 4-byte VAD frame properly! XXX 
675                    we have to pad it to 24 bytes still.  */
676                 if (frame->datalen == 4) {
677                         if (p->silencesupression) {
678                                 memset(tmpbuf + 4, 0, sizeof(tmpbuf) - 4);
679                                 memcpy(tmpbuf, frame->data, 4);
680                                 expected = 24;
681                                 res = phone_write_buf(p, tmpbuf, expected, maxfr);
682                         }
683                         res = 4;
684                         expected=4;
685                 } else {
686                         res = phone_write_buf(p, pos, expected, maxfr);
687                 }
688                 if (res != expected) {
689                         if ((errno != EAGAIN) && (errno != EINTR)) {
690                                 if (res < 0) 
691                                         ast_log(LOG_WARNING, "Write returned error (%s)\n", strerror(errno));
692         /*
693          * Card is in non-blocking mode now and it works well now, but there are
694          * lot of messages like this. So, this message is temporarily disabled.
695          */
696 #if 0
697                                 else
698                                         ast_log(LOG_WARNING, "Only wrote %d of %d bytes\n", res, frame->datalen);
699 #endif
700                                 return -1;
701                         } else /* Pretend it worked */
702                                 res = expected;
703                 }
704                 sofar += res;
705                 pos += res;
706         }
707         return 0;
708 }
709
710 static struct ast_channel *phone_new(struct phone_pvt *i, int state, char *context)
711 {
712         struct ast_channel *tmp;
713         struct phone_codec_data codec;
714         tmp = ast_channel_alloc(1);
715         if (tmp) {
716                 snprintf(tmp->name, sizeof(tmp->name), "Phone/%s", i->dev + 5);
717                 tmp->type = type;
718                 tmp->fds[0] = i->fd;
719                 /* XXX Switching formats silently causes kernel panics XXX */
720                 if (i->mode == MODE_FXS &&
721                     ioctl(i->fd, PHONE_QUERY_CODEC, &codec) == 0) {
722                         if (codec.type == LINEAR16)
723                                 tmp->nativeformats =
724                                 tmp->pvt->rawreadformat =
725                                 tmp->pvt->rawwriteformat =
726                                 AST_FORMAT_SLINEAR;
727                         else {
728                                 tmp->nativeformats =
729                                 tmp->pvt->rawreadformat =
730                                 tmp->pvt->rawwriteformat =
731                                 prefformat & ~AST_FORMAT_SLINEAR;
732                         }
733                 }
734                 else {
735                         tmp->nativeformats = prefformat;
736                         tmp->pvt->rawreadformat = prefformat;
737                         tmp->pvt->rawwriteformat = prefformat;
738                 }
739                 ast_setstate(tmp, state);
740                 if (state == AST_STATE_RING)
741                         tmp->rings = 1;
742                 tmp->pvt->pvt = i;
743                 tmp->pvt->send_digit = phone_digit;
744                 tmp->pvt->call = phone_call;
745                 tmp->pvt->hangup = phone_hangup;
746                 tmp->pvt->answer = phone_answer;
747                 tmp->pvt->read = phone_read;
748                 tmp->pvt->write = phone_write;
749                 if (i->mode == MODE_FXS) {
750                         tmp->pvt->write_video = phone_write;
751                         tmp->pvt->send_text = phone_send_text;
752                 }
753                 tmp->pvt->exception = phone_exception;
754                 strncpy(tmp->context, context, sizeof(tmp->context)-1);
755                 if (strlen(i->ext))
756                         strncpy(tmp->exten, i->ext, sizeof(tmp->exten)-1);
757                 else
758                         strncpy(tmp->exten, "s",  sizeof(tmp->exten) - 1);
759                 if (strlen(i->language))
760                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
761                 if (!ast_strlen_zero(i->cid_num))
762                         tmp->cid.cid_num = strdup(i->cid_num);
763                 if (!ast_strlen_zero(i->cid_name))
764                         tmp->cid.cid_name = strdup(i->cid_name);
765                 i->owner = tmp;
766                 ast_mutex_lock(&usecnt_lock);
767                 usecnt++;
768                 ast_mutex_unlock(&usecnt_lock);
769                 ast_update_use_count();
770                 if (state != AST_STATE_DOWN) {
771                         if (state == AST_STATE_RING) {
772                                 ioctl(tmp->fds[0], PHONE_RINGBACK);
773                                 i->cpt = 1;
774                         }
775                         if (ast_pbx_start(tmp)) {
776                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
777                                 ast_hangup(tmp);
778                         }
779                 }
780         } else
781                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
782         return tmp;
783 }
784
785 static void phone_mini_packet(struct phone_pvt *i)
786 {
787         int res;
788         char buf[1024];
789         /* Ignore stuff we read... */
790         res = read(i->fd, buf, sizeof(buf));
791         if (res < 1) {
792                 ast_log(LOG_WARNING, "Read returned %d: %s\n", res, strerror(errno));
793                 return;
794         }
795 }
796
797 static void phone_check_exception(struct phone_pvt *i)
798 {
799         int offhook=0;
800         char digit[2] = {0 , 0};
801         union telephony_exception phonee;
802         /* XXX Do something XXX */
803 #if 0
804         ast_log(LOG_DEBUG, "Exception!\n");
805 #endif
806         phonee.bytes = ioctl(i->fd, PHONE_EXCEPTION);
807         if (phonee.bits.dtmf_ready)  {
808                 digit[0] = ioctl(i->fd, PHONE_GET_DTMF_ASCII);
809                 if (i->mode == MODE_DIALTONE || i->mode == MODE_FXS) {
810                         ioctl(i->fd, PHONE_PLAY_STOP);
811                         ioctl(i->fd, PHONE_REC_STOP);
812                         ioctl(i->fd, PHONE_CPT_STOP);
813                         i->dialtone = 0;
814                         if (strlen(i->ext) < AST_MAX_EXTENSION - 1)
815                                 strncat(i->ext, digit, sizeof(i->ext) - strlen(i->ext) - 1);
816                         if ((i->mode != MODE_FXS ||
817                              !(phonee.bytes = ioctl(i->fd, PHONE_EXCEPTION)) ||
818                              !phonee.bits.dtmf_ready) &&
819                             ast_exists_extension(NULL, i->context, i->ext, 1, i->cid_num)) {
820                                 /* It's a valid extension in its context, get moving! */
821                                 phone_new(i, AST_STATE_RING, i->context);
822                                 /* No need to restart monitor, we are the monitor */
823                         } else if (!ast_canmatch_extension(NULL, i->context, i->ext, 1, i->cid_num)) {
824                                 /* There is nothing in the specified extension that can match anymore.
825                                    Try the default */
826                                 if (ast_exists_extension(NULL, "default", i->ext, 1, i->cid_num)) {
827                                         /* Check the default, too... */
828                                         phone_new(i, AST_STATE_RING, "default");
829                                         /* XXX This should probably be justified better XXX */
830                                 }  else if (!ast_canmatch_extension(NULL, "default", i->ext, 1, i->cid_num)) {
831                                         /* It's not a valid extension, give a busy signal */
832                                         if (option_debug)
833                                                 ast_log(LOG_DEBUG, "%s can't match anything in %s or default\n", i->ext, i->context);
834                                         ioctl(i->fd, PHONE_BUSY);
835                                         i->cpt = 1;
836                                 }
837                         }
838 #if 0
839                         ast_verbose("Extension is %s\n", i->ext);
840 #endif
841                 }
842         }
843         if (phonee.bits.hookstate) {
844                 offhook = ioctl(i->fd, PHONE_HOOKSTATE);
845                 if (offhook) {
846                         if (i->mode == MODE_IMMEDIATE) {
847                                 phone_new(i, AST_STATE_RING, i->context);
848                         } else if (i->mode == MODE_DIALTONE) {
849                                 ast_mutex_lock(&usecnt_lock);
850                                 usecnt++;
851                                 ast_mutex_unlock(&usecnt_lock);
852                                 ast_update_use_count();
853                                 /* Reset the extension */
854                                 i->ext[0] = '\0';
855                                 /* Play the dialtone */
856                                 i->dialtone++;
857                                 ioctl(i->fd, PHONE_PLAY_STOP);
858                                 ioctl(i->fd, PHONE_PLAY_CODEC, ULAW);
859                                 ioctl(i->fd, PHONE_PLAY_START);
860                                 i->lastformat = -1;
861                         }
862                 } else {
863                         if (i->dialtone) {
864                                 ast_mutex_lock(&usecnt_lock);
865                                 usecnt--;
866                                 ast_mutex_unlock(&usecnt_lock);
867                                 ast_update_use_count();
868                         }
869                         memset(i->ext, 0, sizeof(i->ext));
870                         if (i->cpt)
871                         {
872                                 ioctl(i->fd, PHONE_CPT_STOP);
873                                 i->cpt = 0;
874                         }
875                         ioctl(i->fd, PHONE_PLAY_STOP);
876                         ioctl(i->fd, PHONE_REC_STOP);
877                         i->dialtone = 0;
878                         i->lastformat = -1;
879                 }
880         }
881         if (phonee.bits.pstn_ring) {
882                 ast_verbose("Unit is ringing\n");
883                 phone_new(i, AST_STATE_RING, i->context);
884         }
885         if (phonee.bits.caller_id)
886                 ast_verbose("We have caller ID\n");
887         
888         
889 }
890
891 static void *do_monitor(void *data)
892 {
893         fd_set rfds, efds;
894         int n, res;
895         struct phone_pvt *i;
896         int tonepos = 0;
897         /* The tone we're playing this round */
898         struct timeval tv = {0,0};
899         int dotone;
900         /* This thread monitors all the frame relay interfaces which are not yet in use
901            (and thus do not have a separate thread) indefinitely */
902         /* From here on out, we die whenever asked */
903         if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
904                 ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
905                 return NULL;
906         }
907         for(;;) {
908                 /* Don't let anybody kill us right away.  Nobody should lock the interface list
909                    and wait for the monitor list, but the other way around is okay. */
910                 if (ast_mutex_lock(&monlock)) {
911                         ast_log(LOG_ERROR, "Unable to grab monitor lock\n");
912                         return NULL;
913                 }
914                 /* Lock the interface list */
915                 if (ast_mutex_lock(&iflock)) {
916                         ast_log(LOG_ERROR, "Unable to grab interface lock\n");
917                         ast_mutex_unlock(&monlock);
918                         return NULL;
919                 }
920                 /* Build the stuff we're going to select on, that is the socket of every
921                    phone_pvt that does not have an associated owner channel */
922                 n = -1;
923                 FD_ZERO(&rfds);
924                 FD_ZERO(&efds);
925                 i = iflist;
926                 dotone = 0;
927                 while(i) {
928                         if (FD_ISSET(i->fd, &rfds)) 
929                                 ast_log(LOG_WARNING, "Descriptor %d appears twice (%s)?\n", i->fd, i->dev);
930                         if (!i->owner) {
931                                 /* This needs to be watched, as it lacks an owner */
932                                 FD_SET(i->fd, &rfds);
933                                 FD_SET(i->fd, &efds);
934                                 if (i->fd > n)
935                                         n = i->fd;
936                                 if (i->dialtone) {
937                                         /* Remember we're going to have to come back and play
938                                            more dialtones */
939                                         if (!tv.tv_usec && !tv.tv_sec) {
940                                                 /* If we're due for a dialtone, play one */
941                                                 if (write(i->fd, DialTone + tonepos, 240) != 240)
942                                                         ast_log(LOG_WARNING, "Dial tone write error\n");
943                                         }
944                                         dotone++;
945                                 }
946                         }
947                         
948                         i = i->next;
949                 }
950                 /* Okay, now that we know what to do, release the interface lock */
951                 ast_mutex_unlock(&iflock);
952
953                 /* And from now on, we're okay to be killed, so release the monitor lock as well */
954                 ast_mutex_unlock(&monlock);
955
956                 /* Wait indefinitely for something to happen */
957                 if (dotone) {
958                         /* If we're ready to recycle the time, set it to 30 ms */
959                         tonepos += 240;
960                         if (tonepos >= sizeof(DialTone))
961                                         tonepos = 0;
962                         if (!tv.tv_usec && !tv.tv_sec) {
963                                 tv.tv_usec = 30000;
964                                 tv.tv_sec = 0;
965                         }
966                         res = ast_select(n + 1, &rfds, NULL, &efds, &tv);
967                 } else {
968                         res = ast_select(n + 1, &rfds, NULL, &efds, NULL);
969                         tv.tv_usec = 0;
970                         tv.tv_sec = 0;
971                         tonepos = 0;
972                 }
973                 /* Okay, select has finished.  Let's see what happened.  */
974                 if (res < 0) {
975                         ast_log(LOG_WARNING, "select return %d: %s\n", res, strerror(errno));
976                         continue;
977                 }
978                 /* If there are no fd's changed, just continue, it's probably time
979                    to play some more dialtones */
980                 if (!res)
981                         continue;
982                 /* Alright, lock the interface list again, and let's look and see what has
983                    happened */
984                 if (ast_mutex_lock(&iflock)) {
985                         ast_log(LOG_WARNING, "Unable to lock the interface list\n");
986                         continue;
987                 }
988
989                 i = iflist;
990                 for(; i; i=i->next) {
991                         if (FD_ISSET(i->fd, &rfds)) {
992                                 if (i->owner) {
993                                         continue;
994                                 }
995                                 phone_mini_packet(i);
996                         }
997                         if (FD_ISSET(i->fd, &efds)) {
998                                 if (i->owner) {
999                                         continue;
1000                                 }
1001                                 phone_check_exception(i);
1002                         }
1003                 }
1004                 ast_mutex_unlock(&iflock);
1005         }
1006         /* Never reached */
1007         return NULL;
1008         
1009 }
1010
1011 static int restart_monitor()
1012 {
1013         /* If we're supposed to be stopped -- stay stopped */
1014         if (monitor_thread == AST_PTHREADT_STOP)
1015                 return 0;
1016         if (ast_mutex_lock(&monlock)) {
1017                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1018                 return -1;
1019         }
1020         if (monitor_thread == pthread_self()) {
1021                 ast_mutex_unlock(&monlock);
1022                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1023                 return -1;
1024         }
1025         if (monitor_thread != AST_PTHREADT_NULL) {
1026                 if (ast_mutex_lock(&iflock)) {
1027                   ast_mutex_unlock(&monlock);
1028                   ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1029                   return -1;
1030                 }
1031                 pthread_cancel(monitor_thread);
1032 #if 0
1033                 pthread_join(monitor_thread, NULL);
1034 #endif
1035                 ast_mutex_unlock(&iflock);
1036         }
1037         /* Start a new monitor */
1038         if (ast_pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1039                 ast_mutex_unlock(&monlock);
1040                 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1041                 return -1;
1042         }
1043         ast_mutex_unlock(&monlock);
1044         return 0;
1045 }
1046
1047 static struct phone_pvt *mkif(char *iface, int mode, int txgain, int rxgain)
1048 {
1049         /* Make a phone_pvt structure for this interface */
1050         struct phone_pvt *tmp;
1051         int flags;      
1052         
1053         tmp = malloc(sizeof(struct phone_pvt));
1054         if (tmp) {
1055                 tmp->fd = open(iface, O_RDWR);
1056                 if (tmp->fd < 0) {
1057                         ast_log(LOG_WARNING, "Unable to open '%s'\n", iface);
1058                         free(tmp);
1059                         return NULL;
1060                 }
1061                 if (mode == MODE_FXO) {
1062                         if (ioctl(tmp->fd, IXJCTL_PORT, PORT_PSTN)) 
1063                                 ast_log(LOG_DEBUG, "Unable to set port to PSTN\n");
1064                 } else {
1065                         if (ioctl(tmp->fd, IXJCTL_PORT, PORT_POTS)) 
1066                                  if (mode != MODE_FXS)
1067                                       ast_log(LOG_DEBUG, "Unable to set port to POTS\n");
1068                 }
1069                 ioctl(tmp->fd, PHONE_PLAY_STOP);
1070                 ioctl(tmp->fd, PHONE_REC_STOP);
1071                 ioctl(tmp->fd, PHONE_RING_STOP);
1072                 ioctl(tmp->fd, PHONE_CPT_STOP);
1073                 if (ioctl(tmp->fd, PHONE_PSTN_SET_STATE, PSTN_ON_HOOK)) 
1074                         ast_log(LOG_DEBUG, "ioctl(PHONE_PSTN_SET_STATE) failed on %s (%s)\n",iface, strerror(errno));
1075                 if (echocancel != AEC_OFF)
1076                         ioctl(tmp->fd, IXJCTL_AEC_START, echocancel);
1077                 if (silencesupression) 
1078                         tmp->silencesupression = 1;
1079 #ifdef PHONE_VAD
1080                 ioctl(tmp->fd, PHONE_VAD, tmp->silencesupression);
1081 #endif
1082                 tmp->mode = mode;
1083                 flags = fcntl(tmp->fd, F_GETFL);
1084                 fcntl(tmp->fd, F_SETFL, flags | O_NONBLOCK);
1085                 tmp->owner = NULL;
1086                 tmp->lastformat = -1;
1087                 tmp->lastinput = -1;
1088                 tmp->ministate = 0;
1089                 memset(tmp->ext, 0, sizeof(tmp->ext));
1090                 strncpy(tmp->language, language, sizeof(tmp->language)-1);
1091                 strncpy(tmp->dev, iface, sizeof(tmp->dev)-1);
1092                 strncpy(tmp->context, context, sizeof(tmp->context)-1);
1093                 tmp->next = NULL;
1094                 tmp->obuflen = 0;
1095                 tmp->dialtone = 0;
1096                 tmp->cpt = 0;
1097                 strncpy(tmp->cid_num, cid_num, sizeof(tmp->cid_num)-1);
1098                 strncpy(tmp->cid_name, cid_name, sizeof(tmp->cid_name)-1);
1099                 tmp->txgain = txgain;
1100                 ioctl(tmp->fd, PHONE_PLAY_VOLUME, tmp->txgain);
1101                 tmp->rxgain = rxgain;
1102                 ioctl(tmp->fd, PHONE_REC_VOLUME, tmp->rxgain);
1103         }
1104         return tmp;
1105 }
1106
1107 static struct ast_channel *phone_request(const char *type, int format, void *data, int *cause)
1108 {
1109         int oldformat;
1110         struct phone_pvt *p;
1111         struct ast_channel *tmp = NULL;
1112         char *name = data;
1113
1114         /* Search for an unowned channel */
1115         if (ast_mutex_lock(&iflock)) {
1116                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
1117                 return NULL;
1118         }
1119         p = iflist;
1120         while(p) {
1121                 if (p->mode == MODE_FXS ||
1122                     format & (AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW)) {
1123                     size_t length = strlen(p->dev + 5);
1124                 if (strncmp(name, p->dev + 5, length) == 0 &&
1125                     !isalnum(name[length])) {
1126                     if (!p->owner) {
1127                      tmp = phone_new(p, AST_STATE_DOWN, p->context);
1128                      break;
1129                 } else
1130                      *cause = AST_CAUSE_BUSY;
1131             }
1132                 }
1133                 p = p->next;
1134         }
1135         ast_mutex_unlock(&iflock);
1136         restart_monitor();
1137         if (tmp == NULL) {
1138                 oldformat = format;
1139                 format &= (AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW);
1140                 if (!format) {
1141                         ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", oldformat);
1142                         return NULL;
1143                 }
1144         }
1145         return tmp;
1146 }
1147
1148 /* parse gain value from config file */
1149 static int parse_gain_value(char *gain_type, char *value)
1150 {
1151         float gain;
1152
1153         /* try to scan number */
1154         if (sscanf(value, "%f", &gain) != 1)
1155         {
1156                 ast_log(LOG_ERROR, "Invalid %s value '%s' in '%s' config\n",
1157                         value, gain_type, config);
1158                 return DEFAULT_GAIN;
1159         }
1160
1161         /* multiplicate gain by 1.0 gain value */ 
1162         gain = gain * (float)DEFAULT_GAIN;
1163
1164         /* percentage? */
1165         if (value[strlen(value) - 1] == '%')
1166                 return (int)(gain / (float)100);
1167
1168         return (int)gain;
1169 }
1170
1171 static int __unload_module(void)
1172 {
1173         struct phone_pvt *p, *pl;
1174         /* First, take us out of the channel loop */
1175         ast_channel_unregister(type);
1176         if (!ast_mutex_lock(&iflock)) {
1177                 /* Hangup all interfaces if they have an owner */
1178                 p = iflist;
1179                 while(p) {
1180                         if (p->owner)
1181                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1182                         p = p->next;
1183                 }
1184                 iflist = NULL;
1185                 ast_mutex_unlock(&iflock);
1186         } else {
1187                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1188                 return -1;
1189         }
1190         if (!ast_mutex_lock(&monlock)) {
1191                 if (monitor_thread > AST_PTHREADT_NULL) {
1192                         pthread_cancel(monitor_thread);
1193                         pthread_join(monitor_thread, NULL);
1194                 }
1195                 monitor_thread = AST_PTHREADT_STOP;
1196                 ast_mutex_unlock(&monlock);
1197         } else {
1198                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1199                 return -1;
1200         }
1201
1202         if (!ast_mutex_lock(&iflock)) {
1203                 /* Destroy all the interfaces and free their memory */
1204                 p = iflist;
1205                 while(p) {
1206                         /* Close the socket, assuming it's real */
1207                         if (p->fd > -1)
1208                                 close(p->fd);
1209                         pl = p;
1210                         p = p->next;
1211                         /* Free associated memory */
1212                         free(pl);
1213                 }
1214                 iflist = NULL;
1215                 ast_mutex_unlock(&iflock);
1216         } else {
1217                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1218                 return -1;
1219         }
1220                 
1221         return 0;
1222 }
1223
1224 int unload_module(void)
1225 {
1226         return __unload_module();
1227 }
1228
1229 int load_module()
1230 {
1231         struct ast_config *cfg;
1232         struct ast_variable *v;
1233         struct phone_pvt *tmp;
1234         int mode = MODE_IMMEDIATE;
1235         int txgain = DEFAULT_GAIN, rxgain = DEFAULT_GAIN; /* default gain 1.0 */
1236         cfg = ast_config_load(config);
1237
1238         /* We *must* have a config file otherwise stop immediately */
1239         if (!cfg) {
1240                 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
1241                 return -1;
1242         }
1243         if (ast_mutex_lock(&iflock)) {
1244                 /* It's a little silly to lock it, but we mind as well just to be sure */
1245                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
1246                 return -1;
1247         }
1248         v = ast_variable_browse(cfg, "interfaces");
1249         while(v) {
1250                 /* Create the interface list */
1251                 if (!strcasecmp(v->name, "device")) {
1252                                 tmp = mkif(v->value, mode, txgain, rxgain);
1253                                 if (tmp) {
1254                                         tmp->next = iflist;
1255                                         iflist = tmp;
1256                                         
1257                                 } else {
1258                                         ast_log(LOG_ERROR, "Unable to register channel '%s'\n", v->value);
1259                                         ast_config_destroy(cfg);
1260                                         ast_mutex_unlock(&iflock);
1261                                         __unload_module();
1262                                         return -1;
1263                                 }
1264                 } else if (!strcasecmp(v->name, "silencesupression")) {
1265                         silencesupression = ast_true(v->value);
1266                 } else if (!strcasecmp(v->name, "language")) {
1267                         strncpy(language, v->value, sizeof(language)-1);
1268                 } else if (!strcasecmp(v->name, "callerid")) {
1269                         ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
1270                 } else if (!strcasecmp(v->name, "mode")) {
1271                         if (!strncasecmp(v->value, "di", 2)) 
1272                                 mode = MODE_DIALTONE;
1273                         else if (!strncasecmp(v->value, "im", 2))
1274                                 mode = MODE_IMMEDIATE;
1275                         else if (!strncasecmp(v->value, "fxs", 3)) {
1276                                 mode = MODE_FXS;
1277                                 prefformat = 0x01ff0000; /* All non-voice */
1278                         }
1279                         else if (!strncasecmp(v->value, "fx", 2))
1280                                 mode = MODE_FXO;
1281                         else
1282                                 ast_log(LOG_WARNING, "Unknown mode: %s\n", v->value);
1283                 } else if (!strcasecmp(v->name, "context")) {
1284                         strncpy(context, v->value, sizeof(context)-1);
1285                 } else if (!strcasecmp(v->name, "format")) {
1286                         if (!strcasecmp(v->value, "g723.1")) {
1287                                 prefformat = AST_FORMAT_G723_1;
1288                         } else if (!strcasecmp(v->value, "slinear")) {
1289                                 if (mode == MODE_FXS)
1290                                     prefformat |= AST_FORMAT_SLINEAR;
1291                                 else prefformat = AST_FORMAT_SLINEAR;
1292                         } else if (!strcasecmp(v->value, "ulaw")) {
1293                                 prefformat = AST_FORMAT_ULAW;
1294                         } else
1295                                 ast_log(LOG_WARNING, "Unknown format '%s'\n", v->value);
1296                 } else if (!strcasecmp(v->name, "echocancel")) {
1297                         if (!strcasecmp(v->value, "off")) {
1298                                 echocancel = AEC_OFF;
1299                         } else if (!strcasecmp(v->value, "low")) {
1300                                 echocancel = AEC_LOW;
1301                         } else if (!strcasecmp(v->value, "medium")) {
1302                                 echocancel = AEC_MED;
1303                         } else if (!strcasecmp(v->value, "high")) {
1304                                 echocancel = AEC_HIGH;
1305                         } else 
1306                                 ast_log(LOG_WARNING, "Unknown echo cancellation '%s'\n", v->value);
1307                 } else if (!strcasecmp(v->name, "txgain")) {
1308                         txgain = parse_gain_value(v->name, v->value);
1309                 } else if (!strcasecmp(v->name, "rxgain")) {
1310                         rxgain = parse_gain_value(v->name, v->value);
1311                 }       
1312                 v = v->next;
1313         }
1314         ast_mutex_unlock(&iflock);
1315         /* Make sure we can register our Adtranphone channel type */
1316         if (ast_channel_register(type, tdesc, mode != MODE_FXS ?
1317                          AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | 
1318                          AST_FORMAT_ULAW : prefformat, phone_request)) {
1319                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1320                 ast_config_destroy(cfg);
1321                 __unload_module();
1322                 return -1;
1323         }
1324         ast_config_destroy(cfg);
1325         /* And start the monitor for the first time */
1326         restart_monitor();
1327         return 0;
1328 }
1329
1330 int usecount()
1331 {
1332         int res;
1333         ast_mutex_lock(&usecnt_lock);
1334         res = usecnt;
1335         ast_mutex_unlock(&usecnt_lock);
1336         return res;
1337 }
1338
1339 char *description()
1340 {
1341         return desc;
1342 }
1343
1344 char *key()
1345 {
1346         return ASTERISK_GPL_KEY;
1347 }