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