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