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