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