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