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