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