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