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