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