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