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