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