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