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