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