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