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