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