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