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