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