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