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