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