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