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