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