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