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