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