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