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