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