[chan_lcr] Fixed caller ID for calls from AST->LCR
[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                                 CDEBUG(NULL, NULL, "No call found, that requests a ref.\n");
1526                                 send_release_and_import(call, CAUSE_NORMAL, LOCATION_PRIVATE_LOCAL);
1527                                 return 0;
1528                         }
1529                         /* store new ref */
1530                         call->ref = ref;
1531                         call->ref_was_assigned = 1;
1532                         /* set dtmf (default, use option 'n' to disable */
1533                         call->dsp_dtmf = 1;
1534                         /* send pending setup info */
1535                         if (call->state == CHAN_LCR_STATE_OUT_PREPARE)
1536                                 send_setup_to_lcr(call);
1537                         /* release if asterisk has signed off */
1538                         else if (call->state == CHAN_LCR_STATE_RELEASE) {
1539                                 /* send release */
1540                                 if (call->cause)
1541                                         send_release_and_import(call, call->cause, call->location);
1542                                 else
1543                                         send_release_and_import(call, CAUSE_NORMAL, LOCATION_PRIVATE_LOCAL);
1544                                 /* free call */
1545                                 free_call(call);
1546                                 return 0;
1547                         }
1548                 }
1549                 return 0;
1550         }
1551
1552         /* check ref */
1553         if (!ref) {
1554                 CERROR(NULL, NULL, "Received message %d without ref.\n", message_type);
1555                 return -1;
1556         }
1557         call = find_call_ref(ref);
1558         if (!call) {
1559                 /* ignore ref that is not used (anymore) */
1560                 CDEBUG(NULL, NULL, "Message %d from LCR ignored, because no call instance found.\n", message_type);
1561                 return 0;
1562         }
1563
1564         /* handle messages */
1565         switch(message_type) {
1566                 case MESSAGE_SETUP:
1567                 lcr_in_setup(call, message_type, param);
1568                 break;
1569
1570                 case MESSAGE_OVERLAP:
1571                 lcr_in_overlap(call, message_type, param);
1572                 break;
1573
1574                 case MESSAGE_PROCEEDING:
1575                 lcr_in_proceeding(call, message_type, param);
1576                 break;
1577
1578                 case MESSAGE_ALERTING:
1579                 lcr_in_alerting(call, message_type, param);
1580                 break;
1581
1582                 case MESSAGE_CONNECT:
1583                 lcr_in_connect(call, message_type, param);
1584                 break;
1585
1586                 case MESSAGE_DISCONNECT:
1587                 lcr_in_disconnect(call, message_type, param);
1588                 break;
1589
1590                 case MESSAGE_RELEASE:
1591                 lcr_in_release(call, message_type, param);
1592                 break;
1593
1594                 case MESSAGE_INFORMATION:
1595                 lcr_in_information(call, message_type, param);
1596                 break;
1597
1598                 case MESSAGE_NOTIFY:
1599                 lcr_in_notify(call, message_type, param);
1600                 break;
1601
1602                 case MESSAGE_FACILITY:
1603                 lcr_in_facility(call, message_type, param);
1604                 break;
1605
1606                 case MESSAGE_PATTERN: // audio available from LCR
1607                 if (!call->has_pattern)
1608                         lcr_in_pattern(call, message_type, param);
1609                 break;
1610
1611                 case MESSAGE_NOPATTERN: // audio not available from LCR
1612                 break;
1613
1614                 case MESSAGE_AUDIOPATH: // if remote audio connected or hold
1615                 call->audiopath = param->audiopath;
1616                 break;
1617
1618                 default:
1619                 CDEBUG(call, call->ast, "Message %d from LCR unhandled.\n", message_type);
1620                 break;
1621         }
1622         return 0;
1623 }
1624
1625 /*
1626  * release all calls (due to broken socket)
1627  */
1628 static void release_all_calls(void)
1629 {
1630         struct chan_call *call;
1631
1632 again:
1633         call = call_first;
1634         while(call) {
1635                 /* no ast, so we may directly free call */
1636                 if (!call->ast) {
1637                         CDEBUG(call, NULL, "Freeing call, because no Asterisk channel is linked.\n");
1638                         free_call(call);
1639                         goto again;
1640                 }
1641                 /* already in release process */
1642                 if (call->state == CHAN_LCR_STATE_RELEASE) {
1643                         call = call->next;
1644                         continue;
1645                 }
1646                 /* release or queue release */
1647                 call->ref = 0;
1648                 call->state = CHAN_LCR_STATE_RELEASE;
1649                 if (!call->pbx_started) {
1650                         CDEBUG(call, call->ast, "Releasing call, because no Asterisk channel is not started.\n");
1651                         ast_hangup(call->ast); // call will be destroyed here
1652                         goto again;
1653                 }
1654                 CDEBUG(call, call->ast, "Queue call release, because Asterisk channel is running.\n");
1655                 if (!wake_global) {
1656                         wake_global = 1;
1657                         char byte = 0;
1658                         write(wake_pipe[1], &byte, 1);
1659                 }
1660                 strcpy(call->queue_string, "H");
1661                 call = call->next;
1662         }
1663
1664         /* release all bchannels */
1665         while(bchannel_first)
1666                 free_bchannel(bchannel_first);
1667 }
1668
1669 void close_socket(void);
1670
1671 /* asterisk handler
1672  * warning! not thread safe
1673  * returns -1 for socket error, 0 for no work, 1 for work
1674  */
1675 static int handle_socket(struct lcr_fd *fd, unsigned int what, void *instance, int index)
1676 {
1677         int len;
1678         struct admin_list *admin;
1679         struct admin_message msg;
1680
1681         if ((what & LCR_FD_READ)) {
1682                 /* read from socket */
1683                 len = read(lcr_sock, &msg, sizeof(msg));
1684                 if (len == 0) {
1685                         CERROR(NULL, NULL, "Socket closed.(read)\n");
1686                         error:
1687                         CERROR(NULL, NULL, "Handling of socket failed - closing for some seconds.\n");
1688                         close_socket();
1689                         release_all_calls();
1690                         schedule_timer(&socket_retry, SOCKET_RETRY_TIMER, 0);
1691                         return 0;
1692                 }
1693                 if (len > 0) {
1694                         if (len != sizeof(msg)) {
1695                                 CERROR(NULL, NULL, "Socket short read. (len %d)\n", len);
1696                                 goto error;
1697                         }
1698                         if (msg.message != ADMIN_MESSAGE) {
1699                                 CERROR(NULL, NULL, "Socket received illegal message %d.\n", msg.message);
1700                                 goto error;
1701                         }
1702                         receive_message(msg.u.msg.type, msg.u.msg.ref, &msg.u.msg.param);
1703                 } else {
1704                         CERROR(NULL, NULL, "Socket failed (errno %d).\n", errno);
1705                         goto error;
1706                 }
1707         }
1708
1709         if ((what & LCR_FD_WRITE)) {
1710                 /* write to socket */
1711                 if (!admin_first) {
1712                         socket_fd.when &= ~LCR_FD_WRITE;
1713                         return 0;
1714                 }
1715                 admin = admin_first;
1716                 len = write(lcr_sock, &admin->msg, sizeof(msg));
1717                 if (len == 0) {
1718                         CERROR(NULL, NULL, "Socket closed.(write)\n");
1719                         goto error;
1720                 }
1721                 if (len > 0) {
1722                         if (len != sizeof(msg)) {
1723                                 CERROR(NULL, NULL, "Socket short write. (len %d)\n", len);
1724                                 goto error;
1725                         }
1726                         /* free head */
1727                         admin_first = admin->next;
1728                         free(admin);
1729                         global_change = 1;
1730                 } else {
1731                         CERROR(NULL, NULL, "Socket failed (errno %d).\n", errno);
1732                         goto error;
1733                 }
1734         }
1735
1736         return 0;
1737 }
1738
1739 /*
1740  * open and close socket and thread
1741  */
1742 int open_socket(void)
1743 {
1744         int conn;
1745         struct sockaddr_un sock_address;
1746         union parameter param;
1747
1748         /* open socket */
1749         if ((lcr_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
1750                 CERROR(NULL, NULL, "Failed to create socket.\n");
1751                 return lcr_sock;
1752         }
1753
1754         /* set socket address and name */
1755         memset(&sock_address, 0, sizeof(sock_address));
1756         sock_address.sun_family = PF_UNIX;
1757         sprintf(sock_address.sun_path, SOCKET_NAME, options.lock);
1758
1759         /* connect socket */
1760         if ((conn = connect(lcr_sock, (struct sockaddr *)&sock_address, SUN_LEN(&sock_address))) < 0) {
1761                 close(lcr_sock);
1762                 lcr_sock = -1;
1763                 CDEBUG(NULL, NULL, "Failed to connect to socket '%s'. Is LCR running?\n", sock_address.sun_path);
1764                 return conn;
1765         }
1766
1767         /* register socket fd */
1768         memset(&socket_fd, 0, sizeof(socket_fd));
1769         socket_fd.fd = lcr_sock;
1770         register_fd(&socket_fd, LCR_FD_READ | LCR_FD_EXCEPT, handle_socket, NULL, 0);
1771
1772         /* enque hello message */
1773         memset(&param, 0, sizeof(param));
1774         strcpy(param.hello.application, "asterisk");
1775         send_message(MESSAGE_HELLO, 0, &param);
1776
1777         return lcr_sock;
1778 }
1779
1780 void close_socket(void)
1781 {
1782         struct admin_list *admin, *temp;
1783
1784         unregister_fd(&socket_fd);
1785
1786         /* flush pending messages */
1787         admin = admin_first;
1788         while(admin) {
1789                 temp = admin;
1790                 admin = admin->next;
1791                 free(temp);
1792         }
1793         admin_first = NULL;
1794
1795         /* close socket */
1796         if (lcr_sock >= 0)
1797                 close(lcr_sock);
1798         lcr_sock = -1;
1799         global_change = 1;
1800 }
1801
1802
1803 /* sending queue to asterisk */
1804 static int wake_event(struct lcr_fd *fd, unsigned int what, void *instance, int index)
1805 {
1806         char byte;
1807
1808         read(wake_pipe[0], &byte, 1);
1809
1810         wake_global = 0;
1811
1812         return 0;
1813 }
1814
1815 static void handle_queue()
1816 {
1817         struct chan_call *call;
1818         struct ast_channel *ast;
1819         struct ast_frame fr;
1820         char *p;
1821
1822 again:
1823         call = call_first;
1824         while(call) {
1825                 p = call->queue_string;
1826                 ast = call->ast;
1827                 if (*p && ast) {
1828                         if (ast_channel_trylock(ast)) {
1829                                 ast_mutex_unlock(&chan_lock);
1830                                 usleep(1);
1831                                 ast_mutex_lock(&chan_lock);
1832                                 goto again;
1833                         }
1834                         while(*p) {
1835                                 switch (*p) {
1836                                 case 'T':
1837                                         CDEBUG(call, ast, "Sending queued PROGRESS to Asterisk.\n");
1838                                         ast_queue_control(ast, AST_CONTROL_PROGRESS);
1839                                         break;
1840                                 case 'P':
1841                                         CDEBUG(call, ast, "Sending queued PROCEEDING to Asterisk.\n");
1842                                         ast_queue_control(ast, AST_CONTROL_PROCEEDING);
1843                                         break;
1844                                 case 'R':
1845                                         CDEBUG(call, ast, "Sending queued RINGING to Asterisk.\n");
1846                                         ast_queue_control(ast, AST_CONTROL_RINGING);
1847                                         ast_setstate(ast, AST_STATE_RINGING);
1848                                         break;
1849                                 case 'N':
1850                                         CDEBUG(call, ast, "Sending queued ANSWER to Asterisk.\n");
1851                                         ast_queue_control(ast, AST_CONTROL_ANSWER);
1852                                         break;
1853                                 case 'H':
1854                                         CDEBUG(call, ast, "Sending queued HANGUP to Asterisk.\n");
1855                                         ast_queue_hangup(ast);
1856                                         break;
1857                                 case '1': case '2': case '3': case 'A':
1858                                 case '4': case '5': case '6': case 'B':
1859                                 case '7': case '8': case '9': case 'C':
1860                                 case '*': case '0': case '#': case 'D':
1861                                         CDEBUG(call, ast, "Sending queued digit '%c' to Asterisk.\n", *p);
1862                                         /* send digit to asterisk */
1863                                         memset(&fr, 0, sizeof(fr));
1864
1865                                         #ifdef LCR_FOR_ASTERISK
1866                                         fr.frametype = AST_FRAME_DTMF_BEGIN;
1867                                         #endif
1868
1869                                         #ifdef LCR_FOR_CALLWEAVER
1870                                         fr.frametype = AST_FRAME_DTMF;
1871                                         #endif
1872
1873 #ifdef AST_1_8_OR_HIGHER
1874                                         fr.subclass.integer = *p;
1875 #else
1876                                         fr.subclass = *p;
1877 #endif
1878                                         fr.delivery = ast_tv(0, 0);
1879                                         ast_queue_frame(ast, &fr);
1880
1881                                         #ifdef LCR_FOR_ASTERISK
1882                                         fr.frametype = AST_FRAME_DTMF_END;
1883                                         ast_queue_frame(ast, &fr);
1884                                         #endif
1885
1886                                         break;
1887                                 default:
1888                                         CDEBUG(call, ast, "Ignoring queued digit 0x%02x.\n", *p);
1889                                 }
1890                                 p++;
1891                         }
1892                         call->queue_string[0] = '\0';
1893                         ast_channel_unlock(ast);
1894                 }
1895                 call = call->next;
1896         }
1897 }
1898
1899 static int handle_retry(struct lcr_timer *timer, void *instance, int index)
1900 {
1901         CDEBUG(NULL, NULL, "Retry to open socket.\n");
1902         if (open_socket() < 0)
1903                 schedule_timer(&socket_retry, SOCKET_RETRY_TIMER, 0);
1904
1905         return 0;
1906 }
1907
1908 void lock_chan(void)
1909 {
1910         ast_mutex_lock(&chan_lock);
1911 }
1912
1913 void unlock_chan(void)
1914 {
1915         ast_mutex_unlock(&chan_lock);
1916 }
1917
1918 /* chan_lcr thread */
1919 static void *chan_thread(void *arg)
1920 {
1921         if (pipe(wake_pipe) < 0) {
1922                 CERROR(NULL, NULL, "Failed to open pipe.\n");
1923                 return NULL;
1924         }
1925         memset(&wake_fd, 0, sizeof(wake_fd));
1926         wake_fd.fd = wake_pipe[0];
1927         register_fd(&wake_fd, LCR_FD_READ, wake_event, NULL, 0);
1928
1929         memset(&socket_retry, 0, sizeof(socket_retry));
1930         add_timer(&socket_retry, handle_retry, NULL, 0);
1931
1932         bchannel_pid = getpid();
1933
1934         /* open socket the first time */
1935         handle_retry(NULL, NULL, 0);
1936
1937         ast_mutex_lock(&chan_lock);
1938
1939         while(!quit) {
1940                 handle_queue();
1941                 select_main(0, &global_change, lock_chan, unlock_chan);
1942         }
1943
1944         close_socket();
1945
1946         del_timer(&socket_retry);
1947
1948         unregister_fd(&wake_fd);
1949         close(wake_pipe[0]);
1950         close(wake_pipe[1]);
1951
1952         CERROR(NULL, NULL, "Thread exit.\n");
1953
1954         ast_mutex_unlock(&chan_lock);
1955
1956         return NULL;
1957 }
1958
1959 /*
1960  * new asterisk instance
1961  */
1962 static
1963 #ifdef AST_1_8_OR_HIGHER
1964 struct ast_channel *lcr_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
1965 #else
1966 struct ast_channel *lcr_request(const char *type, int format, void *data, int *cause)
1967 #endif
1968 {
1969         char exten[256], *dial, *interface, *opt;
1970         struct ast_channel *ast;
1971         struct chan_call *call;
1972
1973         ast_mutex_lock(&chan_lock);
1974         CDEBUG(NULL, NULL, "Received request from Asterisk. (data=%s)\n", (char *)data);
1975
1976         /* if socket is closed */
1977         if (lcr_sock < 0) {
1978                 CERROR(NULL, NULL, "Rejecting call from Asterisk, because LCR not running.\n");
1979                 ast_mutex_unlock(&chan_lock);
1980                 return NULL;
1981         }
1982
1983         /* create call instance */
1984         call = alloc_call();
1985         if (!call) {
1986                 /* failed to create instance */
1987                 ast_mutex_unlock(&chan_lock);
1988                 return NULL;
1989         }
1990
1991         /* create asterisk channel instrance */
1992
1993         #ifdef LCR_FOR_ASTERISK
1994 #ifdef AST_1_8_OR_HIGHER
1995         ast = ast_channel_alloc(1, AST_STATE_RESERVED, NULL, NULL, NULL, NULL, NULL, NULL, 0, "%s/%d", lcr_type, ++glob_channel);
1996 #else
1997         ast = ast_channel_alloc(1, AST_STATE_RESERVED, NULL, NULL, "", NULL, "", 0, "%s/%d", lcr_type, ++glob_channel);
1998 #endif
1999         #endif
2000
2001         #ifdef LCR_FOR_CALLWEAVER
2002         ast = ast_channel_alloc(1);
2003         #endif
2004
2005         if (!ast) {
2006                 CERROR(NULL, NULL, "Failed to create Asterisk channel.\n");
2007                 free_call(call);
2008                 /* failed to create instance */
2009                 ast_mutex_unlock(&chan_lock);
2010                 return NULL;
2011         }
2012         ast->tech = &lcr_tech;
2013         ast->tech_pvt = (void *)1L; // set pointer or asterisk will not call
2014         /* configure channel */
2015         ast->nativeformats = (options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW;
2016         ast->readformat = ast->rawreadformat = ast->nativeformats;
2017         ast->writeformat = ast->rawwriteformat =  ast->nativeformats;
2018         ast->priority = 1;
2019         ast->hangupcause = 0;
2020
2021         /* link together */
2022         call->ast = ast;
2023         ast->tech_pvt = call;
2024         ast->fds[0] = call->pipe[0];
2025         call->pbx_started = 0;
2026         /* set state */
2027         call->state = CHAN_LCR_STATE_OUT_PREPARE;
2028
2029         /*
2030          * Extract interface, dialstring, options from data.
2031          * Formats can be:
2032          *      <dialstring>
2033          *      <interface>/<dialstring>
2034          *      <interface>/<dialstring>/options
2035          */
2036         strncpy(exten, (char *)data, sizeof(exten)-1);
2037         exten[sizeof(exten)-1] = '\0';
2038         if ((dial = strchr(exten, '/'))) {
2039                 *dial++ = '\0';
2040                 interface = exten;
2041                 if ((opt = strchr(dial, '/')))
2042                         *opt++ = '\0';
2043                 else
2044                         opt = "";
2045         } else {
2046                 dial = exten;
2047                 interface = "";
2048                 opt = "";
2049         }
2050         strncpy(call->interface, interface, sizeof(call->interface)-1);
2051         strncpy(call->dialstring, dial, sizeof(call->dialstring)-1);
2052         apply_opt(call, (char *)opt);
2053
2054 #ifdef AST_1_8_OR_HIGHER
2055 //      clone_variables(requestor, ast);
2056
2057 #if 0
2058         ast->caller.ani.number.valid=                   requestor->caller.ani.number.valid;
2059         if (requestor->caller.ani.number.valid)
2060           if (requestor->caller.ani.number.str)
2061             if (requestor->caller.ani.number.str[0])
2062                 ast->caller.ani.number.str=             strdup(requestor->caller.ani.number.str);
2063         ast->caller.ani.number.plan=                    requestor->caller.ani.number.plan;
2064         ast->caller.ani.number.presentation=            requestor->caller.ani.number.presentation;
2065
2066         ast->caller.ani.name.valid=                     requestor->caller.ani.name.valid;
2067         if (requestor->caller.ani.name.valid)
2068           if (requestor->caller.ani.name.str)
2069             if (requestor->caller.ani.name.str[0])
2070                 ast->caller.ani.name.str=               strdup(requestor->caller.ani.name.str);
2071         ast->caller.ani.name.presentation=              requestor->caller.ani.name.presentation;
2072
2073         ast->caller.ani.subaddress.valid=               requestor->caller.ani.subaddress.valid;
2074         if (requestor->caller.ani.subaddress.valid)
2075           if (requestor->caller.ani.subaddress.str)
2076             if (requestor->caller.ani.subaddress.str[0])
2077                 ast->caller.ani.subaddress.str=         strdup(requestor->caller.ani.subaddress.str);
2078         ast->caller.ani.subaddress.type=                requestor->caller.ani.subaddress.type;
2079
2080         ast->caller.id.number.valid=                    requestor->caller.id.number.valid;
2081         if (requestor->caller.id.number.valid)
2082           if (requestor->caller.id.number.str)
2083             if (requestor->caller.id.number.str[0])
2084                 ast->caller.id.number.str=              strdup(requestor->caller.id.number.str);
2085         ast->caller.id.number.plan=                     requestor->caller.id.number.plan;
2086         ast->caller.id.number.presentation=             requestor->caller.id.number.presentation;
2087
2088         ast->caller.id.name.valid=                      requestor->caller.id.name.valid;
2089         if (requestor->caller.id.name.valid)
2090           if (requestor->caller.id.name.str)
2091             if (requestor->caller.id.name.str[0])
2092                 ast->caller.id.name.str=                strdup(requestor->caller.id.name.str);
2093         ast->caller.id.name.presentation=               requestor->caller.id.name.presentation;
2094
2095         ast->caller.id.subaddress.valid=                requestor->caller.id.subaddress.valid;
2096         if (requestor->caller.id.subaddress.valid)
2097           if (requestor->caller.id.subaddress.str)
2098             if (requestor->caller.id.subaddress.str[0])
2099                 ast->caller.id.subaddress.str=          strdup(requestor->caller.id.subaddress.str);
2100         ast->caller.id.subaddress.type=                 requestor->caller.id.subaddress.type;
2101
2102         if (requestor->dialed.number.str)
2103           if (requestor->dialed.number.str[0])
2104                 ast->dialed.number.str=                 strdup(requestor->dialed.number.str);
2105         ast->dialed.number.plan=                        requestor->dialed.number.plan;
2106
2107         ast->dialed.subaddress.valid=                   requestor->dialed.subaddress.valid;
2108         if (requestor->dialed.subaddress.valid)
2109           if (requestor->dialed.subaddress.str)
2110             if (requestor->dialed.subaddress.str[0])
2111                 ast->dialed.subaddress.str=             strdup(requestor->dialed.subaddress.str);
2112         ast->dialed.subaddress.type=                    requestor->dialed.subaddress.type;
2113
2114         ast->dialed.transit_network_select=             requestor->dialed.transit_network_select;
2115         ast->redirecting.count=                         requestor->redirecting.count;
2116         ast->redirecting.reason=                        requestor->redirecting.reason;
2117
2118         ast->redirecting.from.number.valid=             requestor->redirecting.from.number.valid;
2119         if (requestor->redirecting.from.number.valid)
2120           if (requestor->redirecting.from.number.str)
2121             if (requestor->redirecting.from.number.str[0])
2122                 ast->redirecting.from.number.str=       strdup(requestor->redirecting.from.number.str);
2123         ast->redirecting.from.number.plan=              requestor->redirecting.from.number.plan;
2124         ast->redirecting.from.number.presentation=      requestor->redirecting.from.number.presentation;
2125
2126         ast->redirecting.to.number.valid=               requestor->redirecting.to.number.valid;
2127         if (requestor->redirecting.to.number.valid)
2128           if (requestor->redirecting.to.number.str)
2129             if (requestor->redirecting.to.number.str[0])
2130                 ast->redirecting.to.number.str=         strdup(requestor->redirecting.to.number.str);
2131         ast->redirecting.to.number.plan=                requestor->redirecting.to.number.plan;
2132         ast->redirecting.to.number.presentation=        requestor->redirecting.to.number.presentation;
2133 #endif
2134         /* store call information for setup */
2135
2136         /* caller ID */
2137         if (requestor->caller.id.number.valid) {
2138                 if (requestor->caller.id.number.str)
2139                         strncpy(call->callerinfo.id, requestor->caller.id.number.str, sizeof(call->callerinfo.id)-1);
2140                 switch(requestor->caller.id.number.presentation & AST_PRES_RESTRICTION) {
2141                         case AST_PRES_RESTRICTED:
2142                         call->callerinfo.present = INFO_PRESENT_RESTRICTED;
2143                         break;
2144                         case AST_PRES_UNAVAILABLE:
2145                         call->callerinfo.present = INFO_PRESENT_NOTAVAIL;
2146                         break;
2147                         case AST_PRES_ALLOWED:
2148                         default:
2149                         call->callerinfo.present = INFO_PRESENT_ALLOWED;
2150                 }
2151                 switch(requestor->caller.id.number.presentation & AST_PRES_NUMBER_TYPE) {
2152                         case AST_PRES_USER_NUMBER_UNSCREENED:
2153                         call->callerinfo.screen = INFO_SCREEN_USER;
2154                         break;
2155                         case AST_PRES_USER_NUMBER_PASSED_SCREEN:
2156                         call->callerinfo.screen = INFO_SCREEN_USER_VERIFIED_PASSED;
2157                         break;
2158                         case AST_PRES_USER_NUMBER_FAILED_SCREEN:
2159                         call->callerinfo.screen = INFO_SCREEN_USER_VERIFIED_FAILED;
2160                         break;
2161                         default:
2162                         call->callerinfo.screen = INFO_SCREEN_NETWORK;
2163                 }
2164                 switch((requestor->caller.id.number.plan >> 4) & 7) {
2165                         case 4:
2166                         call->callerinfo.ntype = INFO_NTYPE_SUBSCRIBER;
2167                         break;
2168                         case 2:
2169                         call->callerinfo.ntype = INFO_NTYPE_NATIONAL;
2170                         break;
2171                         case 1:
2172                         call->callerinfo.ntype = INFO_NTYPE_INTERNATIONAL;
2173                         break;
2174                         default:
2175                         call->callerinfo.ntype = INFO_NTYPE_UNKNOWN;
2176                 }
2177         } else
2178                 call->callerinfo.present = INFO_PRESENT_NOTAVAIL;
2179
2180         /* caller ID 2 */
2181         if (requestor->caller.ani.number.valid) {
2182                 if (requestor->caller.ani.number.str)
2183                         strncpy(call->callerinfo.id2, requestor->caller.ani.number.str, sizeof(call->callerinfo.id2)-1);
2184                 switch(requestor->caller.ani.number.presentation & AST_PRES_RESTRICTION) {
2185                         case AST_PRES_RESTRICTED:
2186                         call->callerinfo.present2 = INFO_PRESENT_RESTRICTED;
2187                         break;
2188                         case AST_PRES_UNAVAILABLE:
2189                         call->callerinfo.present2 = INFO_PRESENT_NOTAVAIL;
2190                         break;
2191                         case AST_PRES_ALLOWED:
2192                         default:
2193                         call->callerinfo.present2 = INFO_PRESENT_ALLOWED;
2194                 }
2195                 switch(requestor->caller.ani.number.presentation & AST_PRES_NUMBER_TYPE) {
2196                         case AST_PRES_USER_NUMBER_UNSCREENED:
2197                         call->callerinfo.screen2 = INFO_SCREEN_USER;
2198                         break;
2199                         case AST_PRES_USER_NUMBER_PASSED_SCREEN:
2200                         call->callerinfo.screen2 = INFO_SCREEN_USER_VERIFIED_PASSED;
2201                         break;
2202                         case AST_PRES_USER_NUMBER_FAILED_SCREEN:
2203                         call->callerinfo.screen2 = INFO_SCREEN_USER_VERIFIED_FAILED;
2204                         break;
2205                         default:
2206                         call->callerinfo.screen2 = INFO_SCREEN_NETWORK;
2207                 }
2208                 switch((requestor->caller.ani.number.plan >> 4) & 7) {
2209                         case 4:
2210                         call->callerinfo.ntype2 = INFO_NTYPE_SUBSCRIBER;
2211                         break;
2212                         case 2:
2213                         call->callerinfo.ntype2 = INFO_NTYPE_NATIONAL;
2214                         break;
2215                         case 1:
2216                         call->callerinfo.ntype2 = INFO_NTYPE_INTERNATIONAL;
2217                         break;
2218                         default:
2219                         call->callerinfo.ntype2 = INFO_NTYPE_UNKNOWN;
2220                 }
2221         } else
2222                 call->callerinfo.present2 = INFO_PRESENT_NOTAVAIL;
2223
2224         /* caller name */
2225         if (requestor->caller.id.name.valid) {
2226                 if (requestor->caller.id.name.str)
2227                         strncpy(call->callerinfo.name, requestor->caller.id.name.str, sizeof(call->callerinfo.name)-1);
2228         }
2229
2230         /* redir number */
2231         if (requestor->redirecting.from.number.valid) {
2232                 call->redirinfo.itype = INFO_ITYPE_CHAN;
2233                 if (requestor->redirecting.from.number.str)
2234                         strncpy(call->redirinfo.id, requestor->redirecting.from.number.str, sizeof(call->redirinfo.id)-1);
2235                 switch(requestor->redirecting.from.number.presentation & AST_PRES_RESTRICTION) {
2236                         case AST_PRES_RESTRICTED:
2237                         call->redirinfo.present = INFO_PRESENT_RESTRICTED;
2238                         break;
2239                         case AST_PRES_UNAVAILABLE:
2240                         call->redirinfo.present = INFO_PRESENT_NOTAVAIL;
2241                         break;
2242                         case AST_PRES_ALLOWED:
2243                         default:
2244                         call->redirinfo.present = INFO_PRESENT_ALLOWED;
2245                 }
2246                 switch(requestor->redirecting.from.number.presentation & AST_PRES_NUMBER_TYPE) {
2247                         case AST_PRES_USER_NUMBER_UNSCREENED:
2248                         call->redirinfo.screen = INFO_SCREEN_USER;
2249                         break;
2250                         case AST_PRES_USER_NUMBER_PASSED_SCREEN:
2251                         call->redirinfo.screen = INFO_SCREEN_USER_VERIFIED_PASSED;
2252                         break;
2253                         case AST_PRES_USER_NUMBER_FAILED_SCREEN:
2254                         call->redirinfo.screen = INFO_SCREEN_USER_VERIFIED_FAILED;
2255                         break;
2256                         default:
2257                         call->redirinfo.screen = INFO_SCREEN_NETWORK;
2258                 }
2259                 switch((requestor->redirecting.from.number.plan >> 4) & 7) {
2260                         case 4:
2261                         call->redirinfo.ntype = INFO_NTYPE_SUBSCRIBER;
2262                         break;
2263                         case 2:
2264                         call->redirinfo.ntype = INFO_NTYPE_NATIONAL;
2265                         break;
2266                         case 1:
2267                         call->redirinfo.ntype = INFO_NTYPE_INTERNATIONAL;
2268                         break;
2269                         default:
2270                         call->redirinfo.ntype = INFO_NTYPE_UNKNOWN;
2271                 }
2272         }
2273 #endif
2274
2275         ast_mutex_unlock(&chan_lock);
2276         return ast;
2277 }
2278
2279 /*
2280  * call from asterisk
2281  */
2282 static int lcr_call(struct ast_channel *ast, char *dest, int timeout)
2283 {
2284         union parameter newparam;
2285         struct chan_call *call;
2286
2287         ast_mutex_lock(&chan_lock);
2288         call = ast->tech_pvt;
2289
2290         #ifdef LCR_FOR_CALLWEAVER
2291         ast->type = "LCR";
2292         snprintf(ast->name, sizeof(ast->name), "LCR/%s-%04x",call->dialstring, ast_random() & 0xffff);
2293         #endif
2294
2295         if (!call) {
2296                 CERROR(NULL, ast, "Received call from Asterisk, but call instance does not exist.\n");
2297                 ast_mutex_unlock(&chan_lock);
2298                 return -1;
2299         }
2300
2301         CDEBUG(NULL, ast, "Received call from Asterisk.\n");
2302
2303         /* pbx process is started */
2304         call->pbx_started = 1;
2305         /* send MESSAGE_NEWREF */
2306         memset(&newparam, 0, sizeof(union parameter));
2307         newparam.newref.direction = 0; /* request from app */
2308         if (!strcmp(call->interface, "pbx"))
2309                 newparam.newref.mode = 1;
2310         send_message(MESSAGE_NEWREF, 0, &newparam);
2311
2312         /* set hdlc if capability requires hdlc */
2313         if (ast->transfercapability == INFO_BC_DATAUNRESTRICTED
2314          || ast->transfercapability == INFO_BC_DATARESTRICTED
2315          || ast->transfercapability == INFO_BC_VIDEO)
2316                 call->hdlc = 1;
2317         /* if hdlc is forced by option, we change transcap to data */
2318         if (call->hdlc
2319          && ast->transfercapability != INFO_BC_DATAUNRESTRICTED
2320          && ast->transfercapability != INFO_BC_DATARESTRICTED
2321          && ast->transfercapability != INFO_BC_VIDEO)
2322                 ast->transfercapability = INFO_BC_DATAUNRESTRICTED;
2323
2324 #ifndef AST_1_8_OR_HIGHER
2325         call->cid_num[0] = 0;
2326         call->cid_name[0] = 0;
2327         call->cid_rdnis[0] = 0;
2328
2329         if (ast->cid.cid_num) if (ast->cid.cid_num[0])
2330                 strncpy(call->cid_num, ast->cid.cid_num,
2331                         sizeof(call->cid_num)-1);
2332         if (ast->cid.cid_name) if (ast->cid.cid_name[0])
2333                 strncpy(call->cid_name, ast->cid.cid_name,
2334                         sizeof(call->cid_name)-1);
2335         if (ast->cid.cid_rdnis) if (ast->cid.cid_rdnis[0])
2336                 strncpy(call->cid_rdnis, ast->cid.cid_rdnis,
2337                         sizeof(call->cid_rdnis)-1);
2338 #endif
2339
2340         ast_mutex_unlock(&chan_lock);
2341         return 0;
2342 }
2343
2344 static void send_digit_to_chan(struct ast_channel * ast, char digit )
2345 {
2346         static const char* dtmf_tones[] = {
2347                 "!941+1336/100,!0/100", /* 0 */
2348                 "!697+1209/100,!0/100", /* 1 */
2349                 "!697+1336/100,!0/100", /* 2 */
2350                 "!697+1477/100,!0/100", /* 3 */
2351                 "!770+1209/100,!0/100", /* 4 */
2352                 "!770+1336/100,!0/100", /* 5 */
2353                 "!770+1477/100,!0/100", /* 6 */
2354                 "!852+1209/100,!0/100", /* 7 */
2355                 "!852+1336/100,!0/100", /* 8 */
2356                 "!852+1477/100,!0/100", /* 9 */
2357                 "!697+1633/100,!0/100", /* A */
2358                 "!770+1633/100,!0/100", /* B */
2359                 "!852+1633/100,!0/100", /* C */
2360                 "!941+1633/100,!0/100", /* D */
2361                 "!941+1209/100,!0/100", /* * */
2362                 "!941+1477/100,!0/100" };       /* # */
2363
2364         if (digit >= '0' && digit <='9')
2365                 ast_playtones_start(ast,0,dtmf_tones[digit-'0'], 0);
2366         else if (digit >= 'A' && digit <= 'D')
2367                 ast_playtones_start(ast,0,dtmf_tones[digit-'A'+10], 0);
2368         else if (digit == '*')
2369                 ast_playtones_start(ast,0,dtmf_tones[14], 0);
2370         else if (digit == '#')
2371                 ast_playtones_start(ast,0,dtmf_tones[15], 0);
2372         else {
2373                 /* not handled */
2374                 CDEBUG(NULL, ast, "Unable to handle DTMF tone "
2375                         "'%c' for '%s'\n", digit, ast->name);
2376         }
2377 }
2378
2379 #ifdef LCR_FOR_ASTERISK
2380 static int lcr_digit_begin(struct ast_channel *ast, char digit)
2381 #endif
2382 #ifdef LCR_FOR_CALLWEAVER
2383 static int lcr_digit(struct ast_channel *ast, char digit)
2384 #endif
2385 {
2386         struct chan_call *call;
2387         union parameter newparam;
2388         char buf[]="x";
2389
2390 #ifdef LCR_FOR_CALLWEAVER
2391         int inband_dtmf = 0;
2392 #endif
2393
2394         /* only pass IA5 number space */
2395         if (digit > 126 || digit < 32)
2396                 return 0;
2397
2398         ast_mutex_lock(&chan_lock);
2399         call = ast->tech_pvt;
2400         if (!call) {
2401                 CERROR(NULL, ast, "Received digit from Asterisk, but no call instance exists.\n");
2402                 ast_mutex_unlock(&chan_lock);
2403                 return -1;
2404         }
2405
2406         CDEBUG(call, ast, "Received digit '%c' from Asterisk.\n", digit);
2407
2408         /* send information or queue them */
2409         if (call->ref && call->state == CHAN_LCR_STATE_OUT_DIALING) {
2410                 CDEBUG(call, ast, "Sending digit to LCR, because we are in dialing state.\n");
2411                 memset(&newparam, 0, sizeof(union parameter));
2412                 if (call->keypad) {
2413                         newparam.information.keypad[0] = digit;
2414                         newparam.information.keypad[1] = '\0';
2415                 } else {
2416                         newparam.information.id[0] = digit;
2417                         newparam.information.id[1] = '\0';
2418                 }
2419                 send_message(MESSAGE_INFORMATION, call->ref, &newparam);
2420         } else
2421         if (!call->ref
2422          && (call->state == CHAN_LCR_STATE_OUT_PREPARE || call->state == CHAN_LCR_STATE_OUT_SETUP)) {
2423                 CDEBUG(call, ast, "Queue digits, because we are in setup/dialing state and have no ref yet.\n");
2424                 *buf = digit;
2425                 strncat(call->dialque, buf, strlen(call->dialque)-1);
2426         }
2427
2428         ast_mutex_unlock(&chan_lock);
2429
2430 #ifdef LCR_FOR_ASTERISK
2431         return 0;
2432 }
2433
2434 static int lcr_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
2435 {
2436         int inband_dtmf = 0;
2437         struct chan_call *call;
2438 #endif
2439
2440         ast_mutex_lock(&chan_lock);
2441
2442         call = ast->tech_pvt;
2443
2444         if (!call) {
2445                 CERROR(NULL, ast,
2446                         "Received digit from Asterisk, "
2447                         "but no call instance exists.\n");
2448                 ast_mutex_unlock(&chan_lock);
2449                 return -1;
2450         }
2451
2452         CDEBUG(call, ast, "DIGIT END '%c' from Asterisk.\n", digit);
2453
2454         if (call->state == CHAN_LCR_STATE_CONNECT && call->inband_dtmf) {
2455                 inband_dtmf = 1;
2456         }
2457
2458         ast_mutex_unlock(&chan_lock);
2459
2460         if (inband_dtmf) {
2461                 CDEBUG(call, ast, "-> sending '%c' inband.\n", digit);
2462                 send_digit_to_chan(ast, digit);
2463         }
2464
2465         return 0;
2466 }
2467
2468 static int lcr_answer(struct ast_channel *ast)
2469 {
2470         union parameter newparam;
2471         struct chan_call *call;
2472
2473         ast_mutex_lock(&chan_lock);
2474         call = ast->tech_pvt;
2475         if (!call) {
2476                 CERROR(NULL, ast, "Received answer from Asterisk, but no call instance exists.\n");
2477                 ast_mutex_unlock(&chan_lock);
2478                 return -1;
2479         }
2480
2481         CDEBUG(call, ast, "Received answer from Asterisk (maybe during lcr_bridge).\n");
2482
2483         /* copy connectinfo, if bridged */
2484         if (call->bridge_call)
2485                 memcpy(&call->connectinfo, &call->bridge_call->connectinfo, sizeof(struct connect_info));
2486         /* send connect message to lcr */
2487         if (call->state != CHAN_LCR_STATE_CONNECT) {
2488                 memset(&newparam, 0, sizeof(union parameter));
2489                 memcpy(&newparam.connectinfo, &call->connectinfo, sizeof(struct connect_info));
2490                 send_message(MESSAGE_CONNECT, call->ref, &newparam);
2491                 call->state = CHAN_LCR_STATE_CONNECT;
2492         }
2493         /* change state */
2494         /* request bchannel */
2495         if (!call->bchannel) {
2496                 CDEBUG(call, ast, "Requesting B-channel.\n");
2497                 memset(&newparam, 0, sizeof(union parameter));
2498                 newparam.bchannel.type = BCHANNEL_REQUEST;
2499                 send_message(MESSAGE_BCHANNEL, call->ref, &newparam);
2500         }
2501         /* enable keypad */
2502 //      memset(&newparam, 0, sizeof(union parameter));
2503 //      send_message(MESSAGE_ENABLEKEYPAD, call->ref, &newparam);
2504
2505         ast_mutex_unlock(&chan_lock);
2506         return 0;
2507 }
2508
2509 static int lcr_hangup(struct ast_channel *ast)
2510 {
2511         struct chan_call *call;
2512         pthread_t tid = pthread_self();
2513
2514         if (!pthread_equal(tid, chan_tid)) {
2515                 ast_mutex_lock(&chan_lock);
2516         }
2517         call = ast->tech_pvt;
2518         if (!call) {
2519                 CERROR(NULL, ast, "Received hangup from Asterisk, but no call instance exists.\n");
2520                 if (!pthread_equal(tid, chan_tid)) {
2521                         ast_mutex_unlock(&chan_lock);
2522                 }
2523                 return -1;
2524         }
2525
2526         if (!pthread_equal(tid, chan_tid))
2527                 CDEBUG(call, ast, "Received hangup from Asterisk thread.\n");
2528         else
2529                 CDEBUG(call, ast, "Received hangup from LCR thread.\n");
2530
2531         /* disconnect asterisk, maybe not required */
2532         ast->tech_pvt = NULL;
2533         ast->fds[0] = -1;
2534         if (call->ref) {
2535                 /* release */
2536                 CDEBUG(call, ast, "Releasing ref and freeing call instance.\n");
2537                 if (ast->hangupcause > 0)
2538                         send_release_and_import(call, ast->hangupcause, LOCATION_PRIVATE_LOCAL);
2539                 else
2540                         send_release_and_import(call, CAUSE_NORMAL, LOCATION_PRIVATE_LOCAL);
2541                 /* remove call */
2542                 free_call(call);
2543                 if (!pthread_equal(tid, chan_tid)) {
2544                         ast_mutex_unlock(&chan_lock);
2545                 }
2546                 return 0;
2547         } else {
2548                 /* ref is not set, due to prepare setup or release */
2549                 if (call->state == CHAN_LCR_STATE_RELEASE) {
2550                         /* we get the response to our release */
2551                         CDEBUG(call, ast, "Freeing call instance, because we have no ref AND we are requesting no ref.\n");
2552                         free_call(call);
2553                 } else {
2554                         /* during prepare, we change to release state */
2555                         CDEBUG(call, ast, "We must wait until we received our ref, until we can free call instance.\n");
2556                         call->state = CHAN_LCR_STATE_RELEASE;
2557                         call->ast = NULL;
2558                 }
2559         }
2560         if (!pthread_equal(tid, chan_tid)) {
2561                 ast_mutex_unlock(&chan_lock);
2562         }
2563         return 0;
2564 }
2565
2566 static int lcr_write(struct ast_channel *ast, struct ast_frame *fr)
2567 {
2568         struct chan_call *call;
2569         struct ast_frame * f = fr;
2570
2571 #ifdef AST_1_8_OR_HIGHER
2572         if (!f->subclass.integer)
2573 #else
2574         if (!f->subclass)
2575 #endif
2576                 CDEBUG(NULL, ast, "No subclass\n");
2577 #ifdef AST_1_8_OR_HIGHER
2578         if (!(f->subclass.integer & ast->nativeformats)) {
2579 #else
2580         if (!(f->subclass & ast->nativeformats)) {
2581 #endif
2582                 CDEBUG(NULL, ast, 
2583                                "Unexpected format. "
2584                        "Activating emergency conversion...\n");
2585
2586 #ifdef AST_1_8_OR_HIGHER
2587                 ast_set_write_format(ast, f->subclass.integer);
2588 #else
2589                 ast_set_write_format(ast, f->subclass);
2590 #endif
2591                 f = (ast->writetrans) ? ast_translate(
2592                         ast->writetrans, fr, 0) : fr;
2593         }
2594         
2595         ast_mutex_lock(&chan_lock);
2596         call = ast->tech_pvt;
2597         if (!call) {
2598                 ast_mutex_unlock(&chan_lock);
2599                 if (f != fr) {
2600                         ast_frfree(f);
2601                 }
2602                 return -1;
2603         }
2604         if (call->bchannel && f->samples)
2605                 bchannel_transmit(call->bchannel, *((unsigned char **)&(f->data)), f->samples);
2606         ast_mutex_unlock(&chan_lock);
2607         if (f != fr) {
2608                 ast_frfree(f);
2609         }
2610         return 0;
2611 }
2612
2613
2614 static struct ast_frame *lcr_read(struct ast_channel *ast)
2615 {
2616         struct chan_call *call;
2617         int len = 0;
2618
2619         ast_mutex_lock(&chan_lock);
2620         call = ast->tech_pvt;
2621         if (!call) {
2622                 ast_mutex_unlock(&chan_lock);
2623                 return NULL;
2624         }
2625         if (call->pipe[0] > -1) {
2626                 if (call->rebuffer && !call->hdlc) {
2627                         /* Make sure we have a complete 20ms (160byte) frame */
2628                         len=read(call->pipe[0],call->read_buff + call->framepos, 160 - call->framepos);
2629                         if (len > 0) {
2630                                 call->framepos += len;
2631                         }
2632                 } else {
2633                         len = read(call->pipe[0], call->read_buff, sizeof(call->read_buff));
2634                 }
2635                 if (len < 0 && errno == EAGAIN) {
2636                         ast_mutex_unlock(&chan_lock);
2637
2638                         #ifdef LCR_FOR_ASTERISK
2639                         return &ast_null_frame;
2640                         #endif
2641
2642                         #ifdef LCR_FOR_CALLWEAVER
2643                         return &nullframe;
2644                         #endif
2645
2646                 }
2647                 if (len <= 0) {
2648                         close(call->pipe[0]);
2649                         call->pipe[0] = -1;
2650                         global_change = 1;
2651                         ast_mutex_unlock(&chan_lock);
2652                         return NULL;
2653                 } else if (call->rebuffer && call->framepos < 160) {
2654                         /* Not a complete frame, so we send a null-frame */
2655                         ast_mutex_unlock(&chan_lock);
2656                         return &ast_null_frame;
2657                 }
2658         }
2659
2660         call->read_fr.frametype = AST_FRAME_VOICE;
2661 #ifdef AST_1_8_OR_HIGHER
2662         call->read_fr.subclass.integer = ast->nativeformats;
2663 #else
2664         call->read_fr.subclass = ast->nativeformats;
2665 #endif
2666         if (call->rebuffer) {
2667                 call->read_fr.datalen = call->framepos;
2668                 call->read_fr.samples = call->framepos;
2669                 call->framepos = 0;
2670         } else {
2671                 call->read_fr.datalen = len;
2672                 call->read_fr.samples = len;
2673         }
2674         call->read_fr.delivery = ast_tv(0,0);
2675         *((unsigned char **)&(call->read_fr.data)) = call->read_buff;
2676         ast_mutex_unlock(&chan_lock);
2677
2678         return &call->read_fr;
2679 }
2680
2681 static int lcr_indicate(struct ast_channel *ast, int cond, const void *data, size_t datalen)
2682 {
2683         union parameter newparam;
2684         int res = 0;
2685         struct chan_call *call;
2686         const struct tone_zone_sound *ts = NULL;
2687
2688         ast_mutex_lock(&chan_lock);
2689         call = ast->tech_pvt;
2690         if (!call) {
2691                 CERROR(NULL, ast, "Received indicate from Asterisk, but no call instance exists.\n");
2692                 ast_mutex_unlock(&chan_lock);
2693                 return -1;
2694         }
2695
2696         switch (cond) {
2697                 case AST_CONTROL_BUSY:
2698                         CDEBUG(call, ast, "Received indicate AST_CONTROL_BUSY from Asterisk.\n");
2699                         ast_setstate(ast, AST_STATE_BUSY);
2700                         if (call->state != CHAN_LCR_STATE_OUT_DISCONNECT) {
2701                                 /* send message to lcr */
2702                                 memset(&newparam, 0, sizeof(union parameter));
2703                                 newparam.disconnectinfo.cause = 17;
2704                                 newparam.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
2705                                 send_message(MESSAGE_DISCONNECT, call->ref, &newparam);
2706                                 /* change state */
2707                                 call->state = CHAN_LCR_STATE_OUT_DISCONNECT;
2708                         } else {
2709                                 CDEBUG(call, ast, "Using Asterisk 'busy' indication\n");
2710                                 ts = ast_get_indication_tone(ast->zone, "busy");
2711                         }
2712                         break;
2713                 case AST_CONTROL_CONGESTION:
2714                         CDEBUG(call, ast, "Received indicate AST_CONTROL_CONGESTION from Asterisk. (cause %d)\n", ast->hangupcause);
2715                         if (call->state != CHAN_LCR_STATE_OUT_DISCONNECT) {
2716                                 /* send message to lcr */
2717                                 memset(&newparam, 0, sizeof(union parameter));
2718                                 newparam.disconnectinfo.cause = ast->hangupcause;
2719                                 newparam.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
2720                                 send_message(MESSAGE_DISCONNECT, call->ref, &newparam);
2721                                 /* change state */
2722                                 call->state = CHAN_LCR_STATE_OUT_DISCONNECT;
2723                         } else {
2724                                 CDEBUG(call, ast, "Using Asterisk 'congestion' indication\n");
2725                                 ts = ast_get_indication_tone(ast->zone, "congestion");
2726                         }
2727                         break;
2728                 case AST_CONTROL_PROCEEDING:
2729                         CDEBUG(call, ast, "Received indicate AST_CONTROL_PROCEEDING from Asterisk.\n");
2730                         if (call->state == CHAN_LCR_STATE_IN_SETUP
2731                          || call->state == CHAN_LCR_STATE_IN_DIALING) {
2732                                 /* send message to lcr */
2733                                 memset(&newparam, 0, sizeof(union parameter));
2734                                 send_message(MESSAGE_PROCEEDING, call->ref, &newparam);
2735                                 /* change state */
2736                                 call->state = CHAN_LCR_STATE_IN_PROCEEDING;
2737                         }
2738                         break;
2739                 case AST_CONTROL_RINGING:
2740                         CDEBUG(call, ast, "Received indicate AST_CONTROL_RINGING from Asterisk.\n");
2741                         ast_setstate(ast, AST_STATE_RING);
2742                         if (call->state == CHAN_LCR_STATE_IN_SETUP
2743                          || call->state == CHAN_LCR_STATE_IN_DIALING
2744                          || call->state == CHAN_LCR_STATE_IN_PROCEEDING) {
2745                                 /* send message to lcr */
2746                                 memset(&newparam, 0, sizeof(union parameter));
2747                                 send_message(MESSAGE_ALERTING, call->ref, &newparam);
2748                                 /* change state */
2749                                 call->state = CHAN_LCR_STATE_IN_ALERTING;
2750                         } else {
2751                                 CDEBUG(call, ast, "Using Asterisk 'ring' indication\n");
2752                                 ts = ast_get_indication_tone(ast->zone, "ring");
2753                         }
2754                         break;
2755                 case AST_CONTROL_PROGRESS:
2756                         CDEBUG(call, ast, "Received indicate AST_CONTROL_PROGRESS from Asterisk.\n");
2757                         /* request bchannel */
2758                         if (!call->bchannel) {
2759                                 CDEBUG(call, ast, "Requesting B-channel.\n");
2760                                 memset(&newparam, 0, sizeof(union parameter));
2761                                 newparam.bchannel.type = BCHANNEL_REQUEST;
2762                                 send_message(MESSAGE_BCHANNEL, call->ref, &newparam);
2763                         }
2764                         break;
2765                 case -1:
2766                         CDEBUG(call, ast, "Received indicate -1.\n");
2767                         ast_playtones_stop(ast);
2768                         res = -1;
2769                         break;
2770
2771                 case AST_CONTROL_VIDUPDATE:
2772                         CDEBUG(call, ast, "Received indicate AST_CONTROL_VIDUPDATE.\n");
2773                         res = -1;
2774                         break;
2775                 case AST_CONTROL_HOLD:
2776                         CDEBUG(call, ast, "Received indicate AST_CONTROL_HOLD from Asterisk.\n");
2777                         /* send message to lcr */
2778                         memset(&newparam, 0, sizeof(union parameter));
2779                         newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_HOLD;
2780                         send_message(MESSAGE_NOTIFY, call->ref, &newparam);
2781
2782                         /*start music onhold*/
2783                         #ifdef LCR_FOR_ASTERISK
2784                         ast_moh_start(ast,data,ast->musicclass);
2785                         #endif
2786
2787                         #ifdef LCR_FOR_CALLWEAVER
2788                         ast_moh_start(ast, NULL);
2789                         #endif
2790
2791                         call->on_hold = 1;
2792                         break;
2793                 case AST_CONTROL_UNHOLD:
2794                         CDEBUG(call, ast, "Received indicate AST_CONTROL_UNHOLD from Asterisk.\n");
2795                         /* send message to lcr */
2796                         memset(&newparam, 0, sizeof(union parameter));
2797                         newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_RETRIEVAL;
2798                         send_message(MESSAGE_NOTIFY, call->ref, &newparam);
2799
2800                         /*stop moh*/
2801                         ast_moh_stop(ast);
2802                         call->on_hold = 0;
2803                         break;
2804 #ifdef AST_CONTROL_SRCUPDATE
2805                 case AST_CONTROL_SRCUPDATE:
2806 #else
2807                 case 20:
2808 #endif
2809                         CDEBUG(call, ast, "Received AST_CONTROL_SRCUPDATE from Asterisk.\n");
2810                         break;
2811                 default:
2812                         CERROR(call, ast, "Received indicate from Asterisk with unknown condition %d.\n", cond);
2813                         res = -1;
2814                         break;
2815         }
2816
2817         if (ts && ts->data[0]) {
2818                 ast_playtones_start(ast, 0, ts->data, 1);
2819         }
2820
2821         /* return */
2822         ast_mutex_unlock(&chan_lock);
2823         return res;
2824 }
2825
2826 /*
2827  * fixup asterisk
2828  */
2829 static int lcr_fixup(struct ast_channel *oldast, struct ast_channel *ast)
2830 {
2831         struct chan_call *call;
2832
2833         if (!ast) {
2834                 return -1;
2835         }
2836
2837         ast_mutex_lock(&chan_lock);
2838         call = ast->tech_pvt;
2839         if (!call) {
2840                 CERROR(NULL, ast, "Received fixup from Asterisk, but no call instance exists.\n");
2841                 ast_mutex_unlock(&chan_lock);
2842                 return -1;
2843         }
2844
2845         CDEBUG(call, ast, "Received fixup from Asterisk.\n");
2846         call->ast = ast;
2847         ast_mutex_unlock(&chan_lock);
2848         return 0;
2849 }
2850
2851 /*
2852  * send_text asterisk
2853  */
2854 static int lcr_send_text(struct ast_channel *ast, const char *text)
2855 {
2856         struct chan_call *call;
2857         union parameter newparam;
2858
2859         ast_mutex_lock(&chan_lock);
2860         call = ast->tech_pvt;
2861         if (!call) {
2862                 CERROR(NULL, ast, "Received send_text from Asterisk, but no call instance exists.\n");
2863                 ast_mutex_unlock(&chan_lock);
2864                 return -1;
2865         }
2866
2867         CDEBUG(call, ast, "Received send_text from Asterisk. (text=%s)\n", text);
2868         memset(&newparam, 0, sizeof(union parameter));
2869         strncpy(newparam.notifyinfo.display, text, sizeof(newparam.notifyinfo.display)-1);
2870         send_message(MESSAGE_NOTIFY, call->ref, &newparam);
2871         ast_mutex_unlock(&chan_lock);
2872         return 0;
2873 }
2874
2875 /*
2876  * bridge process
2877  */
2878 enum ast_bridge_result lcr_bridge(struct ast_channel *ast1,
2879                                   struct ast_channel *ast2, int flags,
2880                                   struct ast_frame **fo,
2881                                   struct ast_channel **rc, int timeoutms)
2882
2883 {
2884         struct chan_call        *call1, *call2;
2885         struct ast_channel      *carr[2], *who;
2886         int                     to;
2887         struct ast_frame        *f;
2888         int                     bridge_id;
2889
2890         CDEBUG(NULL, NULL, "Received bridging request from Asterisk.\n");
2891
2892         carr[0] = ast1;
2893         carr[1] = ast2;
2894
2895         /* join via dsp (if the channels are currently open) */
2896         ast_mutex_lock(&chan_lock);
2897         call1 = ast1->tech_pvt;
2898         call2 = ast2->tech_pvt;
2899         if (!call1 || !call2) {
2900                 CDEBUG(NULL, NULL, "Bridge, but we don't have two call instances, exitting.\n");
2901                 ast_mutex_unlock(&chan_lock);
2902                 return AST_BRIDGE_COMPLETE;
2903         }
2904
2905         /* join, if both call instances uses dsp
2906            ignore the case of fax detection here it may be benificial for ISDN fax machines or pass through.
2907         */
2908         if (!call1->nodsp && !call2->nodsp) {
2909                 CDEBUG(NULL, NULL, "Both calls use DSP, bridging via DSP.\n");
2910
2911                 /* get bridge id and join */
2912                 bridge_id = new_bridge_id();
2913
2914                 call1->bridge_id = bridge_id;
2915                 if (call1->bchannel)
2916                         bchannel_join(call1->bchannel, bridge_id);
2917
2918                 call2->bridge_id = bridge_id;
2919                 if (call2->bchannel)
2920                         bchannel_join(call2->bchannel, bridge_id);
2921         } else
2922         if (call1->nodsp && call2->nodsp)
2923                 CDEBUG(NULL, NULL, "Both calls use no DSP, bridging in channel driver.\n");
2924         else
2925                 CDEBUG(NULL, NULL, "One call uses no DSP, bridging in channel driver.\n");
2926         call1->bridge_call = call2;
2927         call2->bridge_call = call1;
2928
2929         if (call1->state == CHAN_LCR_STATE_IN_SETUP
2930          || call1->state == CHAN_LCR_STATE_IN_DIALING
2931          || call1->state == CHAN_LCR_STATE_IN_PROCEEDING
2932          || call1->state == CHAN_LCR_STATE_IN_ALERTING) {
2933                 CDEBUG(call1, ast1, "Bridge established before lcr_answer, so we call it ourself: Calling lcr_answer...\n");
2934                 lcr_answer(ast1);
2935         }
2936         if (call2->state == CHAN_LCR_STATE_IN_SETUP
2937          || call2->state == CHAN_LCR_STATE_IN_DIALING
2938          || call2->state == CHAN_LCR_STATE_IN_PROCEEDING
2939          || call2->state == CHAN_LCR_STATE_IN_ALERTING) {
2940                 CDEBUG(call2, ast2, "Bridge established before lcr_answer, so we call it ourself: Calling lcr_answer...\n");
2941                 lcr_answer(ast2);
2942         }
2943
2944         /* sometimes SIP phones forget to send RETRIEVE before TRANSFER
2945            so let's do it for them. Hmpf.
2946         */
2947
2948         if (call1->on_hold) {
2949                 union parameter newparam;
2950
2951                 memset(&newparam, 0, sizeof(union parameter));
2952                 newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_RETRIEVAL;
2953                 send_message(MESSAGE_NOTIFY, call1->ref, &newparam);
2954
2955                 call1->on_hold = 0;
2956         }
2957
2958         if (call2->on_hold) {
2959                 union parameter newparam;
2960
2961                 memset(&newparam, 0, sizeof(union parameter));
2962                 newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_RETRIEVAL;
2963                 send_message(MESSAGE_NOTIFY, call2->ref, &newparam);
2964
2965                 call2->on_hold = 0;
2966         }
2967
2968         ast_mutex_unlock(&chan_lock);
2969
2970         while(1) {
2971                 to = -1;
2972                 who = ast_waitfor_n(carr, 2, &to);
2973
2974                 if (!who) {
2975                         CDEBUG(NULL, NULL, "Empty read on bridge, breaking out.\n");
2976                         break;
2977                 }
2978                 f = ast_read(who);
2979
2980                 if (!f || f->frametype == AST_FRAME_CONTROL) {
2981                         if (!f)
2982                                 CDEBUG(NULL, NULL, "Got hangup.\n");
2983                         else
2984                                 CDEBUG(NULL, NULL, "Got CONTROL.\n");
2985                         /* got hangup .. */
2986                         *fo=f;
2987                         *rc=who;
2988                         break;
2989                 }
2990
2991                 if ( f->frametype == AST_FRAME_DTMF ) {
2992                         CDEBUG(NULL, NULL, "Got DTMF.\n");
2993                         *fo=f;
2994                         *rc=who;
2995                         break;
2996                 }
2997
2998
2999                 if (who == ast1) {
3000                         ast_write(ast2,f);
3001                 }
3002                 else {
3003                         ast_write(ast1,f);
3004                 }
3005
3006         }
3007
3008         CDEBUG(NULL, NULL, "Releasing bridge.\n");
3009
3010         /* split channels */
3011         ast_mutex_lock(&chan_lock);
3012         call1 = ast1->tech_pvt;
3013         call2 = ast2->tech_pvt;
3014         if (call1 && call1->bridge_id) {
3015                 call1->bridge_id = 0;
3016                 if (call1->bchannel)
3017                         bchannel_join(call1->bchannel, 0);
3018                 if (call1->bridge_call)
3019                         call1->bridge_call->bridge_call = NULL;
3020         }
3021         if (call2 && call1->bridge_id) {
3022                 call2->bridge_id = 0;
3023                 if (call2->bchannel)
3024                         bchannel_join(call2->bchannel, 0);
3025                 if (call2->bridge_call)
3026                         call2->bridge_call->bridge_call = NULL;
3027         }
3028         call1->bridge_call = NULL;
3029         call2->bridge_call = NULL;
3030
3031         ast_mutex_unlock(&chan_lock);
3032         return AST_BRIDGE_COMPLETE;
3033 }
3034 static struct ast_channel_tech lcr_tech = {
3035         .type="LCR",
3036         .description = "Channel driver for connecting to Linux-Call-Router",
3037         .capabilities = AST_FORMAT_ALAW,
3038         .requester = lcr_request,
3039
3040         #ifdef LCR_FOR_ASTERISK
3041         .send_digit_begin = lcr_digit_begin,
3042         .send_digit_end = lcr_digit_end,
3043         #endif
3044
3045         #ifdef LCR_FOR_CALLWEAVER
3046         .send_digit = lcr_digit,
3047         #endif
3048
3049         .call = lcr_call,
3050         .bridge = lcr_bridge,
3051         .hangup = lcr_hangup,
3052         .answer = lcr_answer,
3053         .read = lcr_read,
3054         .write = lcr_write,
3055         .indicate = lcr_indicate,
3056         .fixup = lcr_fixup,
3057         .send_text = lcr_send_text,
3058         .properties = 0
3059 };
3060
3061
3062 /*
3063  * cli
3064  */
3065 #if 0
3066 static int lcr_show_lcr (int fd, int argc, char *argv[])
3067 {
3068         return 0;
3069 }
3070
3071 static int lcr_show_calls (int fd, int argc, char *argv[])
3072 {
3073         return 0;
3074 }
3075
3076 static int lcr_reload_routing (int fd, int argc, char *argv[])
3077 {
3078         return 0;
3079 }
3080
3081 static int lcr_reload_interfaces (int fd, int argc, char *argv[])
3082 {
3083         return 0;
3084 }
3085
3086 static int lcr_port_block (int fd, int argc, char *argv[])
3087 {
3088         return 0;
3089 }
3090
3091 static int lcr_port_unblock (int fd, int argc, char *argv[])
3092 {
3093         return 0;
3094 }
3095
3096 static int lcr_port_unload (int fd, int argc, char *argv[])
3097 {
3098         return 0;
3099 }
3100
3101 static struct ast_cli_entry cli_show_lcr =
3102 { {"lcr", "show", "lcr", NULL},
3103  lcr_show_lcr,
3104  "Shows current states of LCR core",
3105  "Usage: lcr show lcr\n",
3106 };
3107
3108 static struct ast_cli_entry cli_show_calls =
3109 { {"lcr", "show", "calls", NULL},
3110  lcr_show_calls,
3111  "Shows current calls made by LCR and Asterisk",
3112  "Usage: lcr show calls\n",
3113 };
3114
3115 static struct ast_cli_entry cli_reload_routing =
3116 { {"lcr", "reload", "routing", NULL},
3117  lcr_reload_routing,
3118  "Reloads routing conf of LCR, current uncomplete calls will be disconnected",
3119  "Usage: lcr reload routing\n",
3120 };
3121
3122 static struct ast_cli_entry cli_reload_interfaces =
3123 { {"lcr", "reload", "interfaces", NULL},
3124  lcr_reload_interfaces,
3125  "Reloads interfaces conf of LCR",
3126  "Usage: lcr reload interfaces\n",
3127 };
3128
3129 static struct ast_cli_entry cli_port_block =
3130 { {"lcr", "port", "block", NULL},
3131  lcr_port_block,
3132  "Blocks LCR port for further calls",
3133  "Usage: lcr port block \"<port>\"\n",
3134 };
3135
3136 static struct ast_cli_entry cli_port_unblock =
3137 { {"lcr", "port", "unblock", NULL},
3138  lcr_port_unblock,
3139  "Unblocks or loads LCR port, port is opened my mISDN",
3140  "Usage: lcr port unblock \"<port>\"\n",
3141 };
3142
3143 static struct ast_cli_entry cli_port_unload =
3144 { {"lcr", "port", "unload", NULL},
3145  lcr_port_unload,
3146  "Unloads LCR port, port is closes by mISDN",
3147  "Usage: lcr port unload \"<port>\"\n",
3148 };
3149 #endif
3150
3151
3152 #ifdef LCR_FOR_ASTERISK
3153 #ifdef AST_1_8_OR_HIGHER
3154 static int lcr_config_exec(struct ast_channel *ast, const char *data)
3155 #else
3156 static int lcr_config_exec(struct ast_channel *ast, void *data)
3157 #endif
3158 #endif
3159
3160 #ifdef LCR_FOR_CALLWEAVER
3161 static int lcr_config_exec(struct ast_channel *ast, void *data, char **argv)
3162 #endif
3163 {
3164         struct chan_call *call;
3165
3166         ast_mutex_lock(&chan_lock);
3167
3168         #ifdef LCR_FOR_ASTERISK
3169         CDEBUG(NULL, ast, "Received lcr_config (data=%s)\n", (char *)data);
3170         #endif
3171
3172         #ifdef LCR_FOR_CALLWEAVER
3173         CDEBUG(NULL, ast, "Received lcr_config (data=%s)\n", argv[0]);
3174         #endif
3175
3176         /* find channel */
3177         call = call_first;
3178         while(call) {
3179                 if (call->ast == ast)
3180                         break;
3181                 call = call->next;
3182         }
3183         if (call)
3184
3185                 #ifdef LCR_FOR_ASTERISK
3186                 apply_opt(call, (char *)data);
3187                 #endif
3188
3189                 #ifdef LCR_FOR_CALLWEAVER
3190                 apply_opt(call, (char *)argv[0]);
3191                 #endif
3192
3193         else
3194                 CERROR(NULL, ast, "lcr_config app not called by chan_lcr channel.\n");
3195
3196         ast_mutex_unlock(&chan_lock);
3197         return 0;
3198 }
3199
3200 /*
3201  * module loading and destruction
3202  */
3203 int load_module(void)
3204 {
3205         u_short i;
3206         char options_error[256];
3207
3208         for (i = 0; i < 256; i++) {
3209                 flip_bits[i] = (i>>7) | ((i>>5)&2) | ((i>>3)&4) | ((i>>1)&8)
3210                              | (i<<7) | ((i&2)<<5) | ((i&4)<<3) | ((i&8)<<1);
3211         }
3212
3213         if (read_options(options_error) == 0) {
3214                 CERROR(NULL, NULL, "%s", options_error);
3215
3216                 #ifdef LCR_FOR_ASTERISK
3217                 return AST_MODULE_LOAD_DECLINE;
3218                 #endif
3219
3220                 #ifdef LCR_FOR_CALLWEAVER
3221                 return 0;
3222                 #endif
3223
3224         }
3225
3226         ast_mutex_init(&chan_lock);
3227         ast_mutex_init(&log_lock);
3228
3229         if (bchannel_initialize()) {
3230                 CERROR(NULL, NULL, "Unable to open mISDN device\n");
3231                 close_socket();
3232
3233                 #ifdef LCR_FOR_ASTERISK
3234                 return AST_MODULE_LOAD_DECLINE;
3235                 #endif
3236
3237                 #ifdef LCR_FOR_CALLWEAVER
3238                 return 0;
3239                 #endif
3240         }
3241         mISDN_created = 1;
3242
3243         lcr_tech.capabilities = (options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW;
3244         if (ast_channel_register(&lcr_tech)) {
3245                 CERROR(NULL, NULL, "Unable to register channel class\n");
3246                 bchannel_deinitialize();
3247                 close_socket();
3248
3249                 #ifdef LCR_FOR_ASTERISK
3250                 return AST_MODULE_LOAD_DECLINE;
3251                 #endif
3252
3253                 #ifdef LCR_FOR_CALLWEAVER
3254                 return 0;
3255                 #endif
3256         }
3257
3258         ast_register_application("lcr_config", lcr_config_exec, "lcr_config",
3259
3260                                  #ifdef LCR_FOR_ASTERISK
3261                                  "lcr_config(<opt><optarg>:<opt>:...)\n"
3262                                  #endif
3263
3264                                  #ifdef LCR_FOR_CALLWEAVER
3265                                  "lcr_config(<opt><optarg>:<opt>:...)\n",
3266                                  #endif
3267
3268                                  "Sets LCR opts. and optargs\n"
3269                                  "\n"
3270                                  "The available options are:\n"
3271                                  "    d - Send display text on called phone, text is the optarg.\n"
3272                                  "    n - Don't detect dtmf tones on called channel.\n"
3273                                  "    h - Force data call (HDLC).\n"
3274                                  "    t - Disable mISDN_dsp features (required for fax application).\n"
3275                                  "    q - Add queue to make fax stream seamless (required for fax app).\n"
3276                                  "        Use queue size in miliseconds for optarg. (try 250)\n"
3277                                  "    f - Adding fax detection. It it timeouts, mISDN_dsp is used.\n"
3278                                  "        Use time to detect for optarg.\n"
3279                                  "    c - Make crypted outgoing call, optarg is keyindex.\n"
3280                                  "    e - Perform echo cancelation on this channel.\n"
3281                                  "        Takes mISDN pipeline option as optarg.\n"
3282                                  "    s - Send Non Inband DTMF as inband.\n"
3283                                  "    r - re-buffer packets (160 bytes). Required for some SIP-phones and fax applications.\n"
3284                                  "   vr - rxgain control\n"
3285                                  "   vt - txgain control\n"
3286                                  "        Volume changes at factor 2 ^ optarg.\n"
3287                                  "    k - use keypad to dial this call.\n"
3288                                  "\n"
3289                                  "set LCR_TRANSFERCAPABILITY to the numerical bearer capabilty in order to alter caller's capability\n"
3290                                  " -> use 16 for fax (3.1k audio)\n"
3291                                  "\n"
3292                                  "To send a fax, you need to set LCR_TRANSFERCAPABILITY environment to 16, also you need to set\n"
3293                                  "options: \"n:t:q250\" for seamless audio transmission.\n"
3294                 );
3295
3296
3297 #if 0
3298         ast_cli_register(&cli_show_lcr);
3299         ast_cli_register(&cli_show_calls);
3300         ast_cli_register(&cli_reload_routing);
3301         ast_cli_register(&cli_reload_interfaces);
3302         ast_cli_register(&cli_port_block);
3303         ast_cli_register(&cli_port_unblock);
3304         ast_cli_register(&cli_port_unload);
3305 #endif
3306
3307         quit = 0;
3308         if ((pthread_create(&chan_tid, NULL, chan_thread, NULL)<0)) {
3309                 /* failed to create thread */
3310                 bchannel_deinitialize();
3311                 close_socket();
3312                 ast_channel_unregister(&lcr_tech);
3313
3314                 #ifdef LCR_FOR_ASTERISK
3315                 return AST_MODULE_LOAD_DECLINE;
3316                 #endif
3317
3318                 #ifdef LCR_FOR_CALLWEAVER
3319                 return 0;
3320                 #endif
3321
3322         }
3323         return 0;
3324 }
3325
3326 int unload_module(void)
3327 {
3328         /* First, take us out of the channel loop */
3329         CDEBUG(NULL, NULL, "-- Unregistering mISDN Channel Driver --\n");
3330
3331         quit = 1;
3332         pthread_join(chan_tid, NULL);
3333
3334         ast_channel_unregister(&lcr_tech);
3335
3336         ast_unregister_application("lcr_config");
3337
3338
3339         if (mISDN_created) {
3340                 bchannel_deinitialize();
3341                 mISDN_created = 0;
3342         }
3343
3344         if (lcr_sock >= 0) {
3345                 close(lcr_sock);
3346                 lcr_sock = -1;
3347         }
3348
3349         return 0;
3350 }
3351
3352 int reload_module(void)
3353 {
3354 //      reload_config();
3355         return 0;
3356 }
3357
3358 #ifdef LCR_FOR_ASTERISK
3359 #define AST_MODULE "chan_lcr"
3360 #endif
3361
3362 #ifdef LCR_FOR_CALLWEAVER
3363 int usecount(void)
3364 hae
3365 {
3366         int res;
3367         ast_mutex_lock(&usecnt_lock);
3368         res = usecnt;
3369         ast_mutex_unlock(&usecnt_lock);
3370         return res;
3371 }
3372 #endif
3373
3374 #ifdef LCR_FOR_ASTERISK
3375 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Channel driver for Linux-Call-Router Support (ISDN BRI/PRI)",
3376                 .load = load_module,
3377                 .unload = unload_module,
3378                 .reload = reload_module,
3379                );
3380 #endif
3381
3382 #ifdef LCR_FOR_CALLWEAVER
3383 char *description(void)
3384 {
3385         return desc;
3386 }
3387 #endif