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