Fixed chan_lcr unload bug, found by Patrick
[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         /* socket not created */
1845         if (lcr_sock < 0)
1846                 return;
1847
1848         unregister_fd(&socket_fd);
1849
1850         /* flush pending messages */
1851         admin = admin_first;
1852         while(admin) {
1853                 temp = admin;
1854                 admin = admin->next;
1855                 free(temp);
1856         }
1857         admin_first = NULL;
1858
1859         /* close socket */
1860         close(lcr_sock);
1861         lcr_sock = -1;
1862         global_change = 1;
1863 }
1864
1865
1866 /* sending queue to asterisk */
1867 static int wake_event(struct lcr_fd *fd, unsigned int what, void *instance, int index)
1868 {
1869         char byte;
1870
1871         read(wake_pipe[0], &byte, 1);
1872
1873         wake_global = 0;
1874
1875         return 0;
1876 }
1877
1878 static void handle_queue()
1879 {
1880         struct chan_call *call;
1881         struct ast_channel *ast;
1882         struct ast_frame fr;
1883         char *p;
1884
1885 again:
1886         call = call_first;
1887         while(call) {
1888                 p = call->queue_string;
1889                 ast = call->ast;
1890                 if (*p && ast) {
1891                         if (ast_channel_trylock(ast)) {
1892                                 ast_mutex_unlock(&chan_lock);
1893                                 usleep(1);
1894                                 ast_mutex_lock(&chan_lock);
1895                                 goto again;
1896                         }
1897                         while(*p) {
1898                                 switch (*p) {
1899                                 case 'T':
1900                                         CDEBUG(call, ast, "Sending queued PROGRESS to Asterisk.\n");
1901                                         ast_queue_control(ast, AST_CONTROL_PROGRESS);
1902                                         break;
1903                                 case 'P':
1904                                         CDEBUG(call, ast, "Sending queued PROCEEDING to Asterisk.\n");
1905                                         ast_queue_control(ast, AST_CONTROL_PROCEEDING);
1906                                         break;
1907                                 case 'R':
1908                                         CDEBUG(call, ast, "Sending queued RINGING to Asterisk.\n");
1909                                         ast_queue_control(ast, AST_CONTROL_RINGING);
1910                                         ast_setstate(ast, AST_STATE_RINGING);
1911                                         break;
1912                                 case 'N':
1913                                         CDEBUG(call, ast, "Sending queued ANSWER to Asterisk.\n");
1914                                         ast_queue_control(ast, AST_CONTROL_ANSWER);
1915                                         break;
1916                                 case 'H':
1917                                         CDEBUG(call, ast, "Sending queued HANGUP to Asterisk.\n");
1918                                         ast_queue_hangup(ast);
1919                                         break;
1920                                 case '1': case '2': case '3': case 'A':
1921                                 case '4': case '5': case '6': case 'B':
1922                                 case '7': case '8': case '9': case 'C':
1923                                 case '*': case '0': case '#': case 'D':
1924                                         CDEBUG(call, ast, "Sending queued digit '%c' to Asterisk.\n", *p);
1925                                         /* send digit to asterisk */
1926                                         memset(&fr, 0, sizeof(fr));
1927
1928                                         #ifdef LCR_FOR_ASTERISK
1929                                         fr.frametype = AST_FRAME_DTMF_BEGIN;
1930                                         #endif
1931
1932                                         #ifdef LCR_FOR_CALLWEAVER
1933                                         fr.frametype = AST_FRAME_DTMF;
1934                                         #endif
1935
1936 #ifdef AST_1_8_OR_HIGHER
1937                                         fr.subclass.integer = *p;
1938 #else
1939                                         fr.subclass = *p;
1940 #endif
1941                                         fr.delivery = ast_tv(0, 0);
1942                                         ast_queue_frame(ast, &fr);
1943
1944                                         #ifdef LCR_FOR_ASTERISK
1945                                         fr.frametype = AST_FRAME_DTMF_END;
1946                                         ast_queue_frame(ast, &fr);
1947                                         #endif
1948
1949                                         break;
1950                                 default:
1951                                         CDEBUG(call, ast, "Ignoring queued digit 0x%02x.\n", *p);
1952                                 }
1953                                 p++;
1954                         }
1955                         call->queue_string[0] = '\0';
1956                         ast_channel_unlock(ast);
1957                 }
1958                 call = call->next;
1959         }
1960 }
1961
1962 static int handle_retry(struct lcr_timer *timer, void *instance, int index)
1963 {
1964         CDEBUG(NULL, NULL, "Retry to open socket.\n");
1965         if (open_socket() < 0)
1966                 schedule_timer(&socket_retry, SOCKET_RETRY_TIMER, 0);
1967
1968         return 0;
1969 }
1970
1971 void lock_chan(void)
1972 {
1973         ast_mutex_lock(&chan_lock);
1974 }
1975
1976 void unlock_chan(void)
1977 {
1978         ast_mutex_unlock(&chan_lock);
1979 }
1980
1981 /* chan_lcr thread */
1982 static void *chan_thread(void *arg)
1983 {
1984         if (pipe(wake_pipe) < 0) {
1985                 CERROR(NULL, NULL, "Failed to open pipe.\n");
1986                 return NULL;
1987         }
1988         memset(&wake_fd, 0, sizeof(wake_fd));
1989         wake_fd.fd = wake_pipe[0];
1990         register_fd(&wake_fd, LCR_FD_READ, wake_event, NULL, 0);
1991
1992         memset(&socket_retry, 0, sizeof(socket_retry));
1993         add_timer(&socket_retry, handle_retry, NULL, 0);
1994
1995         bchannel_pid = getpid();
1996
1997         /* open socket the first time */
1998         handle_retry(NULL, NULL, 0);
1999
2000         ast_mutex_lock(&chan_lock);
2001
2002         while(1) {
2003                 handle_queue();
2004                 select_main(0, &global_change, lock_chan, unlock_chan);
2005         }
2006
2007         return NULL;
2008 }
2009
2010 /*
2011  * new asterisk instance
2012  */
2013 static
2014 #ifdef AST_1_8_OR_HIGHER
2015 #if ASTERISK_VERSION_NUM < 100000
2016 struct ast_channel *lcr_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
2017 #else
2018 struct ast_channel *lcr_request(const char *type, struct ast_format_cap *format, const struct ast_channel *requestor, void *data, int *cause)
2019 #endif
2020 #else
2021 struct ast_channel *lcr_request(const char *type, int format, void *data, int *cause)
2022 #endif
2023 {
2024         char exten[256], *dial, *interface, *opt;
2025         struct ast_channel *ast;
2026         struct chan_call *call;
2027
2028         ast_mutex_lock(&chan_lock);
2029         CDEBUG(NULL, NULL, "Received request from Asterisk. (data=%s)\n", (char *)data);
2030
2031         /* if socket is closed */
2032         if (lcr_sock < 0) {
2033                 CERROR(NULL, NULL, "Rejecting call from Asterisk, because LCR not running.\n");
2034                 ast_mutex_unlock(&chan_lock);
2035                 return NULL;
2036         }
2037
2038         /* create call instance */
2039         call = alloc_call();
2040         if (!call) {
2041                 /* failed to create instance */
2042                 ast_mutex_unlock(&chan_lock);
2043                 return NULL;
2044         }
2045
2046         /* create asterisk channel instrance */
2047
2048         #ifdef LCR_FOR_ASTERISK
2049 #ifdef AST_1_8_OR_HIGHER
2050         ast = ast_channel_alloc(1, AST_STATE_RESERVED, NULL, NULL, NULL, NULL, NULL, NULL, 0, "%s/%d", lcr_type, ++glob_channel);
2051 #else
2052         ast = ast_channel_alloc(1, AST_STATE_RESERVED, NULL, NULL, "", NULL, "", 0, "%s/%d", lcr_type, ++glob_channel);
2053 #endif
2054         #endif
2055
2056         #ifdef LCR_FOR_CALLWEAVER
2057         ast = ast_channel_alloc(1);
2058         #endif
2059
2060         if (!ast) {
2061                 CERROR(NULL, NULL, "Failed to create Asterisk channel.\n");
2062                 free_call(call);
2063                 /* failed to create instance */
2064                 ast_mutex_unlock(&chan_lock);
2065                 return NULL;
2066         }
2067         ast->tech = &lcr_tech;
2068         ast->tech_pvt = (void *)1L; // set pointer or asterisk will not call
2069         /* configure channel */
2070 #if ASTERISK_VERSION_NUM < 100000
2071         ast->nativeformats = (options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW;
2072         ast->readformat = ast->rawreadformat = ast->nativeformats;
2073         ast->writeformat = ast->rawwriteformat =  ast->nativeformats;
2074 #else
2075         ast_format_set(&ast->rawwriteformat ,(options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW , 0);
2076         ast_format_copy(&ast->rawreadformat, &ast->rawwriteformat);
2077         ast_format_cap_set(ast->nativeformats, &ast->rawwriteformat);
2078         ast_set_write_format(ast, &ast->rawwriteformat);
2079         ast_set_read_format(ast, &ast->rawreadformat);
2080 #endif
2081         ast->priority = 1;
2082         ast->hangupcause = 0;
2083
2084         /* link together */
2085         call->ast = ast;
2086         ast->tech_pvt = call;
2087         ast->fds[0] = call->pipe[0];
2088         call->pbx_started = 0;
2089         /* set state */
2090         call->state = CHAN_LCR_STATE_OUT_PREPARE;
2091
2092         /*
2093          * Extract interface, dialstring, options from data.
2094          * Formats can be:
2095          *      <dialstring>
2096          *      <interface>/<dialstring>
2097          *      <interface>/<dialstring>/options
2098          */
2099         strncpy(exten, (char *)data, sizeof(exten)-1);
2100         exten[sizeof(exten)-1] = '\0';
2101         if ((dial = strchr(exten, '/'))) {
2102                 *dial++ = '\0';
2103                 interface = exten;
2104                 if ((opt = strchr(dial, '/')))
2105                         *opt++ = '\0';
2106                 else
2107                         opt = "";
2108         } else {
2109                 dial = exten;
2110                 interface = "";
2111                 opt = "";
2112         }
2113         strncpy(call->interface, interface, sizeof(call->interface)-1);
2114         strncpy(call->dialstring, dial, sizeof(call->dialstring)-1);
2115         apply_opt(call, (char *)opt);
2116
2117 #ifdef AST_1_8_OR_HIGHER
2118 //      clone_variables(requestor, ast);
2119
2120 #if 0
2121         ast->caller.ani.number.valid=                   requestor->caller.ani.number.valid;
2122         if (requestor->caller.ani.number.valid)
2123           if (requestor->caller.ani.number.str)
2124             if (requestor->caller.ani.number.str[0])
2125                 ast->caller.ani.number.str=             strdup(requestor->caller.ani.number.str);
2126         ast->caller.ani.number.plan=                    requestor->caller.ani.number.plan;
2127         ast->caller.ani.number.presentation=            requestor->caller.ani.number.presentation;
2128
2129         ast->caller.ani.name.valid=                     requestor->caller.ani.name.valid;
2130         if (requestor->caller.ani.name.valid)
2131           if (requestor->caller.ani.name.str)
2132             if (requestor->caller.ani.name.str[0])
2133                 ast->caller.ani.name.str=               strdup(requestor->caller.ani.name.str);
2134         ast->caller.ani.name.presentation=              requestor->caller.ani.name.presentation;
2135
2136         ast->caller.ani.subaddress.valid=               requestor->caller.ani.subaddress.valid;
2137         if (requestor->caller.ani.subaddress.valid)
2138           if (requestor->caller.ani.subaddress.str)
2139             if (requestor->caller.ani.subaddress.str[0])
2140                 ast->caller.ani.subaddress.str=         strdup(requestor->caller.ani.subaddress.str);
2141         ast->caller.ani.subaddress.type=                requestor->caller.ani.subaddress.type;
2142
2143         ast->caller.id.number.valid=                    requestor->caller.id.number.valid;
2144         if (requestor->caller.id.number.valid)
2145           if (requestor->caller.id.number.str)
2146             if (requestor->caller.id.number.str[0])
2147                 ast->caller.id.number.str=              strdup(requestor->caller.id.number.str);
2148         ast->caller.id.number.plan=                     requestor->caller.id.number.plan;
2149         ast->caller.id.number.presentation=             requestor->caller.id.number.presentation;
2150
2151         ast->caller.id.name.valid=                      requestor->caller.id.name.valid;
2152         if (requestor->caller.id.name.valid)
2153           if (requestor->caller.id.name.str)
2154             if (requestor->caller.id.name.str[0])
2155                 ast->caller.id.name.str=                strdup(requestor->caller.id.name.str);
2156         ast->caller.id.name.presentation=               requestor->caller.id.name.presentation;
2157
2158         ast->caller.id.subaddress.valid=                requestor->caller.id.subaddress.valid;
2159         if (requestor->caller.id.subaddress.valid)
2160           if (requestor->caller.id.subaddress.str)
2161             if (requestor->caller.id.subaddress.str[0])
2162                 ast->caller.id.subaddress.str=          strdup(requestor->caller.id.subaddress.str);
2163         ast->caller.id.subaddress.type=                 requestor->caller.id.subaddress.type;
2164
2165         if (requestor->dialed.number.str)
2166           if (requestor->dialed.number.str[0])
2167                 ast->dialed.number.str=                 strdup(requestor->dialed.number.str);
2168         ast->dialed.number.plan=                        requestor->dialed.number.plan;
2169
2170         ast->dialed.subaddress.valid=                   requestor->dialed.subaddress.valid;
2171         if (requestor->dialed.subaddress.valid)
2172           if (requestor->dialed.subaddress.str)
2173             if (requestor->dialed.subaddress.str[0])
2174                 ast->dialed.subaddress.str=             strdup(requestor->dialed.subaddress.str);
2175         ast->dialed.subaddress.type=                    requestor->dialed.subaddress.type;
2176
2177         ast->dialed.transit_network_select=             requestor->dialed.transit_network_select;
2178         ast->redirecting.count=                         requestor->redirecting.count;
2179         ast->redirecting.reason=                        requestor->redirecting.reason;
2180
2181         ast->redirecting.from.number.valid=             requestor->redirecting.from.number.valid;
2182         if (requestor->redirecting.from.number.valid)
2183           if (requestor->redirecting.from.number.str)
2184             if (requestor->redirecting.from.number.str[0])
2185                 ast->redirecting.from.number.str=       strdup(requestor->redirecting.from.number.str);
2186         ast->redirecting.from.number.plan=              requestor->redirecting.from.number.plan;
2187         ast->redirecting.from.number.presentation=      requestor->redirecting.from.number.presentation;
2188
2189         ast->redirecting.to.number.valid=               requestor->redirecting.to.number.valid;
2190         if (requestor->redirecting.to.number.valid)
2191           if (requestor->redirecting.to.number.str)
2192             if (requestor->redirecting.to.number.str[0])
2193                 ast->redirecting.to.number.str=         strdup(requestor->redirecting.to.number.str);
2194         ast->redirecting.to.number.plan=                requestor->redirecting.to.number.plan;
2195         ast->redirecting.to.number.presentation=        requestor->redirecting.to.number.presentation;
2196 #endif
2197         /* store call information for setup */
2198
2199         /* caller ID */
2200         if (requestor && requestor->caller.id.number.valid) {
2201                 if (requestor->caller.id.number.str)
2202                         strncpy(call->callerinfo.id, requestor->caller.id.number.str, sizeof(call->callerinfo.id)-1);
2203                 switch(requestor->caller.id.number.presentation & AST_PRES_RESTRICTION) {
2204                         case AST_PRES_RESTRICTED:
2205                         call->callerinfo.present = INFO_PRESENT_RESTRICTED;
2206                         break;
2207                         case AST_PRES_UNAVAILABLE:
2208                         call->callerinfo.present = INFO_PRESENT_NOTAVAIL;
2209                         break;
2210                         case AST_PRES_ALLOWED:
2211                         default:
2212                         call->callerinfo.present = INFO_PRESENT_ALLOWED;
2213                 }
2214                 switch(requestor->caller.id.number.presentation & AST_PRES_NUMBER_TYPE) {
2215                         case AST_PRES_USER_NUMBER_UNSCREENED:
2216                         call->callerinfo.screen = INFO_SCREEN_USER;
2217                         break;
2218                         case AST_PRES_USER_NUMBER_PASSED_SCREEN:
2219                         call->callerinfo.screen = INFO_SCREEN_USER_VERIFIED_PASSED;
2220                         break;
2221                         case AST_PRES_USER_NUMBER_FAILED_SCREEN:
2222                         call->callerinfo.screen = INFO_SCREEN_USER_VERIFIED_FAILED;
2223                         break;
2224                         default:
2225                         call->callerinfo.screen = INFO_SCREEN_NETWORK;
2226                 }
2227                 switch((requestor->caller.id.number.plan >> 4) & 7) {
2228                         case 4:
2229                         call->callerinfo.ntype = INFO_NTYPE_SUBSCRIBER;
2230                         break;
2231                         case 2:
2232                         call->callerinfo.ntype = INFO_NTYPE_NATIONAL;
2233                         break;
2234                         case 1:
2235                         call->callerinfo.ntype = INFO_NTYPE_INTERNATIONAL;
2236                         break;
2237                         default:
2238                         call->callerinfo.ntype = INFO_NTYPE_UNKNOWN;
2239                 }
2240         } else
2241                 call->callerinfo.present = INFO_PRESENT_NOTAVAIL;
2242
2243         /* caller ID 2 */
2244         if (requestor && requestor->caller.ani.number.valid) {
2245                 if (requestor->caller.ani.number.str)
2246                         strncpy(call->callerinfo.id2, requestor->caller.ani.number.str, sizeof(call->callerinfo.id2)-1);
2247                 switch(requestor->caller.ani.number.presentation & AST_PRES_RESTRICTION) {
2248                         case AST_PRES_RESTRICTED:
2249                         call->callerinfo.present2 = INFO_PRESENT_RESTRICTED;
2250                         break;
2251                         case AST_PRES_UNAVAILABLE:
2252                         call->callerinfo.present2 = INFO_PRESENT_NOTAVAIL;
2253                         break;
2254                         case AST_PRES_ALLOWED:
2255                         default:
2256                         call->callerinfo.present2 = INFO_PRESENT_ALLOWED;
2257                 }
2258                 switch(requestor->caller.ani.number.presentation & AST_PRES_NUMBER_TYPE) {
2259                         case AST_PRES_USER_NUMBER_UNSCREENED:
2260                         call->callerinfo.screen2 = INFO_SCREEN_USER;
2261                         break;
2262                         case AST_PRES_USER_NUMBER_PASSED_SCREEN:
2263                         call->callerinfo.screen2 = INFO_SCREEN_USER_VERIFIED_PASSED;
2264                         break;
2265                         case AST_PRES_USER_NUMBER_FAILED_SCREEN:
2266                         call->callerinfo.screen2 = INFO_SCREEN_USER_VERIFIED_FAILED;
2267                         break;
2268                         default:
2269                         call->callerinfo.screen2 = INFO_SCREEN_NETWORK;
2270                 }
2271                 switch((requestor->caller.ani.number.plan >> 4) & 7) {
2272                         case 4:
2273                         call->callerinfo.ntype2 = INFO_NTYPE_SUBSCRIBER;
2274                         break;
2275                         case 2:
2276                         call->callerinfo.ntype2 = INFO_NTYPE_NATIONAL;
2277                         break;
2278                         case 1:
2279                         call->callerinfo.ntype2 = INFO_NTYPE_INTERNATIONAL;
2280                         break;
2281                         default:
2282                         call->callerinfo.ntype2 = INFO_NTYPE_UNKNOWN;
2283                 }
2284         } else
2285                 call->callerinfo.present2 = INFO_PRESENT_NOTAVAIL;
2286
2287         /* caller name */
2288         if (requestor && requestor->caller.id.name.valid) {
2289                 if (requestor->caller.id.name.str)
2290                         strncpy(call->callerinfo.name, requestor->caller.id.name.str, sizeof(call->callerinfo.name)-1);
2291         }
2292
2293         /* redir number */
2294         if (requestor && requestor->redirecting.from.number.valid) {
2295                 call->redirinfo.itype = INFO_ITYPE_CHAN;
2296                 if (requestor->redirecting.from.number.str)
2297                         strncpy(call->redirinfo.id, requestor->redirecting.from.number.str, sizeof(call->redirinfo.id)-1);
2298                 switch(requestor->redirecting.from.number.presentation & AST_PRES_RESTRICTION) {
2299                         case AST_PRES_RESTRICTED:
2300                         call->redirinfo.present = INFO_PRESENT_RESTRICTED;
2301                         break;
2302                         case AST_PRES_UNAVAILABLE:
2303                         call->redirinfo.present = INFO_PRESENT_NOTAVAIL;
2304                         break;
2305                         case AST_PRES_ALLOWED:
2306                         default:
2307                         call->redirinfo.present = INFO_PRESENT_ALLOWED;
2308                 }
2309                 switch(requestor->redirecting.from.number.presentation & AST_PRES_NUMBER_TYPE) {
2310                         case AST_PRES_USER_NUMBER_UNSCREENED:
2311                         call->redirinfo.screen = INFO_SCREEN_USER;
2312                         break;
2313                         case AST_PRES_USER_NUMBER_PASSED_SCREEN:
2314                         call->redirinfo.screen = INFO_SCREEN_USER_VERIFIED_PASSED;
2315                         break;
2316                         case AST_PRES_USER_NUMBER_FAILED_SCREEN:
2317                         call->redirinfo.screen = INFO_SCREEN_USER_VERIFIED_FAILED;
2318                         break;
2319                         default:
2320                         call->redirinfo.screen = INFO_SCREEN_NETWORK;
2321                 }
2322                 switch((requestor->redirecting.from.number.plan >> 4) & 7) {
2323                         case 4:
2324                         call->redirinfo.ntype = INFO_NTYPE_SUBSCRIBER;
2325                         break;
2326                         case 2:
2327                         call->redirinfo.ntype = INFO_NTYPE_NATIONAL;
2328                         break;
2329                         case 1:
2330                         call->redirinfo.ntype = INFO_NTYPE_INTERNATIONAL;
2331                         break;
2332                         default:
2333                         call->redirinfo.ntype = INFO_NTYPE_UNKNOWN;
2334                 }
2335         }
2336 #endif
2337
2338         ast_mutex_unlock(&chan_lock);
2339         return ast;
2340 }
2341
2342 /*
2343  * call from asterisk
2344  */
2345 static int lcr_call(struct ast_channel *ast, char *dest, int timeout)
2346 {
2347         union parameter newparam;
2348         struct chan_call *call;
2349
2350         ast_mutex_lock(&chan_lock);
2351         call = ast->tech_pvt;
2352
2353         #ifdef LCR_FOR_CALLWEAVER
2354         ast->type = "LCR";
2355         snprintf(ast->name, sizeof(ast->name), "%s/%s-%04x",lcr_type, call->dialstring, ast_random() & 0xffff);
2356         #endif
2357
2358         if (!call) {
2359                 CERROR(NULL, ast, "Received call from Asterisk, but call instance does not exist.\n");
2360                 ast_mutex_unlock(&chan_lock);
2361                 return -1;
2362         }
2363
2364         CDEBUG(NULL, ast, "Received call from Asterisk.\n");
2365
2366         /* pbx process is started */
2367         call->pbx_started = 1;
2368         /* send MESSAGE_NEWREF */
2369         memset(&newparam, 0, sizeof(union parameter));
2370         newparam.newref.direction = 0; /* request from app */
2371         if (!strcmp(call->interface, "pbx"))
2372                 newparam.newref.mode = 1;
2373         send_message(MESSAGE_NEWREF, 0, &newparam);
2374
2375         /* set hdlc if capability requires hdlc */
2376         if (ast->transfercapability == INFO_BC_DATAUNRESTRICTED
2377          || ast->transfercapability == INFO_BC_DATARESTRICTED
2378          || ast->transfercapability == INFO_BC_VIDEO)
2379                 call->hdlc = 1;
2380         /* if hdlc is forced by option, we change transcap to data */
2381         if (call->hdlc
2382          && ast->transfercapability != INFO_BC_DATAUNRESTRICTED
2383          && ast->transfercapability != INFO_BC_DATARESTRICTED
2384          && ast->transfercapability != INFO_BC_VIDEO)
2385                 ast->transfercapability = INFO_BC_DATAUNRESTRICTED;
2386
2387 #ifndef AST_1_8_OR_HIGHER
2388         call->cid_num[0] = 0;
2389         call->cid_name[0] = 0;
2390         call->cid_rdnis[0] = 0;
2391
2392         if (ast->cid.cid_num) if (ast->cid.cid_num[0])
2393                 strncpy(call->cid_num, ast->cid.cid_num,
2394                         sizeof(call->cid_num)-1);
2395         if (ast->cid.cid_name) if (ast->cid.cid_name[0])
2396                 strncpy(call->cid_name, ast->cid.cid_name,
2397                         sizeof(call->cid_name)-1);
2398         if (ast->cid.cid_rdnis) if (ast->cid.cid_rdnis[0])
2399                 strncpy(call->cid_rdnis, ast->cid.cid_rdnis,
2400                         sizeof(call->cid_rdnis)-1);
2401 #endif
2402
2403         ast_mutex_unlock(&chan_lock);
2404         return 0;
2405 }
2406
2407 static void send_digit_to_chan(struct ast_channel * ast, char digit )
2408 {
2409         static const char* dtmf_tones[] = {
2410                 "!941+1336/100,!0/100", /* 0 */
2411                 "!697+1209/100,!0/100", /* 1 */
2412                 "!697+1336/100,!0/100", /* 2 */
2413                 "!697+1477/100,!0/100", /* 3 */
2414                 "!770+1209/100,!0/100", /* 4 */
2415                 "!770+1336/100,!0/100", /* 5 */
2416                 "!770+1477/100,!0/100", /* 6 */
2417                 "!852+1209/100,!0/100", /* 7 */
2418                 "!852+1336/100,!0/100", /* 8 */
2419                 "!852+1477/100,!0/100", /* 9 */
2420                 "!697+1633/100,!0/100", /* A */
2421                 "!770+1633/100,!0/100", /* B */
2422                 "!852+1633/100,!0/100", /* C */
2423                 "!941+1633/100,!0/100", /* D */
2424                 "!941+1209/100,!0/100", /* * */
2425                 "!941+1477/100,!0/100" };       /* # */
2426
2427         if (digit >= '0' && digit <='9')
2428                 ast_playtones_start(ast,0,dtmf_tones[digit-'0'], 0);
2429         else if (digit >= 'A' && digit <= 'D')
2430                 ast_playtones_start(ast,0,dtmf_tones[digit-'A'+10], 0);
2431         else if (digit == '*')
2432                 ast_playtones_start(ast,0,dtmf_tones[14], 0);
2433         else if (digit == '#')
2434                 ast_playtones_start(ast,0,dtmf_tones[15], 0);
2435         else {
2436 #if ASTERISK_VERSION_NUM < 110000
2437                 CDEBUG(NULL, ast, "Unable to handle DTMF tone '%c' for '%s'\n", digit, ast->name);
2438 #else
2439                 CDEBUG(NULL, ast, "Unable to handle DTMF tone '%c' for '%s'\n", digit, ast_channel_name(ast));
2440 #endif
2441         }
2442 }
2443
2444 #ifdef LCR_FOR_ASTERISK
2445 static int lcr_digit_begin(struct ast_channel *ast, char digit)
2446 #endif
2447 #ifdef LCR_FOR_CALLWEAVER
2448 static int lcr_digit(struct ast_channel *ast, char digit)
2449 #endif
2450 {
2451         struct chan_call *call;
2452         union parameter newparam;
2453         char buf[]="x";
2454
2455 #ifdef LCR_FOR_CALLWEAVER
2456         int inband_dtmf = 0;
2457 #endif
2458
2459         /* only pass IA5 number space */
2460         if (digit > 126 || digit < 32)
2461                 return 0;
2462
2463         ast_mutex_lock(&chan_lock);
2464         call = ast->tech_pvt;
2465         if (!call) {
2466                 CERROR(NULL, ast, "Received digit from Asterisk, but no call instance exists.\n");
2467                 ast_mutex_unlock(&chan_lock);
2468                 return -1;
2469         }
2470
2471         CDEBUG(call, ast, "Received digit '%c' from Asterisk.\n", digit);
2472
2473         /* send information or queue them */
2474         if (call->ref && call->state == CHAN_LCR_STATE_OUT_DIALING) {
2475                 CDEBUG(call, ast, "Sending digit to LCR, because we are in dialing state.\n");
2476                 memset(&newparam, 0, sizeof(union parameter));
2477                 if (call->keypad) {
2478                         newparam.information.keypad[0] = digit;
2479                         newparam.information.keypad[1] = '\0';
2480                 } else {
2481                         newparam.information.id[0] = digit;
2482                         newparam.information.id[1] = '\0';
2483                 }
2484                 send_message(MESSAGE_INFORMATION, call->ref, &newparam);
2485         } else
2486         if (!call->ref
2487          && (call->state == CHAN_LCR_STATE_OUT_PREPARE || call->state == CHAN_LCR_STATE_OUT_SETUP)) {
2488                 CDEBUG(call, ast, "Queue digits, because we are in setup/dialing state and have no ref yet.\n");
2489                 *buf = digit;
2490                 strncat(call->dialque, buf, strlen(call->dialque)-1);
2491         }
2492
2493         ast_mutex_unlock(&chan_lock);
2494
2495 #ifdef LCR_FOR_ASTERISK
2496         return 0;
2497 }
2498
2499 static int lcr_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
2500 {
2501         int inband_dtmf = 0;
2502         struct chan_call *call;
2503 #endif
2504
2505         ast_mutex_lock(&chan_lock);
2506
2507         call = ast->tech_pvt;
2508
2509         if (!call) {
2510                 CERROR(NULL, ast,
2511                         "Received digit from Asterisk, "
2512                         "but no call instance exists.\n");
2513                 ast_mutex_unlock(&chan_lock);
2514                 return -1;
2515         }
2516
2517         CDEBUG(call, ast, "DIGIT END '%c' from Asterisk.\n", digit);
2518
2519         if (call->state == CHAN_LCR_STATE_CONNECT && call->inband_dtmf) {
2520                 inband_dtmf = 1;
2521         }
2522
2523         ast_mutex_unlock(&chan_lock);
2524
2525         if (inband_dtmf) {
2526                 CDEBUG(call, ast, "-> sending '%c' inband.\n", digit);
2527                 send_digit_to_chan(ast, digit);
2528         }
2529
2530         return 0;
2531 }
2532
2533 static int lcr_answer(struct ast_channel *ast)
2534 {
2535         union parameter newparam;
2536         struct chan_call *call;
2537
2538         ast_mutex_lock(&chan_lock);
2539         call = ast->tech_pvt;
2540         if (!call) {
2541                 CERROR(NULL, ast, "Received answer from Asterisk, but no call instance exists.\n");
2542                 ast_mutex_unlock(&chan_lock);
2543                 return -1;
2544         }
2545
2546         CDEBUG(call, ast, "Received answer from Asterisk (maybe during lcr_bridge).\n");
2547
2548         /* copy connectinfo, if bridged */
2549         if (call->bridge_call)
2550                 memcpy(&call->connectinfo, &call->bridge_call->connectinfo, sizeof(struct connect_info));
2551         /* send connect message to lcr */
2552         if (call->state != CHAN_LCR_STATE_CONNECT) {
2553                 memset(&newparam, 0, sizeof(union parameter));
2554                 memcpy(&newparam.connectinfo, &call->connectinfo, sizeof(struct connect_info));
2555                 send_message(MESSAGE_CONNECT, call->ref, &newparam);
2556                 call->state = CHAN_LCR_STATE_CONNECT;
2557         }
2558         /* change state */
2559         /* request bchannel */
2560         if (!call->bchannel) {
2561                 CDEBUG(call, ast, "Requesting B-channel.\n");
2562                 memset(&newparam, 0, sizeof(union parameter));
2563                 newparam.bchannel.type = BCHANNEL_REQUEST;
2564                 send_message(MESSAGE_BCHANNEL, call->ref, &newparam);
2565         }
2566         /* enable keypad */
2567 //      memset(&newparam, 0, sizeof(union parameter));
2568 //      send_message(MESSAGE_ENABLEKEYPAD, call->ref, &newparam);
2569
2570         ast_mutex_unlock(&chan_lock);
2571         return 0;
2572 }
2573
2574 static int lcr_hangup(struct ast_channel *ast)
2575 {
2576         struct chan_call *call;
2577         pthread_t tid = pthread_self();
2578
2579         if (!pthread_equal(tid, chan_tid)) {
2580                 ast_mutex_lock(&chan_lock);
2581         }
2582         call = ast->tech_pvt;
2583         if (!call) {
2584                 CERROR(NULL, ast, "Received hangup from Asterisk, but no call instance exists.\n");
2585                 if (!pthread_equal(tid, chan_tid)) {
2586                         ast_mutex_unlock(&chan_lock);
2587                 }
2588                 return -1;
2589         }
2590
2591         if (!pthread_equal(tid, chan_tid))
2592                 CDEBUG(call, ast, "Received hangup from Asterisk thread.\n");
2593         else
2594                 CDEBUG(call, ast, "Received hangup from LCR thread.\n");
2595
2596         /* disconnect asterisk, maybe not required */
2597         ast->tech_pvt = NULL;
2598         ast->fds[0] = -1;
2599         if (call->ref) {
2600                 /* release */
2601                 CDEBUG(call, ast, "Releasing ref and freeing call instance.\n");
2602                 if (ast->hangupcause > 0)
2603                         send_release_and_import(call, ast->hangupcause, LOCATION_PRIVATE_LOCAL);
2604                 else
2605                         send_release_and_import(call, CAUSE_NORMAL, LOCATION_PRIVATE_LOCAL);
2606                 /* remove call */
2607                 free_call(call);
2608                 if (!pthread_equal(tid, chan_tid)) {
2609                         ast_mutex_unlock(&chan_lock);
2610                 }
2611                 return 0;
2612         } else {
2613                 /* ref is not set, due to prepare setup or release */
2614                 if (call->state == CHAN_LCR_STATE_RELEASE) {
2615                         /* we get the response to our release */
2616                         CDEBUG(call, ast, "Freeing call instance, because we have no ref AND we are requesting no ref.\n");
2617                         free_call(call);
2618                 } else {
2619                         /* during prepare, we change to release state */
2620                         CDEBUG(call, ast, "We must wait until we received our ref, until we can free call instance.\n");
2621                         call->state = CHAN_LCR_STATE_RELEASE;
2622                         call->ast = NULL;
2623                 }
2624         }
2625         if (!pthread_equal(tid, chan_tid)) {
2626                 ast_mutex_unlock(&chan_lock);
2627         }
2628         return 0;
2629 }
2630
2631 static int lcr_write(struct ast_channel *ast, struct ast_frame *fr)
2632 {
2633         struct chan_call *call;
2634         struct ast_frame * f = fr;
2635
2636 #if ASTERISK_VERSION_NUM < 100000
2637 #ifdef AST_1_8_OR_HIGHER
2638         if (!f->subclass.codec)
2639 #else
2640         if (!f->subclass)
2641 #endif
2642                 CDEBUG(NULL, ast, "No subclass\n");
2643 #endif
2644 #ifdef AST_1_8_OR_HIGHER
2645 #if ASTERISK_VERSION_NUM < 100000
2646         if (!(f->subclass.codec & ast->nativeformats)) {
2647 #else
2648         if (!ast_format_cap_iscompatible(ast->nativeformats, &f->subclass.format)) {
2649 #endif
2650 #else
2651         if (!(f->subclass & ast->nativeformats)) {
2652 #endif
2653                 CDEBUG(NULL, ast,
2654                                "Unexpected format. "
2655                        "Activating emergency conversion...\n");
2656
2657 #ifdef AST_1_8_OR_HIGHER
2658 #if ASTERISK_VERSION_NUM < 100000
2659                 ast_set_write_format(ast, f->subclass.codec);
2660 #else
2661                 ast_set_write_format(ast, &f->subclass.format);
2662 #endif
2663 #else
2664                 ast_set_write_format(ast, f->subclass);
2665 #endif
2666                 f = (ast->writetrans) ? ast_translate(
2667                         ast->writetrans, fr, 0) : fr;
2668         }
2669
2670         ast_mutex_lock(&chan_lock);
2671         call = ast->tech_pvt;
2672         if (!call) {
2673                 ast_mutex_unlock(&chan_lock);
2674                 if (f != fr) {
2675                         ast_frfree(f);
2676                 }
2677                 return -1;
2678         }
2679         if (call->bchannel && f->samples)
2680                 bchannel_transmit(call->bchannel, *((unsigned char **)&(f->data)), f->samples);
2681         ast_mutex_unlock(&chan_lock);
2682         if (f != fr) {
2683                 ast_frfree(f);
2684         }
2685         return 0;
2686 }
2687
2688
2689 static struct ast_frame *lcr_read(struct ast_channel *ast)
2690 {
2691         struct chan_call *call;
2692         int len = 0;
2693
2694         ast_mutex_lock(&chan_lock);
2695         call = ast->tech_pvt;
2696         if (!call) {
2697                 ast_mutex_unlock(&chan_lock);
2698                 return NULL;
2699         }
2700         if (call->pipe[0] > -1) {
2701                 if (call->rebuffer && !call->hdlc) {
2702                         /* Make sure we have a complete 20ms (160byte) frame */
2703                         len=read(call->pipe[0],call->read_buff + call->framepos, 160 - call->framepos);
2704                         if (len > 0) {
2705                                 call->framepos += len;
2706                         }
2707                 } else {
2708                         len = read(call->pipe[0], call->read_buff, sizeof(call->read_buff));
2709                 }
2710                 if (len < 0 && errno == EAGAIN) {
2711                         ast_mutex_unlock(&chan_lock);
2712
2713                         #ifdef LCR_FOR_ASTERISK
2714                         return &ast_null_frame;
2715                         #endif
2716
2717                         #ifdef LCR_FOR_CALLWEAVER
2718                         return &nullframe;
2719                         #endif
2720
2721                 }
2722                 if (len <= 0) {
2723                         close(call->pipe[0]);
2724                         call->pipe[0] = -1;
2725                         global_change = 1;
2726                         ast_mutex_unlock(&chan_lock);
2727                         return NULL;
2728                 } else if (call->rebuffer && call->framepos < 160) {
2729                         /* Not a complete frame, so we send a null-frame */
2730                         ast_mutex_unlock(&chan_lock);
2731                         return &ast_null_frame;
2732                 }
2733         }
2734
2735         call->read_fr.frametype = AST_FRAME_VOICE;
2736 #ifdef AST_1_8_OR_HIGHER
2737 #if ASTERISK_VERSION_NUM < 100000
2738         call->read_fr.subclass.codec = ast->nativeformats;
2739 #else
2740         ast_best_codec(ast->nativeformats, &call->read_fr.subclass.format);
2741         call->read_fr.subclass.integer = call->read_fr.subclass.format.id;
2742 #endif
2743 #else
2744         call->read_fr.subclass = ast->nativeformats;
2745 #endif
2746         if (call->rebuffer) {
2747                 call->read_fr.datalen = call->framepos;
2748                 call->read_fr.samples = call->framepos;
2749                 call->framepos = 0;
2750         } else {
2751                 call->read_fr.datalen = len;
2752                 call->read_fr.samples = len;
2753         }
2754         call->read_fr.delivery = ast_tv(0,0);
2755         *((unsigned char **)&(call->read_fr.data)) = call->read_buff;
2756         ast_mutex_unlock(&chan_lock);
2757
2758         return &call->read_fr;
2759 }
2760
2761 static int lcr_indicate(struct ast_channel *ast, int cond, const void *data, size_t datalen)
2762 {
2763         union parameter newparam;
2764         int res = 0;
2765         struct chan_call *call;
2766         const struct tone_zone_sound *ts = NULL;
2767
2768         ast_mutex_lock(&chan_lock);
2769         call = ast->tech_pvt;
2770         if (!call) {
2771                 CERROR(NULL, ast, "Received indicate from Asterisk, but no call instance exists.\n");
2772                 ast_mutex_unlock(&chan_lock);
2773                 return -1;
2774         }
2775
2776         switch (cond) {
2777                 case AST_CONTROL_BUSY:
2778                         CDEBUG(call, ast, "Received indicate AST_CONTROL_BUSY from Asterisk.\n");
2779                         ast_setstate(ast, AST_STATE_BUSY);
2780                         if (call->state != CHAN_LCR_STATE_OUT_DISCONNECT) {
2781                                 /* send message to lcr */
2782                                 memset(&newparam, 0, sizeof(union parameter));
2783                                 newparam.disconnectinfo.cause = 17;
2784                                 newparam.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
2785                                 send_message(MESSAGE_DISCONNECT, call->ref, &newparam);
2786                                 /* change state */
2787                                 call->state = CHAN_LCR_STATE_OUT_DISCONNECT;
2788                         } else {
2789                                 CDEBUG(call, ast, "Using Asterisk 'busy' indication\n");
2790                                 ts = ast_get_indication_tone(ast->zone, "busy");
2791                         }
2792                         break;
2793                 case AST_CONTROL_CONGESTION:
2794                         CDEBUG(call, ast, "Received indicate AST_CONTROL_CONGESTION from Asterisk. (cause %d)\n", ast->hangupcause);
2795                         if (call->state != CHAN_LCR_STATE_OUT_DISCONNECT) {
2796                                 /* send message to lcr */
2797                                 memset(&newparam, 0, sizeof(union parameter));
2798                                 newparam.disconnectinfo.cause = ast->hangupcause;
2799                                 newparam.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
2800                                 send_message(MESSAGE_DISCONNECT, call->ref, &newparam);
2801                                 /* change state */
2802                                 call->state = CHAN_LCR_STATE_OUT_DISCONNECT;
2803                         } else {
2804                                 CDEBUG(call, ast, "Using Asterisk 'congestion' indication\n");
2805                                 ts = ast_get_indication_tone(ast->zone, "congestion");
2806                         }
2807                         break;
2808                 case AST_CONTROL_PROCEEDING:
2809                         CDEBUG(call, ast, "Received indicate AST_CONTROL_PROCEEDING from Asterisk.\n");
2810                         if (call->state == CHAN_LCR_STATE_IN_SETUP
2811                          || call->state == CHAN_LCR_STATE_IN_DIALING) {
2812                                 /* send message to lcr */
2813                                 memset(&newparam, 0, sizeof(union parameter));
2814                                 send_message(MESSAGE_PROCEEDING, call->ref, &newparam);
2815                                 /* change state */
2816                                 call->state = CHAN_LCR_STATE_IN_PROCEEDING;
2817                         }
2818                         break;
2819                 case AST_CONTROL_RINGING:
2820                         CDEBUG(call, ast, "Received indicate AST_CONTROL_RINGING from Asterisk.\n");
2821                         ast_setstate(ast, AST_STATE_RING);
2822                         if (call->state == CHAN_LCR_STATE_IN_SETUP
2823                          || call->state == CHAN_LCR_STATE_IN_DIALING
2824                          || call->state == CHAN_LCR_STATE_IN_PROCEEDING) {
2825                                 /* send message to lcr */
2826                                 memset(&newparam, 0, sizeof(union parameter));
2827                                 send_message(MESSAGE_ALERTING, call->ref, &newparam);
2828                                 /* change state */
2829                                 call->state = CHAN_LCR_STATE_IN_ALERTING;
2830                         } else {
2831                                 CDEBUG(call, ast, "Using Asterisk 'ring' indication\n");
2832                                 ts = ast_get_indication_tone(ast->zone, "ring");
2833                         }
2834                         break;
2835                 case AST_CONTROL_PROGRESS:
2836                         CDEBUG(call, ast, "Received indicate AST_CONTROL_PROGRESS from Asterisk.\n");
2837                         /* request bchannel */
2838                         if (!call->bchannel) {
2839                                 CDEBUG(call, ast, "Requesting B-channel.\n");
2840                                 memset(&newparam, 0, sizeof(union parameter));
2841                                 newparam.bchannel.type = BCHANNEL_REQUEST;
2842                                 send_message(MESSAGE_BCHANNEL, call->ref, &newparam);
2843                         }
2844                         break;
2845                 case -1:
2846                         CDEBUG(call, ast, "Received indicate -1.\n");
2847                         ast_playtones_stop(ast);
2848                         res = -1;
2849                         break;
2850
2851                 case AST_CONTROL_VIDUPDATE:
2852                         CDEBUG(call, ast, "Received indicate AST_CONTROL_VIDUPDATE.\n");
2853                         res = -1;
2854                         break;
2855                 case AST_CONTROL_HOLD:
2856                         CDEBUG(call, ast, "Received indicate AST_CONTROL_HOLD from Asterisk.\n");
2857                         /* send message to lcr */
2858                         memset(&newparam, 0, sizeof(union parameter));
2859                         newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_HOLD;
2860                         send_message(MESSAGE_NOTIFY, call->ref, &newparam);
2861
2862                         /*start music onhold*/
2863                         #ifdef LCR_FOR_ASTERISK
2864                         #if ASTERISK_VERSION_NUM <110000
2865                         ast_moh_start(ast,data,ast->musicclass);
2866                         #else
2867                         ast_moh_start(ast,data,ast_channel_musicclass(ast));
2868                         #endif
2869                         #endif
2870
2871                         #ifdef LCR_FOR_CALLWEAVER
2872                         ast_moh_start(ast, NULL);
2873                         #endif
2874
2875                         call->on_hold = 1;
2876                         break;
2877                 case AST_CONTROL_UNHOLD:
2878                         CDEBUG(call, ast, "Received indicate AST_CONTROL_UNHOLD from Asterisk.\n");
2879                         /* send message to lcr */
2880                         memset(&newparam, 0, sizeof(union parameter));
2881                         newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_RETRIEVAL;
2882                         send_message(MESSAGE_NOTIFY, call->ref, &newparam);
2883
2884                         /*stop moh*/
2885                         ast_moh_stop(ast);
2886                         call->on_hold = 0;
2887                         break;
2888 #ifdef AST_CONTROL_SRCUPDATE
2889                 case AST_CONTROL_SRCUPDATE:
2890 #else
2891                 case 20:
2892 #endif
2893                         CDEBUG(call, ast, "Received AST_CONTROL_SRCUPDATE from Asterisk.\n");
2894                         break;
2895                 default:
2896                         CERROR(call, ast, "Received indicate from Asterisk with unknown condition %d.\n", cond);
2897                         res = -1;
2898                         break;
2899         }
2900
2901         if (ts && ts->data[0]) {
2902                 ast_playtones_start(ast, 0, ts->data, 1);
2903         }
2904
2905         /* return */
2906         ast_mutex_unlock(&chan_lock);
2907         return res;
2908 }
2909
2910 /*
2911  * fixup asterisk
2912  */
2913 static int lcr_fixup(struct ast_channel *oldast, struct ast_channel *ast)
2914 {
2915         struct chan_call *call;
2916
2917         if (!ast) {
2918                 return -1;
2919         }
2920
2921         ast_mutex_lock(&chan_lock);
2922         call = ast->tech_pvt;
2923         if (!call) {
2924                 CERROR(NULL, ast, "Received fixup from Asterisk, but no call instance exists.\n");
2925                 ast_mutex_unlock(&chan_lock);
2926                 return -1;
2927         }
2928
2929         CDEBUG(call, ast, "Received fixup from Asterisk.\n");
2930         call->ast = ast;
2931         ast_mutex_unlock(&chan_lock);
2932         return 0;
2933 }
2934
2935 /*
2936  * send_text asterisk
2937  */
2938 static int lcr_send_text(struct ast_channel *ast, const char *text)
2939 {
2940         struct chan_call *call;
2941         union parameter newparam;
2942
2943         ast_mutex_lock(&chan_lock);
2944         call = ast->tech_pvt;
2945         if (!call) {
2946                 CERROR(NULL, ast, "Received send_text from Asterisk, but no call instance exists.\n");
2947                 ast_mutex_unlock(&chan_lock);
2948                 return -1;
2949         }
2950
2951         CDEBUG(call, ast, "Received send_text from Asterisk. (text=%s)\n", text);
2952         memset(&newparam, 0, sizeof(union parameter));
2953         strncpy(newparam.notifyinfo.display, text, sizeof(newparam.notifyinfo.display)-1);
2954         send_message(MESSAGE_NOTIFY, call->ref, &newparam);
2955         ast_mutex_unlock(&chan_lock);
2956         return 0;
2957 }
2958
2959 /*
2960  * bridge process
2961  */
2962 enum ast_bridge_result lcr_bridge(struct ast_channel *ast1,
2963                                   struct ast_channel *ast2, int flags,
2964                                   struct ast_frame **fo,
2965                                   struct ast_channel **rc, int timeoutms)
2966
2967 {
2968         struct chan_call        *call1, *call2;
2969         struct ast_channel      *carr[2], *who;
2970         int                     to;
2971         struct ast_frame        *f;
2972         int                     bridge_id;
2973
2974         CDEBUG(NULL, NULL, "Received bridging request from Asterisk.\n");
2975
2976         carr[0] = ast1;
2977         carr[1] = ast2;
2978
2979         /* join via dsp (if the channels are currently open) */
2980         ast_mutex_lock(&chan_lock);
2981         call1 = ast1->tech_pvt;
2982         call2 = ast2->tech_pvt;
2983         if (!call1 || !call2) {
2984                 CDEBUG(NULL, NULL, "Bridge, but we don't have two call instances, exitting.\n");
2985                 ast_mutex_unlock(&chan_lock);
2986                 return AST_BRIDGE_COMPLETE;
2987         }
2988
2989         /* join, if both call instances uses dsp
2990            ignore the case of fax detection here it may be benificial for ISDN fax machines or pass through.
2991         */
2992         if (!call1->nodsp && !call2->nodsp) {
2993                 CDEBUG(NULL, NULL, "Both calls use DSP, bridging via DSP.\n");
2994
2995                 /* get bridge id and join */
2996                 bridge_id = new_bridge_id();
2997
2998                 call1->bridge_id = bridge_id;
2999                 if (call1->bchannel)
3000                         bchannel_join(call1->bchannel, bridge_id);
3001
3002                 call2->bridge_id = bridge_id;
3003                 if (call2->bchannel)
3004                         bchannel_join(call2->bchannel, bridge_id);
3005         } else
3006         if (call1->nodsp && call2->nodsp)
3007                 CDEBUG(NULL, NULL, "Both calls use no DSP, bridging in channel driver.\n");
3008         else
3009                 CDEBUG(NULL, NULL, "One call uses no DSP, bridging in channel driver.\n");
3010         call1->bridge_call = call2;
3011         call2->bridge_call = call1;
3012
3013         if (call1->state == CHAN_LCR_STATE_IN_SETUP
3014          || call1->state == CHAN_LCR_STATE_IN_DIALING
3015          || call1->state == CHAN_LCR_STATE_IN_PROCEEDING
3016          || call1->state == CHAN_LCR_STATE_IN_ALERTING) {
3017                 CDEBUG(call1, ast1, "Bridge established before lcr_answer, so we call it ourself: Calling lcr_answer...\n");
3018                 lcr_answer(ast1);
3019         }
3020         if (call2->state == CHAN_LCR_STATE_IN_SETUP
3021          || call2->state == CHAN_LCR_STATE_IN_DIALING
3022          || call2->state == CHAN_LCR_STATE_IN_PROCEEDING
3023          || call2->state == CHAN_LCR_STATE_IN_ALERTING) {
3024                 CDEBUG(call2, ast2, "Bridge established before lcr_answer, so we call it ourself: Calling lcr_answer...\n");
3025                 lcr_answer(ast2);
3026         }
3027
3028         /* sometimes SIP phones forget to send RETRIEVE before TRANSFER
3029            so let's do it for them. Hmpf.
3030         */
3031
3032         if (call1->on_hold) {
3033                 union parameter newparam;
3034
3035                 memset(&newparam, 0, sizeof(union parameter));
3036                 newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_RETRIEVAL;
3037                 send_message(MESSAGE_NOTIFY, call1->ref, &newparam);
3038
3039                 call1->on_hold = 0;
3040         }
3041
3042         if (call2->on_hold) {
3043                 union parameter newparam;
3044
3045                 memset(&newparam, 0, sizeof(union parameter));
3046                 newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_RETRIEVAL;
3047                 send_message(MESSAGE_NOTIFY, call2->ref, &newparam);
3048
3049                 call2->on_hold = 0;
3050         }
3051
3052         ast_mutex_unlock(&chan_lock);
3053
3054         while(1) {
3055                 to = -1;
3056                 who = ast_waitfor_n(carr, 2, &to);
3057
3058                 if (!who) {
3059                         CDEBUG(NULL, NULL, "Empty read on bridge, breaking out.\n");
3060                         break;
3061                 }
3062                 f = ast_read(who);
3063
3064                 if (!f || f->frametype == AST_FRAME_CONTROL) {
3065                         if (!f)
3066                                 CDEBUG(NULL, NULL, "Got hangup.\n");
3067                         else
3068                                 CDEBUG(NULL, NULL, "Got CONTROL.\n");
3069                         /* got hangup .. */
3070                         *fo=f;
3071                         *rc=who;
3072                         break;
3073                 }
3074
3075                 if ( f->frametype == AST_FRAME_DTMF ) {
3076                         CDEBUG(NULL, NULL, "Got DTMF.\n");
3077                         *fo=f;
3078                         *rc=who;
3079                         break;
3080                 }
3081
3082
3083                 if (who == ast1) {
3084                         ast_write(ast2,f);
3085                 }
3086                 else {
3087                         ast_write(ast1,f);
3088                 }
3089
3090         }
3091
3092         CDEBUG(NULL, NULL, "Releasing bridge.\n");
3093
3094         /* split channels */
3095         ast_mutex_lock(&chan_lock);
3096         call1 = ast1->tech_pvt;
3097         call2 = ast2->tech_pvt;
3098         if (call1 && call1->bridge_id) {
3099                 call1->bridge_id = 0;
3100                 if (call1->bchannel)
3101                         bchannel_join(call1->bchannel, 0);
3102                 if (call1->bridge_call)
3103                         call1->bridge_call->bridge_call = NULL;
3104         }
3105         if (call2 && call1->bridge_id) {
3106                 call2->bridge_id = 0;
3107                 if (call2->bchannel)
3108                         bchannel_join(call2->bchannel, 0);
3109                 if (call2->bridge_call)
3110                         call2->bridge_call->bridge_call = NULL;
3111         }
3112         call1->bridge_call = NULL;
3113         call2->bridge_call = NULL;
3114
3115         ast_mutex_unlock(&chan_lock);
3116         return AST_BRIDGE_COMPLETE;
3117 }
3118 static struct ast_channel_tech lcr_tech = {
3119         .type= lcr_type,
3120         .description = "Channel driver for connecting to Linux-Call-Router",
3121         #if ASTERISK_VERSION_NUM < 100000
3122         .capabilities = AST_FORMAT_ALAW,
3123         #endif
3124         .requester = lcr_request,
3125
3126         #ifdef LCR_FOR_ASTERISK
3127         .send_digit_begin = lcr_digit_begin,
3128         .send_digit_end = lcr_digit_end,
3129         #endif
3130
3131         #ifdef LCR_FOR_CALLWEAVER
3132         .send_digit = lcr_digit,
3133         #endif
3134
3135         .call = lcr_call,
3136         .bridge = lcr_bridge,
3137         .hangup = lcr_hangup,
3138         .answer = lcr_answer,
3139         .read = lcr_read,
3140         .write = lcr_write,
3141         .indicate = lcr_indicate,
3142         .fixup = lcr_fixup,
3143         .send_text = lcr_send_text,
3144         .properties = 0
3145 };
3146
3147
3148 /*
3149  * cli
3150  */
3151 #if 0
3152 static int lcr_show_lcr (int fd, int argc, char *argv[])
3153 {
3154         return 0;
3155 }
3156
3157 static int lcr_show_calls (int fd, int argc, char *argv[])
3158 {
3159         return 0;
3160 }
3161
3162 static int lcr_reload_routing (int fd, int argc, char *argv[])
3163 {
3164         return 0;
3165 }
3166
3167 static int lcr_reload_interfaces (int fd, int argc, char *argv[])
3168 {
3169         return 0;
3170 }
3171
3172 static int lcr_port_block (int fd, int argc, char *argv[])
3173 {
3174         return 0;
3175 }
3176
3177 static int lcr_port_unblock (int fd, int argc, char *argv[])
3178 {
3179         return 0;
3180 }
3181
3182 static int lcr_port_unload (int fd, int argc, char *argv[])
3183 {
3184         return 0;
3185 }
3186
3187 static struct ast_cli_entry cli_show_lcr =
3188 { {"lcr", "show", "lcr", NULL},
3189  lcr_show_lcr,
3190  "Shows current states of LCR core",
3191  "Usage: lcr show lcr\n",
3192 };
3193
3194 static struct ast_cli_entry cli_show_calls =
3195 { {"lcr", "show", "calls", NULL},
3196  lcr_show_calls,
3197  "Shows current calls made by LCR and Asterisk",
3198  "Usage: lcr show calls\n",
3199 };
3200
3201 static struct ast_cli_entry cli_reload_routing =
3202 { {"lcr", "reload", "routing", NULL},
3203  lcr_reload_routing,
3204  "Reloads routing conf of LCR, current uncomplete calls will be disconnected",
3205  "Usage: lcr reload routing\n",
3206 };
3207
3208 static struct ast_cli_entry cli_reload_interfaces =
3209 { {"lcr", "reload", "interfaces", NULL},
3210  lcr_reload_interfaces,
3211  "Reloads interfaces conf of LCR",
3212  "Usage: lcr reload interfaces\n",
3213 };
3214
3215 static struct ast_cli_entry cli_port_block =
3216 { {"lcr", "port", "block", NULL},
3217  lcr_port_block,
3218  "Blocks LCR port for further calls",
3219  "Usage: lcr port block \"<port>\"\n",
3220 };
3221
3222 static struct ast_cli_entry cli_port_unblock =
3223 { {"lcr", "port", "unblock", NULL},
3224  lcr_port_unblock,
3225  "Unblocks or loads LCR port, port is opened my mISDN",
3226  "Usage: lcr port unblock \"<port>\"\n",
3227 };
3228
3229 static struct ast_cli_entry cli_port_unload =
3230 { {"lcr", "port", "unload", NULL},
3231  lcr_port_unload,
3232  "Unloads LCR port, port is closes by mISDN",
3233  "Usage: lcr port unload \"<port>\"\n",
3234 };
3235 #endif
3236
3237
3238 #ifdef LCR_FOR_ASTERISK
3239 #ifdef AST_1_8_OR_HIGHER
3240 static int lcr_config_exec(struct ast_channel *ast, const char *data)
3241 #else
3242 static int lcr_config_exec(struct ast_channel *ast, void *data)
3243 #endif
3244 #endif
3245
3246 #ifdef LCR_FOR_CALLWEAVER
3247 static int lcr_config_exec(struct ast_channel *ast, void *data, char **argv)
3248 #endif
3249 {
3250         struct chan_call *call;
3251
3252         ast_mutex_lock(&chan_lock);
3253
3254         #ifdef LCR_FOR_ASTERISK
3255         CDEBUG(NULL, ast, "Received lcr_config (data=%s)\n", (char *)data);
3256         #endif
3257
3258         #ifdef LCR_FOR_CALLWEAVER
3259         CDEBUG(NULL, ast, "Received lcr_config (data=%s)\n", argv[0]);
3260         #endif
3261
3262         /* find channel */
3263         call = call_first;
3264         while(call) {
3265                 if (call->ast == ast)
3266                         break;
3267                 call = call->next;
3268         }
3269         if (call)
3270
3271                 #ifdef LCR_FOR_ASTERISK
3272                 apply_opt(call, (char *)data);
3273                 #endif
3274
3275                 #ifdef LCR_FOR_CALLWEAVER
3276                 apply_opt(call, (char *)argv[0]);
3277                 #endif
3278
3279         else
3280                 CERROR(NULL, ast, "lcr_config app not called by chan_lcr channel.\n");
3281
3282         ast_mutex_unlock(&chan_lock);
3283         return 0;
3284 }
3285
3286 /*
3287  * module loading and destruction
3288  */
3289 int load_module(void)
3290 {
3291         u_short i;
3292         char options_error[256];
3293
3294         for (i = 0; i < 256; i++) {
3295                 flip_bits[i] = (i>>7) | ((i>>5)&2) | ((i>>3)&4) | ((i>>1)&8)
3296                              | (i<<7) | ((i&2)<<5) | ((i&4)<<3) | ((i&8)<<1);
3297         }