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