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