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