remove useless usecnt stuff
[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);
839         if (tmp) {
840                 tmp->tech = cur_tech;
841                 ast_string_field_build(tmp, name, "Phone/%s", i->dev + 5);
842                 tmp->fds[0] = i->fd;
843                 /* XXX Switching formats silently causes kernel panics XXX */
844                 if (i->mode == MODE_FXS &&
845                     ioctl(i->fd, PHONE_QUERY_CODEC, &codec) == 0) {
846                         if (codec.type == LINEAR16)
847                                 tmp->nativeformats =
848                                 tmp->rawreadformat =
849                                 tmp->rawwriteformat =
850                                 AST_FORMAT_SLINEAR;
851                         else {
852                                 tmp->nativeformats =
853                                 tmp->rawreadformat =
854                                 tmp->rawwriteformat =
855                                 prefformat & ~AST_FORMAT_SLINEAR;
856                         }
857                 }
858                 else {
859                         tmp->nativeformats = prefformat;
860                         tmp->rawreadformat = prefformat;
861                         tmp->rawwriteformat = prefformat;
862                 }
863                 ast_setstate(tmp, state);
864                 if (state == AST_STATE_RING)
865                         tmp->rings = 1;
866                 tmp->tech_pvt = i;
867                 ast_copy_string(tmp->context, context, sizeof(tmp->context));
868                 if (!ast_strlen_zero(i->ext))
869                         ast_copy_string(tmp->exten, i->ext, sizeof(tmp->exten));
870                 else
871                         strcpy(tmp->exten, "s");
872                 if (!ast_strlen_zero(i->language))
873                         ast_string_field_set(tmp, language, i->language);
874
875                 /* Don't use ast_set_callerid() here because it will
876                  * generate a NewCallerID event before the NewChannel event */
877                 tmp->cid.cid_num = ast_strdup(i->cid_num);
878                 tmp->cid.cid_ani = ast_strdup(i->cid_num);
879                 tmp->cid.cid_name = ast_strdup(i->cid_name);
880
881                 i->owner = tmp;
882                 if (state != AST_STATE_DOWN) {
883                         if (state == AST_STATE_RING) {
884                                 ioctl(tmp->fds[0], PHONE_RINGBACK);
885                                 i->cpt = 1;
886                         }
887                         if (ast_pbx_start(tmp)) {
888                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
889                                 ast_hangup(tmp);
890                         }
891                 }
892         } else
893                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
894         return tmp;
895 }
896
897 static void phone_mini_packet(struct phone_pvt *i)
898 {
899         int res;
900         char buf[1024];
901         /* Ignore stuff we read... */
902         res = read(i->fd, buf, sizeof(buf));
903         if (res < 1) {
904                 ast_log(LOG_WARNING, "Read returned %d: %s\n", res, strerror(errno));
905                 return;
906         }
907 }
908
909 static void phone_check_exception(struct phone_pvt *i)
910 {
911         int offhook=0;
912         char digit[2] = {0 , 0};
913         union telephony_exception phonee;
914         /* XXX Do something XXX */
915 #if 0
916         if (option_debug)
917                 ast_log(LOG_DEBUG, "Exception!\n");
918 #endif
919         phonee.bytes = ioctl(i->fd, PHONE_EXCEPTION);
920         if (phonee.bits.dtmf_ready)  {
921                 digit[0] = ioctl(i->fd, PHONE_GET_DTMF_ASCII);
922                 if (i->mode == MODE_DIALTONE || i->mode == MODE_FXS || i->mode == MODE_SIGMA) {
923                         ioctl(i->fd, PHONE_PLAY_STOP);
924                         ioctl(i->fd, PHONE_REC_STOP);
925                         ioctl(i->fd, PHONE_CPT_STOP);
926                         i->dialtone = 0;
927                         if (strlen(i->ext) < AST_MAX_EXTENSION - 1)
928                                 strncat(i->ext, digit, sizeof(i->ext) - strlen(i->ext) - 1);
929                         if ((i->mode != MODE_FXS ||
930                              !(phonee.bytes = ioctl(i->fd, PHONE_EXCEPTION)) ||
931                              !phonee.bits.dtmf_ready) &&
932                             ast_exists_extension(NULL, i->context, i->ext, 1, i->cid_num)) {
933                                 /* It's a valid extension in its context, get moving! */
934                                 phone_new(i, AST_STATE_RING, i->context);
935                                 /* No need to restart monitor, we are the monitor */
936                         } else if (!ast_canmatch_extension(NULL, i->context, i->ext, 1, i->cid_num)) {
937                                 /* There is nothing in the specified extension that can match anymore.
938                                    Try the default */
939                                 if (ast_exists_extension(NULL, "default", i->ext, 1, i->cid_num)) {
940                                         /* Check the default, too... */
941                                         phone_new(i, AST_STATE_RING, "default");
942                                         /* XXX This should probably be justified better XXX */
943                                 }  else if (!ast_canmatch_extension(NULL, "default", i->ext, 1, i->cid_num)) {
944                                         /* It's not a valid extension, give a busy signal */
945                                         if (option_debug)
946                                                 ast_log(LOG_DEBUG, "%s can't match anything in %s or default\n", i->ext, i->context);
947                                         ioctl(i->fd, PHONE_BUSY);
948                                         i->cpt = 1;
949                                 }
950                         }
951 #if 0
952                         ast_verbose("Extension is %s\n", i->ext);
953 #endif
954                 }
955         }
956         if (phonee.bits.hookstate) {
957                 offhook = ioctl(i->fd, PHONE_HOOKSTATE);
958                 if (offhook) {
959                         if (i->mode == MODE_IMMEDIATE) {
960                                 phone_new(i, AST_STATE_RING, i->context);
961                         } else if (i->mode == MODE_DIALTONE) {
962                                 /* Reset the extension */
963                                 i->ext[0] = '\0';
964                                 /* Play the dialtone */
965                                 i->dialtone++;
966                                 ioctl(i->fd, PHONE_PLAY_STOP);
967                                 ioctl(i->fd, PHONE_PLAY_CODEC, ULAW);
968                                 ioctl(i->fd, PHONE_PLAY_START);
969                                 i->lastformat = -1;
970                         } else if (i->mode == MODE_SIGMA) {
971                                 /* Reset the extension */
972                                 i->ext[0] = '\0';
973                                 /* Play the dialtone */
974                                 i->dialtone++;
975                                 ioctl(i->fd, PHONE_DIALTONE);
976                         }
977                 } else {
978                         memset(i->ext, 0, sizeof(i->ext));
979                         if (i->cpt)
980                         {
981                                 ioctl(i->fd, PHONE_CPT_STOP);
982                                 i->cpt = 0;
983                         }
984                         ioctl(i->fd, PHONE_PLAY_STOP);
985                         ioctl(i->fd, PHONE_REC_STOP);
986                         i->dialtone = 0;
987                         i->lastformat = -1;
988                 }
989         }
990         if (phonee.bits.pstn_ring) {
991                 ast_verbose("Unit is ringing\n");
992                 phone_new(i, AST_STATE_RING, i->context);
993         }
994         if (phonee.bits.caller_id)
995                 ast_verbose("We have caller ID\n");
996         
997         
998 }
999
1000 static void *do_monitor(void *data)
1001 {
1002         fd_set rfds, efds;
1003         int n, res;
1004         struct phone_pvt *i;
1005         int tonepos = 0;
1006         /* The tone we're playing this round */
1007         struct timeval tv = {0,0};
1008         int dotone;
1009         /* This thread monitors all the frame relay interfaces which are not yet in use
1010            (and thus do not have a separate thread) indefinitely */
1011         while (monitor) {
1012                 /* Don't let anybody kill us right away.  Nobody should lock the interface list
1013                    and wait for the monitor list, but the other way around is okay. */
1014                 /* Lock the interface list */
1015                 if (ast_mutex_lock(&iflock)) {
1016                         ast_log(LOG_ERROR, "Unable to grab interface lock\n");
1017                         return NULL;
1018                 }
1019                 /* Build the stuff we're going to select on, that is the socket of every
1020                    phone_pvt that does not have an associated owner channel */
1021                 n = -1;
1022                 FD_ZERO(&rfds);
1023                 FD_ZERO(&efds);
1024                 i = iflist;
1025                 dotone = 0;
1026                 while (i) {
1027                         if (FD_ISSET(i->fd, &rfds)) 
1028                                 ast_log(LOG_WARNING, "Descriptor %d appears twice (%s)?\n", i->fd, i->dev);
1029                         if (!i->owner) {
1030                                 /* This needs to be watched, as it lacks an owner */
1031                                 FD_SET(i->fd, &rfds);
1032                                 FD_SET(i->fd, &efds);
1033                                 if (i->fd > n)
1034                                         n = i->fd;
1035                                 if (i->dialtone && i->mode != MODE_SIGMA) {
1036                                         /* Remember we're going to have to come back and play
1037                                            more dialtones */
1038                                         if (ast_tvzero(tv)) {
1039                                                 /* If we're due for a dialtone, play one */
1040                                                 if (write(i->fd, DialTone + tonepos, 240) != 240)
1041                                                         ast_log(LOG_WARNING, "Dial tone write error\n");
1042                                         }
1043                                         dotone++;
1044                                 }
1045                         }
1046                         
1047                         i = i->next;
1048                 }
1049                 /* Okay, now that we know what to do, release the interface lock */
1050                 ast_mutex_unlock(&iflock);
1051
1052                 /* Wait indefinitely for something to happen */
1053                 if (dotone && i->mode != MODE_SIGMA) {
1054                         /* If we're ready to recycle the time, set it to 30 ms */
1055                         tonepos += 240;
1056                         if (tonepos >= sizeof(DialTone))
1057                                         tonepos = 0;
1058                         if (ast_tvzero(tv)) {
1059                                 tv = ast_tv(30000, 0);
1060                         }
1061                         res = ast_select(n + 1, &rfds, NULL, &efds, &tv);
1062                 } else {
1063                         res = ast_select(n + 1, &rfds, NULL, &efds, NULL);
1064                         tv = ast_tv(0,0);
1065                         tonepos = 0;
1066                 }
1067                 /* Okay, select has finished.  Let's see what happened.  */
1068                 if (res < 0) {
1069                         if (option_debug)
1070                                 ast_log(LOG_DEBUG, "select return %d: %s\n", res, strerror(errno));
1071                         continue;
1072                 }
1073                 /* If there are no fd's changed, just continue, it's probably time
1074                    to play some more dialtones */
1075                 if (!res)
1076                         continue;
1077                 /* Alright, lock the interface list again, and let's look and see what has
1078                    happened */
1079                 if (ast_mutex_lock(&iflock)) {
1080                         ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1081                         continue;
1082                 }
1083
1084                 i = iflist;
1085                 for(; i; i=i->next) {
1086                         if (FD_ISSET(i->fd, &rfds)) {
1087                                 if (i->owner) {
1088                                         continue;
1089                                 }
1090                                 phone_mini_packet(i);
1091                         }
1092                         if (FD_ISSET(i->fd, &efds)) {
1093                                 if (i->owner) {
1094                                         continue;
1095                                 }
1096                                 phone_check_exception(i);
1097                         }
1098                 }
1099                 ast_mutex_unlock(&iflock);
1100         }
1101         return NULL;
1102         
1103 }
1104
1105 static int restart_monitor()
1106 {
1107         /* If we're supposed to be stopped -- stay stopped */
1108         if (monitor_thread == AST_PTHREADT_STOP)
1109                 return 0;
1110         if (ast_mutex_lock(&monlock)) {
1111                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1112                 return -1;
1113         }
1114         if (monitor_thread == pthread_self()) {
1115                 ast_mutex_unlock(&monlock);
1116                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1117                 return -1;
1118         }
1119         if (monitor_thread != AST_PTHREADT_NULL) {
1120                 if (ast_mutex_lock(&iflock)) {
1121                         ast_mutex_unlock(&monlock);
1122                         ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1123                         return -1;
1124                 }
1125                 monitor = 0;
1126                 while (pthread_kill(monitor_thread, SIGURG) == 0)
1127                         sched_yield();
1128                 pthread_join(monitor_thread, NULL);
1129                 ast_mutex_unlock(&iflock);
1130         }
1131         monitor = 1;
1132         /* Start a new monitor */
1133         if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1134                 ast_mutex_unlock(&monlock);
1135                 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1136                 return -1;
1137         }
1138         ast_mutex_unlock(&monlock);
1139         return 0;
1140 }
1141
1142 static struct phone_pvt *mkif(char *iface, int mode, int txgain, int rxgain)
1143 {
1144         /* Make a phone_pvt structure for this interface */
1145         struct phone_pvt *tmp;
1146         int flags;      
1147         
1148         tmp = malloc(sizeof(struct phone_pvt));
1149         if (tmp) {
1150                 tmp->fd = open(iface, O_RDWR);
1151                 if (tmp->fd < 0) {
1152                         ast_log(LOG_WARNING, "Unable to open '%s'\n", iface);
1153                         free(tmp);
1154                         return NULL;
1155                 }
1156                 if (mode == MODE_FXO) {
1157                         if (ioctl(tmp->fd, IXJCTL_PORT, PORT_PSTN)) {
1158                                 if (option_debug)
1159                                         ast_log(LOG_DEBUG, "Unable to set port to PSTN\n");
1160                         }
1161                 } else {
1162                         if (ioctl(tmp->fd, IXJCTL_PORT, PORT_POTS)) 
1163                                  if (mode != MODE_FXS)
1164                                       ast_log(LOG_DEBUG, "Unable to set port to POTS\n");
1165                 }
1166                 ioctl(tmp->fd, PHONE_PLAY_STOP);
1167                 ioctl(tmp->fd, PHONE_REC_STOP);
1168                 ioctl(tmp->fd, PHONE_RING_STOP);
1169                 ioctl(tmp->fd, PHONE_CPT_STOP);
1170                 if (ioctl(tmp->fd, PHONE_PSTN_SET_STATE, PSTN_ON_HOOK)) {
1171                         if (option_debug)
1172                                 ast_log(LOG_DEBUG, "ioctl(PHONE_PSTN_SET_STATE) failed on %s (%s)\n",iface, strerror(errno));
1173                 }
1174                 if (echocancel != AEC_OFF)
1175                         ioctl(tmp->fd, IXJCTL_AEC_START, echocancel);
1176                 if (silencesupression) 
1177                         tmp->silencesupression = 1;
1178 #ifdef PHONE_VAD
1179                 ioctl(tmp->fd, PHONE_VAD, tmp->silencesupression);
1180 #endif
1181                 tmp->mode = mode;
1182                 flags = fcntl(tmp->fd, F_GETFL);
1183                 fcntl(tmp->fd, F_SETFL, flags | O_NONBLOCK);
1184                 tmp->owner = NULL;
1185                 tmp->lastformat = -1;
1186                 tmp->lastinput = -1;
1187                 tmp->ministate = 0;
1188                 memset(tmp->ext, 0, sizeof(tmp->ext));
1189                 ast_copy_string(tmp->language, language, sizeof(tmp->language));
1190                 ast_copy_string(tmp->dev, iface, sizeof(tmp->dev));
1191                 ast_copy_string(tmp->context, context, sizeof(tmp->context));
1192                 tmp->next = NULL;
1193                 tmp->obuflen = 0;
1194                 tmp->dialtone = 0;
1195                 tmp->cpt = 0;
1196                 ast_copy_string(tmp->cid_num, cid_num, sizeof(tmp->cid_num));
1197                 ast_copy_string(tmp->cid_name, cid_name, sizeof(tmp->cid_name));
1198                 tmp->txgain = txgain;
1199                 ioctl(tmp->fd, PHONE_PLAY_VOLUME, tmp->txgain);
1200                 tmp->rxgain = rxgain;
1201                 ioctl(tmp->fd, PHONE_REC_VOLUME, tmp->rxgain);
1202         }
1203         return tmp;
1204 }
1205
1206 static struct ast_channel *phone_request(const char *type, int format, void *data, int *cause)
1207 {
1208         int oldformat;
1209         struct phone_pvt *p;
1210         struct ast_channel *tmp = NULL;
1211         char *name = data;
1212
1213         /* Search for an unowned channel */
1214         if (ast_mutex_lock(&iflock)) {
1215                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
1216                 return NULL;
1217         }
1218         p = iflist;
1219         while(p) {
1220                 if (p->mode == MODE_FXS ||
1221                     format & (AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW)) {
1222                     size_t length = strlen(p->dev + 5);
1223                 if (strncmp(name, p->dev + 5, length) == 0 &&
1224                     !isalnum(name[length])) {
1225                     if (!p->owner) {
1226                      tmp = phone_new(p, AST_STATE_DOWN, p->context);
1227                      break;
1228                 } else
1229                      *cause = AST_CAUSE_BUSY;
1230             }
1231                 }
1232                 p = p->next;
1233         }
1234         ast_mutex_unlock(&iflock);
1235         restart_monitor();
1236         if (tmp == NULL) {
1237                 oldformat = format;
1238                 format &= (AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW);
1239                 if (!format) {
1240                         ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", oldformat);
1241                         return NULL;
1242                 }
1243         }
1244         return tmp;
1245 }
1246
1247 /* parse gain value from config file */
1248 static int parse_gain_value(char *gain_type, char *value)
1249 {
1250         float gain;
1251
1252         /* try to scan number */
1253         if (sscanf(value, "%f", &gain) != 1)
1254         {
1255                 ast_log(LOG_ERROR, "Invalid %s value '%s' in '%s' config\n",
1256                         value, gain_type, config);
1257                 return DEFAULT_GAIN;
1258         }
1259
1260         /* multiplicate gain by 1.0 gain value */ 
1261         gain = gain * (float)DEFAULT_GAIN;
1262
1263         /* percentage? */
1264         if (value[strlen(value) - 1] == '%')
1265                 return (int)(gain / (float)100);
1266
1267         return (int)gain;
1268 }
1269
1270 static int __unload_module(void)
1271 {
1272         struct phone_pvt *p, *pl;
1273         /* First, take us out of the channel loop */
1274         ast_channel_unregister(cur_tech);
1275         if (!ast_mutex_lock(&iflock)) {
1276                 /* Hangup all interfaces if they have an owner */
1277                 p = iflist;
1278                 while(p) {
1279                         if (p->owner)
1280                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1281                         p = p->next;
1282                 }
1283                 iflist = NULL;
1284                 ast_mutex_unlock(&iflock);
1285         } else {
1286                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1287                 return -1;
1288         }
1289         if (!ast_mutex_lock(&monlock)) {
1290                 if (monitor_thread > AST_PTHREADT_NULL) {
1291                         monitor = 0;
1292                         while (pthread_kill(monitor_thread, SIGURG) == 0)
1293                                 sched_yield();
1294                         pthread_join(monitor_thread, NULL);
1295                 }
1296                 monitor_thread = AST_PTHREADT_STOP;
1297                 ast_mutex_unlock(&monlock);
1298         } else {
1299                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1300                 return -1;
1301         }
1302
1303         if (!ast_mutex_lock(&iflock)) {
1304                 /* Destroy all the interfaces and free their memory */
1305                 p = iflist;
1306                 while(p) {
1307                         /* Close the socket, assuming it's real */
1308                         if (p->fd > -1)
1309                                 close(p->fd);
1310                         pl = p;
1311                         p = p->next;
1312                         /* Free associated memory */
1313                         free(pl);
1314                 }
1315                 iflist = NULL;
1316                 ast_mutex_unlock(&iflock);
1317         } else {
1318                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1319                 return -1;
1320         }
1321                 
1322         return 0;
1323 }
1324
1325 static int unload_module(void)
1326 {
1327         return __unload_module();
1328 }
1329
1330 static int load_module(void)
1331 {
1332         struct ast_config *cfg;
1333         struct ast_variable *v;
1334         struct phone_pvt *tmp;
1335         int mode = MODE_IMMEDIATE;
1336         int txgain = DEFAULT_GAIN, rxgain = DEFAULT_GAIN; /* default gain 1.0 */
1337         cfg = ast_config_load(config);
1338
1339         /* We *must* have a config file otherwise stop immediately */
1340         if (!cfg) {
1341                 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
1342                 return AST_MODULE_LOAD_DECLINE;
1343         }
1344         if (ast_mutex_lock(&iflock)) {
1345                 /* It's a little silly to lock it, but we mind as well just to be sure */
1346                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
1347                 return -1;
1348         }
1349         v = ast_variable_browse(cfg, "interfaces");
1350         while(v) {
1351                 /* Create the interface list */
1352                 if (!strcasecmp(v->name, "device")) {
1353                                 tmp = mkif(v->value, mode, txgain, rxgain);
1354                                 if (tmp) {
1355                                         tmp->next = iflist;
1356                                         iflist = tmp;
1357                                         
1358                                 } else {
1359                                         ast_log(LOG_ERROR, "Unable to register channel '%s'\n", v->value);
1360                                         ast_config_destroy(cfg);
1361                                         ast_mutex_unlock(&iflock);
1362                                         __unload_module();
1363                                         return -1;
1364                                 }
1365                 } else if (!strcasecmp(v->name, "silencesupression")) {
1366                         silencesupression = ast_true(v->value);
1367                 } else if (!strcasecmp(v->name, "language")) {
1368                         ast_copy_string(language, v->value, sizeof(language));
1369                 } else if (!strcasecmp(v->name, "callerid")) {
1370                         ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
1371                 } else if (!strcasecmp(v->name, "mode")) {
1372                         if (!strncasecmp(v->value, "di", 2)) 
1373                                 mode = MODE_DIALTONE;
1374                         else if (!strncasecmp(v->value, "sig", 3))
1375                                 mode = MODE_SIGMA;
1376                         else if (!strncasecmp(v->value, "im", 2))
1377                                 mode = MODE_IMMEDIATE;
1378                         else if (!strncasecmp(v->value, "fxs", 3)) {
1379                                 mode = MODE_FXS;
1380                                 prefformat = 0x01ff0000; /* All non-voice */
1381                         }
1382                         else if (!strncasecmp(v->value, "fx", 2))
1383                                 mode = MODE_FXO;
1384                         else
1385                                 ast_log(LOG_WARNING, "Unknown mode: %s\n", v->value);
1386                 } else if (!strcasecmp(v->name, "context")) {
1387                         ast_copy_string(context, v->value, sizeof(context));
1388                 } else if (!strcasecmp(v->name, "format")) {
1389                         if (!strcasecmp(v->value, "g723.1")) {
1390                                 prefformat = AST_FORMAT_G723_1;
1391                         } else if (!strcasecmp(v->value, "slinear")) {
1392                                 if (mode == MODE_FXS)
1393                                     prefformat |= AST_FORMAT_SLINEAR;
1394                                 else prefformat = AST_FORMAT_SLINEAR;
1395                         } else if (!strcasecmp(v->value, "ulaw")) {
1396                                 prefformat = AST_FORMAT_ULAW;
1397                         } else
1398                                 ast_log(LOG_WARNING, "Unknown format '%s'\n", v->value);
1399                 } else if (!strcasecmp(v->name, "echocancel")) {
1400                         if (!strcasecmp(v->value, "off")) {
1401                                 echocancel = AEC_OFF;
1402                         } else if (!strcasecmp(v->value, "low")) {
1403                                 echocancel = AEC_LOW;
1404                         } else if (!strcasecmp(v->value, "medium")) {
1405                                 echocancel = AEC_MED;
1406                         } else if (!strcasecmp(v->value, "high")) {
1407                                 echocancel = AEC_HIGH;
1408                         } else 
1409                                 ast_log(LOG_WARNING, "Unknown echo cancellation '%s'\n", v->value);
1410                 } else if (!strcasecmp(v->name, "txgain")) {
1411                         txgain = parse_gain_value(v->name, v->value);
1412                 } else if (!strcasecmp(v->name, "rxgain")) {
1413                         rxgain = parse_gain_value(v->name, v->value);
1414                 }       
1415                 v = v->next;
1416         }
1417         ast_mutex_unlock(&iflock);
1418
1419         if (mode == MODE_FXS) {
1420                 phone_tech_fxs.capabilities = prefformat;
1421                 cur_tech = &phone_tech_fxs;
1422         } else
1423                 cur_tech = (struct ast_channel_tech *) &phone_tech;
1424
1425         /* Make sure we can register our Adtranphone channel type */
1426
1427         if (ast_channel_register(cur_tech)) {
1428                 ast_log(LOG_ERROR, "Unable to register channel class 'Phone'\n");
1429                 ast_config_destroy(cfg);
1430                 __unload_module();
1431                 return -1;
1432         }
1433         ast_config_destroy(cfg);
1434         /* And start the monitor for the first time */
1435         restart_monitor();
1436         return 0;
1437 }
1438
1439 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Linux Telephony API Support");