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