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