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