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