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