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