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