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