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