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