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