61905bf1524aee42b0d1e3bcd10824966ce04a7f
[lcr.git] / chan_lcr.c
1 /*****************************************************************************\
2 **                                                                           **
3 ** Linux Call Router                                                         **
4 **                                                                           **
5 **---------------------------------------------------------------------------**
6 ** Copyright: Andreas Eversberg                                              **
7 **                                                                           **
8 ** Asterisk socket client                                                    **
9 **                                                                           **
10 \*****************************************************************************/
11
12 /*
13
14 Registering to LCR:
15
16 To connect, open an LCR socket and send a MESSAGE_HELLO to socket with
17 the application name. This name is unique an can be used for routing calls.
18 Now the channel driver is linked to LCR and can receive and make calls.
19
20
21 Call is initiated by LCR:
22
23 If a call is received from LCR, a MESSAGE_NEWREF is received first.
24 The ref_was_assigned ist set to 1.
25 A new chan_call instance is created. The call reference (ref) is given by
26 the received MESSAGE_NEWREF. The state is CHAN_LCR_STATE_IN_PREPARE.
27 After receiving MESSAGE_SETUP from LCR, the ast_channel instance is created
28 using ast_channel_alloc(1).  The setup information is given to asterisk.
29 The new Asterisk instance pointer (ast) is stored to chan_call structure.
30 The state changes to CHAN_LCR_STATE_IN_SETUP.
31
32
33 Call is initiated by Asterisk:
34
35 If a call is requested from Asterisk, a new chan_call instance is created.
36 The new Asterisk instance pointer (ast) is stored to chan_call structure.
37 The current call ref is set to 0, the state is CHAN_LCR_STATE_OUT_PREPARE.
38 If the call is received (lcr_call) A MESSAGE_NEWREF is sent to LCR requesting
39 a new call reference (ref).
40 The ref_was_assigned ist set to 1.
41 Further dialing information is queued.
42 After the new callref is received by special MESSAGE_NEWREF reply, new ref
43 is stored in the chan_call structure. 
44 The setup information is sent to LCR using MESSAGE_SETUP.
45 The state changes to CHAN_LCR_STATE_OUT_SETUP.
46
47
48 Call is in process:
49
50 During call process, messages are received and sent.
51 The state changes accordingly.
52 Any message is allowed to be sent to LCR at any time except MESSAGE_RELEASE.
53 If a MESSAGE_OVERLAP is received, further dialing is required.
54 Queued dialing information, if any, is sent to LCR using MESSAGE_DIALING.
55 In this case, the state changes to CHAN_LCR_STATE_OUT_DIALING.
56
57
58 Call is released by LCR:
59
60 A MESSAGE_RELEASE is received with the call reference (ref) to be released.
61 The current ref is set to 0, to indicate released reference.
62 The ref_was_assigned==1 shows that there is no other ref to be assigned.
63 The state changes to CHAN_LCR_STATE_RELEASE.
64 ast_queue_hangup() is called, if asterisk instance (ast) exists, if not,
65 the chan_call instance is destroyed.
66 After lcr_hangup() is called-back by Asterisk, the chan_call instance
67 is destroyed, because the current ref is set to 0 and the state equals
68 CHAN_LCR_STATE_RELEASE.
69 If the ref is 0 and the state is not CHAN_LCR_STATE_RELEASE, see the proceedure
70 "Call is released by Asterisk".
71
72
73 Call is released by Asterisk:
74
75 lcr_hangup() is called-back by Asterisk. If the call reference (ref) is set,
76 a MESSAGE_RELEASE is sent to LCR and the chan_call instance is destroyed.
77 If the ref is 0 and the state is not CHAN_LCR_STATE_RELEASE, the new state is
78 set to CHAN_LCR_STATE_RELEASE.
79 The ref_was_assigned==0 shows that a ref is still requested.
80 Later, if the MESSAGE_NEWREF reply is received, a MESSAGE_RELEASE is sent to
81 LCR and the chan_call instance is destroyed.
82 If the ref is 0 and the state is CHAN_LCR_STATE_RELEASE, see the proceedure
83 "Call is released by LCR".
84
85
86 Locking issues:
87
88 The deadlocking problem:
89
90 - chan_lcr locks chan_lock and waits inside ast_queue_xxxx() for ast_channel
91 to be unlocked.
92 - ast_channel thread locks ast_channel and calls a tech function and waits
93 there for chan_lock to be unlocked.
94
95 The solution:
96
97 Never call ast_queue_xxxx() if ast_channel is not locked and don't wait until
98 ast_channel can be locked. All messages to asterisk are queued inside call
99 instance and will be handled using a try-lock to get ast_channel lock.
100 If it succeeds to lock ast_channel, the ast_queue_xxxx can safely called even
101 if the lock is incremented and decremented there.
102
103 Exception: Calling ast_queue_frame inside ast->tech->read is safe, because
104 it is called from ast_channel process which has already locked ast_channel.
105
106 */
107
108
109 /* Choose if you want to have chan_lcr for Asterisk 1.4.x or CallWeaver 1.2.x */
110 #define LCR_FOR_ASTERISK
111 /* #define LCR_FOR_CALLWEAVER */
112
113 #include <stdio.h>
114 #include <stdlib.h>
115 #include <string.h>
116 #include <stdarg.h>
117 #include <errno.h>
118 #include <sys/types.h>
119 #include <time.h>
120 //#include <signal.h>
121 #include <unistd.h>
122 #include <fcntl.h>
123 #include <sys/ioctl.h>
124 #include <sys/socket.h>
125 #include <sys/un.h>
126
127 #include <semaphore.h>
128
129 #define HAVE_ATTRIBUTE_always_inline 1
130 #define HAVE_ARPA_INET_H 1
131 #define HAVE_TIMERSUB 1
132 #define HAVE_STRTOQ 1
133 #define HAVE_INET_ATON 1
134
135 #include <asterisk/compiler.h>
136 #ifdef LCR_FOR_ASTERISK
137 #include <asterisk/buildopts.h>
138 #endif
139 #include <asterisk/module.h>
140 #include <asterisk/channel.h>
141 #include <asterisk/config.h>
142 #include <asterisk/logger.h>
143 #include <asterisk/pbx.h>
144 #include <asterisk/options.h>
145 #include <asterisk/io.h>
146 #include <asterisk/frame.h>
147 #include <asterisk/translate.h>
148 #include <asterisk/cli.h>
149 #include <asterisk/musiconhold.h>
150 #include <asterisk/dsp.h>
151 #include <asterisk/translate.h>
152 #include <asterisk/file.h>
153 #ifdef LCR_FOR_ASTERISK
154 #include <asterisk/callerid.h>
155 #endif
156 #ifdef LCR_FOR_CALLWEAVER
157 #include <asterisk/phone_no_utils.h>
158 #endif
159
160 #include <asterisk/indications.h>
161 #include <asterisk/app.h>
162 #include <asterisk/features.h>
163 #include <asterisk/sched.h>
164
165 #include "extension.h"
166 #include "message.h"
167 #include "callerid.h"
168 #include "lcrsocket.h"
169 #include "cause.h"
170 #include "bchannel.h"
171 #include "options.h"
172 #include "chan_lcr.h"
173
174 CHAN_LCR_STATE // state description structure
175 MESSAGES // message text
176
177 #ifdef LCR_FOR_CALLWEAVER
178 AST_MUTEX_DEFINE_STATIC(rand_lock);
179 #endif
180
181 unsigned char flip_bits[256];
182
183 #ifdef LCR_FOR_CALLWEAVER
184 static struct ast_frame nullframe = { AST_FRAME_NULL, };
185 #endif
186
187 int lcr_debug=1;
188 int mISDN_created=1;
189
190 char lcr_type[]="lcr";
191
192 #ifdef LCR_FOR_CALLWEAVER
193 static ast_mutex_t usecnt_lock;
194 static int usecnt=0;
195 static char *desc = "Channel driver for mISDN/LCR Support (Bri/Pri)";
196 #endif
197
198 pthread_t chan_tid;
199 ast_mutex_t chan_lock; /* global lock */
200 ast_mutex_t log_lock; /* logging log */
201 int quit;
202
203 int glob_channel = 0;
204
205 int lcr_sock = -1;
206
207 struct admin_list {
208         struct admin_list *next;
209         struct admin_message msg;
210 } *admin_first = NULL;
211
212 static struct ast_channel_tech lcr_tech;
213
214 /*
215  * logging
216  */
217 void chan_lcr_log(int type, const char *file, int line, const char *function, struct chan_call *call, struct ast_channel *ast, const char *fmt, ...)
218 {
219         char buffer[1024];
220         char call_text[128] = "NULL";
221         char ast_text[128] = "NULL";
222         va_list args;
223
224         ast_mutex_lock(&log_lock);
225
226         va_start(args,fmt);
227         vsnprintf(buffer,sizeof(buffer)-1,fmt,args);
228         buffer[sizeof(buffer)-1]=0;
229         va_end(args);
230
231         if (call)
232                 sprintf(call_text, "%d", call->ref);
233         if (ast)
234                 strncpy(ast_text, ast->name, sizeof(ast_text)-1);
235         ast_text[sizeof(ast_text)-1] = '\0';
236         
237         ast_log(type, file, line, function, "[call=%s ast=%s] %s", call_text, ast_text, buffer);
238
239         ast_mutex_unlock(&log_lock);
240 }
241
242 /*
243  * channel and call instances
244  */
245 struct chan_call *call_first;
246
247 /*
248  * find call by ref
249  * special case: 0: find new ref, that has not been assigned a ref yet
250  */
251
252 struct chan_call *find_call_ref(unsigned int ref)
253 {
254         struct chan_call *call = call_first;
255         int assigned = (ref > 0);
256         
257         while(call) {
258                 if (call->ref == ref && call->ref_was_assigned == assigned)
259                         break;
260                 call = call->next;
261         }
262         return(call);
263 }
264
265 void free_call(struct chan_call *call)
266 {
267         struct chan_call **temp = &call_first;
268
269         while(*temp) {
270                 if (*temp == call) {
271                         *temp = (*temp)->next;
272                         if (call->pipe[0] > -1)
273                                 close(call->pipe[0]);
274                         if (call->pipe[1] > -1)
275                                 close(call->pipe[1]);
276                         if (call->bchannel) {
277                                 if (call->bchannel->call != call)
278                                         CERROR(call, NULL, "Linked bchannel structure has no link to us.\n");
279                                 call->bchannel->call = NULL;
280                         }
281                         if (call->bridge_call) {
282                                 if (call->bridge_call->bridge_call != call)
283                                         CERROR(call, NULL, "Linked call structure has no link to us.\n");
284                                 call->bridge_call->bridge_call = NULL;
285                         }
286                         if (call->trans)
287                                 ast_translator_free_path(call->trans);
288                         if (call->dsp)
289                                 ast_dsp_free(call->dsp);
290                         CDEBUG(call, NULL, "Call instance freed.\n");
291                         free(call);
292                         return;
293                 }
294                 temp = &((*temp)->next);
295         }
296         CERROR(call, NULL, "Call instance not found in list.\n");
297 }
298
299 struct chan_call *alloc_call(void)
300 {
301         struct chan_call **callp = &call_first;
302
303         while(*callp)
304                 callp = &((*callp)->next);
305
306         *callp = (struct chan_call *)calloc(1, sizeof(struct chan_call));
307         if (*callp)
308                 memset(*callp, 0, sizeof(struct chan_call));
309         if (pipe((*callp)->pipe) < 0) {
310                 CERROR(*callp, NULL, "Failed to create pipe.\n");
311                 free_call(*callp);
312                 return(NULL);
313         }
314         fcntl((*callp)->pipe[0], F_SETFL, O_NONBLOCK);
315         CDEBUG(*callp, NULL, "Call instance allocated.\n");
316         return(*callp);
317 }
318
319 unsigned short new_bridge_id(void)
320 {
321         struct chan_call *call;
322         unsigned short id = 1;
323
324         /* search for lowest bridge id that is not in use and not 0 */
325         while(id) {
326                 call = call_first;
327                 while(call) {
328                         if (call->bridge_id == id)
329                                 break;
330                         call = call->next;
331                 }
332                 if (!call)
333                         break;
334                 id++;
335         }
336         CDEBUG(NULL, NULL, "New bridge ID %d.\n", id);
337         return(id);
338 }
339
340 /*
341  * enque message to LCR
342  */
343 int send_message(int message_type, unsigned int ref, union parameter *param)
344 {
345         struct admin_list *admin, **adminp;
346
347         if (lcr_sock < 0) {
348                 CDEBUG(NULL, NULL, "Ignoring message %d, because socket is closed.\n", message_type);
349                 return -1;
350         }
351         CDEBUG(NULL, NULL, "Sending %s to socket.\n", messages_txt[message_type]);
352
353         adminp = &admin_first;
354         while(*adminp)
355                 adminp = &((*adminp)->next);
356         admin = (struct admin_list *)calloc(1, sizeof(struct admin_list));
357         if (!admin) {
358                 CERROR(NULL, NULL, "No memory for message to LCR.\n");
359                 return -1;
360         }
361         *adminp = admin;
362
363         admin->msg.message = ADMIN_MESSAGE;
364         admin->msg.u.msg.type = message_type;
365         admin->msg.u.msg.ref = ref;
366         memcpy(&admin->msg.u.msg.param, param, sizeof(union parameter));
367
368         return(0);
369 }
370
371 /*
372  * apply options (in locked state)
373  */
374 void apply_opt(struct chan_call *call, char *data)
375 {
376         union parameter newparam;
377         char string[1024], *p = string, *opt, *key;
378         int gain, i;
379
380         if (!data[0])
381                 return; // no opts
382
383         strncpy(string, data, sizeof(string)-1);
384         string[sizeof(string)-1] = '\0';
385
386         /* parse options */
387         while((opt = strsep(&p, ":"))) {
388                 switch(opt[0]) {
389                 case 'd':
390                         if (opt[1] == '\0') {
391                                 CERROR(call, call->ast, "Option 'd' (display) expects parameter.\n", opt);
392                                 break;
393                         }
394                         CDEBUG(call, call->ast, "Option 'd' (display) with text '%s'.\n", opt+1);
395                         if (call->state == CHAN_LCR_STATE_OUT_PREPARE)
396                                 strncpy(call->display, opt+1, sizeof(call->display)-1);
397                         else {
398                                 memset(&newparam, 0, sizeof(union parameter));
399                                 strncpy(newparam.notifyinfo.display, opt+1, sizeof(newparam.notifyinfo.display)-1);
400                                 send_message(MESSAGE_NOTIFY, call->ref, &newparam);
401                         }
402                         break;
403                 case 'n':
404                         if (opt[1] != '\0') {
405                                 CERROR(call, call->ast, "Option 'n' (no DTMF) expects no parameter.\n", opt);
406                                 break;
407                         }
408                         CDEBUG(call, call->ast, "Option 'n' (no DTMF).\n");
409                         if (call->dsp_dtmf) {
410                                 call->dsp_dtmf = 0;
411                                 if (call->bchannel)
412                                         bchannel_dtmf(call->bchannel, 0);
413                         }
414                         break;
415                 case 'c':
416                         if (opt[1] == '\0') {
417                                 CERROR(call, call->ast, "Option 'c' (encrypt) expects key parameter.\n", opt);
418                                 break;
419                         }
420                         key = opt+1;
421                         /* check for 0xXXXX... type of key */
422                         if (!!strncmp((char *)key, "0x", 2)) {
423                                 CERROR(call, call->ast, "Option 'c' (encrypt) expects key parameter starting with '0x'.\n", opt);
424                                 break;
425                         }
426                         key+=2;
427                         if (strlen(key) > 56*2 || (strlen(key) % 1)) {
428                                 CERROR(call, call->ast, "Option 'c' (encrypt) expects key parameter with max 56 bytes ('0x' + 112 characters)\n", opt);
429                                 break;
430                         }
431                         i = 0;
432                         while(*key) {
433                                 if (*key>='0' && *key<='9')
434                                         call->bf_key[i] = (*key-'0') << 8;
435                                 else if (*key>='a' && *key<='f')
436                                         call->bf_key[i] = (*key-'a'+10) << 8;
437                                 else if (*key>='A' && *key<='F')
438                                         call->bf_key[i] = (*key-'A'+10) << 8;
439                                 else
440                                         break;
441                                 key++;
442                                 if (*key>='0' && *key<='9')
443                                         call->bf_key[i] += (*key - '0');
444                                 else if (*key>='a' && *key<='f')
445                                         call->bf_key[i] += (*key - 'a' + 10);
446                                 else if (*key>='A' && *key<='F')
447                                         call->bf_key[i] += (*key - 'A' + 10);
448                                 else
449                                         break;
450                                 key++;
451                                 i++;
452                         }
453                         if (*key) {
454                                 CERROR(call, call->ast, "Option 'c' (encrypt) expects key parameter with hex values 0-9,a-f.\n");
455                                 break;
456                         }
457                         call->bf_len = i;
458                         CDEBUG(call, call->ast, "Option 'c' (encrypt) blowfish key '%s' (len=%d).\n", opt+1, i);
459                         if (call->bchannel)
460                                 bchannel_blowfish(call->bchannel, call->bf_key, call->bf_len);
461                         break;
462                 case 'h':
463                         if (opt[1] != '\0') {
464                                 CERROR(call, call->ast, "Option 'h' (HDLC) expects no parameter.\n", opt);
465                                 break;
466                         }
467                         CDEBUG(call, call->ast, "Option 'h' (HDLC).\n");
468                         if (!call->hdlc)
469                                 call->hdlc = 1;
470                         break;
471                 case 't':
472                         if (opt[1] != '\0') {
473                                 CERROR(call, call->ast, "Option 't' (no_dsp) expects no parameter.\n", opt);
474                                 break;
475                         }
476                         CDEBUG(call, call->ast, "Option 't' (no dsp).\n");
477                         if (!call->nodsp)
478                                 call->nodsp = 1;
479                         break;
480                 case 'e':
481                         if (opt[1] == '\0') {
482                                 CERROR(call, call->ast, "Option 'e' (echo cancel) expects parameter.\n", opt);
483                                 break;
484                         }
485                         CDEBUG(call, call->ast, "Option 'e' (echo cancel) with config '%s'.\n", opt+1);
486                         strncpy(call->pipeline, opt+1, sizeof(call->pipeline)-1);
487                         if (call->bchannel)
488                                 bchannel_pipeline(call->bchannel, call->pipeline);
489                         break;
490                 case 'f':
491                         if (opt[1] == '\0') {
492                                 CERROR(call, call->ast, "Option 'f' (faxdetect) expects parameter.\n", opt);
493                                 break;
494                         }
495                         call->faxdetect=atoi(opt+1);
496                         if (!call->dsp)
497                                 call->dsp=ast_dsp_new();
498                         if (call->dsp) {
499                                 #ifdef LCR_FOR_CALLWEAVER
500                                 ast_dsp_set_features(call->dsp, DSP_FEATURE_DTMF_DETECT| DSP_FEATURE_FAX_CNG_DETECT);
501                                 #endif
502                                 #ifdef LCR_FOR_ASTERISK
503                                 #ifdef DSP_FEATURE_DTMF_DETECT
504                                 ast_dsp_set_features(call->dsp, DSP_FEATURE_DTMF_DETECT| DSP_FEATURE_FAX_DETECT);
505                                 #else
506                                 ast_dsp_set_features(call->dsp, DSP_FEATURE_DIGIT_DETECT| DSP_FEATURE_FAX_DETECT);
507                                 #endif
508
509                                 #endif
510                                 if (!call->trans)
511                                         #ifdef LCR_FOR_CALLWEAVER
512                                         call->trans=ast_translator_build_path(AST_FORMAT_SLINEAR, 8000, (options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW, 8000);
513                                         #endif
514                                         #ifdef LCR_FOR_ASTERISK
515                                         call->trans=ast_translator_build_path(AST_FORMAT_SLINEAR, (options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW);
516                                         #endif
517                         }
518                         CDEBUG(call, call->ast, "Option 'f' (faxdetect) with config '%s'.\n", call->faxdetect);
519                         break;
520                 case 'r':
521                         if (opt[1] != '\0') {
522                                 CERROR(call, call->ast, "Option 'r' (re-buffer 160 bytes) expects no parameter.\n", opt);
523                                 break;
524                         }
525                         CDEBUG(call, call->ast, "Option 'r' (re-buffer 160 bytes)");
526                         call->rebuffer = 1;
527                         call->framepos = 0;
528                         break;
529                 case 's':
530                         if (opt[1] != '\0') {
531                                 CERROR(call, call->ast, "Option 's' (inband DTMF) expects no parameter.\n", opt);
532                                 break;
533                         }
534                         CDEBUG(call, call->ast, "Option 's' (inband DTMF).\n");
535                         call->inband_dtmf = 1;
536                         break;
537                 case 'v':
538                         if (opt[1] != 'r' && opt[1] != 't') {
539                                 CERROR(call, call->ast, "Option 'v' (volume) expects parameter.\n", opt);
540                                 break;
541                         }
542                         gain = atoi(opt+2);
543                         if (gain < -8 || gain >8) {
544                                 CERROR(call, call->ast, "Option 'v' (volume) expects parameter in range of -8 through 8.\n");
545                                 break;
546                         }
547                         CDEBUG(call, call->ast, "Option 'v' (volume) with gain 2^%d.\n", gain);
548                         if (opt[1] == 'r') {
549                                 call->rx_gain = gain;
550                                 if (call->bchannel)
551                                         bchannel_gain(call->bchannel, call->rx_gain, 0);
552                         } else {
553                                 call->tx_gain = gain;
554                                 if (call->bchannel)
555                                         bchannel_gain(call->bchannel, call->tx_gain, 1);
556                         }
557                         break;
558                 case 'k':
559                         if (opt[1] != '\0') {
560                                 CERROR(call, call->ast, "Option 'k' (keypad) expects no parameter.\n", opt);
561                                 break;
562                         }
563                         CDEBUG(call, call->ast, "Option 'k' (keypad).\n");
564                         if (!call->keypad)
565                                 call->keypad = 1;
566                         break;
567                 default:
568                         CERROR(call, call->ast, "Option '%s' unknown.\n", opt);
569                 }
570         }               
571         
572         /* re-open, if bchannel is created */
573         if (call->bchannel && call->bchannel->b_sock > -1) {
574                 bchannel_destroy(call->bchannel);
575                 if (bchannel_create(call->bchannel, ((call->nodsp || call->faxdetect > 0)?1:0) + ((call->hdlc)?2:0)))
576                         bchannel_activate(call->bchannel, 1);
577         }
578 }
579
580 /*
581  * send setup info to LCR
582  * this function is called, when asterisk call is received and ref is received
583  */
584 static void send_setup_to_lcr(struct chan_call *call)
585 {
586         union parameter newparam;
587         struct ast_channel *ast = call->ast;
588
589         if (!call->ast || !call->ref)
590                 return;
591
592         CDEBUG(call, call->ast, "Sending setup to LCR. (interface=%s dialstring=%s, cid=%s)\n", call->interface, call->dialstring, call->cid_num);
593
594         /* send setup message to LCR */
595         memset(&newparam, 0, sizeof(union parameter));
596         newparam.setup.dialinginfo.itype = INFO_ITYPE_ISDN;     
597         newparam.setup.dialinginfo.ntype = INFO_NTYPE_UNKNOWN;
598         if (call->keypad)
599                 strncpy(newparam.setup.dialinginfo.keypad, call->dialstring, sizeof(newparam.setup.dialinginfo.keypad)-1);
600         else
601                 strncpy(newparam.setup.dialinginfo.id, call->dialstring, sizeof(newparam.setup.dialinginfo.id)-1);
602         strncpy(newparam.setup.dialinginfo.interfaces, call->interface, sizeof(newparam.setup.dialinginfo.interfaces)-1);
603         newparam.setup.callerinfo.itype = INFO_ITYPE_CHAN;      
604         newparam.setup.callerinfo.ntype = INFO_NTYPE_UNKNOWN;
605         strncpy(newparam.setup.callerinfo.display, call->display, sizeof(newparam.setup.callerinfo.display)-1);
606         call->display[0] = '\0';
607         if (call->cid_num[0])
608                 strncpy(newparam.setup.callerinfo.id, call->cid_num, sizeof(newparam.setup.callerinfo.id)-1);
609         if (call->cid_name[0])
610                 strncpy(newparam.setup.callerinfo.name, call->cid_name, sizeof(newparam.setup.callerinfo.name)-1);
611         if (call->cid_rdnis[0]) {
612                 strncpy(newparam.setup.redirinfo.id, call->cid_rdnis, sizeof(newparam.setup.redirinfo.id)-1);
613                 newparam.setup.redirinfo.itype = INFO_ITYPE_CHAN;       
614                 newparam.setup.redirinfo.ntype = INFO_NTYPE_UNKNOWN;    
615         }
616         switch(ast->cid.cid_pres & AST_PRES_RESTRICTION) {
617                 case AST_PRES_RESTRICTED:
618                 newparam.setup.callerinfo.present = INFO_PRESENT_RESTRICTED;
619                 break;
620                 case AST_PRES_UNAVAILABLE:
621                 newparam.setup.callerinfo.present = INFO_PRESENT_NOTAVAIL;
622                 break;
623                 case AST_PRES_ALLOWED:
624                 default:
625                 newparam.setup.callerinfo.present = INFO_PRESENT_ALLOWED;
626         }
627         switch(ast->cid.cid_ton) {
628                 case 4:
629                 newparam.setup.callerinfo.ntype = INFO_NTYPE_SUBSCRIBER;
630                 break;
631                 case 2:
632                 newparam.setup.callerinfo.ntype = INFO_NTYPE_NATIONAL;
633                 break;
634                 case 1:
635                 newparam.setup.callerinfo.ntype = INFO_NTYPE_INTERNATIONAL;
636                 break;
637                 default:
638                 newparam.setup.callerinfo.ntype = INFO_NTYPE_UNKNOWN;
639         }
640         newparam.setup.capainfo.bearer_capa = ast->transfercapability;
641         newparam.setup.capainfo.bearer_mode = INFO_BMODE_CIRCUIT;
642         if (call->hdlc)
643                 newparam.setup.capainfo.source_mode = B_MODE_HDLC;
644         else {
645                 newparam.setup.capainfo.source_mode = B_MODE_TRANSPARENT;
646                 newparam.setup.capainfo.bearer_info1 = (options.law=='a')?3:2;
647         }
648         newparam.setup.capainfo.hlc = INFO_HLC_NONE;
649         newparam.setup.capainfo.exthlc = INFO_HLC_NONE;
650         send_message(MESSAGE_SETUP, call->ref, &newparam);
651
652         /* change to outgoing setup state */
653         call->state = CHAN_LCR_STATE_OUT_SETUP;
654 }
655
656 /*
657  * send dialing info to LCR
658  * this function is called, when setup acknowledge is received and dialing
659  * info is available.
660  */
661 static void send_dialque_to_lcr(struct chan_call *call)
662 {
663         union parameter newparam;
664
665         if (!call->ast || !call->ref || !call->dialque[0])
666                 return;
667         
668         CDEBUG(call, call->ast, "Sending dial queue to LCR. (dialing=%s)\n", call->dialque);
669
670         /* send setup message to LCR */
671         memset(&newparam, 0, sizeof(union parameter));
672         if (call->keypad)
673                 strncpy(newparam.information.keypad, call->dialque, sizeof(newparam.information.keypad)-1);
674         else
675                 strncpy(newparam.information.id, call->dialque, sizeof(newparam.information.id)-1);
676         call->dialque[0] = '\0';
677         send_message(MESSAGE_INFORMATION, call->ref, &newparam);
678 }
679
680 /*
681  * in case of a bridge, the unsupported message can be forwarded directly
682  * to the remote call.
683  */
684 static void bridge_message_if_bridged(struct chan_call *call, int message_type, union parameter *param)
685 {
686         /* check bridge */
687         if (!call) return;
688         if (!call->bridge_call) return;
689         CDEBUG(call, NULL, "Sending message due bridging.\n");
690         send_message(message_type, call->bridge_call->ref, param);
691 }
692
693 /*
694  * send release message to LCR and import bchannel if exported
695  */
696 static void send_release_and_import(struct chan_call *call, int cause, int location)
697 {
698         union parameter newparam;
699
700         /* importing channel */
701         if (call->bchannel) {
702                 memset(&newparam, 0, sizeof(union parameter));
703                 newparam.bchannel.type = BCHANNEL_RELEASE;
704                 newparam.bchannel.handle = call->bchannel->handle;
705                 send_message(MESSAGE_BCHANNEL, call->ref, &newparam);
706         }
707         /* sending release */
708         memset(&newparam, 0, sizeof(union parameter));
709         newparam.disconnectinfo.cause = cause;
710         newparam.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
711         send_message(MESSAGE_RELEASE, call->ref, &newparam);
712 }
713
714 /*
715  * check if extension matches and start asterisk
716  * if it can match, proceed
717  * if not, release
718  */
719 static void lcr_start_pbx(struct chan_call *call, struct ast_channel *ast, int complete)
720 {
721         int cause, ret;
722         union parameter newparam;
723         char *exten = ast->exten;
724         if (!*exten)
725                 exten = "s";
726
727         CDEBUG(call, ast, "Try to start pbx. (exten=%s context=%s complete=%s)\n", exten, ast->context, complete?"yes":"no");
728         
729         if (complete) {
730                 /* if not match */
731                 if (!ast_canmatch_extension(ast, ast->context, exten, 1, call->oad)) {
732                         CDEBUG(call, ast, "Got 'sending complete', but extension '%s' will not match at context '%s' - releasing.\n", exten, ast->context);
733                         cause = 1;
734                         goto release;
735                 }
736                 if (!ast_exists_extension(ast, ast->context, exten, 1, call->oad)) {
737                         CDEBUG(call, ast, "Got 'sending complete', but extension '%s' would match at context '%s', if more digits would be dialed - releasing.\n", exten, ast->context);
738                         cause = 28;
739                         goto release;
740                 }
741                 CDEBUG(call, ast, "Got 'sending complete', extensions matches.\n");
742                 /* send setup acknowledge to lcr */
743                 memset(&newparam, 0, sizeof(union parameter));
744                 send_message(MESSAGE_PROCEEDING, call->ref, &newparam);
745
746                 /* change state */
747                 call->state = CHAN_LCR_STATE_IN_PROCEEDING;
748
749                 goto start;
750         }
751
752         if (ast_canmatch_extension(ast, ast->context, exten, 1, call->oad)) {
753                 /* send setup acknowledge to lcr */
754                 if (call->state != CHAN_LCR_STATE_IN_DIALING) {
755                         memset(&newparam, 0, sizeof(union parameter));
756                         send_message(MESSAGE_OVERLAP, call->ref, &newparam);
757                 }
758
759                 /* change state */
760                 call->state = CHAN_LCR_STATE_IN_DIALING;
761
762                 /* if match, start pbx */
763                 if (ast_exists_extension(ast, ast->context, exten, 1, call->oad)) {
764                         CDEBUG(call, ast, "Extensions matches.\n");
765                         goto start;
766                 }
767
768                 /* if can match */
769                 CDEBUG(call, ast, "Extensions may match, if more digits are dialed.\n");
770                 return;
771         }
772
773         if (!*ast->exten) {
774                 /* if can match */
775                 CDEBUG(call, ast, "There is no 's' extension (and we tried to match it implicitly). Extensions may match, if more digits are dialed.\n");
776                 return;
777         }
778
779         /* if not match */
780         cause = 1;
781         release:
782         /* release lcr */
783         CDEBUG(call, ast, "Releasing due to extension missmatch.\n");
784         send_release_and_import(call, cause, LOCATION_PRIVATE_LOCAL);
785         call->ref = 0;
786         /* release asterisk */
787         ast->hangupcause = call->cause;
788         /* change to release state */
789         call->state = CHAN_LCR_STATE_RELEASE;
790         ast_hangup(ast); // call will be destroyed here
791         return;
792         
793         start:
794         /* send setup to asterisk */
795         CDEBUG(call, ast, "Starting call to Asterisk due to matching extension.\n");
796
797         #ifdef LCR_FOR_CALLWEAVER       
798         ast->type = "LCR";
799         snprintf(ast->name, sizeof(ast->name), "LCR/%s-%04x",ast->cid.cid_num, ast_random() & 0xffff);
800         #endif
801         
802         ret = ast_pbx_start(ast);
803         if (ret < 0) {
804                 cause = (ret==-2)?34:27;
805                 goto release;
806         }
807         call->pbx_started = 1;
808                 ast_setstate(ast, AST_STATE_RING);
809 }
810
811 /*
812  * incoming setup from LCR
813  */
814 static void lcr_in_setup(struct chan_call *call, int message_type, union parameter *param)
815 {
816         struct ast_channel *ast;
817
818         CDEBUG(call, NULL, "Incomming setup from LCR. (callerid %s, dialing %s)\n", param->setup.callerinfo.id, param->setup.dialinginfo.id);
819
820         /* create asterisk channel instrance */
821
822         #ifdef LCR_FOR_CALLWEAVER
823         ast = ast_channel_alloc(1);
824         #endif
825
826         #ifdef LCR_FOR_ASTERISK
827         ast = ast_channel_alloc(1, AST_STATE_RESERVED, NULL, NULL, "", NULL, "", 0, "%s/%d", lcr_type, ++glob_channel);
828         #endif
829         
830         if (!ast) {
831                 /* release */
832                 CERROR(call, NULL, "Failed to create Asterisk channel - releasing.\n");
833                 send_release_and_import(call, CAUSE_RESSOURCEUNAVAIL, LOCATION_PRIVATE_LOCAL);
834                 /* remove call */
835                 free_call(call);
836                 return;
837         }
838         /* link together */
839         call->ast = ast;
840         ast->tech_pvt = call;
841         ast->tech = &lcr_tech;
842         ast->fds[0] = call->pipe[0];
843         
844         /* fill setup information */
845         if (param->setup.dialinginfo.id)
846                 strncpy(ast->exten, param->setup.dialinginfo.id, AST_MAX_EXTENSION-1);
847         if (param->setup.context[0])
848                 strncpy(ast->context, param->setup.context, AST_MAX_CONTEXT-1);
849         else
850                 strncpy(ast->context, param->setup.callerinfo.interface, AST_MAX_CONTEXT-1);
851         if (param->setup.callerinfo.id[0])
852                 ast->cid.cid_num = strdup(param->setup.callerinfo.id);
853         if (param->setup.callerinfo.name[0])
854                 ast->cid.cid_name = strdup(param->setup.callerinfo.name);
855         if (param->setup.redirinfo.id[0])
856                 ast->cid.cid_name = strdup(numberrize_callerinfo(param->setup.callerinfo.id, param->setup.callerinfo.ntype, options.national, options.international));
857         switch (param->setup.callerinfo.present) {
858                 case INFO_PRESENT_ALLOWED:
859                         ast->cid.cid_pres = AST_PRES_ALLOWED;
860                 break;
861                 case INFO_PRESENT_RESTRICTED:
862                         ast->cid.cid_pres = AST_PRES_RESTRICTED;
863                 break;
864                 default:
865                         ast->cid.cid_pres = AST_PRES_UNAVAILABLE;
866         }
867         switch (param->setup.callerinfo.ntype) {
868                 case INFO_NTYPE_SUBSCRIBER:
869                         ast->cid.cid_ton = 4;
870                 break;
871                 case INFO_NTYPE_NATIONAL:
872                         ast->cid.cid_ton = 2;
873                 break;
874                 case INFO_NTYPE_INTERNATIONAL:
875                         ast->cid.cid_ton = 1;
876                 break;
877                 default:
878                         ast->cid.cid_ton = 0;
879         }
880         ast->transfercapability = param->setup.capainfo.bearer_capa;
881         /* enable hdlc if transcap is data */
882         if (param->setup.capainfo.source_mode == B_MODE_HDLC)
883                 call->hdlc = 1;
884         strncpy(call->oad, numberrize_callerinfo(param->setup.callerinfo.id, param->setup.callerinfo.ntype, options.national, options.international), sizeof(call->oad)-1);
885
886         /* configure channel */
887         ast->nativeformats = (options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW;
888         ast->readformat = ast->rawreadformat = ast->nativeformats;
889         ast->writeformat = ast->rawwriteformat =  ast->nativeformats;
890         ast->priority = 1;
891         ast->hangupcause = 0;
892
893         /* change state */
894         call->state = CHAN_LCR_STATE_IN_SETUP;
895
896         if (!call->pbx_started)
897                 lcr_start_pbx(call, ast, param->setup.dialinginfo.sending_complete);
898 }
899
900 /*
901  * incoming setup acknowledge from LCR
902  */
903 static void lcr_in_overlap(struct chan_call *call, int message_type, union parameter *param)
904 {
905         if (!call->ast) return;
906
907         CDEBUG(call, call->ast, "Incomming setup acknowledge from LCR.\n");
908
909         /* send pending digits in dialque */
910         if (call->dialque[0])
911                 send_dialque_to_lcr(call);
912         /* change to overlap state */
913         call->state = CHAN_LCR_STATE_OUT_DIALING;
914 }
915
916 /*
917  * incoming proceeding from LCR
918  */
919 static void lcr_in_proceeding(struct chan_call *call, int message_type, union parameter *param)
920 {
921         CDEBUG(call, call->ast, "Incomming proceeding from LCR.\n");
922
923         /* change state */
924         call->state = CHAN_LCR_STATE_OUT_PROCEEDING;
925         /* queue event for asterisk */
926         if (call->ast && call->pbx_started)
927                 strncat(call->queue_string, "P", sizeof(call->queue_string)-1);
928 }
929
930 /*
931  * incoming alerting from LCR
932  */
933 static void lcr_in_alerting(struct chan_call *call, int message_type, union parameter *param)
934 {
935         CDEBUG(call, call->ast, "Incomming alerting from LCR.\n");
936
937         /* change state */
938         call->state = CHAN_LCR_STATE_OUT_ALERTING;
939         /* queue event to asterisk */
940         if (call->ast && call->pbx_started)
941                 strncat(call->queue_string, "R", sizeof(call->queue_string)-1);
942 }
943
944 /*
945  * incoming connect from LCR
946  */
947 static void lcr_in_connect(struct chan_call *call, int message_type, union parameter *param)
948 {
949         union parameter newparam;
950
951         CDEBUG(call, call->ast, "Incomming connect (answer) from LCR.\n");
952
953         /* change state */
954         call->state = CHAN_LCR_STATE_CONNECT;
955         /* request bchannel */
956         if (!call->bchannel) {
957                 CDEBUG(call, call->ast, "Requesting B-channel.\n");
958                 memset(&newparam, 0, sizeof(union parameter));
959                 newparam.bchannel.type = BCHANNEL_REQUEST;
960                 send_message(MESSAGE_BCHANNEL, call->ref, &newparam);
961         }
962         /* copy connectinfo */
963         memcpy(&call->connectinfo, &param->connectinfo, sizeof(struct connect_info));
964         /* queue event to asterisk */
965         if (call->ast && call->pbx_started)
966                 strncat(call->queue_string, "N", sizeof(call->queue_string)-1);
967 }
968
969 /*
970  * incoming disconnect from LCR
971  */
972 static void lcr_in_disconnect(struct chan_call *call, int message_type, union parameter *param)
973 {
974         struct ast_channel *ast = call->ast;
975
976         CDEBUG(call, call->ast, "Incomming disconnect from LCR. (cause=%d)\n", param->disconnectinfo.cause);
977
978         /* change state */
979         call->state = CHAN_LCR_STATE_IN_DISCONNECT;
980         /* save cause */
981         call->cause = param->disconnectinfo.cause;
982         call->location = param->disconnectinfo.location;
983         /* if bridge, forward disconnect and return */
984 #ifdef TODO
985         feature flag
986         if (call->bridge_call) {
987                 CDEBUG(call, call->ast, "Only signal disconnect via bridge.\n");
988                 bridge_message_if_bridged(call, message_type, param);
989                 return;
990         }
991 #endif
992         /* release lcr with same cause */
993         send_release_and_import(call, call->cause, call->location);
994         call->ref = 0;
995         /* change to release state */
996         call->state = CHAN_LCR_STATE_RELEASE;
997         /* queue release asterisk */
998         if (ast) {
999                 ast->hangupcause = call->cause;
1000                 if (call->pbx_started)
1001                         strcpy(call->queue_string, "H"); // overwrite other indications
1002                 else {
1003                         ast_hangup(ast); // call will be destroyed here
1004                 }
1005         }
1006 }
1007
1008 /*
1009  * incoming release from LCR
1010  */
1011 static void lcr_in_release(struct chan_call *call, int message_type, union parameter *param)
1012 {
1013         struct ast_channel *ast = call->ast;
1014
1015         CDEBUG(call, call->ast, "Incomming release from LCR, releasing ref. (cause=%d)\n", param->disconnectinfo.cause);
1016
1017         /* release ref */
1018         call->ref = 0;
1019         /* change to release state */
1020         call->state = CHAN_LCR_STATE_RELEASE;
1021         /* copy release info */
1022         if (!call->cause) {
1023                call->cause = param->disconnectinfo.cause;
1024                call->location = param->disconnectinfo.location;
1025         }
1026         /* if we have an asterisk instance, queue hangup, else we are done */
1027         if (ast) {
1028                 ast->hangupcause = call->cause;
1029                 if (call->pbx_started)
1030                         strcpy(call->queue_string, "H");
1031                 else {
1032                         ast_hangup(ast); // call will be destroyed here
1033                 }
1034         } else {
1035                 free_call(call);
1036         }
1037         
1038 }
1039
1040 /*
1041  * incoming information from LCR
1042  */
1043 static void lcr_in_information(struct chan_call *call, int message_type, union parameter *param)
1044 {
1045         struct ast_channel *ast = call->ast;
1046
1047         CDEBUG(call, call->ast, "Incoming information from LCR. (dialing=%s)\n", param->information.id);
1048         
1049         if (!ast) return;
1050
1051         /* pbx not started */
1052         if (!call->pbx_started) {
1053                 CDEBUG(call, call->ast, "Asterisk not started, adding digits to number.\n");
1054                 strncat(ast->exten, param->information.id, AST_MAX_EXTENSION-1);
1055                 lcr_start_pbx(call, ast, param->information.sending_complete);
1056                 return;
1057         }
1058         
1059         /* change dailing state after setup */
1060         if (call->state == CHAN_LCR_STATE_IN_SETUP) {
1061                 CDEBUG(call, call->ast, "Changing from SETUP to DIALING state.\n");
1062                 call->state = CHAN_LCR_STATE_IN_DIALING;
1063 //              ast_setstate(ast, AST_STATE_DIALING);
1064         }
1065         
1066         /* queue digits */
1067         if (call->state == CHAN_LCR_STATE_IN_DIALING && param->information.id[0])
1068                 strncat(call->queue_string, param->information.id, sizeof(call->queue_string)-1);
1069
1070         /* use bridge to forware message not supported by asterisk */
1071         if (call->state == CHAN_LCR_STATE_CONNECT) {
1072                 CDEBUG(call, call->ast, "Call is connected, bridging.\n");
1073                 bridge_message_if_bridged(call, message_type, param);
1074         }
1075 }
1076
1077 /*
1078  * incoming information from LCR
1079  */
1080 static void lcr_in_notify(struct chan_call *call, int message_type, union parameter *param)
1081 {
1082         union parameter newparam;
1083
1084         CDEBUG(call, call->ast, "Incomming notify from LCR. (notify=%d)\n", param->notifyinfo.notify);
1085
1086         /* request bchannel, if call is resumed and we don't have it */
1087         if (param->notifyinfo.notify == INFO_NOTIFY_USER_RESUMED && !call->bchannel && call->ref) {
1088                 CDEBUG(call, call->ast, "Reqesting bchannel at resume.\n");
1089                 memset(&newparam, 0, sizeof(union parameter));
1090                 newparam.bchannel.type = BCHANNEL_REQUEST;
1091                 send_message(MESSAGE_BCHANNEL, call->ref, &newparam);
1092         }
1093
1094         if (!call->ast) return;
1095
1096         /* use bridge to forware message not supported by asterisk */
1097         bridge_message_if_bridged(call, message_type, param);
1098 }
1099
1100 /*
1101  * incoming information from LCR
1102  */
1103 static void lcr_in_facility(struct chan_call *call, int message_type, union parameter *param)
1104 {
1105         CDEBUG(call, call->ast, "Incomming facility from LCR.\n");
1106
1107         if (!call->ast) return;
1108
1109         /* use bridge to forware message not supported by asterisk */
1110         bridge_message_if_bridged(call, message_type, param);
1111 }
1112
1113 /*
1114  * incoming pattern from LCR
1115  */
1116 static void lcr_in_pattern(struct chan_call *call, int message_type, union parameter *param)
1117 {
1118         union parameter newparam;
1119
1120         CDEBUG(call, call->ast, "Incomming pattern indication from LCR.\n");
1121
1122         if (!call->ast) return;
1123
1124         /* pattern are indicated only once */
1125         if (call->has_pattern)
1126                 return;
1127         call->has_pattern = 1;
1128
1129         /* request bchannel */
1130         if (!call->bchannel) {
1131                 CDEBUG(call, call->ast, "Requesting B-channel.\n");
1132                 memset(&newparam, 0, sizeof(union parameter));
1133                 newparam.bchannel.type = BCHANNEL_REQUEST;
1134                 send_message(MESSAGE_BCHANNEL, call->ref, &newparam);
1135         }
1136         /* queue PROGRESS, because tones are available */
1137         if (call->ast && call->pbx_started)
1138                 strncat(call->queue_string, "T", sizeof(call->queue_string)-1);
1139 }
1140
1141 /*
1142  * got dtmf from bchannel (locked state)
1143  */
1144 void lcr_in_dtmf(struct chan_call *call, int val)
1145 {
1146         struct ast_channel *ast = call->ast;
1147         char digit[2];
1148
1149         if (!ast)
1150                 return;
1151         if (!call->pbx_started)
1152                 return;
1153
1154         if (!call->dsp_dtmf) {
1155                 CDEBUG(call, call->ast, "Recognised DTMF digit '%c', but ignoring. This is fixed in later mISDN driver.\n", val);
1156                 return;
1157         }
1158
1159         CDEBUG(call, call->ast, "Recognised DTMF digit '%c'.\n", val);
1160         digit[0] = val;
1161         digit[1] = '\0';
1162         strncat(call->queue_string, digit, sizeof(call->queue_string)-1);
1163 }
1164
1165 /*
1166  * message received from LCR
1167  */
1168 int receive_message(int message_type, unsigned int ref, union parameter *param)
1169 {
1170         struct bchannel *bchannel;
1171         struct chan_call *call;
1172         union parameter newparam;
1173
1174         memset(&newparam, 0, sizeof(union parameter));
1175
1176         /* handle bchannel message*/
1177         if (message_type == MESSAGE_BCHANNEL) {
1178                 switch(param->bchannel.type) {
1179                         case BCHANNEL_ASSIGN:
1180                         CDEBUG(NULL, NULL, "Received BCHANNEL_ASSIGN message. (handle=%08lx) for ref %d\n", param->bchannel.handle, ref);
1181                         if ((bchannel = find_bchannel_handle(param->bchannel.handle))) {
1182                                 CERROR(NULL, NULL, "bchannel handle %x already assigned.\n", (int)param->bchannel.handle);
1183                                 return(-1);
1184                         }
1185                         /* create bchannel */
1186                         bchannel = alloc_bchannel(param->bchannel.handle);
1187                         if (!bchannel) {
1188                                 CERROR(NULL, NULL, "alloc bchannel handle %x failed.\n", (int)param->bchannel.handle);
1189                                 return(-1);
1190                         }
1191
1192                         /* configure channel */
1193                         bchannel->b_tx_gain = param->bchannel.tx_gain;
1194                         bchannel->b_rx_gain = param->bchannel.rx_gain;
1195                         strncpy(bchannel->b_pipeline, param->bchannel.pipeline, sizeof(bchannel->b_pipeline)-1);
1196                         if (param->bchannel.crypt_len && param->bchannel.crypt_len <= sizeof(bchannel->b_bf_key)) {
1197                                 bchannel->b_bf_len = param->bchannel.crypt_len;
1198                                 memcpy(bchannel->b_bf_key, param->bchannel.crypt, param->bchannel.crypt_len);
1199                         }
1200                         bchannel->b_txdata = 0;
1201                         bchannel->b_tx_dejitter = 1;
1202
1203                         /* in case, ref is not set, this bchannel instance must
1204                          * be created until it is removed again by LCR */
1205                         /* link to call */
1206                         call = find_call_ref(ref);
1207                         if (call) {
1208                                 bchannel->call = call;
1209                                 call->bchannel = bchannel;
1210                                 if (call->dsp_dtmf)
1211                                         bchannel_dtmf(bchannel, 1);
1212                                 if (call->bf_len)
1213                                         bchannel_blowfish(bchannel, call->bf_key, call->bf_len);
1214                                 if (call->pipeline[0])
1215                                         bchannel_pipeline(bchannel, call->pipeline);
1216                                 if (call->rx_gain)
1217                                         bchannel_gain(bchannel, call->rx_gain, 0);
1218                                 if (call->tx_gain)
1219                                         bchannel_gain(bchannel, call->tx_gain, 1);
1220                                 if (call->bridge_id) {
1221                                         CDEBUG(call, call->ast, "Join bchannel, because call is already bridged.\n");
1222                                         bchannel_join(bchannel, call->bridge_id);
1223                                 }
1224                                 /* create only, if call exists, othewhise it bchannel is freed below... */
1225                                 if (bchannel_create(bchannel, ((call->nodsp || call->faxdetect > 0)?1:0) + ((call->hdlc)?2:0)))
1226                                         bchannel_activate(bchannel, 1);
1227                         }
1228                         /* acknowledge */
1229                         newparam.bchannel.type = BCHANNEL_ASSIGN_ACK;
1230                         newparam.bchannel.handle = param->bchannel.handle;
1231                         send_message(MESSAGE_BCHANNEL, 0, &newparam);
1232                         /* if call has released before bchannel is assigned */
1233                         if (!call) {
1234                                 newparam.bchannel.type = BCHANNEL_RELEASE;
1235                                 newparam.bchannel.handle = param->bchannel.handle;
1236                                 send_message(MESSAGE_BCHANNEL, 0, &newparam);
1237                         }
1238
1239                         break;
1240
1241                         case BCHANNEL_REMOVE:
1242                         CDEBUG(NULL, NULL, "Received BCHANNEL_REMOVE message. (handle=%08lx)\n", param->bchannel.handle);
1243                         if (!(bchannel = find_bchannel_handle(param->bchannel.handle))) {
1244                                 CERROR(NULL, NULL, "Bchannel handle %x not assigned.\n", (int)param->bchannel.handle);
1245                                 return(-1);
1246                         }
1247                         /* unklink from call and destroy bchannel */
1248                         free_bchannel(bchannel);
1249
1250                         /* acknowledge */
1251                         newparam.bchannel.type = BCHANNEL_REMOVE_ACK;
1252                         newparam.bchannel.handle = param->bchannel.handle;
1253                         send_message(MESSAGE_BCHANNEL, 0, &newparam);
1254                         
1255                         break;
1256
1257                         default:
1258                         CDEBUG(NULL, NULL, "Received unknown bchannel message %d.\n", param->bchannel.type);
1259                 }
1260                 return(0);
1261         }
1262
1263         /* handle new ref */
1264         if (message_type == MESSAGE_NEWREF) {
1265                 if (param->direction) {
1266                         /* new ref from lcr */
1267                         CDEBUG(NULL, NULL, "Received new ref by LCR, due to incomming call. (ref=%ld)\n", ref);
1268                         if (!ref || find_call_ref(ref)) {
1269                                 CERROR(NULL, NULL, "Illegal new ref %ld received.\n", ref);
1270                                 return(-1);
1271                         }
1272                         /* allocate new call instance */
1273                         call = alloc_call();
1274                         /* new state */
1275                         call->state = CHAN_LCR_STATE_IN_PREPARE;
1276                         /* set ref */
1277                         call->ref = ref;
1278                         call->ref_was_assigned = 1;
1279                         /* set dtmf (default, use option 'n' to disable */
1280                         call->dsp_dtmf = 1;
1281                         /* wait for setup (or release from asterisk) */
1282                 } else {
1283                         /* new ref, as requested from this remote application */
1284                         CDEBUG(NULL, NULL, "Received new ref by LCR, as requested from chan_lcr. (ref=%ld)\n", ref);
1285                         call = find_call_ref(0);
1286                         if (!call) {
1287                                 /* send release, if ref does not exist */
1288                                 CDEBUG(NULL, NULL, "No call found, that requests a ref.\n");
1289                                 send_release_and_import(call, CAUSE_NORMAL, LOCATION_PRIVATE_LOCAL);
1290                                 return(0);
1291                         }
1292                         /* store new ref */
1293                         call->ref = ref;
1294                         call->ref_was_assigned = 1;
1295                         /* set dtmf (default, use option 'n' to disable */
1296                         call->dsp_dtmf = 1;
1297                         /* send pending setup info */
1298                         if (call->state == CHAN_LCR_STATE_OUT_PREPARE)
1299                                 send_setup_to_lcr(call);
1300                         /* release if asterisk has signed off */
1301                         else if (call->state == CHAN_LCR_STATE_RELEASE) {
1302                                 /* send release */
1303                                 if (call->cause)
1304                                         send_release_and_import(call, call->cause, call->location);
1305                                 else
1306                                         send_release_and_import(call, CAUSE_NORMAL, LOCATION_PRIVATE_LOCAL);
1307                                 /* free call */
1308                                 free_call(call);
1309                                 return(0);
1310                         }
1311                 }
1312                 return(0);
1313         }
1314
1315         /* check ref */
1316         if (!ref) {
1317                 CERROR(NULL, NULL, "Received message %d without ref.\n", message_type);
1318                 return(-1);
1319         }
1320         call = find_call_ref(ref);
1321         if (!call) {
1322                 /* ignore ref that is not used (anymore) */
1323                 CDEBUG(NULL, NULL, "Message %d from LCR ignored, because no call instance found.\n", message_type);
1324                 return(0);
1325         }
1326
1327         /* handle messages */
1328         switch(message_type) {
1329                 case MESSAGE_SETUP:
1330                 lcr_in_setup(call, message_type, param);
1331                 break;
1332
1333                 case MESSAGE_OVERLAP:
1334                 lcr_in_overlap(call, message_type, param);
1335                 break;
1336
1337                 case MESSAGE_PROCEEDING:
1338                 lcr_in_proceeding(call, message_type, param);
1339                 break;
1340
1341                 case MESSAGE_ALERTING:
1342                 lcr_in_alerting(call, message_type, param);
1343                 break;
1344
1345                 case MESSAGE_CONNECT:
1346                 lcr_in_connect(call, message_type, param);
1347                 break;
1348
1349                 case MESSAGE_DISCONNECT:
1350                 lcr_in_disconnect(call, message_type, param);
1351                 break;
1352
1353                 case MESSAGE_RELEASE:
1354                 lcr_in_release(call, message_type, param);
1355                 break;
1356
1357                 case MESSAGE_INFORMATION:
1358                 lcr_in_information(call, message_type, param);
1359                 break;
1360
1361                 case MESSAGE_NOTIFY:
1362                 lcr_in_notify(call, message_type, param);
1363                 break;
1364
1365                 case MESSAGE_FACILITY:
1366                 lcr_in_facility(call, message_type, param);
1367                 break;
1368
1369                 case MESSAGE_PATTERN: // audio available from LCR
1370                 if (!call->has_pattern)
1371                         lcr_in_pattern(call, message_type, param);
1372                 break;
1373
1374                 case MESSAGE_NOPATTERN: // audio not available from LCR
1375                 break;
1376
1377                 case MESSAGE_AUDIOPATH: // if remote audio connected or hold
1378                 call->audiopath = param->audiopath;
1379                 break;
1380
1381                 default:
1382                 CDEBUG(call, call->ast, "Message %d from LCR unhandled.\n", message_type);
1383                 break;
1384         }
1385         return(0);
1386 }
1387
1388 /*
1389  * release all calls (due to broken socket)
1390  */
1391 static void release_all_calls(void)
1392 {
1393         struct chan_call *call;
1394
1395 again:
1396         call = call_first;
1397         while(call) {
1398                 /* no ast, so we may directly free call */
1399                 if (!call->ast) {
1400                         CDEBUG(call, NULL, "Freeing call, because no Asterisk channel is linked.\n");
1401                         free_call(call);
1402                         goto again;
1403                 }
1404                 /* already in release process */
1405                 if (call->state == CHAN_LCR_STATE_RELEASE) {
1406                         call = call->next;
1407                         continue;
1408                 }
1409                 /* release or queue release */
1410                 call->ref = 0;
1411                 call->state = CHAN_LCR_STATE_RELEASE;
1412                 if (!call->pbx_started) {
1413                         CDEBUG(call, call->ast, "Releasing call, because no Asterisk channel is not started.\n");
1414                         ast_hangup(call->ast); // call will be destroyed here
1415                         goto again;
1416                 }
1417                 CDEBUG(call, call->ast, "Queue call release, because Asterisk channel is running.\n");
1418                 strcpy(call->queue_string, "H");
1419                 call = call->next;
1420         }
1421
1422         /* release all bchannels */
1423         while(bchannel_first)
1424                 free_bchannel(bchannel_first);
1425 }
1426
1427
1428 /* asterisk handler
1429  * warning! not thread safe
1430  * returns -1 for socket error, 0 for no work, 1 for work
1431  */
1432 int handle_socket(void)
1433 {
1434         int work = 0;
1435         int len;
1436         struct admin_list *admin;
1437         struct admin_message msg;
1438
1439         /* read from socket */
1440         len = read(lcr_sock, &msg, sizeof(msg));
1441         if (len == 0) {
1442                 CERROR(NULL, NULL, "Socket closed.\n");
1443                 return(-1); // socket closed
1444         }
1445         if (len > 0) {
1446                 if (len != sizeof(msg)) {
1447                         CERROR(NULL, NULL, "Socket short read. (len %d)\n", len);
1448                         return(-1); // socket error
1449                 }
1450                 if (msg.message != ADMIN_MESSAGE) {
1451                         CERROR(NULL, NULL, "Socket received illegal message %d.\n", msg.message);
1452                         return(-1);
1453                 }
1454                 receive_message(msg.u.msg.type, msg.u.msg.ref, &msg.u.msg.param);
1455                 work = 1;
1456         } else {
1457                 if (errno != EWOULDBLOCK) {
1458                         CERROR(NULL, NULL, "Socket failed (errno %d).\n", errno);
1459                         return(-1);
1460                 }
1461         }
1462
1463         /* write to socket */
1464         if (!admin_first)
1465                 return(work);
1466         admin = admin_first;
1467         len = write(lcr_sock, &admin->msg, sizeof(msg));
1468         if (len == 0) {
1469                 CERROR(NULL, NULL, "Socket closed.\n");
1470                 return(-1); // socket closed
1471         }
1472         if (len > 0) {
1473                 if (len != sizeof(msg)) {
1474                         CERROR(NULL, NULL, "Socket short write. (len %d)\n", len);
1475                         return(-1); // socket error
1476                 }
1477                 /* free head */
1478                 admin_first = admin->next;
1479                 free(admin);
1480
1481                 work = 1;
1482         } else {
1483                 if (errno != EWOULDBLOCK) {
1484                         CERROR(NULL, NULL, "Socket failed (errno %d).\n", errno);
1485                         return(-1);
1486                 }
1487         }
1488
1489         return(work);
1490 }
1491
1492 /*
1493  * open and close socket and thread
1494  */
1495 int open_socket(void)
1496 {
1497         int ret;
1498         int conn;
1499         struct sockaddr_un sock_address;
1500         unsigned int on = 1;
1501         union parameter param;
1502
1503         /* open socket */
1504         if ((lcr_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
1505                 CERROR(NULL, NULL, "Failed to create socket.\n");
1506                 return(lcr_sock);
1507         }
1508
1509         /* set socket address and name */
1510         memset(&sock_address, 0, sizeof(sock_address));
1511         sock_address.sun_family = PF_UNIX;
1512         sprintf(sock_address.sun_path, SOCKET_NAME, options.lock);
1513
1514         /* connect socket */
1515         if ((conn = connect(lcr_sock, (struct sockaddr *)&sock_address, SUN_LEN(&sock_address))) < 0) {
1516                 close(lcr_sock);
1517                 lcr_sock = -1;
1518                 CDEBUG(NULL, NULL, "Failed to connect to socket '%s'. Is LCR running?\n", sock_address.sun_path);
1519                 return(conn);
1520         }
1521
1522         /* set non-blocking io */
1523         if ((ret = ioctl(lcr_sock, FIONBIO, (unsigned char *)(&on))) < 0) {
1524                 close(lcr_sock);
1525                 lcr_sock = -1;
1526                 CERROR(NULL, NULL, "Failed to set socket into non-blocking IO.\n");
1527                 return(ret);
1528         }
1529
1530         /* enque hello message */
1531         memset(&param, 0, sizeof(param));
1532         strcpy(param.hello.application, "asterisk");
1533         send_message(MESSAGE_HELLO, 0, &param);
1534
1535         return(lcr_sock);
1536 }
1537
1538 void close_socket(void)
1539 {
1540         struct admin_list *admin, *temp;
1541         
1542         /* flush pending messages */
1543         admin = admin_first;
1544         while(admin) {
1545                 temp = admin;
1546                 admin = admin->next;
1547                 free(temp);
1548         }
1549         admin_first = NULL;
1550
1551         /* close socket */
1552         if (lcr_sock >= 0)      
1553                 close(lcr_sock);
1554         lcr_sock = -1;
1555 }
1556
1557
1558 /* sending queue to asterisk */
1559 static int queue_send(void)
1560 {
1561         int work = 0;
1562         struct chan_call *call;
1563         struct ast_channel *ast;
1564         struct ast_frame fr;
1565         char *p;
1566
1567         call = call_first;
1568         while(call) {
1569                 p = call->queue_string;
1570                 ast = call->ast;
1571                 if (*p && ast) {
1572                         /* there is something to queue */
1573                         if (!ast_channel_trylock(ast)) { /* succeed */
1574                                 while(*p) {
1575                                         switch (*p) {
1576                                         case 'T':
1577                                                 CDEBUG(call, ast, "Sending queued PROGRESS to Asterisk.\n");
1578                                                 ast_queue_control(ast, AST_CONTROL_PROGRESS);
1579                                                 break;
1580                                         case 'P':
1581                                                 CDEBUG(call, ast, "Sending queued PROCEEDING to Asterisk.\n");
1582                                                 ast_queue_control(ast, AST_CONTROL_PROCEEDING);
1583                                                 break;
1584                                         case 'R':
1585                                                 CDEBUG(call, ast, "Sending queued RINGING to Asterisk.\n");
1586                                                 ast_queue_control(ast, AST_CONTROL_RINGING);
1587                                                 ast_setstate(ast, AST_STATE_RINGING);
1588                                                 break;
1589                                         case 'N':
1590                                                 CDEBUG(call, ast, "Sending queued ANSWER to Asterisk.\n");
1591                                                 ast_queue_control(ast, AST_CONTROL_ANSWER);
1592                                                 break;
1593                                         case 'H':
1594                                                 CDEBUG(call, ast, "Sending queued HANGUP to Asterisk.\n");
1595                                                 ast_queue_hangup(ast);
1596                                                 break;
1597                                         case '1': case '2': case '3': case 'A':
1598                                         case '4': case '5': case '6': case 'B':
1599                                         case '7': case '8': case '9': case 'C':
1600                                         case '*': case '0': case '#': case 'D':
1601                                                 CDEBUG(call, ast, "Sending queued digit '%c' to Asterisk.\n", *p);
1602                                                 /* send digit to asterisk */
1603                                                 memset(&fr, 0, sizeof(fr));
1604                                                 
1605                                                 #ifdef LCR_FOR_ASTERISK
1606                                                 fr.frametype = AST_FRAME_DTMF_BEGIN;
1607                                                 #endif
1608
1609                                                 #ifdef LCR_FOR_CALLWEAVER
1610                                                 fr.frametype = AST_FRAME_DTMF;
1611                                                 #endif
1612                                                 
1613                                                 fr.subclass = *p;
1614                                                 fr.delivery = ast_tv(0, 0);
1615                                                 ast_queue_frame(ast, &fr);
1616                                                 
1617                                                 #ifdef LCR_FOR_ASTERISK
1618                                                 fr.frametype = AST_FRAME_DTMF_END;
1619                                                 ast_queue_frame(ast, &fr);
1620                                                 #endif
1621                                                                                                 
1622                                                 break;
1623                                         default:
1624                                                 CDEBUG(call, ast, "Ignoring queued digit 0x%02x.\n", *p);
1625                                         }
1626                                         p++;
1627                                 }
1628                                 call->queue_string[0] = '\0';
1629                                 ast_channel_unlock(ast);
1630                                 work = 1;
1631                         }
1632                 }
1633                 call = call->next;
1634         }
1635
1636         return work;
1637 }
1638
1639 /* signal handler */
1640 void sighandler(int sigset)
1641 {
1642 }
1643
1644 /* chan_lcr thread */
1645 static void *chan_thread(void *arg)
1646 {
1647         int work;
1648         int ret;
1649         union parameter param;
1650         time_t retry = 0, now;
1651
1652         bchannel_pid = getpid();
1653
1654 //      signal(SIGPIPE, sighandler);
1655         
1656         memset(&param, 0, sizeof(union parameter));
1657         if (lcr_sock < 0)
1658                 time(&retry);
1659
1660         ast_mutex_lock(&chan_lock);
1661
1662         while(!quit) {
1663                 work = 0;
1664
1665                 if (lcr_sock > 0) {
1666                         /* handle socket */
1667                         ret = handle_socket();
1668                         if (ret < 0) {
1669                                 CERROR(NULL, NULL, "Handling of socket failed - closing for some seconds.\n");
1670                                 close_socket();
1671                                 release_all_calls();
1672                                 time(&retry);
1673                         }
1674                         if (ret)
1675                                 work = 1;
1676                 } else {
1677                         time(&now);
1678                         if (retry && now-retry > 5) {
1679                                 CDEBUG(NULL, NULL, "Retry to open socket.\n");
1680                                 retry = 0;
1681                                 if (open_socket() < 0) {
1682                                         time(&retry);
1683                                 }
1684                                 work = 1;
1685                         }
1686                                         
1687                 }
1688
1689                 /* handle mISDN */
1690                 ret = bchannel_handle();
1691                 if (ret)
1692                         work = 1;
1693
1694                 /* handle messages to asterisk */
1695                 ret = queue_send();
1696                 if (ret)
1697                         work = 1;
1698
1699                 /* delay if no work done */
1700                 if (!work) {
1701                         ast_mutex_unlock(&chan_lock);
1702
1703                         #ifdef LCR_FOR_ASTERISK                 
1704                         usleep(30000);
1705                         #endif
1706                         
1707                         #ifdef LCR_FOR_CALLWEAVER                       
1708                         usleep(20000);
1709                         #endif
1710                         
1711                         ast_mutex_lock(&chan_lock);
1712                 }
1713         }
1714
1715         close_socket();
1716
1717         CERROR(NULL, NULL, "Thread exit.\n");
1718         
1719         ast_mutex_unlock(&chan_lock);
1720
1721 //      signal(SIGPIPE, SIG_DFL);
1722
1723         return NULL;
1724 }
1725
1726 /*
1727  * new asterisk instance
1728  */
1729 static
1730 struct ast_channel *lcr_request(const char *type, int format, void *data, int *cause)
1731 {
1732         char exten[256], *dial, *interface, *opt;
1733         struct ast_channel *ast;
1734         struct chan_call *call;
1735
1736         ast_mutex_lock(&chan_lock);
1737         CDEBUG(NULL, NULL, "Received request from Asterisk. (data=%s)\n", (char *)data);
1738
1739         /* if socket is closed */
1740         if (lcr_sock < 0) {
1741                 CERROR(NULL, NULL, "Rejecting call from Asterisk, because LCR not running.\n");
1742                 ast_mutex_unlock(&chan_lock);
1743                 return NULL;
1744         }
1745
1746         /* create call instance */
1747         call = alloc_call();
1748         if (!call) {
1749                 /* failed to create instance */
1750                 ast_mutex_unlock(&chan_lock);
1751                 return NULL;
1752         }
1753
1754         /* create asterisk channel instrance */
1755
1756         #ifdef LCR_FOR_ASTERISK
1757         ast = ast_channel_alloc(1, AST_STATE_RESERVED, NULL, NULL, "", NULL, "", 0, "%s/%d", lcr_type, ++glob_channel);
1758         #endif
1759         
1760         #ifdef LCR_FOR_CALLWEAVER
1761         ast = ast_channel_alloc(1);
1762         #endif
1763                 
1764         if (!ast) {
1765                 CERROR(NULL, NULL, "Failed to create Asterisk channel.\n");
1766                 free_call(call);
1767                 /* failed to create instance */
1768                 ast_mutex_unlock(&chan_lock);
1769                 return NULL;
1770         }
1771         ast->tech = &lcr_tech;
1772         ast->tech_pvt = (void *)1L; // set pointer or asterisk will not call
1773         /* configure channel */
1774         ast->nativeformats = (options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW;
1775         ast->readformat = ast->rawreadformat = ast->nativeformats;
1776         ast->writeformat = ast->rawwriteformat =  ast->nativeformats;
1777         ast->priority = 1;
1778         ast->hangupcause = 0;
1779
1780         /* link together */
1781         call->ast = ast;
1782         ast->tech_pvt = call;
1783         ast->fds[0] = call->pipe[0];
1784         call->pbx_started = 0;
1785         /* set state */
1786         call->state = CHAN_LCR_STATE_OUT_PREPARE;
1787
1788         /*
1789          * Extract interface, dialstring, options from data.
1790          * Formats can be:
1791          *      <dialstring>
1792          *      <interface>/<dialstring>
1793          *      <interface>/<dialstring>/options
1794          */
1795         strncpy(exten, (char *)data, sizeof(exten)-1);
1796         exten[sizeof(exten)-1] = '\0';
1797         if ((dial = strchr(exten, '/'))) {
1798                 *dial++ = '\0';
1799                 interface = exten;
1800                 if ((opt = strchr(dial, '/')))
1801                         *opt++ = '\0';
1802                 else
1803                         opt = "";
1804         } else {
1805                 dial = exten;
1806                 interface = "";
1807                 opt = "";
1808         }
1809         strncpy(call->interface, interface, sizeof(call->interface)-1);
1810         strncpy(call->dialstring, dial, sizeof(call->dialstring)-1);
1811         apply_opt(call, (char *)opt);
1812
1813         ast_mutex_unlock(&chan_lock);
1814         return ast;
1815 }
1816
1817 /*
1818  * call from asterisk
1819  */
1820 static int lcr_call(struct ast_channel *ast, char *dest, int timeout)
1821 {
1822         union parameter newparam;
1823         struct chan_call *call;
1824
1825         ast_mutex_lock(&chan_lock);
1826         call = ast->tech_pvt;
1827         
1828         #ifdef LCR_FOR_CALLWEAVER
1829         ast->type = "LCR";
1830         snprintf(ast->name, sizeof(ast->name), "LCR/%s-%04x",call->dialstring, ast_random() & 0xffff);
1831         #endif
1832         
1833         if (!call) {
1834                 CERROR(NULL, ast, "Received call from Asterisk, but call instance does not exist.\n");
1835                 ast_mutex_unlock(&chan_lock);
1836                 return -1;
1837         }
1838
1839         CDEBUG(NULL, ast, "Received call from Asterisk.\n");
1840
1841         /* pbx process is started */
1842         call->pbx_started = 1;
1843         /* send MESSAGE_NEWREF */
1844         memset(&newparam, 0, sizeof(union parameter));
1845         newparam.direction = 0; /* request from app */
1846         send_message(MESSAGE_NEWREF, 0, &newparam);
1847
1848         /* set hdlc if capability requires hdlc */
1849         if (ast->transfercapability == INFO_BC_DATAUNRESTRICTED
1850          || ast->transfercapability == INFO_BC_DATARESTRICTED
1851          || ast->transfercapability == INFO_BC_VIDEO)
1852                 call->hdlc = 1;
1853         /* if hdlc is forced by option, we change transcap to data */
1854         if (call->hdlc
1855          && ast->transfercapability != INFO_BC_DATAUNRESTRICTED
1856          && ast->transfercapability != INFO_BC_DATARESTRICTED
1857          && ast->transfercapability != INFO_BC_VIDEO)
1858                 ast->transfercapability = INFO_BC_DATAUNRESTRICTED;
1859
1860         call->cid_num[0] = 0;
1861         call->cid_name[0] = 0;
1862         call->cid_rdnis[0] = 0;
1863
1864         if (ast->cid.cid_num) if (ast->cid.cid_num[0])
1865                 strncpy(call->cid_num, ast->cid.cid_num,
1866                         sizeof(call->cid_num)-1);
1867
1868         if (ast->cid.cid_name) if (ast->cid.cid_name[0])
1869                 strncpy(call->cid_name, ast->cid.cid_name, 
1870                         sizeof(call->cid_name)-1);
1871         if (ast->cid.cid_rdnis) if (ast->cid.cid_rdnis[0])
1872                 strncpy(call->cid_rdnis, ast->cid.cid_rdnis, 
1873                         sizeof(call->cid_rdnis)-1);
1874
1875         ast_mutex_unlock(&chan_lock);
1876         return 0; 
1877 }
1878
1879 static void send_digit_to_chan(struct ast_channel * ast, char digit )
1880 {
1881         static const char* dtmf_tones[] = {
1882                 "!941+1336/100,!0/100", /* 0 */
1883                 "!697+1209/100,!0/100", /* 1 */
1884                 "!697+1336/100,!0/100", /* 2 */
1885                 "!697+1477/100,!0/100", /* 3 */
1886                 "!770+1209/100,!0/100", /* 4 */
1887                 "!770+1336/100,!0/100", /* 5 */
1888                 "!770+1477/100,!0/100", /* 6 */
1889                 "!852+1209/100,!0/100", /* 7 */
1890                 "!852+1336/100,!0/100", /* 8 */
1891                 "!852+1477/100,!0/100", /* 9 */
1892                 "!697+1633/100,!0/100", /* A */
1893                 "!770+1633/100,!0/100", /* B */
1894                 "!852+1633/100,!0/100", /* C */
1895                 "!941+1633/100,!0/100", /* D */
1896                 "!941+1209/100,!0/100", /* * */
1897                 "!941+1477/100,!0/100" };       /* # */
1898
1899         if (digit >= '0' && digit <='9')
1900                 ast_playtones_start(ast,0,dtmf_tones[digit-'0'], 0);
1901         else if (digit >= 'A' && digit <= 'D')
1902                 ast_playtones_start(ast,0,dtmf_tones[digit-'A'+10], 0);
1903         else if (digit == '*')
1904                 ast_playtones_start(ast,0,dtmf_tones[14], 0);
1905         else if (digit == '#')
1906                 ast_playtones_start(ast,0,dtmf_tones[15], 0);
1907         else {
1908                 /* not handled */
1909                 ast_log(LOG_DEBUG, "Unable to handle DTMF tone "
1910                         "'%c' for '%s'\n", digit, ast->name);
1911         }
1912 }
1913
1914 #ifdef LCR_FOR_ASTERISK
1915 static int lcr_digit_begin(struct ast_channel *ast, char digit)
1916 #endif
1917 #ifdef LCR_FOR_CALLWEAVER
1918 static int lcr_digit(struct ast_channel *ast, char digit)
1919 #endif
1920 {
1921         struct chan_call *call;
1922         union parameter newparam;
1923         char buf[]="x";
1924
1925 #ifdef LCR_FOR_CALLWEAVER
1926         int inband_dtmf = 0;
1927 #endif
1928
1929         /* only pass IA5 number space */
1930         if (digit > 126 || digit < 32)
1931                 return 0;
1932
1933         ast_mutex_lock(&chan_lock);
1934         call = ast->tech_pvt;
1935         if (!call) {
1936                 CERROR(NULL, ast, "Received digit from Asterisk, but no call instance exists.\n");
1937                 ast_mutex_unlock(&chan_lock);
1938                 return -1;
1939         }
1940
1941         CDEBUG(call, ast, "Received digit '%c' from Asterisk.\n", digit);
1942
1943         /* send information or queue them */
1944         if (call->ref && call->state == CHAN_LCR_STATE_OUT_DIALING) {
1945                 CDEBUG(call, ast, "Sending digit to LCR, because we are in dialing state.\n");
1946                 memset(&newparam, 0, sizeof(union parameter));
1947                 if (call->keypad) {
1948                         newparam.information.keypad[0] = digit;
1949                         newparam.information.keypad[1] = '\0';
1950                 } else {
1951                         newparam.information.id[0] = digit;
1952                         newparam.information.id[1] = '\0';
1953                 }
1954                 send_message(MESSAGE_INFORMATION, call->ref, &newparam);
1955         } else
1956         if (!call->ref
1957          && (call->state == CHAN_LCR_STATE_OUT_PREPARE || call->state == CHAN_LCR_STATE_OUT_SETUP)) {
1958                 CDEBUG(call, ast, "Queue digits, because we are in setup/dialing state and have no ref yet.\n");
1959                 *buf = digit;
1960                 strncat(call->dialque, buf, strlen(call->dialque)-1);
1961         }
1962
1963         ast_mutex_unlock(&chan_lock);
1964
1965 #ifdef LCR_FOR_ASTERISK
1966         return(0);
1967 }
1968
1969 static int lcr_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1970 {
1971         int inband_dtmf = 0;
1972         struct chan_call *call;
1973 #endif
1974
1975         ast_mutex_lock(&chan_lock);
1976
1977         call = ast->tech_pvt;
1978
1979         if (!call) {
1980                 CERROR(NULL, ast, 
1981                        "Received digit from Asterisk, "
1982                        "but no call instance exists.\n");
1983                 ast_mutex_unlock(&chan_lock);
1984                 return -1;
1985         }
1986
1987         CDEBUG(call, ast, "DIGIT END '%c' from Asterisk.\n", digit);
1988
1989         if (call->state == CHAN_LCR_STATE_CONNECT && call->inband_dtmf) {
1990                 inband_dtmf = 1;
1991         }
1992
1993         ast_mutex_unlock(&chan_lock);
1994
1995         if (inband_dtmf) {
1996                 CDEBUG(call, ast, "-> sending '%c' inband.\n", digit);
1997                 send_digit_to_chan(ast, digit);
1998         }
1999
2000         return (0);
2001 }
2002
2003 static int lcr_answer(struct ast_channel *ast)
2004 {
2005         union parameter newparam;
2006         struct chan_call *call;
2007
2008         ast_mutex_lock(&chan_lock);
2009         call = ast->tech_pvt;
2010         if (!call) {
2011                 CERROR(NULL, ast, "Received answer from Asterisk, but no call instance exists.\n");
2012                 ast_mutex_unlock(&chan_lock);
2013                 return -1;
2014         }
2015         
2016         CDEBUG(call, ast, "Received answer from Asterisk (maybe during lcr_bridge).\n");
2017                 
2018         /* copy connectinfo, if bridged */
2019         if (call->bridge_call)
2020                 memcpy(&call->connectinfo, &call->bridge_call->connectinfo, sizeof(struct connect_info));
2021         /* send connect message to lcr */
2022         if (call->state != CHAN_LCR_STATE_CONNECT) {
2023                 memset(&newparam, 0, sizeof(union parameter));
2024                 memcpy(&newparam.connectinfo, &call->connectinfo, sizeof(struct connect_info));
2025                 send_message(MESSAGE_CONNECT, call->ref, &newparam);
2026                 call->state = CHAN_LCR_STATE_CONNECT;
2027         }
2028         /* change state */
2029         /* request bchannel */
2030         if (!call->bchannel) {
2031                 CDEBUG(call, ast, "Requesting B-channel.\n");
2032                 memset(&newparam, 0, sizeof(union parameter));
2033                 newparam.bchannel.type = BCHANNEL_REQUEST;
2034                 send_message(MESSAGE_BCHANNEL, call->ref, &newparam);
2035         }
2036         /* enable keypad */
2037 //      memset(&newparam, 0, sizeof(union parameter));
2038 //      send_message(MESSAGE_ENABLEKEYPAD, call->ref, &newparam);
2039         
2040         ast_mutex_unlock(&chan_lock);
2041         return 0;
2042 }
2043
2044 static int lcr_hangup(struct ast_channel *ast)
2045 {
2046         struct chan_call *call;
2047         pthread_t tid = pthread_self();
2048
2049         if (!pthread_equal(tid, chan_tid))
2050                 ast_mutex_lock(&chan_lock);
2051         call = ast->tech_pvt;
2052         if (!call) {
2053                 CERROR(NULL, ast, "Received hangup from Asterisk, but no call instance exists.\n");
2054                 if (!pthread_equal(tid, chan_tid))
2055                         ast_mutex_unlock(&chan_lock);
2056                 return -1;
2057         }
2058
2059         if (!pthread_equal(tid, chan_tid))
2060                 CDEBUG(call, ast, "Received hangup from Asterisk thread.\n");
2061         else
2062                 CDEBUG(call, ast, "Received hangup from LCR thread.\n");
2063
2064         /* disconnect asterisk, maybe not required */
2065         ast->tech_pvt = NULL;
2066         ast->fds[0] = -1;
2067         if (call->ref) {
2068                 /* release */
2069                 CDEBUG(call, ast, "Releasing ref and freeing call instance.\n");
2070                 if (ast->hangupcause > 0)
2071                         send_release_and_import(call, ast->hangupcause, LOCATION_PRIVATE_LOCAL);
2072                 else
2073                         send_release_and_import(call, CAUSE_NORMAL, LOCATION_PRIVATE_LOCAL);
2074                 /* remove call */
2075                 free_call(call);
2076                 if (!pthread_equal(tid, chan_tid))
2077                         ast_mutex_unlock(&chan_lock);
2078                 return 0;
2079         } else {
2080                 /* ref is not set, due to prepare setup or release */
2081                 if (call->state == CHAN_LCR_STATE_RELEASE) {
2082                         /* we get the response to our release */
2083                         CDEBUG(call, ast, "Freeing call instance, because we have no ref AND we are requesting no ref.\n");
2084                         free_call(call);
2085                 } else {
2086                         /* during prepare, we change to release state */
2087                         CDEBUG(call, ast, "We must wait until we received our ref, until we can free call instance.\n");
2088                         call->state = CHAN_LCR_STATE_RELEASE;
2089                         call->ast = NULL;
2090                 }
2091         } 
2092         if (!pthread_equal(tid, chan_tid))
2093                 ast_mutex_unlock(&chan_lock);
2094         return 0;
2095 }
2096
2097 static int lcr_write(struct ast_channel *ast, struct ast_frame *f)
2098 {
2099         struct chan_call *call;
2100
2101         if (!f->subclass)
2102                 CDEBUG(NULL, ast, "No subclass\n");
2103         if (!(f->subclass & ast->nativeformats))
2104                 CDEBUG(NULL, ast, "Unexpected format.\n");
2105         
2106         ast_mutex_lock(&chan_lock);
2107         call = ast->tech_pvt;
2108         if (!call) {
2109                 ast_mutex_unlock(&chan_lock);
2110                 return -1;
2111         }
2112         if (call->bchannel && f->samples)
2113                 bchannel_transmit(call->bchannel, *((unsigned char **)&(f->data)), f->samples);
2114         ast_mutex_unlock(&chan_lock);
2115         return 0;
2116 }
2117
2118
2119 static struct ast_frame *lcr_read(struct ast_channel *ast)
2120 {
2121         struct chan_call *call;
2122         int len;
2123
2124         ast_mutex_lock(&chan_lock);
2125         call = ast->tech_pvt;
2126         if (!call) {
2127                 ast_mutex_unlock(&chan_lock);
2128                 return NULL;
2129         }
2130         if (call->pipe[0] > -1) {
2131                 if (call->rebuffer && !call->hdlc) {
2132                         /* Make sure we have a complete 20ms (160byte) frame */
2133                         len=read(call->pipe[0],call->read_buff + call->framepos, 160 - call->framepos);
2134                         if (len > 0) {
2135                                 call->framepos += len;
2136                         }
2137                 } else {
2138                         len = read(call->pipe[0], call->read_buff, sizeof(call->read_buff));
2139                 }
2140                 if (len < 0 && errno == EAGAIN) {
2141                         ast_mutex_unlock(&chan_lock);
2142
2143                         #ifdef LCR_FOR_ASTERISK
2144                         return &ast_null_frame;
2145                         #endif
2146                         
2147                         #ifdef LCR_FOR_CALLWEAVER
2148                         return &nullframe;
2149                         #endif
2150                         
2151                 }
2152                 if (len <= 0) {
2153                         close(call->pipe[0]);
2154                         call->pipe[0] = -1;
2155                         ast_mutex_unlock(&chan_lock);
2156                         return NULL;
2157                 } else if (call->rebuffer && call->framepos < 160) {
2158                         /* Not a complete frame, so we send a null-frame */
2159                         ast_mutex_unlock(&chan_lock);
2160                         return &ast_null_frame;
2161                 }
2162         }
2163
2164         call->read_fr.frametype = AST_FRAME_VOICE;
2165         call->read_fr.subclass = ast->nativeformats;
2166         if (call->rebuffer) {
2167                 call->read_fr.datalen = call->framepos;
2168                 call->read_fr.samples = call->framepos;
2169                 call->framepos = 0;
2170         } else {
2171                 call->read_fr.datalen = len;
2172                 call->read_fr.samples = len;
2173         }
2174         call->read_fr.delivery = ast_tv(0,0);
2175         *((unsigned char **)&(call->read_fr.data)) = call->read_buff;
2176         ast_mutex_unlock(&chan_lock);
2177
2178         return &call->read_fr;
2179 }
2180
2181 static int lcr_indicate(struct ast_channel *ast, int cond, const void *data, size_t datalen)
2182 {
2183         union parameter newparam;
2184         int res = 0;
2185         struct chan_call *call;
2186
2187         ast_mutex_lock(&chan_lock);
2188         call = ast->tech_pvt;
2189         if (!call) {
2190                 CERROR(NULL, ast, "Received indicate from Asterisk, but no call instance exists.\n");
2191                 ast_mutex_unlock(&chan_lock);
2192                 return -1;
2193         }
2194
2195         switch (cond) {
2196                 case AST_CONTROL_BUSY:
2197                         CDEBUG(call, ast, "Received indicate AST_CONTROL_BUSY from Asterisk.\n");
2198                         ast_setstate(ast, AST_STATE_BUSY);
2199                         if (call->state != CHAN_LCR_STATE_OUT_DISCONNECT) {
2200                                 /* send message to lcr */
2201                                 memset(&newparam, 0, sizeof(union parameter));
2202                                 newparam.disconnectinfo.cause = 17;
2203                                 newparam.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
2204                                 send_message(MESSAGE_DISCONNECT, call->ref, &newparam);
2205                                 /* change state */
2206                                 call->state = CHAN_LCR_STATE_OUT_DISCONNECT;
2207                         }
2208                         break;
2209                 case AST_CONTROL_CONGESTION:
2210                         CDEBUG(call, ast, "Received indicate AST_CONTROL_CONGESTION from Asterisk. (cause %d)\n", ast->hangupcause);
2211                         if (call->state != CHAN_LCR_STATE_OUT_DISCONNECT) {
2212                                 /* send message to lcr */
2213                                 memset(&newparam, 0, sizeof(union parameter));
2214                                 newparam.disconnectinfo.cause = ast->hangupcause;
2215                                 newparam.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
2216                                 send_message(MESSAGE_DISCONNECT, call->ref, &newparam);
2217                                 /* change state */
2218                                 call->state = CHAN_LCR_STATE_OUT_DISCONNECT;
2219                         }
2220                         break;
2221                 case AST_CONTROL_PROCEEDING:
2222                         CDEBUG(call, ast, "Received indicate AST_CONTROL_PROCEEDING from Asterisk.\n");
2223                         if (call->state == CHAN_LCR_STATE_IN_SETUP
2224                          || call->state == CHAN_LCR_STATE_IN_DIALING) {
2225                                 /* send message to lcr */
2226                                 memset(&newparam, 0, sizeof(union parameter));
2227                                 send_message(MESSAGE_PROCEEDING, call->ref, &newparam);
2228                                 /* change state */
2229                                 call->state = CHAN_LCR_STATE_IN_PROCEEDING;
2230                         }
2231                         break;
2232                 case AST_CONTROL_RINGING:
2233                         CDEBUG(call, ast, "Received indicate AST_CONTROL_RINGING from Asterisk.\n");
2234                         ast_setstate(ast, AST_STATE_RING);
2235                         if (call->state == CHAN_LCR_STATE_IN_SETUP
2236                          || call->state == CHAN_LCR_STATE_IN_DIALING
2237                          || call->state == CHAN_LCR_STATE_IN_PROCEEDING) {
2238                                 /* send message to lcr */
2239                                 memset(&newparam, 0, sizeof(union parameter));
2240                                 send_message(MESSAGE_ALERTING, call->ref, &newparam);
2241                                 /* change state */
2242                                 call->state = CHAN_LCR_STATE_IN_ALERTING;
2243                         }
2244                         break;
2245                 case AST_CONTROL_PROGRESS:
2246                         CDEBUG(call, ast, "Received indicate AST_CONTROL_PROGRESS from Asterisk.\n");
2247                         /* request bchannel */
2248                         if (!call->bchannel) {
2249                                 CDEBUG(call, ast, "Requesting B-channel.\n");
2250                                 memset(&newparam, 0, sizeof(union parameter));
2251                                 newparam.bchannel.type = BCHANNEL_REQUEST;
2252                                 send_message(MESSAGE_BCHANNEL, call->ref, &newparam);
2253                         }
2254                         break;
2255                 case -1:
2256                         CDEBUG(call, ast, "Received indicate -1.\n");
2257                         res = -1;
2258                         break;
2259
2260                 case AST_CONTROL_VIDUPDATE:
2261                         CDEBUG(call, ast, "Received indicate AST_CONTROL_VIDUPDATE.\n");
2262                         res = -1;
2263                         break;
2264                 case AST_CONTROL_HOLD:
2265                         CDEBUG(call, ast, "Received indicate AST_CONTROL_HOLD from Asterisk.\n");
2266                         /* send message to lcr */
2267                         memset(&newparam, 0, sizeof(union parameter));
2268                         newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_HOLD;
2269                         send_message(MESSAGE_NOTIFY, call->ref, &newparam);
2270                         
2271                         /*start music onhold*/
2272                         #ifdef LCR_FOR_ASTERISK
2273                         ast_moh_start(ast,data,ast->musicclass);
2274                         #endif
2275                         
2276                         #ifdef LCR_FOR_CALLWEAVER
2277                         ast_moh_start(ast, NULL);
2278                         #endif
2279                         
2280                         call->on_hold = 1;
2281                         break;
2282                 case AST_CONTROL_UNHOLD:
2283                         CDEBUG(call, ast, "Received indicate AST_CONTROL_UNHOLD from Asterisk.\n");
2284                         /* send message to lcr */
2285                         memset(&newparam, 0, sizeof(union parameter));
2286                         newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_RETRIEVAL;
2287                         send_message(MESSAGE_NOTIFY, call->ref, &newparam);
2288
2289                         /*stop moh*/
2290                         ast_moh_stop(ast);
2291                         call->on_hold = 0;
2292                         break;
2293 #ifdef AST_CONTROL_SRCUPDATE
2294                 case AST_CONTROL_SRCUPDATE:
2295                         CDEBUG(call, ast, "Received AST_CONTROL_SRCUPDATE from Asterisk.\n");
2296                         break;
2297 #endif
2298                 default:
2299                         CERROR(call, ast, "Received indicate from Asterisk with unknown condition %d.\n", cond);
2300                         res = -1;
2301                         break;
2302         }
2303
2304         /* return */
2305         ast_mutex_unlock(&chan_lock);
2306         return res;
2307 }
2308
2309 /*
2310  * fixup asterisk
2311  */
2312 static int lcr_fixup(struct ast_channel *oldast, struct ast_channel *ast)
2313 {
2314         struct chan_call *call;
2315
2316         if (!ast) {
2317                 return -1;
2318         }
2319
2320         ast_mutex_lock(&chan_lock);
2321         call = ast->tech_pvt;
2322         if (!call) {
2323                 CERROR(NULL, ast, "Received fixup from Asterisk, but no call instance exists.\n");
2324                 ast_mutex_unlock(&chan_lock);
2325                 return -1;
2326         }
2327
2328         CDEBUG(call, ast, "Received fixup from Asterisk.\n");
2329         call->ast = ast;
2330         ast_mutex_unlock(&chan_lock);
2331         return 0;
2332 }
2333
2334 /*
2335  * send_text asterisk
2336  */
2337 static int lcr_send_text(struct ast_channel *ast, const char *text)
2338 {
2339         struct chan_call *call;
2340         union parameter newparam;
2341
2342         ast_mutex_lock(&chan_lock);
2343         call = ast->tech_pvt;
2344         if (!call) {
2345                 CERROR(NULL, ast, "Received send_text from Asterisk, but no call instance exists.\n");
2346                 ast_mutex_unlock(&chan_lock);
2347                 return -1;
2348         }
2349
2350         CDEBUG(call, ast, "Received send_text from Asterisk. (text=%s)\n", text);
2351         memset(&newparam, 0, sizeof(union parameter));
2352         strncpy(newparam.notifyinfo.display, text, sizeof(newparam.notifyinfo.display)-1);
2353         send_message(MESSAGE_NOTIFY, call->ref, &newparam);
2354         ast_mutex_lock(&chan_lock);
2355         return 0;
2356 }
2357
2358 /*
2359  * bridge process
2360  */
2361 enum ast_bridge_result lcr_bridge(struct ast_channel *ast1,
2362                                   struct ast_channel *ast2, int flags,
2363                                   struct ast_frame **fo,
2364                                   struct ast_channel **rc, int timeoutms)
2365
2366 {
2367         struct chan_call        *call1, *call2;
2368         struct ast_channel      *carr[2], *who;
2369         int                     to;
2370         struct ast_frame        *f;
2371         int                     bridge_id;
2372
2373         CDEBUG(NULL, NULL, "Received bridging request from Asterisk.\n");
2374
2375         carr[0] = ast1;
2376         carr[1] = ast2;
2377
2378         /* join via dsp (if the channels are currently open) */
2379         ast_mutex_lock(&chan_lock);
2380         call1 = ast1->tech_pvt;
2381         call2 = ast2->tech_pvt;
2382         if (!call1 || !call2) {
2383                 CDEBUG(NULL, NULL, "Bridge, but we don't have two call instances, exitting.\n");
2384                 ast_mutex_unlock(&chan_lock);
2385                 return AST_BRIDGE_COMPLETE;
2386         }
2387
2388         /* join, if both call instances uses dsp 
2389            ignore the case of fax detection here it may be benificial for ISDN fax machines or pass through.
2390         */
2391         if (!call1->nodsp && !call2->nodsp) {
2392                 CDEBUG(NULL, NULL, "Both calls use DSP, bridging via DSP.\n");
2393
2394                 /* get bridge id and join */
2395                 bridge_id = new_bridge_id();
2396                 
2397                 call1->bridge_id = bridge_id;
2398                 if (call1->bchannel)
2399                         bchannel_join(call1->bchannel, bridge_id);
2400
2401                 call2->bridge_id = bridge_id;
2402                 if (call2->bchannel)
2403                         bchannel_join(call2->bchannel, bridge_id);
2404         } else
2405         if (call1->nodsp && call2->nodsp)
2406                 CDEBUG(NULL, NULL, "Both calls use no DSP, bridging in channel driver.\n");
2407         else
2408                 CDEBUG(NULL, NULL, "One call uses no DSP, bridging in channel driver.\n");
2409         call1->bridge_call = call2;
2410         call2->bridge_call = call1;
2411
2412         if (call1->state == CHAN_LCR_STATE_IN_SETUP
2413          || call1->state == CHAN_LCR_STATE_IN_DIALING
2414          || call1->state == CHAN_LCR_STATE_IN_PROCEEDING
2415          || call1->state == CHAN_LCR_STATE_IN_ALERTING) {
2416                 CDEBUG(call1, ast1, "Bridge established before lcr_answer, so we call it ourself: Calling lcr_answer...\n");
2417                 lcr_answer(ast1);
2418         }
2419         if (call2->state == CHAN_LCR_STATE_IN_SETUP
2420          || call2->state == CHAN_LCR_STATE_IN_DIALING
2421          || call2->state == CHAN_LCR_STATE_IN_PROCEEDING
2422          || call2->state == CHAN_LCR_STATE_IN_ALERTING) {
2423                 CDEBUG(call2, ast2, "Bridge established before lcr_answer, so we call it ourself: Calling lcr_answer...\n");
2424                 lcr_answer(ast2);
2425         }
2426
2427         /* sometimes SIP phones forget to send RETRIEVE before TRANSFER
2428            so let's do it for them. Hmpf.
2429         */
2430
2431         if (call1->on_hold) {
2432                 union parameter newparam;
2433
2434                 memset(&newparam, 0, sizeof(union parameter));
2435                 newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_RETRIEVAL;
2436                 send_message(MESSAGE_NOTIFY, call1->ref, &newparam);
2437
2438                 call1->on_hold = 0;
2439         }
2440
2441         if (call2->on_hold) {
2442                 union parameter newparam;
2443
2444                 memset(&newparam, 0, sizeof(union parameter));
2445                 newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_RETRIEVAL;
2446                 send_message(MESSAGE_NOTIFY, call2->ref, &newparam);
2447
2448                 call2->on_hold = 0;
2449         }
2450         
2451         ast_mutex_unlock(&chan_lock);
2452         
2453         while(1) {
2454                 to = -1;
2455                 who = ast_waitfor_n(carr, 2, &to);
2456
2457                 if (!who) {
2458                         CDEBUG(NULL, NULL, "Empty read on bridge, breaking out.\n");
2459                         break;
2460                 }
2461                 f = ast_read(who);
2462     
2463                 if (!f || f->frametype == AST_FRAME_CONTROL) {
2464                         if (!f)
2465                                 CDEBUG(NULL, NULL, "Got hangup.\n");
2466                         else
2467                                 CDEBUG(NULL, NULL, "Got CONTROL.\n");
2468                         /* got hangup .. */
2469                         *fo=f;
2470                         *rc=who;
2471                         break;
2472                 }
2473                 
2474                 if ( f->frametype == AST_FRAME_DTMF ) {
2475                         CDEBUG(NULL, NULL, "Got DTMF.\n");
2476                         *fo=f;
2477                         *rc=who;
2478                         break;
2479                 }
2480         
2481
2482                 if (who == ast1) {
2483                         ast_write(ast2,f);
2484                 }
2485                 else {
2486                         ast_write(ast1,f);
2487                 }
2488     
2489         }
2490         
2491         CDEBUG(NULL, NULL, "Releasing bridge.\n");
2492
2493         /* split channels */
2494         ast_mutex_lock(&chan_lock);
2495         call1 = ast1->tech_pvt;
2496         call2 = ast2->tech_pvt;
2497         if (call1 && call1->bridge_id) {
2498                 call1->bridge_id = 0;
2499                 if (call1->bchannel)
2500                         bchannel_join(call1->bchannel, 0);
2501                 if (call1->bridge_call)
2502                         call1->bridge_call->bridge_call = NULL;
2503         }
2504         if (call2 && call1->bridge_id) {
2505                 call2->bridge_id = 0;
2506                 if (call2->bchannel)
2507                         bchannel_join(call2->bchannel, 0);
2508                 if (call2->bridge_call)
2509                         call2->bridge_call->bridge_call = NULL;
2510         }
2511         call1->bridge_call = NULL;
2512         call2->bridge_call = NULL;
2513
2514         ast_mutex_unlock(&chan_lock);
2515         return AST_BRIDGE_COMPLETE;
2516 }
2517 static struct ast_channel_tech lcr_tech = {
2518         .type="LCR",
2519         .description = "Channel driver for connecting to Linux-Call-Router",
2520         .capabilities = AST_FORMAT_ALAW,
2521         .requester = lcr_request,
2522
2523         #ifdef LCR_FOR_ASTERISK
2524         .send_digit_begin = lcr_digit_begin,
2525         .send_digit_end = lcr_digit_end,
2526         #endif
2527
2528         #ifdef LCR_FOR_CALLWEAVER
2529         .send_digit = lcr_digit,
2530         #endif
2531
2532         .call = lcr_call,
2533         .bridge = lcr_bridge, 
2534         .hangup = lcr_hangup,
2535         .answer = lcr_answer,
2536         .read = lcr_read,
2537         .write = lcr_write,
2538         .indicate = lcr_indicate,
2539         .fixup = lcr_fixup,
2540         .send_text = lcr_send_text,
2541         .properties = 0
2542 };
2543
2544
2545 /*
2546  * cli
2547  */
2548 #if 0
2549 static int lcr_show_lcr (int fd, int argc, char *argv[])
2550 {
2551         return 0;
2552 }
2553
2554 static int lcr_show_calls (int fd, int argc, char *argv[])
2555 {
2556         return 0;
2557 }
2558
2559 static int lcr_reload_routing (int fd, int argc, char *argv[])
2560 {
2561         return 0;
2562 }
2563
2564 static int lcr_reload_interfaces (int fd, int argc, char *argv[])
2565 {
2566         return 0;
2567 }
2568
2569 static int lcr_port_block (int fd, int argc, char *argv[])
2570 {
2571         return 0;
2572 }
2573
2574 static int lcr_port_unblock (int fd, int argc, char *argv[])
2575 {
2576         return 0;
2577 }
2578
2579 static int lcr_port_unload (int fd, int argc, char *argv[])
2580 {
2581         return 0;
2582 }
2583
2584 static struct ast_cli_entry cli_show_lcr =
2585 { {"lcr", "show", "lcr", NULL},
2586  lcr_show_lcr,
2587  "Shows current states of LCR core",
2588  "Usage: lcr show lcr\n",
2589 };
2590
2591 static struct ast_cli_entry cli_show_calls =
2592 { {"lcr", "show", "calls", NULL},
2593  lcr_show_calls,
2594  "Shows current calls made by LCR and Asterisk",
2595  "Usage: lcr show calls\n",
2596 };
2597
2598 static struct ast_cli_entry cli_reload_routing =
2599 { {"lcr", "reload", "routing", NULL},
2600  lcr_reload_routing,
2601  "Reloads routing conf of LCR, current uncomplete calls will be disconnected",
2602  "Usage: lcr reload routing\n",
2603 };
2604
2605 static struct ast_cli_entry cli_reload_interfaces =
2606 { {"lcr", "reload", "interfaces", NULL},
2607  lcr_reload_interfaces,
2608  "Reloads interfaces conf of LCR",
2609  "Usage: lcr reload interfaces\n",
2610 };
2611
2612 static struct ast_cli_entry cli_port_block =
2613 { {"lcr", "port", "block", NULL},
2614  lcr_port_block,
2615  "Blocks LCR port for further calls",
2616  "Usage: lcr port block \"<port>\"\n",
2617 };
2618
2619 static struct ast_cli_entry cli_port_unblock =
2620 { {"lcr", "port", "unblock", NULL},
2621  lcr_port_unblock,
2622  "Unblocks or loads LCR port, port is opened my mISDN",
2623  "Usage: lcr port unblock \"<port>\"\n",
2624 };
2625
2626 static struct ast_cli_entry cli_port_unload =
2627 { {"lcr", "port", "unload", NULL},
2628  lcr_port_unload,
2629  "Unloads LCR port, port is closes by mISDN",
2630  "Usage: lcr port unload \"<port>\"\n",
2631 };
2632 #endif
2633
2634
2635 #ifdef LCR_FOR_ASTERISK
2636 static int lcr_config_exec(struct ast_channel *ast, void *data)
2637 #endif
2638
2639 #ifdef LCR_FOR_CALLWEAVER
2640 static int lcr_config_exec(struct ast_channel *ast, void *data, char **argv)
2641 #endif
2642 {
2643         struct chan_call *call;
2644
2645         ast_mutex_lock(&chan_lock);
2646
2647         #ifdef LCR_FOR_ASTERISK
2648         CDEBUG(NULL, ast, "Received lcr_config (data=%s)\n", (char *)data);
2649         #endif
2650         
2651         #ifdef LCR_FOR_CALLWEAVER
2652         CDEBUG(NULL, ast, "Received lcr_config (data=%s)\n", argv[0]);
2653         #endif
2654         
2655         /* find channel */
2656         call = call_first;
2657         while(call) {
2658                 if (call->ast == ast)
2659                         break;
2660                 call = call->next;
2661         }
2662         if (call)
2663                 
2664                 #ifdef LCR_FOR_ASTERISK
2665                 apply_opt(call, (char *)data);
2666                 #endif          
2667                 
2668                 #ifdef LCR_FOR_CALLWEAVER               
2669                 apply_opt(call, (char *)argv[0]);
2670                 #endif
2671
2672         else
2673                 CERROR(NULL, ast, "lcr_config app not called by chan_lcr channel.\n");
2674
2675         ast_mutex_unlock(&chan_lock);
2676         return 0;
2677 }
2678
2679 /*
2680  * module loading and destruction
2681  */
2682 int load_module(void)
2683 {
2684         u_short i;
2685
2686         for (i = 0; i < 256; i++) {
2687                 flip_bits[i] = (i>>7) | ((i>>5)&2) | ((i>>3)&4) | ((i>>1)&8)
2688                              | (i<<7) | ((i&2)<<5) | ((i&4)<<3) | ((i&8)<<1);
2689         }
2690
2691         if (read_options() == 0) {
2692                 CERROR(NULL, NULL, "%s", options_error);
2693
2694                 #ifdef LCR_FOR_ASTERISK
2695                 return AST_MODULE_LOAD_DECLINE;
2696                 #endif          
2697                 
2698                 #ifdef LCR_FOR_CALLWEAVER
2699                 return 0;
2700                 #endif
2701                         
2702         }
2703
2704         ast_mutex_init(&chan_lock);
2705         ast_mutex_init(&log_lock);
2706
2707         if (open_socket() < 0) {
2708                 /* continue with closed socket */
2709         }
2710
2711         if (bchannel_initialize()) {
2712                 CERROR(NULL, NULL, "Unable to open mISDN device\n");
2713                 close_socket();
2714                 
2715                 #ifdef LCR_FOR_ASTERISK
2716                 return AST_MODULE_LOAD_DECLINE;
2717                 #endif          
2718                 
2719                 #ifdef LCR_FOR_CALLWEAVER
2720                 return 0;
2721                 #endif
2722         }
2723         mISDN_created = 1;
2724
2725         lcr_tech.capabilities = (options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW;
2726         if (ast_channel_register(&lcr_tech)) {
2727                 CERROR(NULL, NULL, "Unable to register channel class\n");
2728                 bchannel_deinitialize();
2729                 close_socket();
2730
2731                 #ifdef LCR_FOR_ASTERISK
2732                 return AST_MODULE_LOAD_DECLINE;
2733                 #endif          
2734                 
2735                 #ifdef LCR_FOR_CALLWEAVER
2736                 return 0;
2737                 #endif
2738         }
2739
2740         ast_register_application("lcr_config", lcr_config_exec, "lcr_config",
2741                                 
2742                                  #ifdef LCR_FOR_ASTERISK
2743                                  "lcr_config(<opt><optarg>:<opt>:...)\n"
2744                                  #endif
2745                                  
2746                                  #ifdef LCR_FOR_CALLWEAVER
2747                                  "lcr_config(<opt><optarg>:<opt>:...)\n",                                
2748                                  #endif
2749                                                          
2750                                  "Sets LCR opts. and optargs\n"
2751                                  "\n"
2752                                  "The available options are:\n"
2753                                  "    d - Send display text on called phone, text is the optarg.\n"
2754                                  "    n - Don't detect dtmf tones on called channel.\n"
2755                                  "    h - Force data call (HDLC).\n" 
2756                                  "    t - Disable mISDN_dsp features (required for fax application).\n"
2757                                  "    f - Adding fax detection. It it timeouts, mISDN_dsp is used.\n"
2758                                  "        Use time to detect for optarg.\n"
2759                                  "    c - Make crypted outgoing call, optarg is keyindex.\n"
2760                                  "    e - Perform echo cancelation on this channel.\n"
2761                                  "        Takes mISDN pipeline option as optarg.\n"
2762                                  "    s - Send Non Inband DTMF as inband.\n"
2763                                  "    r - re-buffer packets (160 bytes). Required for some SIP-phones and fax applications.\n"
2764                                  "   vr - rxgain control\n"
2765                                  "   vt - txgain control\n"
2766                                  "        Volume changes at factor 2 ^ optarg.\n"
2767                                  "    k - use keypad to dial this call.\n"
2768                 );
2769
2770  
2771 #if 0   
2772         ast_cli_register(&cli_show_lcr);
2773         ast_cli_register(&cli_show_calls);
2774         ast_cli_register(&cli_reload_routing);
2775         ast_cli_register(&cli_reload_interfaces);
2776         ast_cli_register(&cli_port_block);
2777         ast_cli_register(&cli_port_unblock);
2778         ast_cli_register(&cli_port_unload);
2779 #endif
2780
2781         quit = 0;       
2782         if ((pthread_create(&chan_tid, NULL, chan_thread, NULL)<0)) {
2783                 /* failed to create thread */
2784                 bchannel_deinitialize();
2785                 close_socket();
2786                 ast_channel_unregister(&lcr_tech);
2787
2788                 #ifdef LCR_FOR_ASTERISK
2789                 return AST_MODULE_LOAD_DECLINE;
2790                 #endif          
2791                 
2792                 #ifdef LCR_FOR_CALLWEAVER
2793                 return 0;
2794                 #endif
2795                 
2796         }
2797         return 0;
2798 }
2799
2800 int unload_module(void)
2801 {
2802         /* First, take us out of the channel loop */
2803         CDEBUG(NULL, NULL, "-- Unregistering mISDN Channel Driver --\n");
2804
2805         quit = 1;
2806         pthread_join(chan_tid, NULL);   
2807         
2808         ast_channel_unregister(&lcr_tech);
2809
2810         ast_unregister_application("lcr_config");
2811
2812
2813         if (mISDN_created) {
2814                 bchannel_deinitialize();
2815                 mISDN_created = 0;
2816         }
2817
2818         if (lcr_sock >= 0) {
2819                 close(lcr_sock);
2820                 lcr_sock = -1;
2821         }
2822
2823         return 0;
2824 }
2825
2826 int reload_module(void)
2827 {
2828 //      reload_config();
2829         return 0;
2830 }
2831
2832 #ifdef LCR_FOR_ASTERISK
2833 #define AST_MODULE "chan_lcr"
2834 #endif
2835
2836 #ifdef LCR_FOR_CALLWEAVER
2837 int usecount(void)
2838 {
2839         int res;
2840         ast_mutex_lock(&usecnt_lock);
2841         res = usecnt;
2842         ast_mutex_unlock(&usecnt_lock);
2843         return res;
2844 }
2845 #endif
2846
2847 #ifdef LCR_FOR_ASTERISK
2848 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Channel driver for Linux-Call-Router Support (ISDN BRI/PRI)",
2849                 .load = load_module,
2850                 .unload = unload_module,
2851                 .reload = reload_module,
2852                );
2853 #endif
2854
2855 #ifdef LCR_FOR_CALLWEAVER
2856 char *description(void)
2857 {
2858         return desc;
2859 }
2860 #endif