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