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