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