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