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