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