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