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