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