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