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