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