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