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