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