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