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