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