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