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