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