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