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