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