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