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