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