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