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