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