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