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