Define prload of mISDN buffer by chan_lcr (required for fax)
[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 The ref_was_assigned ist set to 1.
25 A new chan_call instance is created. The call reference (ref) is given by
26 the received MESSAGE_NEWREF. The state is CHAN_LCR_STATE_IN_PREPARE.
27 After receiving MESSAGE_SETUP from LCR, the ast_channel instance is created
28 using ast_channel_alloc(1).  The setup information is given to asterisk.
29 The new Asterisk instance pointer (ast) is stored to chan_call structure.
30 The state changes to CHAN_LCR_STATE_IN_SETUP.
31
32
33 Call is initiated by Asterisk:
34
35 If a call is requested from Asterisk, a new chan_call instance is created.
36 The new Asterisk instance pointer (ast) is stored to chan_call structure.
37 The current call ref is set to 0, the state is CHAN_LCR_STATE_OUT_PREPARE.
38 If the call is received (lcr_call) A MESSAGE_NEWREF is sent to LCR requesting
39 a new call reference (ref).
40 The ref_was_assigned ist set to 1.
41 Further dialing information is queued.
42 After the new callref is received by special MESSAGE_NEWREF reply, new ref
43 is stored in the chan_call structure.
44 The setup information is sent to LCR using MESSAGE_SETUP.
45 The state changes to CHAN_LCR_STATE_OUT_SETUP.
46
47
48 Call is in process:
49
50 During call process, messages are received and sent.
51 The state changes accordingly.
52 Any message is allowed to be sent to LCR at any time except MESSAGE_RELEASE.
53 If a MESSAGE_OVERLAP is received, further dialing is required.
54 Queued dialing information, if any, is sent to LCR using MESSAGE_DIALING.
55 In this case, the state changes to CHAN_LCR_STATE_OUT_DIALING.
56
57
58 Call is released by LCR:
59
60 A MESSAGE_RELEASE is received with the call reference (ref) to be released.
61 The current ref is set to 0, to indicate released reference.
62 The ref_was_assigned==1 shows that there is no other ref to be assigned.
63 The state changes to CHAN_LCR_STATE_RELEASE.
64 ast_queue_hangup() is called, if asterisk instance (ast) exists, if not,
65 the chan_call instance is destroyed.
66 After lcr_hangup() is called-back by Asterisk, the chan_call instance
67 is destroyed, because the current ref is set to 0 and the state equals
68 CHAN_LCR_STATE_RELEASE.
69 If the ref is 0 and the state is not CHAN_LCR_STATE_RELEASE, see the proceedure
70 "Call is released by Asterisk".
71
72
73 Call is released by Asterisk:
74
75 lcr_hangup() is called-back by Asterisk. If the call reference (ref) is set,
76 a MESSAGE_RELEASE is sent to LCR and the chan_call instance is destroyed.
77 If the ref is 0 and the state is not CHAN_LCR_STATE_RELEASE, the new state is
78 set to CHAN_LCR_STATE_RELEASE.
79 The ref_was_assigned==0 shows that a ref is still requested.
80 Later, if the MESSAGE_NEWREF reply is received, a MESSAGE_RELEASE is sent to
81 LCR and the chan_call instance is destroyed.
82 If the ref is 0 and the state is CHAN_LCR_STATE_RELEASE, see the proceedure
83 "Call is released by LCR".
84
85
86 Locking issues:
87
88 The deadlocking problem:
89
90 - chan_lcr locks chan_lock and waits inside ast_queue_xxxx() for ast_channel
91 to be unlocked.
92 - ast_channel thread locks ast_channel and calls a tech function and waits
93 there for chan_lock to be unlocked.
94
95 The solution:
96
97 Never call ast_queue_xxxx() if ast_channel is not locked and don't wait until
98 ast_channel can be locked. All messages to asterisk are queued inside call
99 instance and will be handled using a try-lock to get ast_channel lock.
100 If it succeeds to lock ast_channel, the ast_queue_xxxx can safely called even
101 if the lock is incremented and decremented there.
102
103 Exception: Calling ast_queue_frame inside ast->tech->read is safe, because
104 it is called from ast_channel process which has already locked ast_channel.
105
106 */
107
108
109 /* Choose if you want to have chan_lcr for Asterisk 1.4.x or CallWeaver 1.2.x */
110 #define LCR_FOR_ASTERISK
111 /* #define LCR_FOR_CALLWEAVER */
112
113 #include <stdio.h>
114 #include <stdlib.h>
115 #include <string.h>
116 #include <stdarg.h>
117 #include <errno.h>
118 #include <sys/types.h>
119 #include <time.h>
120 //#include <signal.h>
121 #include <unistd.h>
122 #include <fcntl.h>
123 #include <sys/ioctl.h>
124 #include <sys/socket.h>
125 #include <sys/un.h>
126
127 #include <semaphore.h>
128
129 #define HAVE_ATTRIBUTE_always_inline 1
130 #define HAVE_ARPA_INET_H 1
131 #define HAVE_TIMERSUB 1
132 #define HAVE_STRTOQ 1
133 #define HAVE_INET_ATON 1
134
135 #include <asterisk/compiler.h>
136 #ifdef LCR_FOR_ASTERISK
137 #include <asterisk/buildopts.h>
138 #endif
139
140 /*
141  * Fwd declare struct ast_channel to get rid of gcc warning about
142  * incompatible pointer type passed to ast_register_application2.
143  */
144 struct ast_channel;
145
146 #include <asterisk/module.h>
147 #include <asterisk/channel.h>
148 #include <asterisk/config.h>
149 #include <asterisk/logger.h>
150 #include <asterisk/pbx.h>
151 #include <asterisk/options.h>
152 #include <asterisk/io.h>
153 #include <asterisk/frame.h>
154 #include <asterisk/translate.h>
155 #include <asterisk/cli.h>
156 #include <asterisk/musiconhold.h>
157 #include <asterisk/dsp.h>
158 #include <asterisk/translate.h>
159 #include <asterisk/file.h>
160 #ifdef LCR_FOR_ASTERISK
161 #include <asterisk/callerid.h>
162 #endif
163 #ifdef LCR_FOR_CALLWEAVER
164 #include <asterisk/phone_no_utils.h>
165 #endif
166
167 #include <asterisk/indications.h>
168 #include <asterisk/app.h>
169 #include <asterisk/features.h>
170 #include <asterisk/sched.h>
171 #if ASTERISK_VERSION_NUM < 110000
172 #include <asterisk/version.h>
173 #endif
174 #include "extension.h"
175 #include "message.h"
176 #include "callerid.h"
177 #include "lcrsocket.h"
178 #include "cause.h"
179 #include "select.h"
180 #include "options.h"
181 #include "chan_lcr.h"
182
183 CHAN_LCR_STATE // state description structure
184 MESSAGES // message text
185
186 #ifdef LCR_FOR_CALLWEAVER
187 AST_MUTEX_DEFINE_STATIC(rand_lock);
188 #endif
189
190 unsigned char flip_bits[256];
191
192 #ifdef LCR_FOR_CALLWEAVER
193 static struct ast_frame nullframe = { AST_FRAME_NULL, };
194 #endif
195
196 int lcr_debug=1;
197
198 char lcr_type[]="lcr";
199
200 #ifdef LCR_FOR_CALLWEAVER
201 static ast_mutex_t usecnt_lock;
202 static int usecnt=0;
203 static char *desc = "Channel driver for mISDN/LCR Support (Bri/Pri)";
204 #endif
205
206 pthread_t chan_tid;
207 ast_mutex_t chan_lock; /* global lock */
208 ast_mutex_t log_lock; /* logging log */
209 /* global_change:
210  * used to indicate change in file descriptors, so select function's result may
211  * be obsolete.
212  */
213 int global_change = 0;
214 int wake_global = 0;
215 int wake_pipe[2];
216 struct lcr_fd wake_fd;
217
218 int glob_channel = 0;
219
220 int lcr_sock = -1;
221 struct lcr_fd socket_fd;
222 struct lcr_timer socket_retry;
223
224 struct admin_list {
225         struct admin_list *next;
226         struct admin_message msg;
227 } *admin_first = NULL;
228
229 static struct ast_channel_tech lcr_tech;
230
231 /*
232  * logging
233  */
234 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, ...)
235 {
236         char buffer[1024];
237         char call_text[128] = "NULL";
238         char ast_text[128] = "NULL";
239         va_list args;
240
241         ast_mutex_lock(&log_lock);
242
243         va_start(args,fmt);
244         vsnprintf(buffer,sizeof(buffer)-1,fmt,args);
245         buffer[sizeof(buffer)-1]=0;
246         va_end(args);
247
248         if (call)
249                 sprintf(call_text, "%d", call->ref);
250         if (ast)
251 #if ASTERISK_VERSION_NUM < 110000
252                 strncpy(ast_text, ast->name, sizeof(ast_text)-1);
253 #else
254                 strncpy(ast_text, ast_channel_name(ast), sizeof(ast_text)-1);
255 #endif
256         ast_text[sizeof(ast_text)-1] = '\0';
257
258 //      ast_log(type, file, line, function, "[call=%s ast=%s] %s", call_text, ast_text, buffer);
259         printf("[call=%s ast=%s line=%d] %s", call_text, ast_text, line, buffer);
260
261         ast_mutex_unlock(&log_lock);
262 }
263
264 /*
265  * channel and call instances
266  */
267 struct chan_call *call_first;
268
269 /*
270  * find call by ref
271  * special case: 0: find new ref, that has not been assigned a ref yet
272  */
273
274 struct chan_call *find_call_ref(unsigned int ref)
275 {
276         struct chan_call *call = call_first;
277         int assigned = (ref > 0);
278
279         while(call) {
280                 if (call->ref == ref && call->ref_was_assigned == assigned)
281                         break;
282                 call = call->next;
283         }
284         return call;
285 }
286
287 void free_call(struct chan_call *call)
288 {
289         struct chan_call **temp = &call_first;
290
291         while(*temp) {
292                 if (*temp == call) {
293                         *temp = (*temp)->next;
294                         if (call->pipe[0] > -1)
295                                 close(call->pipe[0]);
296                         if (call->pipe[1] > -1)
297                                 close(call->pipe[1]);
298                         if (call->bridge_call) {
299                                 if (call->bridge_call->bridge_call != call)
300                                         CERROR(call, NULL, "Linked call structure has no link to us.\n");
301                                 call->bridge_call->bridge_call = NULL;
302                         }
303                         if (call->trans)
304                                 ast_translator_free_path(call->trans);
305                         if (call->dsp)
306                                 ast_dsp_free(call->dsp);
307                         CDEBUG(call, NULL, "Call instance freed.\n");
308                         free(call);
309                         global_change = 1;
310                         return;
311                 }
312                 temp = &((*temp)->next);
313         }
314         CERROR(call, NULL, "Call instance not found in list.\n");
315 }
316
317 struct chan_call *alloc_call(void)
318 {
319         struct chan_call **callp = &call_first;
320
321         while(*callp)
322                 callp = &((*callp)->next);
323
324         *callp = (struct chan_call *)calloc(1, sizeof(struct chan_call));
325         if (*callp)
326                 memset(*callp, 0, sizeof(struct chan_call));
327         if (pipe((*callp)->pipe) < 0) {
328                 CERROR(*callp, NULL, "Failed to create pipe.\n");
329                 free_call(*callp);
330                 return NULL;
331         }
332         fcntl((*callp)->pipe[0], F_SETFL, O_NONBLOCK);
333         CDEBUG(*callp, NULL, "Call instance allocated.\n");
334         return *callp;
335 }
336
337 unsigned short new_bridge_id(void)
338 {
339         struct chan_call *call;
340         unsigned short id = 1;
341
342         /* search for lowest bridge id that is not in use and not 0 */
343         while(id) {
344                 call = call_first;
345                 while(call) {
346                         if (call->bridge_id == id)
347                                 break;
348                         call = call->next;
349                 }
350                 if (!call)
351                         break;
352                 id++;
353         }
354         CDEBUG(NULL, NULL, "New bridge ID %d.\n", id);
355         return id;
356 }
357
358 /*
359  * enque message to LCR
360  */
361 int send_message(int message_type, unsigned int ref, union parameter *param)
362 {
363         struct admin_list *admin, **adminp;
364
365         if (lcr_sock < 0) {
366                 CDEBUG(NULL, NULL, "Ignoring message %d, because socket is closed.\n", message_type);
367                 return -1;
368         }
369         if (message_type != MESSAGE_TRAFFIC)
370                 CDEBUG(NULL, NULL, "Sending %s to socket. (ref=%d)\n", messages_txt[message_type], ref);
371
372         adminp = &admin_first;
373         while(*adminp)
374                 adminp = &((*adminp)->next);
375         admin = (struct admin_list *)calloc(1, sizeof(struct admin_list));
376         if (!admin) {
377                 CERROR(NULL, NULL, "No memory for message to LCR.\n");
378                 return -1;
379         }
380         *adminp = admin;
381
382         admin->msg.message = ADMIN_MESSAGE;
383         admin->msg.u.msg.type = message_type;
384         admin->msg.u.msg.ref = ref;
385         memcpy(&admin->msg.u.msg.param, param, sizeof(union parameter));
386         socket_fd.when |= LCR_FD_WRITE;
387         if (!wake_global) {
388                 wake_global = 1;
389                 char byte = 0;
390                 int rc;
391                 rc = write(wake_pipe[1], &byte, 1);
392         }
393
394         return 0;
395 }
396
397 /*
398  * apply options (in locked state)
399  */
400 void apply_opt(struct chan_call *call, char *data)
401 {
402         union parameter newparam;
403         char string[1024], *p = string, *opt;//, *key;
404 //      int gain, i;
405
406         if (!data[0])
407                 return; // no opts
408
409         strncpy(string, data, sizeof(string)-1);
410         string[sizeof(string)-1] = '\0';
411
412         /* parse options */
413         while((opt = strsep(&p, ":"))) {
414                 switch(opt[0]) {
415                 case 'd':
416                         if (opt[1] == '\0') {
417                                 CERROR(call, call->ast, "Option 'd' (display) expects parameter.\n", opt);
418                                 break;
419                         }
420                         CDEBUG(call, call->ast, "Option 'd' (display) with text '%s'.\n", opt+1);
421                         if (call->state == CHAN_LCR_STATE_OUT_PREPARE)
422                                 strncpy(call->display, opt+1, sizeof(call->display)-1);
423                         else {
424                                 memset(&newparam, 0, sizeof(union parameter));
425                                 strncpy(newparam.notifyinfo.display, opt+1, sizeof(newparam.notifyinfo.display)-1);
426                                 send_message(MESSAGE_NOTIFY, call->ref, &newparam);
427                         }
428                         break;
429                 case 'n':
430                         if (opt[1] != '\0') {
431                                 CERROR(call, call->ast, "Option 'n' (no DTMF) expects no parameter.\n", opt);
432                                 break;
433                         }
434                         CDEBUG(call, call->ast, "Option 'n' (no DTMF).\n");
435                         call->dsp_dtmf = 0;
436                         break;
437 #if 0
438                 case 'c':
439                         if (opt[1] == '\0') {
440                                 CERROR(call, call->ast, "Option 'c' (encrypt) expects key parameter.\n", opt);
441                                 break;
442                         }
443                         key = opt+1;
444                         /* check for 0xXXXX... type of key */
445                         if (!!strncmp((char *)key, "0x", 2)) {
446                                 CERROR(call, call->ast, "Option 'c' (encrypt) expects key parameter starting with '0x'.\n", opt);
447                                 break;
448                         }
449                         key+=2;
450                         if (strlen(key) > 56*2 || (strlen(key) % 1)) {
451                                 CERROR(call, call->ast, "Option 'c' (encrypt) expects key parameter with max 56 bytes ('0x' + 112 characters)\n", opt);
452                                 break;
453                         }
454                         i = 0;
455                         while(*key) {
456                                 if (*key>='0' && *key<='9')
457                                         call->bf_key[i] = (*key-'0') << 8;
458                                 else if (*key>='a' && *key<='f')
459                                         call->bf_key[i] = (*key-'a'+10) << 8;
460                                 else if (*key>='A' && *key<='F')
461                                         call->bf_key[i] = (*key-'A'+10) << 8;
462                                 else
463                                         break;
464                                 key++;
465                                 if (*key>='0' && *key<='9')
466                                         call->bf_key[i] += (*key - '0');
467                                 else if (*key>='a' && *key<='f')
468                                         call->bf_key[i] += (*key - 'a' + 10);
469                                 else if (*key>='A' && *key<='F')
470                                         call->bf_key[i] += (*key - 'A' + 10);
471                                 else
472                                         break;
473                                 key++;
474                                 i++;
475                         }
476                         if (*key) {
477                                 CERROR(call, call->ast, "Option 'c' (encrypt) expects key parameter with hex values 0-9,a-f.\n");
478                                 break;
479                         }
480                         call->bf_len = i;
481                         CDEBUG(call, call->ast, "Option 'c' (encrypt) blowfish key '%s' (len=%d).\n", opt+1, i);
482                         if (call->bchannel)
483                                 bchannel_blowfish(call->bchannel, call->bf_key, call->bf_len);
484                         break;
485 #endif
486                 case 'h':
487                         if (opt[1] != '\0') {
488                                 CERROR(call, call->ast, "Option 'h' (HDLC) expects no parameter.\n", opt);
489                                 break;
490                         }
491                         CDEBUG(call, call->ast, "Option 'h' (HDLC).\n");
492                         if (!call->hdlc)
493                                 call->hdlc = 1;
494                         break;
495                 case 'q':
496                         if (opt[1] == '\0') {
497                                 CERROR(call, call->ast, "Option 'q' (queue) expects parameter.\n", opt);
498                                 break;
499                         }
500                         CDEBUG(call, call->ast, "Option 'q' (queue).\n");
501                         call->tx_queue = atoi(opt+1);
502                         break;
503 #if 0
504                 case 'e':
505                         if (opt[1] == '\0') {
506                                 CERROR(call, call->ast, "Option 'e' (echo cancel) expects parameter.\n", opt);
507                                 break;
508                         }
509                         CDEBUG(call, call->ast, "Option 'e' (echo cancel) with config '%s'.\n", opt+1);
510                         strncpy(call->pipeline, opt+1, sizeof(call->pipeline)-1);
511                         if (call->bchannel)
512                                 bchannel_pipeline(call->bchannel, call->pipeline);
513                         break;
514 #endif
515                 case 'f':
516                         if (opt[1] == '\0') {
517                                 CERROR(call, call->ast, "Option 'f' (faxdetect) expects parameter.\n", opt);
518                                 break;
519                         }
520                         call->faxdetect=atoi(opt+1);
521                         if (!call->dsp)
522                                 call->dsp=ast_dsp_new();
523                         if (call->dsp) {
524                                 #ifdef LCR_FOR_CALLWEAVER
525                                 ast_dsp_set_features(call->dsp, DSP_FEATURE_DTMF_DETECT| DSP_FEATURE_FAX_CNG_DETECT);
526                                 #endif
527                                 #ifdef LCR_FOR_ASTERISK
528                                 #ifdef DSP_FEATURE_DTMF_DETECT
529                                 ast_dsp_set_features(call->dsp, DSP_FEATURE_DTMF_DETECT| DSP_FEATURE_FAX_DETECT);
530                                 #else
531                                 ast_dsp_set_features(call->dsp, DSP_FEATURE_DIGIT_DETECT| DSP_FEATURE_FAX_DETECT);
532                                 #endif
533
534                                 #endif
535                                 if (!call->trans) {
536                                         #ifdef LCR_FOR_CALLWEAVER
537                                         call->trans=ast_translator_build_path(AST_FORMAT_SLINEAR, 8000, (options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW, 8000);
538                                         #endif
539                                         #ifdef LCR_FOR_ASTERISK
540                                         #if ASTERISK_VERSION_NUM < 100000
541                                         call->trans=ast_translator_build_path(AST_FORMAT_SLINEAR, (options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW);
542                                         #else
543                                         struct ast_format src;
544                                         struct ast_format dst;
545                                         ast_format_set(&dst, AST_FORMAT_SLINEAR, 0);
546                                         ast_format_set(&dst,(options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW , 0);
547                                         call->trans=ast_translator_build_path(&dst, &src);
548                                         #endif
549                                         #endif
550                                 }
551                         }
552                         CDEBUG(call, call->ast, "Option 'f' (faxdetect) with config '%s'.\n", call->faxdetect);
553                         break;
554                 case 'r':
555                         if (opt[1] != '\0') {
556                                 CERROR(call, call->ast, "Option 'r' (re-buffer 160 bytes) expects no parameter.\n", opt);
557                                 break;
558                         }
559                         CDEBUG(call, call->ast, "Option 'r' (re-buffer 160 bytes)");
560                         call->rebuffer = 1;
561                         call->framepos = 0;
562                         break;
563                 case 's':
564                         if (opt[1] != '\0') {
565                                 CERROR(call, call->ast, "Option 's' (inband DTMF) expects no parameter.\n", opt);
566                                 break;
567                         }
568                         CDEBUG(call, call->ast, "Option 's' (inband DTMF).\n");
569                         call->inband_dtmf = 1;
570                         break;
571 #if 0
572                 case 'v':
573                         if (opt[1] != 'r' && opt[1] != 't') {
574                                 CERROR(call, call->ast, "Option 'v' (volume) expects parameter.\n", opt);
575                                 break;
576                         }
577                         gain = atoi(opt+2);
578                         if (gain < -8 || gain >8) {
579                                 CERROR(call, call->ast, "Option 'v' (volume) expects parameter in range of -8 through 8.\n");
580                                 break;
581                         }
582                         CDEBUG(call, call->ast, "Option 'v' (volume) with gain 2^%d.\n", gain);
583                         if (opt[1] == 'r') {
584                                 call->rx_gain = gain;
585                                 if (call->bchannel)
586                                         bchannel_gain(call->bchannel, call->rx_gain, 0);
587                         } else {
588                                 call->tx_gain = gain;
589                                 if (call->bchannel)
590                                         bchannel_gain(call->bchannel, call->tx_gain, 1);
591                         }
592                         break;
593 #endif
594                 case 'k':
595                         if (opt[1] != '\0') {
596                                 CERROR(call, call->ast, "Option 'k' (keypad) expects no parameter.\n", opt);
597                                 break;
598                         }
599                         CDEBUG(call, call->ast, "Option 'k' (keypad).\n");
600                         if (!call->keypad)
601                                 call->keypad = 1;
602                         break;
603                 default:
604                         CERROR(call, call->ast, "Option '%s' unknown.\n", opt);
605                 }
606         }
607 }
608
609 /*
610  * send setup info to LCR
611  * this function is called, when asterisk call is received and ref is received
612  */
613 static void send_setup_to_lcr(struct chan_call *call)
614 {
615         union parameter newparam;
616         struct ast_channel *ast = call->ast;
617 //      const char *tmp;
618
619         if (!call->ast || !call->ref)
620                 return;
621
622 #ifdef AST_1_8_OR_HIGHER
623         CDEBUG(call, call->ast, "Sending setup to LCR. (interface=%s dialstring=%s, cid=%s)\n", call->interface, call->dialstring, call->callerinfo.id);
624 #else
625         CDEBUG(call, call->ast, "Sending setup to LCR. (interface=%s dialstring=%s, cid=%s)\n", call->interface, call->dialstring, call->cid_num);
626 #endif
627
628         /* send setup message to LCR */
629         memset(&newparam, 0, sizeof(union parameter));
630         newparam.setup.dialinginfo.itype = INFO_ITYPE_ISDN;
631         newparam.setup.dialinginfo.ntype = INFO_NTYPE_UNKNOWN;
632         if (call->keypad)
633                 strncpy(newparam.setup.dialinginfo.keypad, call->dialstring, sizeof(newparam.setup.dialinginfo.keypad)-1);
634         else
635                 strncpy(newparam.setup.dialinginfo.id, call->dialstring, sizeof(newparam.setup.dialinginfo.id)-1);
636         if (!!strcmp(call->interface, "pbx"))
637                 strncpy(newparam.setup.dialinginfo.interfaces, call->interface, sizeof(newparam.setup.dialinginfo.interfaces)-1);
638         newparam.setup.callerinfo.itype = INFO_ITYPE_CHAN;
639         newparam.setup.callerinfo.ntype = INFO_NTYPE_UNKNOWN;
640         strncpy(newparam.setup.callerinfo.display, call->display, sizeof(newparam.setup.callerinfo.display)-1);
641         call->display[0] = '\0';
642
643 #ifdef AST_1_8_OR_HIGHER
644         /* set stored call information */
645         memcpy(&newparam.setup.callerinfo, &call->callerinfo, sizeof(struct caller_info));
646         memcpy(&newparam.setup.redirinfo, &call->redirinfo, sizeof(struct redir_info));
647 #else
648         if (call->cid_num[0])
649                 strncpy(newparam.setup.callerinfo.id, call->cid_num, sizeof(newparam.setup.callerinfo.id)-1);
650         if (call->cid_name[0])
651                 strncpy(newparam.setup.callerinfo.name, call->cid_name, sizeof(newparam.setup.callerinfo.name)-1);
652         if (call->cid_rdnis[0]) {
653                 strncpy(newparam.setup.redirinfo.id, call->cid_rdnis, sizeof(newparam.setup.redirinfo.id)-1);
654                 newparam.setup.redirinfo.itype = INFO_ITYPE_CHAN;
655                 newparam.setup.redirinfo.ntype = INFO_NTYPE_UNKNOWN;
656         }
657         switch(ast->cid.cid_pres & AST_PRES_RESTRICTION) {
658                 case AST_PRES_RESTRICTED:
659                 newparam.setup.callerinfo.present = INFO_PRESENT_RESTRICTED;
660                 break;
661                 case AST_PRES_UNAVAILABLE:
662                 newparam.setup.callerinfo.present = INFO_PRESENT_NOTAVAIL;
663                 break;
664                 case AST_PRES_ALLOWED:
665                 default:
666                 newparam.setup.callerinfo.present = INFO_PRESENT_ALLOWED;
667         }
668         switch(ast->cid.cid_ton) {
669                 case 4:
670                 newparam.setup.callerinfo.ntype = INFO_NTYPE_SUBSCRIBER;
671                 break;
672                 case 2:
673                 newparam.setup.callerinfo.ntype = INFO_NTYPE_NATIONAL;
674                 break;
675                 case 1:
676                 newparam.setup.callerinfo.ntype = INFO_NTYPE_INTERNATIONAL;
677                 break;
678                 default:
679                 newparam.setup.callerinfo.ntype = INFO_NTYPE_UNKNOWN;
680         }
681 #endif
682 #warning DISABLED DUE TO DOUBLE LOCKING PROBLEM
683 //      tmp = pbx_builtin_getvar_helper(ast, "LCR_TRANSFERCAPABILITY");
684 //      if (tmp && *tmp)
685 #if ASTERISK_VERSION_NUM < 110000
686 //              ast->transfercapability = atoi(tmp);
687         newparam.setup.capainfo.bearer_capa = ast->transfercapability;
688 #else
689 //              ast_channel_transfercapability_set(ast, atoi(tmp));
690         newparam.setup.capainfo.bearer_capa = ast_channel_transfercapability(ast);
691 #endif
692         newparam.setup.capainfo.bearer_mode = INFO_BMODE_CIRCUIT;
693         if (call->hdlc)
694                 newparam.setup.capainfo.source_mode = B_MODE_HDLC;
695         else {
696                 newparam.setup.capainfo.source_mode = B_MODE_TRANSPARENT;
697                 newparam.setup.capainfo.bearer_info1 = (options.law=='a')?3:2;
698         }
699         newparam.setup.capainfo.hlc = INFO_HLC_NONE;
700         newparam.setup.capainfo.exthlc = INFO_HLC_NONE;
701         send_message(MESSAGE_SETUP, call->ref, &newparam);
702         if (call->tx_queue) {
703                 memset(&newparam, 0, sizeof(union parameter));
704                 newparam.queue = call->tx_queue * 8;
705                 send_message(MESSAGE_DISABLE_DEJITTER, call->ref, &newparam);
706         }
707
708         /* change to outgoing setup state */
709         call->state = CHAN_LCR_STATE_OUT_SETUP;
710 }
711
712 /*
713  * send dialing info to LCR
714  * this function is called, when setup acknowledge is received and dialing
715  * info is available.
716  */
717 static void send_dialque_to_lcr(struct chan_call *call)
718 {
719         union parameter newparam;
720
721         if (!call->ast || !call->ref || !call->dialque[0])
722                 return;
723
724         CDEBUG(call, call->ast, "Sending dial queue to LCR. (dialing=%s)\n", call->dialque);
725
726         /* send setup message to LCR */
727         memset(&newparam, 0, sizeof(union parameter));
728         if (call->keypad)
729                 strncpy(newparam.information.keypad, call->dialque, sizeof(newparam.information.keypad)-1);
730         else
731                 strncpy(newparam.information.id, call->dialque, sizeof(newparam.information.id)-1);
732         call->dialque[0] = '\0';
733         send_message(MESSAGE_INFORMATION, call->ref, &newparam);
734 }
735
736 /*
737  * in case of a bridge, the unsupported message can be forwarded directly
738  * to the remote call.
739  */
740 static void bridge_message_if_bridged(struct chan_call *call, int message_type, union parameter *param)
741 {
742         /* check bridge */
743         if (!call) return;
744         if (!call->bridge_call) return;
745         CDEBUG(call, NULL, "Sending message due bridging.\n");
746         send_message(message_type, call->bridge_call->ref, param);
747 }
748
749 /*
750  * send release message to LCR
751  */
752 static void send_release(struct chan_call *call, int cause, int location)
753 {
754         union parameter newparam;
755
756         /* sending release */
757         memset(&newparam, 0, sizeof(union parameter));
758         newparam.disconnectinfo.cause = cause;
759         newparam.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
760         send_message(MESSAGE_RELEASE, call->ref, &newparam);
761 }
762
763 /*
764  * check if extension matches and start asterisk
765  * if it can match, proceed
766  * if not, release
767  */
768 static void lcr_start_pbx(struct chan_call *call, struct ast_channel *ast, int complete)
769 {
770         int cause, ret;
771         union parameter newparam;
772 #if ASTERISK_VERSION_NUM < 110000
773         char *exten = ast->exten;
774 #else
775         char s_exten[AST_MAX_EXTENSION];
776         char *exten=s_exten;
777
778         strncpy(exten, ast_channel_exten(ast), AST_MAX_EXTENSION-1);
779 #endif
780
781 if (!*exten)
782                 exten = "s";
783
784 #if ASTERISK_VERSION_NUM < 110000
785         CDEBUG(call, ast, "Try to start pbx. (exten=%s context=%s complete=%s)\n", exten, ast->context, complete?"yes":"no");
786 #else
787         CDEBUG(call, ast, "Try to start pbx. (exten=%s context=%s complete=%s)\n", exten, ast_channel_context(ast), complete?"yes":"no");
788 #endif
789
790         if (complete) {
791                 /* if not match */
792 #if ASTERISK_VERSION_NUM < 110000
793                 if (!ast_canmatch_extension(ast, ast->context, exten, 1, call->oad)) {
794 CDEBUG(call, ast, "Got 'sending complete', but extension '%s' will not match at context '%s' - releasing.\n", exten, ast->context);
795 #else
796                 if (!ast_canmatch_extension(ast, ast_channel_context(ast), exten, 1, call->oad)) {
797 CDEBUG(call, ast, "Got 'sending complete', but extension '%s' will not match at context '%s' - releasing.\n", exten, ast_channel_context(ast));
798 #endif
799                         cause = 1;
800                         goto release;
801                 }
802 #if ASTERISK_VERSION_NUM < 110000
803                 if (!ast_exists_extension(ast, ast->context, exten, 1, call->oad)) {
804                         CDEBUG(call, ast, "Got 'sending complete', but extension '%s' would match at context '%s', if more digits would be dialed - releasing.\n", exten, ast->context);
805 #else
806                 if (!ast_exists_extension(ast, ast_channel_context(ast), exten, 1, call->oad)) {
807                         CDEBUG(call, ast, "Got 'sending complete', but extension '%s' would match at context '%s', if more digits would be dialed - releasing.\n", exten, ast_channel_context(ast));
808 #endif
809                         cause = 28;
810                         goto release;
811                 }
812                 CDEBUG(call, ast, "Got 'sending complete', extensions matches.\n");
813                 /* send setup acknowledge to lcr */
814                 memset(&newparam, 0, sizeof(union parameter));
815                 send_message(MESSAGE_PROCEEDING, call->ref, &newparam);
816
817                 /* change state */
818                 call->state = CHAN_LCR_STATE_IN_PROCEEDING;
819
820                 goto start;
821         }
822
823 #if ASTERISK_VERSION_NUM < 110000
824         if (ast_canmatch_extension(ast, ast->context, exten, 1, call->oad)) {
825 #else
826         if (ast_canmatch_extension(ast, ast_channel_context(ast), exten, 1, call->oad)) {
827 #endif
828                 /* send setup acknowledge to lcr */
829                 if (call->state != CHAN_LCR_STATE_IN_DIALING) {
830                         memset(&newparam, 0, sizeof(union parameter));
831                         send_message(MESSAGE_OVERLAP, call->ref, &newparam);
832                 }
833
834                 /* change state */
835                 call->state = CHAN_LCR_STATE_IN_DIALING;
836
837                 /* if match, start pbx */
838 #if ASTERISK_VERSION_NUM < 110000
839         if (ast_exists_extension(ast, ast->context, exten, 1, call->oad)) {
840 #else
841         if (ast_exists_extension(ast, ast_channel_context(ast), exten, 1, call->oad)) {
842 #endif
843                         CDEBUG(call, ast, "Extensions matches.\n");
844                         goto start;
845                 }
846
847                 /* send setup acknowledge to lcr */
848                 if (call->state != CHAN_LCR_STATE_IN_DIALING) {
849                         memset(&newparam, 0, sizeof(union parameter));
850                         send_message(MESSAGE_OVERLAP, call->ref, &newparam);
851                 }
852
853                 /* change state */
854                 call->state = CHAN_LCR_STATE_IN_DIALING;
855
856                 /* if can match */
857                 CDEBUG(call, ast, "Extensions may match, if more digits are dialed.\n");
858                 return;
859         }
860
861 #if ASTERISK_VERSION_NUM < 110000
862         if (!*ast->exten) {
863 #else
864         if (!*ast_channel_exten(ast)) {
865 #endif
866                 /* send setup acknowledge to lcr */
867                 if (call->state != CHAN_LCR_STATE_IN_DIALING) {
868                         memset(&newparam, 0, sizeof(union parameter));
869                         send_message(MESSAGE_OVERLAP, call->ref, &newparam);
870                 }
871
872                 /* change state */
873                 call->state = CHAN_LCR_STATE_IN_DIALING;
874
875                 /* if can match */
876                 CDEBUG(call, ast, "There is no 's' extension (and we tried to match it implicitly). Extensions may match, if more digits are dialed.\n");
877                 return;
878         }
879
880         /* if not match */
881         cause = 1;
882         release:
883         /* release lcr */
884         CDEBUG(call, ast, "Releasing due to extension missmatch.\n");
885         send_release(call, cause, LOCATION_PRIVATE_LOCAL);
886         call->ref = 0;
887         /* release asterisk */
888 #if ASTERISK_VERSION_NUM < 110000
889         ast->hangupcause = call->cause;
890 #else
891         ast_channel_hangupcause_set(ast, call->cause);
892 #endif
893         /* change to release state */
894         call->state = CHAN_LCR_STATE_RELEASE;
895         ast_hangup(ast); // call will be destroyed here
896         return;
897
898         start:
899         /* send setup to asterisk */
900         CDEBUG(call, ast, "Starting call to Asterisk due to matching extension.\n");
901
902         #ifdef LCR_FOR_CALLWEAVER
903         ast->type = "LCR";
904         snprintf(ast->name, sizeof(ast->name), "%s/%s-%04x",lcr_type ,ast->cid.cid_num, ast_random() & 0xffff);
905         #endif
906
907         ret = ast_pbx_start(ast);
908         if (ret < 0) {
909                 cause = (ret==-2)?34:27;
910                 goto release;
911         }
912         call->pbx_started = 1;
913                 ast_setstate(ast, AST_STATE_RING);
914 }
915
916 /*
917  * incoming setup from LCR
918  */
919 static void lcr_in_setup(struct chan_call *call, int message_type, union parameter *param)
920 {
921         struct ast_channel *ast;
922         struct ast_party_redirecting *ast_redir;
923         struct ast_party_caller *ast_caller;
924 #if ASTERISK_VERSION_NUM >= 110000
925         struct ast_party_redirecting s_ast_redir;
926         struct ast_party_caller s_ast_caller;
927         ast_party_redirecting_init(&s_ast_redir);
928         ast_party_caller_init(&s_ast_caller);
929 #endif
930         CDEBUG(call, NULL, "Incomming setup from LCR. (callerid %s, dialing %s)\n", param->setup.callerinfo.id, param->setup.dialinginfo.id);
931
932         /* create asterisk channel instrance */
933
934         #ifdef LCR_FOR_CALLWEAVER
935         ast = ast_channel_alloc(1);
936         #endif
937
938         #ifdef LCR_FOR_ASTERISK
939 #ifdef AST_1_8_OR_HIGHER
940         ast = ast_channel_alloc(1, AST_STATE_RESERVED, NULL, NULL, "", NULL, "", "", 0, "%s/%d", lcr_type, ++glob_channel);
941 #else
942         ast = ast_channel_alloc(1, AST_STATE_RESERVED, NULL, NULL, "", NULL, "", 0, "%s/%d", lcr_type, ++glob_channel);
943 #endif
944         #endif
945
946 #if ASTERISK_VERSION_NUM < 110000
947         ast_redir = &ast->redirecting;
948         ast_caller = &ast->caller;
949 #else
950         ast_redir = &s_ast_redir;
951         ast_caller = &s_ast_caller;
952 #endif
953
954         if (!ast) {
955                 /* release */
956                 CERROR(call, NULL, "Failed to create Asterisk channel - releasing.\n");
957                 send_release(call, CAUSE_RESSOURCEUNAVAIL, LOCATION_PRIVATE_LOCAL);
958                 /* remove call */
959                 free_call(call);
960                 return;
961         }
962         /* link together */
963         call->ast = ast;
964 #if ASTERISK_VERSION_NUM < 110000
965         ast->tech_pvt = call;
966         ast->tech = &lcr_tech;
967         ast->fds[0] = call->pipe[0];
968 #else
969         ast_channel_tech_pvt_set(ast, call);
970         ast_channel_tech_set(ast, &lcr_tech);
971         ast_channel_set_fd(ast, 0, call->pipe[0]);
972 #endif
973
974         /* fill setup information */
975         if (param->setup.dialinginfo.id)
976 #if ASTERISK_VERSION_NUM < 110000
977                 strncpy(ast->exten, param->setup.dialinginfo.id, AST_MAX_EXTENSION-1);
978         if (param->setup.dialinginfo.context[0])
979                 strncpy(ast->context, param->setup.dialinginfo.context, AST_MAX_CONTEXT-1);
980         else
981                 strncpy(ast->context, param->setup.callerinfo.interface, AST_MAX_CONTEXT-1);
982 #else
983                 ast_channel_exten_set(ast, param->setup.dialinginfo.id);
984         if (param->setup.context[0])
985                 ast_channel_context_set(ast, param->setup.context);
986         else
987                 ast_channel_context_set(ast, param->setup.callerinfo.interface);
988 #endif
989
990
991 #ifdef AST_1_8_OR_HIGHER
992         if (param->setup.callerinfo.id[0]) {
993                 ast_caller->id.number.valid = 1;
994                 ast_caller->id.number.str = strdup(param->setup.callerinfo.id);
995                 if (!param->setup.callerinfo.id[0]) {
996                         ast_caller->id.number.presentation = AST_PRES_RESTRICTED;
997                         ast_caller->id.number.plan = (0 << 4) | 1;
998                 }
999                 switch (param->setup.callerinfo.present) {
1000                         case INFO_PRESENT_ALLOWED:
1001                                 ast_caller->id.number.presentation = AST_PRES_ALLOWED;
1002                         break;
1003                         case INFO_PRESENT_RESTRICTED:
1004                                 ast_caller->id.number.presentation = AST_PRES_RESTRICTED;
1005                         break;
1006                         default:
1007                                 ast_caller->id.number.presentation = AST_PRES_UNAVAILABLE;
1008                 }
1009                 switch (param->setup.callerinfo.screen) {
1010                         case INFO_SCREEN_USER:
1011                                 ast_caller->id.number.presentation |= AST_PRES_USER_NUMBER_UNSCREENED;
1012                         break;
1013                         case INFO_SCREEN_USER_VERIFIED_PASSED:
1014                                 ast_caller->id.number.presentation |= AST_PRES_USER_NUMBER_PASSED_SCREEN;
1015                         break;
1016                         case INFO_SCREEN_USER_VERIFIED_FAILED:
1017                                 ast_caller->id.number.presentation |= AST_PRES_USER_NUMBER_FAILED_SCREEN;
1018                         break;
1019                         default:
1020                                 ast_caller->id.number.presentation |= AST_PRES_NETWORK_NUMBER;
1021                 }
1022                 switch (param->setup.callerinfo.ntype) {
1023                         case INFO_NTYPE_SUBSCRIBER:
1024                                 ast_caller->id.number.plan = (4 << 4) | 1;
1025                         break;
1026                         case INFO_NTYPE_NATIONAL:
1027                                 ast_caller->id.number.plan = (2 << 4) | 1;
1028                         break;
1029                         case INFO_NTYPE_INTERNATIONAL:
1030                                 ast_caller->id.number.plan = (1 << 4) | 1;
1031                         break;
1032                         default:
1033                                 ast_caller->id.number.plan = (0 << 4) | 1;
1034                 }
1035         }
1036         if (param->setup.callerinfo.id2[0]) {
1037                 ast_caller->ani.number.valid = 1;
1038                 ast_caller->ani.number.str = strdup(param->setup.callerinfo.id2);
1039                 switch (param->setup.callerinfo.present2) {
1040                         case INFO_PRESENT_ALLOWED:
1041                                 ast_caller->ani.number.presentation = AST_PRES_ALLOWED;
1042                         break;
1043                         case INFO_PRESENT_RESTRICTED:
1044                                 ast_caller->ani.number.presentation = AST_PRES_RESTRICTED;
1045                         break;
1046                         default:
1047                                 ast_caller->ani.number.presentation = AST_PRES_UNAVAILABLE;
1048                 }
1049                 switch (param->setup.callerinfo.screen2) {
1050                         case INFO_SCREEN_USER:
1051                                 ast_caller->ani.number.presentation |= AST_PRES_USER_NUMBER_UNSCREENED;
1052                         break;
1053                         case INFO_SCREEN_USER_VERIFIED_PASSED:
1054                                 ast_caller->ani.number.presentation |= AST_PRES_USER_NUMBER_PASSED_SCREEN;
1055                         break;
1056                         case INFO_SCREEN_USER_VERIFIED_FAILED:
1057                                 ast_caller->ani.number.presentation |= AST_PRES_USER_NUMBER_FAILED_SCREEN;
1058                         break;
1059                         default:
1060                                 ast_caller->ani.number.presentation |= AST_PRES_NETWORK_NUMBER;
1061                 }
1062                 switch (param->setup.callerinfo.ntype2) {
1063                         case INFO_NTYPE_SUBSCRIBER:
1064                                 ast_caller->ani.number.plan = (4 << 4) | 1;
1065                         break;
1066                         case INFO_NTYPE_NATIONAL:
1067                                 ast_caller->ani.number.plan = (2 << 4) | 1;
1068                         break;
1069                         case INFO_NTYPE_INTERNATIONAL:
1070                                 ast_caller->ani.number.plan = (1 << 4) | 1;
1071                         break;
1072                         default:
1073                                 ast_caller->ani.number.plan = (0 << 4) | 1;
1074                 }
1075         }
1076         if (param->setup.callerinfo.name[0]) {
1077                 ast_caller->id.name.valid = 1;
1078                 ast_caller->id.name.str = strdup(param->setup.callerinfo.name);
1079         }
1080 #if ASTERISK_VERSION_NUM >= 110000
1081         ast_channel_caller_set(ast, ast_caller);
1082 #endif
1083         if (param->setup.redirinfo.id[0]) {
1084                 ast_redir->from.number.valid = 1;
1085                 ast_redir->from.number.str = strdup(param->setup.redirinfo.id);
1086                 switch (param->setup.redirinfo.present) {
1087                         case INFO_PRESENT_ALLOWED:
1088                                 ast_redir->from.number.presentation = AST_PRES_ALLOWED;
1089                         break;
1090                         case INFO_PRESENT_RESTRICTED:
1091                                 ast_redir->from.number.presentation = AST_PRES_RESTRICTED;
1092                         break;
1093                         default:
1094                                 ast_redir->from.number.presentation = AST_PRES_UNAVAILABLE;
1095                 }
1096                 switch (param->setup.redirinfo.screen) {
1097                         case INFO_SCREEN_USER:
1098                                 ast_redir->from.number.presentation |= AST_PRES_USER_NUMBER_UNSCREENED;
1099                         break;
1100                         case INFO_SCREEN_USER_VERIFIED_PASSED:
1101                                 ast_redir->from.number.presentation |= AST_PRES_USER_NUMBER_PASSED_SCREEN;
1102                         break;
1103                         case INFO_SCREEN_USER_VERIFIED_FAILED:
1104                                 ast_redir->from.number.presentation |= AST_PRES_USER_NUMBER_FAILED_SCREEN;
1105                         break;
1106                         default:
1107                                 ast_redir->from.number.presentation |= AST_PRES_NETWORK_NUMBER;
1108                 }
1109                 switch (param->setup.redirinfo.ntype) {
1110                         case INFO_NTYPE_SUBSCRIBER:
1111                                 ast_redir->from.number.plan = (4 << 4) | 1;
1112                         break;
1113                         case INFO_NTYPE_NATIONAL:
1114                                 ast_redir->from.number.plan = (2 << 4) | 1;
1115                         break;
1116                         case INFO_NTYPE_INTERNATIONAL:
1117                                 ast_redir->from.number.plan = (1 << 4) | 1;
1118                         break;
1119                         default:
1120                                 ast_redir->from.number.plan = (0 << 4) | 1;
1121                 }
1122 #if ASTERISK_VERSION_NUM >= 110000
1123                 ast_channel_redirecting_set(ast, ast_redir);
1124 #endif
1125         }
1126 #else
1127         memset(&ast->cid, 0, sizeof(ast->cid));
1128         if (param->setup.callerinfo.id[0])
1129                 ast->cid.cid_num = strdup(param->setup.callerinfo.id);
1130         if (param->setup.callerinfo.id2[0])
1131                 ast->cid.cid_ani = strdup(param->setup.callerinfo.id2);
1132         if (param->setup.callerinfo.name[0])
1133                 ast->cid.cid_name = strdup(param->setup.callerinfo.name);
1134         if (param->setup.redirinfo.id[0])
1135                 ast->cid.cid_rdnis = strdup(numberrize_callerinfo(param->setup.redirinfo.id, param->setup.redirinfo.ntype, options.national, options.international));
1136         switch (param->setup.callerinfo.present) {
1137                 case INFO_PRESENT_ALLOWED:
1138                         ast->cid.cid_pres = AST_PRES_ALLOWED;
1139                 break;
1140                 case INFO_PRESENT_RESTRICTED:
1141                         ast->cid.cid_pres = AST_PRES_RESTRICTED;
1142                 break;
1143                 default:
1144                         ast->cid.cid_pres = AST_PRES_UNAVAILABLE;
1145         }
1146         switch (param->setup.callerinfo.ntype) {
1147                 case INFO_NTYPE_SUBSCRIBER:
1148                         ast->cid.cid_ton = 4;
1149                 break;
1150                 case INFO_NTYPE_NATIONAL:
1151                         ast->cid.cid_ton = 2;
1152                 break;
1153                 case INFO_NTYPE_INTERNATIONAL:
1154                         ast->cid.cid_ton = 1;
1155                 break;
1156                 default:
1157                         ast->cid.cid_ton = 0;
1158         }
1159 #endif
1160
1161 #if ASTERISK_VERSION_NUM < 110000
1162         ast->transfercapability = param->setup.capainfo.bearer_capa;
1163 #else
1164         ast_channel_transfercapability_set(ast, param->setup.capainfo.bearer_capa);
1165 #endif
1166         /* enable hdlc if transcap is data */
1167         if (param->setup.capainfo.source_mode == B_MODE_HDLC)
1168                 call->hdlc = 1;
1169         strncpy(call->oad, numberrize_callerinfo(param->setup.callerinfo.id, param->setup.callerinfo.ntype, options.national, options.international), sizeof(call->oad)-1);
1170
1171         /* configure channel */
1172 #if ASTERISK_VERSION_NUM < 100000
1173         ast->nativeformats = (options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW;
1174         ast->readformat = ast->rawreadformat = ast->nativeformats;
1175         ast->writeformat = ast->rawwriteformat =  ast->nativeformats;
1176 #else
1177 #if ASTERISK_VERSION_NUM < 110000
1178         ast_format_set(&ast->rawwriteformat ,(options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW , 0);
1179         ast_format_copy(&ast->rawreadformat, &ast->rawwriteformat);
1180         ast_format_cap_set(ast->nativeformats, &ast->rawwriteformat);
1181         ast_set_write_format(ast, &ast->rawwriteformat);
1182         ast_set_read_format(ast, &ast->rawreadformat);
1183 #else
1184         ast_format_set(ast_channel_rawwriteformat(ast) ,(options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW , 0);
1185         ast_format_copy(ast_channel_rawreadformat(ast), ast_channel_rawwriteformat(ast));
1186         ast_format_cap_set(ast_channel_nativeformats(ast), ast_channel_rawwriteformat(ast));
1187         ast_set_write_format(ast, ast_channel_rawwriteformat(ast));
1188         ast_set_read_format(ast, ast_channel_rawreadformat(ast));
1189 #endif
1190 #endif
1191 #if ASTERISK_VERSION_NUM < 110000
1192         ast->priority = 1;
1193         ast->hangupcause = 0;
1194 #else
1195         ast_channel_priority_set(ast, 1);
1196         ast_channel_hangupcause_set(ast, 0);
1197 #endif
1198
1199         /* change state */
1200         call->state = CHAN_LCR_STATE_IN_SETUP;
1201
1202         if (!call->pbx_started)
1203                 lcr_start_pbx(call, ast, param->setup.dialinginfo.sending_complete);
1204 }
1205
1206 /*
1207  * incoming setup acknowledge from LCR
1208  */
1209 static void lcr_in_overlap(struct chan_call *call, int message_type, union parameter *param)
1210 {
1211         if (!call->ast) return;
1212
1213         CDEBUG(call, call->ast, "Incomming setup acknowledge from LCR.\n");
1214
1215         /* send pending digits in dialque */
1216         if (call->dialque[0])
1217                 send_dialque_to_lcr(call);
1218         /* change to overlap state */
1219         call->state = CHAN_LCR_STATE_OUT_DIALING;
1220 }
1221
1222 /*
1223  * incoming proceeding from LCR
1224  */
1225 static void lcr_in_proceeding(struct chan_call *call, int message_type, union parameter *param)
1226 {
1227         CDEBUG(call, call->ast, "Incomming proceeding from LCR.\n");
1228
1229         /* change state */
1230         call->state = CHAN_LCR_STATE_OUT_PROCEEDING;
1231         /* queue event for asterisk */
1232         if (call->ast && call->pbx_started) {
1233                 if (!wake_global) {
1234                         wake_global = 1;
1235                         char byte = 0;
1236                         int rc;
1237                         rc = write(wake_pipe[1], &byte, 1);
1238                 }
1239                 strncat(call->queue_string, "P", sizeof(call->queue_string)-1);
1240         }
1241
1242 }
1243
1244 /*
1245  * incoming alerting from LCR
1246  */
1247 static void lcr_in_alerting(struct chan_call *call, int message_type, union parameter *param)
1248 {
1249         CDEBUG(call, call->ast, "Incomming alerting from LCR.\n");
1250
1251         /* change state */
1252         call->state = CHAN_LCR_STATE_OUT_ALERTING;
1253         /* queue event to asterisk */
1254         if (call->ast && call->pbx_started) {
1255                 if (!wake_global) {
1256                         wake_global = 1;
1257                         char byte = 0;
1258                         int rc;
1259                         rc = write(wake_pipe[1], &byte, 1);
1260                 }
1261                 strncat(call->queue_string, "R", sizeof(call->queue_string)-1);
1262         }
1263 }
1264
1265 /*
1266  * incoming connect from LCR
1267  */
1268 static void lcr_in_connect(struct chan_call *call, int message_type, union parameter *param)
1269 {
1270         CDEBUG(call, call->ast, "Incomming connect (answer) from LCR.\n");
1271
1272         /* change state */
1273         call->state = CHAN_LCR_STATE_CONNECT;
1274         /* copy connectinfo */
1275         memcpy(&call->connectinfo, &param->connectinfo, sizeof(struct connect_info));
1276         /* queue event to asterisk */
1277         if (call->ast && call->pbx_started) {
1278                 if (!wake_global) {
1279                         wake_global = 1;
1280                         char byte = 0;
1281                         int rc;
1282                         rc = write(wake_pipe[1], &byte, 1);
1283                 }
1284                 strncat(call->queue_string, "N", sizeof(call->queue_string)-1);
1285         }
1286 }
1287
1288 /*
1289  * incoming disconnect from LCR
1290  */
1291 static void lcr_in_disconnect(struct chan_call *call, int message_type, union parameter *param)
1292 {
1293         struct ast_channel *ast = call->ast;
1294
1295         CDEBUG(call, call->ast, "Incomming disconnect from LCR. (cause=%d)\n", param->disconnectinfo.cause);
1296
1297         /* change state */
1298         call->state = CHAN_LCR_STATE_IN_DISCONNECT;
1299         /* save cause */
1300         call->cause = param->disconnectinfo.cause;
1301         call->location = param->disconnectinfo.location;
1302         /* if bridge, forward disconnect and return */
1303 #ifdef TODO
1304         feature flag
1305         if (call->bridge_call) {
1306                 CDEBUG(call, call->ast, "Only signal disconnect via bridge.\n");
1307                 bridge_message_if_bridged(call, message_type, param);
1308                 return;
1309         }
1310 #endif
1311         /* release lcr with same cause */
1312         send_release(call, call->cause, call->location);
1313         call->ref = 0;
1314         /* change to release state */
1315         call->state = CHAN_LCR_STATE_RELEASE;
1316         /* queue release asterisk */
1317         if (ast) {
1318 #if ASTERISK_VERSION_NUM < 110000
1319                 ast->hangupcause = call->cause;
1320 #else
1321                 ast_channel_hangupcause_set(ast, call->cause);
1322 #endif
1323                 if (call->pbx_started) {
1324                         if (!wake_global) {
1325                                 wake_global = 1;
1326                                 char byte = 0;
1327                                 int rc;
1328                                 rc = write(wake_pipe[1], &byte, 1);
1329                         }
1330                         strcpy(call->queue_string, "H"); // overwrite other indications
1331                 } else {
1332                         ast_hangup(ast); // call will be destroyed here
1333                 }
1334         }
1335 }
1336
1337 /*
1338  * incoming release from LCR
1339  */
1340 static void lcr_in_release(struct chan_call *call, int message_type, union parameter *param)
1341 {
1342         struct ast_channel *ast = call->ast;
1343
1344         CDEBUG(call, call->ast, "Incomming release from LCR, releasing ref. (cause=%d)\n", param->disconnectinfo.cause);
1345
1346         /* release ref */
1347         call->ref = 0;
1348         /* change to release state */
1349         call->state = CHAN_LCR_STATE_RELEASE;
1350         /* copy release info */
1351         if (!call->cause) {
1352                 call->cause = param->disconnectinfo.cause;
1353                 call->location = param->disconnectinfo.location;
1354         }
1355         /* if we have an asterisk instance, queue hangup, else we are done */
1356         if (ast) {
1357 #if ASTERISK_VERSION_NUM < 110000
1358                 ast->hangupcause = call->cause;
1359 #else
1360                 ast_channel_hangupcause_set(ast, call->cause);
1361 #endif
1362                 if (call->pbx_started) {
1363                         if (!wake_global) {
1364                                 wake_global = 1;
1365                                 char byte = 0;
1366                                 int rc;
1367                                 rc = write(wake_pipe[1], &byte, 1);
1368                         }
1369                         strcpy(call->queue_string, "H");
1370                 } else {
1371                         ast_hangup(ast); // call will be destroyed here
1372                 }
1373         } else {
1374                 free_call(call);
1375         }
1376
1377 }
1378
1379 /*
1380  * incoming information from LCR
1381  */
1382 static void lcr_in_information(struct chan_call *call, int message_type, union parameter *param)
1383 {
1384         struct ast_channel *ast = call->ast;
1385
1386         CDEBUG(call, call->ast, "Incoming information from LCR. (dialing=%s)\n", param->information.id);
1387
1388         if (!ast) return;
1389
1390         /* pbx not started */
1391         if (!call->pbx_started) {
1392                 CDEBUG(call, call->ast, "Asterisk not started, adding digits to number.\n");
1393 #if ASTERISK_VERSION_NUM < 110000
1394                 strncat(ast->exten, param->information.id, AST_MAX_EXTENSION-1);
1395 #else
1396                 ast_channel_exten_set(ast, param->information.id);
1397 #endif
1398                 lcr_start_pbx(call, ast, param->information.sending_complete);
1399                 return;
1400         }
1401
1402         /* change dailing state after setup */
1403         if (call->state == CHAN_LCR_STATE_IN_SETUP) {
1404                 CDEBUG(call, call->ast, "Changing from SETUP to DIALING state.\n");
1405                 call->state = CHAN_LCR_STATE_IN_DIALING;
1406 //              ast_setstate(ast, AST_STATE_DIALING);
1407         }
1408
1409         /* queue digits */
1410         if (call->state == CHAN_LCR_STATE_IN_DIALING && param->information.id[0]) {
1411                 if (!wake_global) {
1412                         wake_global = 1;
1413                         char byte = 0;
1414                         int rc;
1415                         rc = write(wake_pipe[1], &byte, 1);
1416                 }
1417                 strncat(call->queue_string, param->information.id, sizeof(call->queue_string)-1);
1418         }
1419
1420         /* use bridge to forware message not supported by asterisk */
1421         if (call->state == CHAN_LCR_STATE_CONNECT) {
1422                 CDEBUG(call, call->ast, "Call is connected, bridging.\n");
1423                 bridge_message_if_bridged(call, message_type, param);
1424         }
1425 }
1426
1427 /*
1428  * incoming information from LCR
1429  */
1430 static void lcr_in_notify(struct chan_call *call, int message_type, union parameter *param)
1431 {
1432         CDEBUG(call, call->ast, "Incomming notify from LCR. (notify=%d)\n", param->notifyinfo.notify);
1433
1434         if (!call->ast) return;
1435
1436         /* use bridge to forware message not supported by asterisk */
1437         bridge_message_if_bridged(call, message_type, param);
1438 }
1439
1440 /*
1441  * incoming information from LCR
1442  */
1443 static void lcr_in_facility(struct chan_call *call, int message_type, union parameter *param)
1444 {
1445         CDEBUG(call, call->ast, "Incomming facility from LCR.\n");
1446
1447         if (!call->ast) return;
1448
1449         /* use bridge to forware message not supported by asterisk */
1450         bridge_message_if_bridged(call, message_type, param);
1451 }
1452
1453 /*
1454  * incoming pattern from LCR
1455  */
1456 static void lcr_in_pattern(struct chan_call *call, int message_type, union parameter *param)
1457 {
1458         union parameter newparam;
1459
1460         CDEBUG(call, call->ast, "Incomming pattern indication from LCR.\n");
1461
1462         if (!call->ast) return;
1463
1464         /* pattern are indicated only once */
1465         if (call->has_pattern)
1466                 return;
1467         call->has_pattern = 1;
1468
1469         /* request bchannel */
1470         CDEBUG(call, call->ast, "Requesting audio path (ref=%d)\n", call->ref);
1471         memset(&newparam, 0, sizeof(union parameter));
1472         send_message(MESSAGE_AUDIOPATH, call->ref, &newparam);
1473
1474         /* queue PROGRESS, because tones are available */
1475         if (call->ast && call->pbx_started) {
1476                 if (!wake_global) {
1477                         wake_global = 1;
1478                         char byte = 0;
1479                         int rc;
1480                         rc = write(wake_pipe[1], &byte, 1);
1481                 }
1482                 strncat(call->queue_string, "T", sizeof(call->queue_string)-1);
1483         }
1484 }
1485
1486 /*
1487  * got dtmf from bchannel (locked state)
1488  */
1489 void lcr_in_dtmf(struct chan_call *call, int val)
1490 {
1491         struct ast_channel *ast = call->ast;
1492         char digit[2];
1493
1494         if (!ast)
1495                 return;
1496         if (!call->pbx_started)
1497                 return;
1498
1499         if (!call->dsp_dtmf) {
1500                 CDEBUG(call, call->ast, "Recognised DTMF digit '%c', but ignoring. This is fixed in later mISDN driver.\n", val);
1501                 return;
1502         }
1503
1504         CDEBUG(call, call->ast, "Recognised DTMF digit '%c'.\n", val);
1505         digit[0] = val;
1506         digit[1] = '\0';
1507         if (!wake_global) {
1508                 wake_global = 1;
1509                 char byte = 0;
1510                 int rc;
1511                 rc = write(wake_pipe[1], &byte, 1);
1512         }
1513         strncat(call->queue_string, digit, sizeof(call->queue_string)-1);
1514 }
1515
1516 /*
1517  * message received from LCR
1518  */
1519 int receive_message(int message_type, unsigned int ref, union parameter *param)
1520 {
1521         struct chan_call *call;
1522         union parameter newparam;
1523         int rc = 0;
1524
1525         memset(&newparam, 0, sizeof(union parameter));
1526
1527         /* handle new ref */
1528         if (message_type == MESSAGE_NEWREF) {
1529                 if (param->newref.direction) {
1530                         /* new ref from lcr */
1531                         CDEBUG(NULL, NULL, "Received new ref by LCR, due to incomming call. (ref=%ld)\n", ref);
1532                         if (!ref || find_call_ref(ref)) {
1533                                 CERROR(NULL, NULL, "Illegal new ref %ld received.\n", ref);
1534                                 return -1;
1535                         }
1536                         /* allocate new call instance */
1537                         call = alloc_call();
1538                         /* new state */
1539                         call->state = CHAN_LCR_STATE_IN_PREPARE;
1540                         /* set ref */
1541                         call->ref = ref;
1542                         call->ref_was_assigned = 1;
1543                         /* set dtmf (default, use option 'n' to disable */
1544                         call->dsp_dtmf = 1;
1545                         /* wait for setup (or release from asterisk) */
1546                 } else {
1547                         /* new ref, as requested from this remote application */
1548                         CDEBUG(NULL, NULL, "Received new ref by LCR, as requested from chan_lcr. (ref=%ld)\n", ref);
1549                         call = find_call_ref(0);
1550                         if (!call) {
1551                                 /* send release, if ref does not exist */
1552                                 CERROR(NULL, NULL, "No call found, that requests a ref.\n");
1553                                 return 0;
1554                         }
1555                         /* store new ref */
1556                         call->ref = ref;
1557                         call->ref_was_assigned = 1;
1558                         /* set dtmf (default, use option 'n' to disable */
1559                         call->dsp_dtmf = 1;
1560                         /* send pending setup info */
1561                         if (call->state == CHAN_LCR_STATE_OUT_PREPARE)
1562                                 send_setup_to_lcr(call);
1563                         /* release if asterisk has signed off */
1564                         else if (call->state == CHAN_LCR_STATE_RELEASE) {
1565                                 /* send release */
1566                                 if (call->cause)
1567                                         send_release(call, call->cause, call->location);
1568                                 else
1569                                         send_release(call, CAUSE_NORMAL, LOCATION_PRIVATE_LOCAL);
1570                                 /* free call */
1571                                 free_call(call);
1572                                 return 0;
1573                         }
1574                 }
1575                 return 0;
1576         }
1577
1578         /* check ref */
1579         if (!ref) {
1580                 CERROR(NULL, NULL, "Received message %d without ref.\n", message_type);
1581                 return -1;
1582         }
1583         call = find_call_ref(ref);
1584         if (!call) {
1585                 /* ignore ref that is not used (anymore) */
1586                 CDEBUG(NULL, NULL, "Message %d from LCR ignored, because no call instance found.\n", message_type);
1587                 return 0;
1588         }
1589
1590         /* handle messages */
1591         switch(message_type) {
1592                 case MESSAGE_SETUP:
1593                 lcr_in_setup(call, message_type, param);
1594                 break;
1595
1596                 case MESSAGE_OVERLAP:
1597                 lcr_in_overlap(call, message_type, param);
1598                 break;
1599
1600                 case MESSAGE_PROCEEDING:
1601                 lcr_in_proceeding(call, message_type, param);
1602                 break;
1603
1604                 case MESSAGE_ALERTING:
1605                 lcr_in_alerting(call, message_type, param);
1606                 break;
1607
1608                 case MESSAGE_CONNECT:
1609                 lcr_in_connect(call, message_type, param);
1610                 break;
1611
1612                 case MESSAGE_DISCONNECT:
1613                 lcr_in_disconnect(call, message_type, param);
1614                 break;
1615
1616                 case MESSAGE_RELEASE:
1617                 lcr_in_release(call, message_type, param);
1618                 break;
1619
1620                 case MESSAGE_INFORMATION:
1621                 lcr_in_information(call, message_type, param);
1622                 break;
1623
1624                 case MESSAGE_NOTIFY:
1625                 lcr_in_notify(call, message_type, param);
1626                 break;
1627
1628                 case MESSAGE_FACILITY:
1629                 lcr_in_facility(call, message_type, param);
1630                 break;
1631
1632                 case MESSAGE_PATTERN: // audio available from LCR
1633                 if (!call->has_pattern)
1634                         lcr_in_pattern(call, message_type, param);
1635                 break;
1636
1637                 case MESSAGE_NOPATTERN: // audio not available from LCR
1638                 break;
1639
1640                 case MESSAGE_AUDIOPATH: // if remote audio connected or hold
1641                 call->audiopath = param->audiopath;
1642                 break;
1643
1644                 case MESSAGE_TRAFFIC: // if remote audio connected or hold
1645                 {
1646                         unsigned char *p = param->traffic.data;
1647                         int i, len = param->traffic.len;
1648                         for (i = 0; i < len; i++, p++)
1649                                 *p = flip_bits[*p];
1650                 }
1651                 rc = write(call->pipe[1], param->traffic.data, param->traffic.len);
1652                 break;
1653
1654                 default:
1655                 CDEBUG(call, call->ast, "Message %d from LCR unhandled.\n", message_type);
1656                 break;
1657         }
1658         return rc;
1659 }
1660
1661 /*
1662  * release all calls (due to broken socket)
1663  */
1664 static void release_all_calls(void)
1665 {
1666         struct chan_call *call;
1667
1668 again:
1669         call = call_first;
1670         while(call) {
1671                 /* no ast, so we may directly free call */
1672                 if (!call->ast) {
1673                         CDEBUG(call, NULL, "Freeing call, because no Asterisk channel is linked.\n");
1674                         free_call(call);
1675                         goto again;
1676                 }
1677                 /* already in release process */
1678                 if (call->state == CHAN_LCR_STATE_RELEASE) {
1679                         call = call->next;
1680                         continue;
1681                 }
1682                 /* release or queue release */
1683                 call->ref = 0;
1684                 call->state = CHAN_LCR_STATE_RELEASE;
1685                 if (!call->pbx_started) {
1686                         CDEBUG(call, call->ast, "Releasing call, because no Asterisk channel is not started.\n");
1687                         ast_hangup(call->ast); // call will be destroyed here
1688                         goto again;
1689                 }
1690                 CDEBUG(call, call->ast, "Queue call release, because Asterisk channel is running.\n");
1691                 if (!wake_global) {
1692                         wake_global = 1;
1693                         char byte = 0;
1694                         int rc;
1695                         rc = write(wake_pipe[1], &byte, 1);
1696                 }
1697                 strcpy(call->queue_string, "H");
1698                 call = call->next;
1699         }
1700 }
1701
1702 void close_socket(void);
1703
1704 /* asterisk handler
1705  * warning! not thread safe
1706  * returns -1 for socket error, 0 for no work, 1 for work
1707  */
1708 static int handle_socket(struct lcr_fd *fd, unsigned int what, void *instance, int index)
1709 {
1710         int len;
1711         struct admin_list *admin;
1712         struct admin_message msg;
1713
1714         if ((what & LCR_FD_READ)) {
1715                 /* read from socket */
1716                 len = read(lcr_sock, &msg, sizeof(msg));
1717                 if (len == 0) {
1718                         CERROR(NULL, NULL, "Socket closed.(read)\n");
1719                         error:
1720                         CERROR(NULL, NULL, "Handling of socket failed - closing for some seconds.\n");
1721                         close_socket();
1722                         release_all_calls();
1723                         schedule_timer(&socket_retry, SOCKET_RETRY_TIMER, 0);
1724                         return 0;
1725                 }
1726                 if (len > 0) {
1727                         if (len != sizeof(msg)) {
1728                                 CERROR(NULL, NULL, "Socket short read. (len %d)\n", len);
1729                                 goto error;
1730                         }
1731                         if (msg.message != ADMIN_MESSAGE) {
1732                                 CERROR(NULL, NULL, "Socket received illegal message %d.\n", msg.message);
1733                                 goto error;
1734                         }
1735                         receive_message(msg.u.msg.type, msg.u.msg.ref, &msg.u.msg.param);
1736                 } else {
1737                         CERROR(NULL, NULL, "Socket failed (errno %d).\n", errno);
1738                         goto error;
1739                 }
1740         }
1741
1742         if ((what & LCR_FD_WRITE)) {
1743                 /* write to socket */
1744                 if (!admin_first) {
1745                         socket_fd.when &= ~LCR_FD_WRITE;
1746                         return 0;
1747                 }
1748                 admin = admin_first;
1749                 len = write(lcr_sock, &admin->msg, sizeof(msg));
1750                 if (len == 0) {
1751                         CERROR(NULL, NULL, "Socket closed.(write)\n");
1752                         goto error;
1753                 }
1754                 if (len > 0) {
1755                         if (len != sizeof(msg)) {
1756                                 CERROR(NULL, NULL, "Socket short write. (len %d)\n", len);
1757                                 goto error;
1758                         }
1759                         /* free head */
1760                         admin_first = admin->next;
1761                         free(admin);
1762                         global_change = 1;
1763                 } else {
1764                         CERROR(NULL, NULL, "Socket failed (errno %d).\n", errno);
1765                         goto error;
1766                 }
1767         }
1768
1769         return 0;
1770 }
1771
1772 /*
1773  * open and close socket and thread
1774  */
1775 int open_socket(void)
1776 {
1777         int conn;
1778         struct sockaddr_un sock_address;
1779         union parameter param;
1780
1781         /* open socket */
1782         if ((lcr_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
1783                 CERROR(NULL, NULL, "Failed to create socket.\n");
1784                 return lcr_sock;
1785         }
1786
1787         /* set socket address and name */
1788         memset(&sock_address, 0, sizeof(sock_address));
1789         sock_address.sun_family = PF_UNIX;
1790         sprintf(sock_address.sun_path, SOCKET_NAME, options.lock);
1791
1792         /* connect socket */
1793         if ((conn = connect(lcr_sock, (struct sockaddr *)&sock_address, SUN_LEN(&sock_address))) < 0) {
1794                 close(lcr_sock);
1795                 lcr_sock = -1;
1796                 CDEBUG(NULL, NULL, "Failed to connect to socket '%s'. Is LCR running?\n", sock_address.sun_path);
1797                 return conn;
1798         }
1799
1800         /* register socket fd */
1801         memset(&socket_fd, 0, sizeof(socket_fd));
1802         socket_fd.fd = lcr_sock;
1803         register_fd(&socket_fd, LCR_FD_READ | LCR_FD_EXCEPT, handle_socket, NULL, 0);
1804
1805         /* enque hello message */
1806         memset(&param, 0, sizeof(param));
1807         strcpy(param.hello.application, "asterisk");
1808         send_message(MESSAGE_HELLO, 0, &param);
1809
1810         return lcr_sock;
1811 }
1812
1813 void close_socket(void)
1814 {
1815         struct admin_list *admin, *temp;
1816
1817         /* socket not created */
1818         if (lcr_sock < 0)
1819                 return;
1820
1821         unregister_fd(&socket_fd);
1822
1823         /* flush pending messages */
1824         admin = admin_first;
1825         while(admin) {
1826                 temp = admin;
1827                 admin = admin->next;
1828                 free(temp);
1829         }
1830         admin_first = NULL;
1831
1832         /* close socket */
1833         close(lcr_sock);
1834         lcr_sock = -1;
1835         global_change = 1;
1836 }
1837
1838
1839 /* sending queue to asterisk */
1840 static int wake_event(struct lcr_fd *fd, unsigned int what, void *instance, int index)
1841 {
1842         char byte;
1843         int rc;
1844
1845         rc = read(wake_pipe[0], &byte, 1);
1846
1847         wake_global = 0;
1848
1849         return 0;
1850 }
1851
1852 static void handle_queue()
1853 {
1854         struct chan_call *call;
1855         struct ast_channel *ast;
1856         struct ast_frame fr;
1857         char *p;
1858
1859 again:
1860         call = call_first;
1861         while(call) {
1862                 p = call->queue_string;
1863                 ast = call->ast;
1864                 if (*p && ast) {
1865                         if (ast_channel_trylock(ast)) {
1866                                 ast_mutex_unlock(&chan_lock);
1867                                 usleep(1);
1868                                 ast_mutex_lock(&chan_lock);
1869                                 goto again;
1870                         }
1871                         while(*p) {
1872                                 switch (*p) {
1873                                 case 'T':
1874                                         CDEBUG(call, ast, "Sending queued PROGRESS to Asterisk.\n");
1875                                         ast_queue_control(ast, AST_CONTROL_PROGRESS);
1876                                         break;
1877                                 case 'P':
1878                                         CDEBUG(call, ast, "Sending queued PROCEEDING to Asterisk.\n");
1879                                         ast_queue_control(ast, AST_CONTROL_PROCEEDING);
1880                                         break;
1881                                 case 'R':
1882                                         CDEBUG(call, ast, "Sending queued RINGING to Asterisk.\n");
1883                                         ast_queue_control(ast, AST_CONTROL_RINGING);
1884                                         ast_setstate(ast, AST_STATE_RINGING);
1885                                         break;
1886                                 case 'N':
1887                                         CDEBUG(call, ast, "Sending queued ANSWER to Asterisk.\n");
1888                                         ast_queue_control(ast, AST_CONTROL_ANSWER);
1889                                         break;
1890                                 case 'H':
1891                                         CDEBUG(call, ast, "Sending queued HANGUP to Asterisk.\n");
1892                                         ast_queue_hangup(ast);
1893                                         break;
1894                                 case '1': case '2': case '3': case 'A':
1895                                 case '4': case '5': case '6': case 'B':
1896                                 case '7': case '8': case '9': case 'C':
1897                                 case '*': case '0': case '#': case 'D':
1898                                         CDEBUG(call, ast, "Sending queued digit '%c' to Asterisk.\n", *p);
1899                                         /* send digit to asterisk */
1900                                         memset(&fr, 0, sizeof(fr));
1901
1902                                         #ifdef LCR_FOR_ASTERISK
1903                                         fr.frametype = AST_FRAME_DTMF_BEGIN;
1904                                         #endif
1905
1906                                         #ifdef LCR_FOR_CALLWEAVER
1907                                         fr.frametype = AST_FRAME_DTMF;
1908                                         #endif
1909
1910 #ifdef AST_1_8_OR_HIGHER
1911                                         fr.subclass.integer = *p;
1912 #else
1913                                         fr.subclass = *p;
1914 #endif
1915                                         fr.delivery = ast_tv(0, 0);
1916                                         ast_queue_frame(ast, &fr);
1917
1918                                         #ifdef LCR_FOR_ASTERISK
1919                                         fr.frametype = AST_FRAME_DTMF_END;
1920                                         ast_queue_frame(ast, &fr);
1921                                         #endif
1922
1923                                         break;
1924                                 default:
1925                                         CDEBUG(call, ast, "Ignoring queued digit 0x%02x.\n", *p);
1926                                 }
1927                                 p++;
1928                         }
1929                         call->queue_string[0] = '\0';
1930                         ast_channel_unlock(ast);
1931                 }
1932                 call = call->next;
1933         }
1934 }
1935
1936 static int handle_retry(struct lcr_timer *timer, void *instance, int index)
1937 {
1938         CDEBUG(NULL, NULL, "Retry to open socket.\n");
1939         if (open_socket() < 0)
1940                 schedule_timer(&socket_retry, SOCKET_RETRY_TIMER, 0);
1941
1942         return 0;
1943 }
1944
1945 void lock_chan(void)
1946 {
1947         ast_mutex_lock(&chan_lock);
1948 }
1949
1950 void unlock_chan(void)
1951 {
1952         ast_mutex_unlock(&chan_lock);
1953 }
1954
1955 /* chan_lcr thread */
1956 static void *chan_thread(void *arg)
1957 {
1958         if (pipe(wake_pipe) < 0) {
1959                 CERROR(NULL, NULL, "Failed to open pipe.\n");
1960                 return NULL;
1961         }
1962         memset(&wake_fd, 0, sizeof(wake_fd));
1963         wake_fd.fd = wake_pipe[0];
1964         register_fd(&wake_fd, LCR_FD_READ, wake_event, NULL, 0);
1965
1966         memset(&socket_retry, 0, sizeof(socket_retry));
1967         add_timer(&socket_retry, handle_retry, NULL, 0);
1968
1969         /* open socket the first time */
1970         handle_retry(NULL, NULL, 0);
1971
1972         ast_mutex_lock(&chan_lock);
1973
1974         while(1) {
1975                 handle_queue();
1976                 select_main(0, &global_change, lock_chan, unlock_chan);
1977         }
1978
1979         return NULL;
1980 }
1981
1982 /*
1983  * new asterisk instance
1984  */
1985 static
1986 #ifdef AST_1_8_OR_HIGHER
1987 #if ASTERISK_VERSION_NUM < 100000
1988 struct ast_channel *lcr_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
1989 #else
1990 struct ast_channel *lcr_request(const char *type, struct ast_format_cap *format, const struct ast_channel *requestor, void *data, int *cause)
1991 #endif
1992 #else
1993 struct ast_channel *lcr_request(const char *type, int format, void *data, int *cause)
1994 #endif
1995 {
1996         char exten[256], *dial, *interface, *opt;
1997         struct ast_channel *ast;
1998         struct chan_call *call;
1999         const struct ast_party_redirecting *req_redir;
2000         const struct ast_party_caller *req_caller;
2001
2002         ast_mutex_lock(&chan_lock);
2003         CDEBUG(NULL, NULL, "Received request from Asterisk. (data=%s)\n", (char *)data);
2004
2005         /* if socket is closed */
2006         if (lcr_sock < 0) {
2007                 CERROR(NULL, NULL, "Rejecting call from Asterisk, because LCR not running.\n");
2008                 ast_mutex_unlock(&chan_lock);
2009                 return NULL;
2010         }
2011
2012         /* create call instance */
2013         call = alloc_call();
2014         if (!call) {
2015                 /* failed to create instance */
2016                 ast_mutex_unlock(&chan_lock);
2017                 return NULL;
2018         }
2019
2020         /* create asterisk channel instrance */
2021
2022         #ifdef LCR_FOR_ASTERISK
2023 #ifdef AST_1_8_OR_HIGHER
2024         ast = ast_channel_alloc(1, AST_STATE_RESERVED, NULL, NULL, NULL, NULL, NULL, NULL, 0, "%s/%d", lcr_type, ++glob_channel);
2025 #else
2026         ast = ast_channel_alloc(1, AST_STATE_RESERVED, NULL, NULL, "", NULL, "", 0, "%s/%d", lcr_type, ++glob_channel);
2027 #endif
2028         #endif
2029
2030         #ifdef LCR_FOR_CALLWEAVER
2031         ast = ast_channel_alloc(1);
2032         #endif
2033
2034         if (!ast) {
2035                 CERROR(NULL, NULL, "Failed to create Asterisk channel.\n");
2036                 free_call(call);
2037                 /* failed to create instance */
2038                 ast_mutex_unlock(&chan_lock);
2039                 return NULL;
2040         }
2041 #if ASTERISK_VERSION_NUM < 110000
2042         ast->tech = &lcr_tech;
2043         ast->tech_pvt = (void *)1L; // set pointer or asterisk will not call
2044         req_redir = &requestor->redirecting;
2045         req_caller = &requestor->caller;
2046 #else
2047         ast_channel_tech_set(ast, &lcr_tech);
2048         ast_channel_tech_pvt_set(ast, (void *)1L); // set pointer or asterisk will not call
2049         req_redir = ast_channel_redirecting(requestor);
2050         req_caller = ast_channel_caller(requestor);
2051 #endif
2052         /* configure channel */
2053 #if ASTERISK_VERSION_NUM < 100000
2054 #if ASTERISK_VERSION_NUM < 110000
2055         ast->nativeformats = (options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW;
2056         ast->readformat = ast->rawreadformat = ast->nativeformats;
2057         ast->writeformat = ast->rawwriteformat =  ast->nativeformats;
2058 #else
2059         ast_channel_nativeformats_set(ast, (options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW);
2060         ast->readformat = ast->rawreadformat = ast_channel_nativeformats(ast);
2061         ast->writeformat = ast->rawwriteformat =  ast_channel_nativeformats(ast);
2062 #endif
2063 #else
2064 #if ASTERISK_VERSION_NUM < 110000
2065         ast_format_set(&ast->rawwriteformat ,(options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW , 0);
2066         ast_format_copy(&ast->rawreadformat, &ast->rawwriteformat);
2067         ast_format_cap_set(ast->nativeformats, &ast->rawwriteformat);
2068         ast_set_write_format(ast, &ast->rawwriteformat);
2069         ast_set_read_format(ast, &ast->rawreadformat);
2070 #else
2071         ast_format_set(ast_channel_rawwriteformat(ast) ,(options.law=='a')?AST_FORMAT_ALAW:AST_FORMAT_ULAW , 0);
2072         ast_format_copy(ast_channel_rawreadformat(ast), ast_channel_rawwriteformat(ast));
2073         ast_format_cap_set(ast_channel_nativeformats(ast), ast_channel_rawwriteformat(ast));
2074         ast_set_write_format(ast, ast_channel_rawwriteformat(ast));
2075         ast_set_read_format(ast, ast_channel_rawreadformat(ast));
2076 #endif
2077 #endif
2078 #if ASTERISK_VERSION_NUM < 110000
2079         ast->priority = 1;
2080         ast->hangupcause = 0;
2081 #else
2082         ast_channel_priority_set(ast, 1);
2083         ast_channel_hangupcause_set(ast, 0);
2084 #endif
2085
2086         /* link together */
2087         call->ast = ast;
2088 #if ASTERISK_VERSION_NUM < 110000
2089         ast->tech_pvt = call;
2090         ast->fds[0] = call->pipe[0];
2091 #else
2092         ast_channel_tech_pvt_set(ast, call);
2093         ast_channel_set_fd(ast, 0, call->pipe[0]);
2094 #endif
2095         call->pbx_started = 0;
2096         /* set state */
2097         call->state = CHAN_LCR_STATE_OUT_PREPARE;
2098
2099         /*
2100          * Extract interface, dialstring, options from data.
2101          * Formats can be:
2102          *      <dialstring>
2103          *      <interface>/<dialstring>
2104          *      <interface>/<dialstring>/options
2105          */
2106         strncpy(exten, (char *)data, sizeof(exten)-1);
2107         exten[sizeof(exten)-1] = '\0';
2108         if ((dial = strchr(exten, '/'))) {
2109                 *dial++ = '\0';
2110                 interface = exten;
2111                 if ((opt = strchr(dial, '/')))
2112                         *opt++ = '\0';
2113                 else
2114                         opt = "";
2115         } else {
2116                 dial = exten;
2117                 interface = "";
2118                 opt = "";
2119         }
2120         strncpy(call->interface, interface, sizeof(call->interface)-1);
2121         strncpy(call->dialstring, dial, sizeof(call->dialstring)-1);
2122         apply_opt(call, (char *)opt);
2123
2124 #ifdef AST_1_8_OR_HIGHER
2125 //      clone_variables(requestor, ast);
2126
2127 #if 0
2128         ast->caller.ani.number.valid=                   req_caller->ani.number.valid;
2129         if (req_caller->ani.number.valid)
2130           if (req_caller->ani.number.str)
2131             if (req_caller->ani.number.str[0])
2132                 ast->caller.ani.number.str=             strdup(req_caller->ani.number.str);
2133         ast->caller.ani.number.plan=                    req_caller->ani.number.plan;
2134         ast->caller.ani.number.presentation=            req_caller->ani.number.presentation;
2135
2136         ast->caller.ani.name.valid=                     req_caller->ani.name.valid;
2137         if (req_caller->ani.name.valid)
2138           if (req_caller->ani.name.str)
2139             if (req_caller->ani.name.str[0])
2140                 ast->caller.ani.name.str=               strdup(req_caller->ani.name.str);
2141         ast->caller.ani.name.presentation=              req_caller->ani.name.presentation;
2142
2143         ast->caller.ani.subaddress.valid=               req_caller->ani.subaddress.valid;
2144         if (req_caller->ani.subaddress.valid)
2145           if (req_caller->ani.subaddress.str)
2146             if (req_caller->ani.subaddress.str[0])
2147                 ast->caller.ani.subaddress.str=         strdup(req_caller->ani.subaddress.str);
2148         ast->caller.ani.subaddress.type=                req_caller->ani.subaddress.type;
2149
2150         ast->caller.id.number.valid=                    req_caller->id.number.valid;
2151         if (req_caller->id.number.valid)
2152           if (req_caller->id.number.str)
2153             if (req_caller->id.number.str[0])
2154                 ast->caller.id.number.str=              strdup(req_caller->id.number.str);
2155         ast->caller.id.number.plan=                     req_caller->id.number.plan;
2156         ast->caller.id.number.presentation=             req_caller->id.number.presentation;
2157
2158         ast->caller.id.name.valid=                      req_caller->id.name.valid;
2159         if (req_caller->id.name.valid)
2160           if (req_caller->id.name.str)
2161             if (req_caller->id.name.str[0])
2162                 ast->caller.id.name.str=                strdup(req_caller->id.name.str);
2163         ast->caller.id.name.presentation=               req_caller->id.name.presentation;
2164
2165         ast->caller.id.subaddress.valid=                req_caller->id.subaddress.valid;
2166         if (req_caller->id.subaddress.valid)
2167           if (req_caller->id.subaddress.str)
2168             if (req_caller->id.subaddress.str[0])
2169                 ast->caller.id.subaddress.str=          strdup(req_caller->id.subaddress.str);
2170         ast->caller.id.subaddress.type=                 req_caller->id.subaddress.type;
2171
2172         if (requestor->dialed.number.str)
2173           if (requestor->dialed.number.str[0])
2174                 ast->dialed.number.str=                 strdup(requestor->dialed.number.str);
2175         ast->dialed.number.plan=                        requestor->dialed.number.plan;
2176
2177         ast->dialed.subaddress.valid=                   requestor->dialed.subaddress.valid;
2178         if (requestor->dialed.subaddress.valid)
2179           if (requestor->dialed.subaddress.str)
2180             if (requestor->dialed.subaddress.str[0])
2181                 ast->dialed.subaddress.str=             strdup(requestor->dialed.subaddress.str);
2182         ast->dialed.subaddress.type=                    requestor->dialed.subaddress.type;
2183
2184         ast->dialed.transit_network_select=             requestor->dialed.transit_network_select;
2185         ast->redirecting.count=                         req_redir->count;
2186         ast->redirecting.reason=                        req_redir->reason;
2187
2188         ast->redirecting.from.number.valid=             req_redir->from.number.valid;
2189         if (req_redir->from.number.valid)
2190           if (req_redir->from.number.str)
2191             if (req_redir->from.number.str[0])
2192                 ast->redirecting.from.number.str=       strdup(req_redir->from.number.str);
2193         ast->redirecting.from.number.plan=              req_redir->from.number.plan;
2194         ast->redirecting.from.number.presentation=      req_redir->from.number.presentation;
2195
2196         ast->redirecting.to.number.valid=               req_redir->to.number.valid;
2197         if (req_redir->to.number.valid)
2198           if (req_redir->to.number.str)
2199             if (req_redir->to.number.str[0])
2200                 ast->redirecting.to.number.str=         strdup(req_redir->to.number.str);
2201         ast->redirecting.to.number.plan=                req_redir->to.number.plan;
2202         ast->redirecting.to.number.presentation=        req_redir->to.number.presentation;
2203 #endif
2204         /* store call information for setup */
2205
2206         /* caller ID */
2207         if (requestor && req_caller->id.number.valid) {
2208                 if (req_caller->id.number.str)
2209                         strncpy(call->callerinfo.id, req_caller->id.number.str, sizeof(call->callerinfo.id)-1);
2210                 switch(req_caller->id.number.presentation & AST_PRES_RESTRICTION) {
2211                         case AST_PRES_RESTRICTED:
2212                         call->callerinfo.present = INFO_PRESENT_RESTRICTED;
2213                         break;
2214                         case AST_PRES_UNAVAILABLE:
2215                         call->callerinfo.present = INFO_PRESENT_NOTAVAIL;
2216                         break;
2217                         case AST_PRES_ALLOWED:
2218                         default:
2219                         call->callerinfo.present = INFO_PRESENT_ALLOWED;
2220                 }
2221                 switch(req_caller->id.number.presentation & AST_PRES_NUMBER_TYPE) {
2222                         case AST_PRES_USER_NUMBER_UNSCREENED:
2223                         call->callerinfo.screen = INFO_SCREEN_USER;
2224                         break;
2225                         case AST_PRES_USER_NUMBER_PASSED_SCREEN:
2226                         call->callerinfo.screen = INFO_SCREEN_USER_VERIFIED_PASSED;
2227                         break;
2228                         case AST_PRES_USER_NUMBER_FAILED_SCREEN:
2229                         call->callerinfo.screen = INFO_SCREEN_USER_VERIFIED_FAILED;
2230                         break;
2231                         default:
2232                         call->callerinfo.screen = INFO_SCREEN_NETWORK;
2233                 }
2234                 switch((req_caller->id.number.plan >> 4) & 7) {
2235                         case 4:
2236                         call->callerinfo.ntype = INFO_NTYPE_SUBSCRIBER;
2237                         break;
2238                         case 2:
2239                         call->callerinfo.ntype = INFO_NTYPE_NATIONAL;
2240                         break;
2241                         case 1:
2242                         call->callerinfo.ntype = INFO_NTYPE_INTERNATIONAL;
2243                         break;
2244                         default:
2245                         call->callerinfo.ntype = INFO_NTYPE_UNKNOWN;
2246                 }
2247         } else
2248                 call->callerinfo.present = INFO_PRESENT_NOTAVAIL;
2249
2250         /* caller ID 2 */
2251         if (requestor && req_caller->ani.number.valid) {
2252                 if (req_caller->ani.number.str)
2253                         strncpy(call->callerinfo.id2, req_caller->ani.number.str, sizeof(call->callerinfo.id2)-1);
2254                 switch(req_caller->ani.number.presentation & AST_PRES_RESTRICTION) {
2255                         case AST_PRES_RESTRICTED:
2256                         call->callerinfo.present2 = INFO_PRESENT_RESTRICTED;
2257                         break;
2258                         case AST_PRES_UNAVAILABLE:
2259                         call->callerinfo.present2 = INFO_PRESENT_NOTAVAIL;
2260                         break;
2261                         case AST_PRES_ALLOWED:
2262                         default:
2263                         call->callerinfo.present2 = INFO_PRESENT_ALLOWED;
2264                 }
2265                 switch(req_caller->ani.number.presentation & AST_PRES_NUMBER_TYPE) {
2266                         case AST_PRES_USER_NUMBER_UNSCREENED:
2267                         call->callerinfo.screen2 = INFO_SCREEN_USER;
2268                         break;
2269                         case AST_PRES_USER_NUMBER_PASSED_SCREEN:
2270                         call->callerinfo.screen2 = INFO_SCREEN_USER_VERIFIED_PASSED;
2271                         break;
2272                         case AST_PRES_USER_NUMBER_FAILED_SCREEN:
2273                         call->callerinfo.screen2 = INFO_SCREEN_USER_VERIFIED_FAILED;
2274                         break;
2275                         default:
2276                         call->callerinfo.screen2 = INFO_SCREEN_NETWORK;
2277                 }
2278                 switch((req_caller->ani.number.plan >> 4) & 7) {
2279                         case 4:
2280                         call->callerinfo.ntype2 = INFO_NTYPE_SUBSCRIBER;
2281                         break;
2282                         case 2:
2283                         call->callerinfo.ntype2 = INFO_NTYPE_NATIONAL;
2284                         break;
2285                         case 1:
2286                         call->callerinfo.ntype2 = INFO_NTYPE_INTERNATIONAL;
2287                         break;
2288                         default:
2289                         call->callerinfo.ntype2 = INFO_NTYPE_UNKNOWN;
2290                 }
2291         } else
2292                 call->callerinfo.present2 = INFO_PRESENT_NOTAVAIL;
2293
2294         /* caller name */
2295         if (requestor && req_caller->id.name.valid) {
2296                 if (req_caller->id.name.str)
2297                         strncpy(call->callerinfo.name, req_caller->id.name.str, sizeof(call->callerinfo.name)-1);
2298         }
2299
2300         /* redir number */
2301         if (requestor && req_redir->from.number.valid) {
2302                 call->redirinfo.itype = INFO_ITYPE_CHAN;
2303                 if (req_redir->from.number.str)
2304                         strncpy(call->redirinfo.id, req_redir->from.number.str, sizeof(call->redirinfo.id)-1);
2305                 switch(req_redir->from.number.presentation & AST_PRES_RESTRICTION) {
2306                         case AST_PRES_RESTRICTED:
2307                         call->redirinfo.present = INFO_PRESENT_RESTRICTED;
2308                         break;
2309                         case AST_PRES_UNAVAILABLE:
2310                         call->redirinfo.present = INFO_PRESENT_NOTAVAIL;
2311                         break;
2312                         case AST_PRES_ALLOWED:
2313                         default:
2314                         call->redirinfo.present = INFO_PRESENT_ALLOWED;
2315                 }
2316                 switch(req_redir->from.number.presentation & AST_PRES_NUMBER_TYPE) {
2317                         case AST_PRES_USER_NUMBER_UNSCREENED:
2318                         call->redirinfo.screen = INFO_SCREEN_USER;
2319                         break;
2320                         case AST_PRES_USER_NUMBER_PASSED_SCREEN:
2321                         call->redirinfo.screen = INFO_SCREEN_USER_VERIFIED_PASSED;
2322                         break;
2323                         case AST_PRES_USER_NUMBER_FAILED_SCREEN:
2324                         call->redirinfo.screen = INFO_SCREEN_USER_VERIFIED_FAILED;
2325                         break;
2326                         default:
2327                         call->redirinfo.screen = INFO_SCREEN_NETWORK;
2328                 }
2329                 switch((req_redir->from.number.plan >> 4) & 7) {
2330                         case 4:
2331                         call->redirinfo.ntype = INFO_NTYPE_SUBSCRIBER;
2332                         break;
2333                         case 2:
2334                         call->redirinfo.ntype = INFO_NTYPE_NATIONAL;
2335                         break;
2336                         case 1:
2337                         call->redirinfo.ntype = INFO_NTYPE_INTERNATIONAL;
2338                         break;
2339                         default:
2340                         call->redirinfo.ntype = INFO_NTYPE_UNKNOWN;
2341                 }
2342         }
2343 #endif
2344
2345         ast_mutex_unlock(&chan_lock);
2346         return ast;
2347 }
2348
2349 /*
2350  * call from asterisk
2351  */
2352 static int lcr_call(struct ast_channel *ast, char *dest, int timeout)
2353 {
2354         union parameter newparam;
2355         struct chan_call *call;
2356 #if ASTERISK_VERSION_NUM >= 110000
2357         int transfercapability;
2358 #endif
2359
2360         ast_mutex_lock(&chan_lock);
2361 #if ASTERISK_VERSION_NUM < 110000
2362         call = ast->tech_pvt;
2363 #else
2364         call = ast_channel_tech_pvt(ast);
2365 #endif
2366
2367         #ifdef LCR_FOR_CALLWEAVER
2368         ast->type = "LCR";
2369         snprintf(ast->name, sizeof(ast->name), "%s/%s-%04x",lcr_type, call->dialstring, ast_random() & 0xffff);
2370         #endif
2371
2372         if (!call) {
2373                 CERROR(NULL, ast, "Received call from Asterisk, but call instance does not exist.\n");
2374                 ast_mutex_unlock(&chan_lock);
2375                 return -1;
2376         }
2377
2378         CDEBUG(NULL, ast, "Received call from Asterisk.\n");
2379
2380         /* pbx process is started */
2381         call->pbx_started = 1;
2382         /* send MESSAGE_NEWREF */
2383         memset(&newparam, 0, sizeof(union parameter));
2384         newparam.newref.direction = 0; /* request from app */
2385         send_message(MESSAGE_NEWREF, 0, &newparam);
2386
2387         /* set hdlc if capability requires hdlc */
2388 #if ASTERISK_VERSION_NUM < 110000
2389         if (ast->transfercapability == INFO_BC_DATAUNRESTRICTED
2390          || ast->transfercapability == INFO_BC_DATARESTRICTED
2391          || ast->transfercapability == INFO_BC_VIDEO)
2392 #else
2393         transfercapability=ast_channel_transfercapability(ast);
2394         if (transfercapability == INFO_BC_DATAUNRESTRICTED
2395          || transfercapability == INFO_BC_DATARESTRICTED
2396          || transfercapability == INFO_BC_VIDEO)
2397 #endif
2398                 call->hdlc = 1;
2399         /* if hdlc is forced by option, we change transcap to data */
2400         if (call->hdlc
2401 #if ASTERISK_VERSION_NUM < 110000
2402          && ast->transfercapability != INFO_BC_DATAUNRESTRICTED
2403          && ast->transfercapability != INFO_BC_DATARESTRICTED
2404          && ast->transfercapability != INFO_BC_VIDEO)
2405                 ast->transfercapability = INFO_BC_DATAUNRESTRICTED;
2406 #else
2407          && transfercapability != INFO_BC_DATAUNRESTRICTED
2408          && transfercapability != INFO_BC_DATARESTRICTED
2409          && transfercapability != INFO_BC_VIDEO)
2410                 transfercapability = INFO_BC_DATAUNRESTRICTED;
2411 #endif
2412
2413 #ifndef AST_1_8_OR_HIGHER
2414         call->cid_num[0] = 0;
2415         call->cid_name[0] = 0;
2416         call->cid_rdnis[0] = 0;
2417
2418         if (ast->cid.cid_num) if (ast->cid.cid_num[0])
2419                 strncpy(call->cid_num, ast->cid.cid_num,
2420                         sizeof(call->cid_num)-1);
2421         if (ast->cid.cid_name) if (ast->cid.cid_name[0])
2422                 strncpy(call->cid_name, ast->cid.cid_name,
2423                         sizeof(call->cid_name)-1);
2424         if (ast->cid.cid_rdnis) if (ast->cid.cid_rdnis[0])
2425                 strncpy(call->cid_rdnis, ast->cid.cid_rdnis,
2426                         sizeof(call->cid_rdnis)-1);
2427 #endif
2428
2429         ast_mutex_unlock(&chan_lock);
2430         return 0;
2431 }
2432
2433 static void send_digit_to_chan(struct ast_channel * ast, char digit )
2434 {
2435         static const char* dtmf_tones[] = {
2436                 "!941+1336/100,!0/100", /* 0 */
2437                 "!697+1209/100,!0/100", /* 1 */
2438                 "!697+1336/100,!0/100", /* 2 */
2439                 "!697+1477/100,!0/100", /* 3 */
2440                 "!770+1209/100,!0/100", /* 4 */
2441                 "!770+1336/100,!0/100", /* 5 */
2442                 "!770+1477/100,!0/100", /* 6 */
2443                 "!852+1209/100,!0/100", /* 7 */
2444                 "!852+1336/100,!0/100", /* 8 */
2445                 "!852+1477/100,!0/100", /* 9 */
2446                 "!697+1633/100,!0/100", /* A */
2447                 "!770+1633/100,!0/100", /* B */
2448                 "!852+1633/100,!0/100", /* C */
2449                 "!941+1633/100,!0/100", /* D */
2450                 "!941+1209/100,!0/100", /* * */
2451                 "!941+1477/100,!0/100" };       /* # */
2452
2453         if (digit >= '0' && digit <='9')
2454                 ast_playtones_start(ast,0,dtmf_tones[digit-'0'], 0);
2455         else if (digit >= 'A' && digit <= 'D')
2456                 ast_playtones_start(ast,0,dtmf_tones[digit-'A'+10], 0);
2457         else if (digit == '*')
2458                 ast_playtones_start(ast,0,dtmf_tones[14], 0);
2459         else if (digit == '#')
2460                 ast_playtones_start(ast,0,dtmf_tones[15], 0);
2461         else {
2462 #if ASTERISK_VERSION_NUM < 110000
2463                 CDEBUG(NULL, ast, "Unable to handle DTMF tone '%c' for '%s'\n", digit, ast->name);
2464 #else
2465                 CDEBUG(NULL, ast, "Unable to handle DTMF tone '%c' for '%s'\n", digit, ast_channel_name(ast));
2466 #endif
2467         }
2468 }
2469
2470 #ifdef LCR_FOR_ASTERISK
2471 static int lcr_digit_begin(struct ast_channel *ast, char digit)
2472 #endif
2473 #ifdef LCR_FOR_CALLWEAVER
2474 static int lcr_digit(struct ast_channel *ast, char digit)
2475 #endif
2476 {
2477         struct chan_call *call;
2478         union parameter newparam;
2479         char buf[]="x";
2480
2481 #ifdef LCR_FOR_CALLWEAVER
2482         int inband_dtmf = 0;
2483 #endif
2484
2485         /* only pass IA5 number space */
2486         if (digit > 126 || digit < 32)
2487                 return 0;
2488
2489         ast_mutex_lock(&chan_lock);
2490 #if ASTERISK_VERSION_NUM < 110000
2491         call = ast->tech_pvt;
2492 #else
2493         call = ast_channel_tech_pvt(ast);
2494 #endif
2495         if (!call) {
2496                 CERROR(NULL, ast, "Received digit from Asterisk, but no call instance exists.\n");
2497                 ast_mutex_unlock(&chan_lock);
2498                 return -1;
2499         }
2500
2501         CDEBUG(call, ast, "Received digit '%c' from Asterisk.\n", digit);
2502
2503         /* send information or queue them */
2504         if (call->ref && call->state == CHAN_LCR_STATE_OUT_DIALING) {
2505                 CDEBUG(call, ast, "Sending digit to LCR, because we are in dialing state.\n");
2506                 memset(&newparam, 0, sizeof(union parameter));
2507                 if (call->keypad) {
2508                         newparam.information.keypad[0] = digit;
2509                         newparam.information.keypad[1] = '\0';
2510                 } else {
2511                         newparam.information.id[0] = digit;
2512                         newparam.information.id[1] = '\0';
2513                 }
2514                 send_message(MESSAGE_INFORMATION, call->ref, &newparam);
2515         } else
2516         if (!call->ref
2517          && (call->state == CHAN_LCR_STATE_OUT_PREPARE || call->state == CHAN_LCR_STATE_OUT_SETUP)) {
2518                 CDEBUG(call, ast, "Queue digits, because we are in setup/dialing state and have no ref yet.\n");
2519                 *buf = digit;
2520                 strncat(call->dialque, buf, strlen(call->dialque)-1);
2521         }
2522
2523         ast_mutex_unlock(&chan_lock);
2524
2525 #ifdef LCR_FOR_ASTERISK
2526         return 0;
2527 }
2528
2529 static int lcr_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
2530 {
2531         int inband_dtmf = 0;
2532         struct chan_call *call;
2533 #endif
2534
2535         ast_mutex_lock(&chan_lock);
2536
2537 #if ASTERISK_VERSION_NUM < 110000
2538         call = ast->tech_pvt;
2539 #else
2540         call = ast_channel_tech_pvt(ast);
2541 #endif
2542
2543         if (!call) {
2544                 CERROR(NULL, ast,
2545                         "Received digit from Asterisk, "
2546                         "but no call instance exists.\n");
2547                 ast_mutex_unlock(&chan_lock);
2548                 return -1;
2549         }
2550
2551         CDEBUG(call, ast, "DIGIT END '%c' from Asterisk.\n", digit);
2552
2553         if (call->state == CHAN_LCR_STATE_CONNECT && call->inband_dtmf) {
2554                 inband_dtmf = 1;
2555         }
2556
2557         ast_mutex_unlock(&chan_lock);
2558
2559         if (inband_dtmf) {
2560                 CDEBUG(call, ast, "-> sending '%c' inband.\n", digit);
2561                 send_digit_to_chan(ast, digit);
2562         }
2563
2564         return 0;
2565 }
2566
2567 static int lcr_answer(struct ast_channel *ast)
2568 {
2569         union parameter newparam;
2570         struct chan_call *call;
2571
2572         ast_mutex_lock(&chan_lock);
2573 #if ASTERISK_VERSION_NUM < 110000
2574         call = ast->tech_pvt;
2575 #else
2576         call = ast_channel_tech_pvt(ast);
2577 #endif
2578         if (!call) {
2579                 CERROR(NULL, ast, "Received answer from Asterisk, but no call instance exists.\n");
2580                 ast_mutex_unlock(&chan_lock);
2581                 return -1;
2582         }
2583
2584         CDEBUG(call, ast, "Received answer from Asterisk (maybe during lcr_bridge).\n");
2585
2586         /* copy connectinfo, if bridged */
2587         if (call->bridge_call)
2588                 memcpy(&call->connectinfo, &call->bridge_call->connectinfo, sizeof(struct connect_info));
2589         /* send connect message to lcr */
2590         if (call->state != CHAN_LCR_STATE_CONNECT) {
2591                 memset(&newparam, 0, sizeof(union parameter));
2592                 memcpy(&newparam.connectinfo, &call->connectinfo, sizeof(struct connect_info));
2593                 send_message(MESSAGE_CONNECT, call->ref, &newparam);
2594                 call->state = CHAN_LCR_STATE_CONNECT;
2595         }
2596         /* change state */
2597         /* enable keypad */
2598 //      memset(&newparam, 0, sizeof(union parameter));
2599 //      send_message(MESSAGE_ENABLEKEYPAD, call->ref, &newparam);
2600
2601         ast_mutex_unlock(&chan_lock);
2602         return 0;
2603 }
2604
2605 static int lcr_hangup(struct ast_channel *ast)
2606 {
2607         struct chan_call *call;
2608         pthread_t tid = pthread_self();
2609
2610         if (!pthread_equal(tid, chan_tid)) {
2611                 ast_mutex_lock(&chan_lock);
2612         }
2613 #if ASTERISK_VERSION_NUM < 110000
2614         call = ast->tech_pvt;
2615 #else
2616         call = ast_channel_tech_pvt(ast);
2617 #endif
2618         if (!call) {
2619                 CERROR(NULL, ast, "Received hangup from Asterisk, but no call instance exists.\n");
2620                 if (!pthread_equal(tid, chan_tid)) {
2621                         ast_mutex_unlock(&chan_lock);
2622                 }
2623                 return -1;
2624         }
2625
2626         if (!pthread_equal(tid, chan_tid))
2627                 CDEBUG(call, ast, "Received hangup from Asterisk thread.\n");
2628         else
2629                 CDEBUG(call, ast, "Received hangup from LCR thread.\n");
2630
2631         /* disconnect asterisk, maybe not required */
2632 #if ASTERISK_VERSION_NUM < 110000
2633         ast->tech_pvt = NULL;
2634         ast->fds[0] = -1;
2635 #else
2636         ast_channel_tech_pvt_set(ast, NULL);
2637         ast_channel_set_fd(ast, 0, -1);
2638 #endif
2639         if (call->ref) {
2640                 /* release */
2641                 CDEBUG(call, ast, "Releasing ref and freeing call instance.\n");
2642 #if ASTERISK_VERSION_NUM < 110000
2643                 if (ast->hangupcause > 0)
2644                         send_release(call, ast->hangupcause, LOCATION_PRIVATE_LOCAL);
2645 #else
2646                 if (ast_channel_hangupcause(ast) > 0)
2647                         send_release(call, ast_channel_hangupcause(ast), LOCATION_PRIVATE_LOCAL);
2648 #endif
2649                 else
2650                         send_release(call, CAUSE_NORMAL, LOCATION_PRIVATE_LOCAL);
2651                 /* remove call */
2652                 free_call(call);
2653                 if (!pthread_equal(tid, chan_tid)) {
2654                         ast_mutex_unlock(&chan_lock);
2655                 }
2656                 return 0;
2657         } else {
2658                 /* ref is not set, due to prepare setup or release */
2659                 if (call->state == CHAN_LCR_STATE_RELEASE) {
2660                         /* we get the response to our release */
2661                         CDEBUG(call, ast, "Freeing call instance, because we have no ref AND we are requesting no ref.\n");
2662                         free_call(call);
2663                 } else {
2664                         /* during prepare, we change to release state */
2665                         CDEBUG(call, ast, "We must wait until we received our ref, until we can free call instance.\n");
2666                         call->state = CHAN_LCR_STATE_RELEASE;
2667                         call->ast = NULL;
2668                 }
2669         }
2670         if (!pthread_equal(tid, chan_tid)) {
2671                 ast_mutex_unlock(&chan_lock);
2672         }
2673         return 0;
2674 }
2675
2676 static int lcr_write(struct ast_channel *ast, struct ast_frame *fr)
2677 {
2678         union parameter newparam;
2679         struct chan_call *call;
2680         struct ast_frame * f = fr;
2681         unsigned char *p, *q;
2682         int len, l;
2683
2684 #if ASTERISK_VERSION_NUM < 100000
2685 #ifdef AST_1_8_OR_HIGHER
2686         if (!f->subclass.codec)
2687 #else
2688         if (!f->subclass)
2689 #endif
2690                 CDEBUG(NULL, ast, "No subclass\n");
2691 #endif
2692 #ifdef AST_1_8_OR_HIGHER
2693 #if ASTERISK_VERSION_NUM < 100000
2694 #if ASTERISK_VERSION_NUM < 110000
2695         if (!(f->subclass.codec & ast->nativeformats)) {
2696 #else
2697         if (!(f->subclass.codec & ast_channel_nativeformats(ast))) {
2698 #endif
2699 #else
2700 #if ASTERISK_VERSION_NUM < 110000
2701         if (!ast_format_cap_iscompatible(ast->nativeformats, &f->subclass.format)) {
2702 #else
2703         if (!ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &f->subclass.format)) {
2704 #endif
2705 #endif
2706 #else
2707 #if ASTERISK_VERSION_NUM < 110000
2708         if (!(f->subclass & ast->nativeformats)) {
2709 #else
2710         if (!(f->subclass & ast_channel_nativeformats(ast))) {
2711 #endif
2712 #endif
2713                 CDEBUG(NULL, ast,
2714                                "Unexpected format. "
2715                        "Activating emergency conversion...\n");
2716
2717 #ifdef AST_1_8_OR_HIGHER
2718 #if ASTERISK_VERSION_NUM < 100000
2719                 ast_set_write_format(ast, f->subclass.codec);
2720 #else
2721                 ast_set_write_format(ast, &f->subclass.format);
2722 #endif
2723 #else
2724                 ast_set_write_format(ast, f->subclass);
2725 #endif
2726 #if ASTERISK_VERSION_NUM < 110000
2727                 f = (ast->writetrans) ? ast_translate(
2728                         ast->writetrans, fr, 0) : fr;
2729 #else
2730                 f = (ast_channel_writetrans(ast)) ? ast_translate(
2731                         ast_channel_writetrans(ast), fr, 0) : fr;
2732 #endif
2733         }
2734
2735         ast_mutex_lock(&chan_lock);
2736 #if ASTERISK_VERSION_NUM < 110000
2737         call = ast->tech_pvt;
2738 #else
2739         call = ast_channel_tech_pvt(ast);
2740 #endif
2741         if (!call) {
2742                 ast_mutex_unlock(&chan_lock);
2743                 if (f != fr) {
2744                         ast_frfree(f);
2745                 }
2746                 return -1;
2747         }
2748         len = f->samples;
2749         p = *((unsigned char **)&(f->data));
2750         q = newparam.traffic.data;
2751         memset(&newparam, 0, sizeof(union parameter));
2752         while (len) {
2753                 l = (len > sizeof(newparam.traffic.data)) ? sizeof(newparam.traffic.data) : len;
2754                 newparam.traffic.len = l;
2755                 len -= l;
2756                 for (; l; l--)
2757                         *q++ = flip_bits[*p++];
2758                 send_message(MESSAGE_TRAFFIC, call->ref, &newparam);
2759         }
2760         ast_mutex_unlock(&chan_lock);
2761         if (f != fr) {
2762                 ast_frfree(f);
2763         }
2764         return 0;
2765 }
2766
2767
2768 static struct ast_frame *lcr_read(struct ast_channel *ast)
2769 {
2770         struct chan_call *call;
2771         int len = 0;
2772
2773         ast_mutex_lock(&chan_lock);
2774 #if ASTERISK_VERSION_NUM < 110000
2775         call = ast->tech_pvt;
2776 #else
2777         call = ast_channel_tech_pvt(ast);
2778 #endif
2779         if (!call) {
2780                 ast_mutex_unlock(&chan_lock);
2781                 return NULL;
2782         }
2783         if (call->pipe[0] > -1) {
2784                 if (call->rebuffer && !call->hdlc) {
2785                         /* Make sure we have a complete 20ms (160byte) frame */
2786                         len=read(call->pipe[0],call->read_buff + call->framepos, 160 - call->framepos);
2787                         if (len > 0) {
2788                                 call->framepos += len;
2789                         }
2790                 } else {
2791                         len = read(call->pipe[0], call->read_buff, sizeof(call->read_buff));
2792                 }
2793                 if (len < 0 && errno == EAGAIN) {
2794                         ast_mutex_unlock(&chan_lock);
2795
2796                         #ifdef LCR_FOR_ASTERISK
2797                         return &ast_null_frame;
2798                         #endif
2799
2800                         #ifdef LCR_FOR_CALLWEAVER
2801                         return &nullframe;
2802                         #endif
2803
2804                 }
2805                 if (len <= 0) {
2806                         close(call->pipe[0]);
2807                         call->pipe[0] = -1;
2808                         global_change = 1;
2809                         ast_mutex_unlock(&chan_lock);
2810                         return NULL;
2811                 } else if (call->rebuffer && call->framepos < 160) {
2812                         /* Not a complete frame, so we send a null-frame */
2813                         ast_mutex_unlock(&chan_lock);
2814                         return &ast_null_frame;
2815                 }
2816         }
2817
2818         call->read_fr.frametype = AST_FRAME_VOICE;
2819 #ifdef AST_1_8_OR_HIGHER
2820 #if ASTERISK_VERSION_NUM < 100000
2821 #if ASTERISK_VERSION_NUM < 110000
2822         call->read_fr.subclass.codec = ast->nativeformats;
2823 #else
2824         call->read_fr.subclass.codec = ast_channel_nativeformats(ast);
2825 #endif
2826 #else
2827 #if ASTERISK_VERSION_NUM < 110000
2828         ast_best_codec(ast->nativeformats, &call->read_fr.subclass.format);
2829 #else
2830         ast_best_codec(ast_channel_nativeformats(ast), &call->read_fr.subclass.format);
2831 #endif
2832         call->read_fr.subclass.integer = call->read_fr.subclass.format.id;
2833 #endif
2834 #else
2835 #if ASTERISK_VERSION_NUM < 110000
2836         call->read_fr.subclass = ast->nativeformats;
2837 #else
2838         call->read_fr.subclass = ast_channel_nativeformats(ast);
2839 #endif
2840 #endif
2841         if (call->rebuffer) {
2842                 call->read_fr.datalen = call->framepos;
2843                 call->read_fr.samples = call->framepos;
2844                 call->framepos = 0;
2845         } else {
2846                 call->read_fr.datalen = len;
2847                 call->read_fr.samples = len;
2848         }
2849         call->read_fr.delivery = ast_tv(0,0);
2850         *((unsigned char **)&(call->read_fr.data)) = call->read_buff;
2851         ast_mutex_unlock(&chan_lock);
2852
2853         return &call->read_fr;
2854 }
2855
2856 static int lcr_indicate(struct ast_channel *ast, int cond, const void *data, size_t datalen)
2857 {
2858         union parameter newparam;
2859         int res = 0;
2860         struct chan_call *call;
2861         const struct ast_tone_zone_sound *ts = NULL;
2862
2863         ast_mutex_lock(&chan_lock);
2864 #if ASTERISK_VERSION_NUM < 110000
2865         call = ast->tech_pvt;
2866 #else
2867         call = ast_channel_tech_pvt(ast);
2868 #endif
2869         if (!call) {
2870                 CERROR(NULL, ast, "Received indicate from Asterisk, but no call instance exists.\n");
2871                 ast_mutex_unlock(&chan_lock);
2872                 return -1;
2873         }
2874
2875         switch (cond) {
2876                 case AST_CONTROL_BUSY:
2877                         CDEBUG(call, ast, "Received indicate AST_CONTROL_BUSY from Asterisk.\n");
2878                         ast_setstate(ast, AST_STATE_BUSY);
2879                         if (call->state != CHAN_LCR_STATE_OUT_DISCONNECT) {
2880                                 /* send message to lcr */
2881                                 memset(&newparam, 0, sizeof(union parameter));
2882                                 newparam.disconnectinfo.cause = 17;
2883                                 newparam.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
2884                                 send_message(MESSAGE_DISCONNECT, call->ref, &newparam);
2885                                 /* change state */
2886                                 call->state = CHAN_LCR_STATE_OUT_DISCONNECT;
2887                         } else {
2888                                 CDEBUG(call, ast, "Using Asterisk 'busy' indication\n");
2889 #if ASTERISK_VERSION_NUM < 110000
2890                                 ts = ast_get_indication_tone(ast->zone, "busy");
2891 #else
2892                                 ts = ast_get_indication_tone(ast_channel_zone(ast), "busy");
2893 #endif
2894                         }
2895                         break;
2896                 case AST_CONTROL_CONGESTION:
2897 #if ASTERISK_VERSION_NUM < 110000
2898                         CDEBUG(call, ast, "Received indicate AST_CONTROL_CONGESTION from Asterisk. (cause %d)\n", ast->hangupcause);
2899 #else
2900                         CDEBUG(call, ast, "Received indicate AST_CONTROL_CONGESTION from Asterisk. (cause %d)\n", ast_channel_hangupcause(ast));
2901 #endif
2902                         if (call->state != CHAN_LCR_STATE_OUT_DISCONNECT) {
2903                                 /* send message to lcr */
2904                                 memset(&newparam, 0, sizeof(union parameter));
2905 #if ASTERISK_VERSION_NUM < 110000
2906                                 newparam.disconnectinfo.cause = ast->hangupcause;
2907 #else
2908                                 newparam.disconnectinfo.cause = ast_channel_hangupcause(ast);
2909 #endif
2910                                 newparam.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
2911                                 send_message(MESSAGE_DISCONNECT, call->ref, &newparam);
2912                                 /* change state */
2913                                 call->state = CHAN_LCR_STATE_OUT_DISCONNECT;
2914                         } else {
2915                                 CDEBUG(call, ast, "Using Asterisk 'congestion' indication\n");
2916 #if ASTERISK_VERSION_NUM < 110000
2917                                 ts = ast_get_indication_tone(ast->zone, "congestion");
2918 #else
2919                                 ts = ast_get_indication_tone(ast_channel_zone(ast), "congestion");
2920 #endif
2921                         }
2922                         break;
2923                 case AST_CONTROL_PROCEEDING:
2924                         CDEBUG(call, ast, "Received indicate AST_CONTROL_PROCEEDING from Asterisk.\n");
2925                         if (call->state == CHAN_LCR_STATE_IN_SETUP
2926                          || call->state == CHAN_LCR_STATE_IN_DIALING) {
2927                                 /* send message to lcr */
2928                                 memset(&newparam, 0, sizeof(union parameter));
2929                                 send_message(MESSAGE_PROCEEDING, call->ref, &newparam);
2930                                 /* change state */
2931                                 call->state = CHAN_LCR_STATE_IN_PROCEEDING;
2932                         }
2933                         break;
2934                 case AST_CONTROL_RINGING:
2935                         CDEBUG(call, ast, "Received indicate AST_CONTROL_RINGING from Asterisk.\n");
2936                         ast_setstate(ast, AST_STATE_RING);
2937                         if (call->state == CHAN_LCR_STATE_IN_SETUP
2938                          || call->state == CHAN_LCR_STATE_IN_DIALING
2939                          || call->state == CHAN_LCR_STATE_IN_PROCEEDING) {
2940                                 /* send message to lcr */
2941                                 memset(&newparam, 0, sizeof(union parameter));
2942                                 send_message(MESSAGE_ALERTING, call->ref, &newparam);
2943                                 /* change state */
2944                                 call->state = CHAN_LCR_STATE_IN_ALERTING;
2945                         } else {
2946                                 CDEBUG(call, ast, "Using Asterisk 'ring' indication\n");
2947 #if ASTERISK_VERSION_NUM < 110000
2948                                 ts = ast_get_indication_tone(ast->zone, "ring");
2949 #else
2950                                 ts = ast_get_indication_tone(ast_channel_zone(ast), "ring");
2951 #endif
2952                         }
2953                         break;
2954                 case AST_CONTROL_PROGRESS:
2955                         CDEBUG(call, ast, "Received indicate AST_CONTROL_PROGRESS from Asterisk.\n");
2956                         /* request bchannel */
2957                         CDEBUG(call, ast, "Requesting audio path.\n");
2958                         memset(&newparam, 0, sizeof(union parameter));
2959                         send_message(MESSAGE_AUDIOPATH, call->ref, &newparam);
2960                         break;
2961                 case -1:
2962                         CDEBUG(call, ast, "Received indicate -1.\n");
2963                         ast_playtones_stop(ast);
2964                         res = -1;
2965                         break;
2966
2967                 case AST_CONTROL_VIDUPDATE:
2968                         CDEBUG(call, ast, "Received indicate AST_CONTROL_VIDUPDATE.\n");
2969                         res = -1;
2970                         break;
2971                 case AST_CONTROL_HOLD:
2972                         CDEBUG(call, ast, "Received indicate AST_CONTROL_HOLD from Asterisk.\n");
2973                         /* send message to lcr */
2974                         memset(&newparam, 0, sizeof(union parameter));
2975                         newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_HOLD;
2976                         send_message(MESSAGE_NOTIFY, call->ref, &newparam);
2977
2978                         /*start music onhold*/
2979                         #ifdef LCR_FOR_ASTERISK
2980                         #if ASTERISK_VERSION_NUM <110000
2981                         ast_moh_start(ast,data,ast->musicclass);
2982                         #else
2983                         ast_moh_start(ast,data,ast_channel_musicclass(ast));
2984                         #endif
2985                         #endif
2986
2987                         #ifdef LCR_FOR_CALLWEAVER
2988                         ast_moh_start(ast, NULL);
2989                         #endif
2990
2991                         call->on_hold = 1;
2992                         break;
2993                 case AST_CONTROL_UNHOLD:
2994                         CDEBUG(call, ast, "Received indicate AST_CONTROL_UNHOLD from Asterisk.\n");
2995                         /* send message to lcr */
2996                         memset(&newparam, 0, sizeof(union parameter));
2997                         newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_RETRIEVAL;
2998                         send_message(MESSAGE_NOTIFY, call->ref, &newparam);
2999
3000                         /*stop moh*/
3001                         ast_moh_stop(ast);
3002                         call->on_hold = 0;
3003                         break;
3004 #ifdef AST_CONTROL_SRCUPDATE
3005                 case AST_CONTROL_SRCUPDATE:
3006 #else
3007                 case 20:
3008 #endif
3009                         CDEBUG(call, ast, "Received AST_CONTROL_SRCUPDATE from Asterisk.\n");
3010                         break;
3011                 default:
3012                         CERROR(call, ast, "Received indicate from Asterisk with unknown condition %d.\n", cond);
3013                         res = -1;
3014                         break;
3015         }
3016
3017         if (ts && ts->data[0]) {
3018                 ast_playtones_start(ast, 0, ts->data, 1);
3019         }
3020
3021         /* return */
3022         ast_mutex_unlock(&chan_lock);
3023         return res;
3024 }
3025
3026 /*
3027  * fixup asterisk
3028  */
3029 static int lcr_fixup(struct ast_channel *oldast, struct ast_channel *ast)
3030 {
3031         struct chan_call *call;
3032
3033         if (!ast) {
3034                 return -1;
3035         }
3036
3037         ast_mutex_lock(&chan_lock);
3038 #if ASTERISK_VERSION_NUM < 110000
3039         call = ast->tech_pvt;
3040 #else
3041         call = ast_channel_tech_pvt(ast);
3042 #endif
3043         if (!call) {
3044                 CERROR(NULL, ast, "Received fixup from Asterisk, but no call instance exists.\n");
3045                 ast_mutex_unlock(&chan_lock);
3046                 return -1;
3047         }
3048
3049         CDEBUG(call, ast, "Received fixup from Asterisk.\n");
3050         call->ast = ast;
3051         ast_mutex_unlock(&chan_lock);
3052         return 0;
3053 }
3054
3055 /*
3056  * send_text asterisk
3057  */
3058 static int lcr_send_text(struct ast_channel *ast, const char *text)
3059 {
3060         struct chan_call *call;
3061         union parameter newparam;
3062
3063         ast_mutex_lock(&chan_lock);
3064 #if ASTERISK_VERSION_NUM < 110000
3065         call = ast->tech_pvt;
3066 #else
3067         call = ast_channel_tech_pvt(ast);
3068 #endif
3069         if (!call) {
3070                 CERROR(NULL, ast, "Received send_text from Asterisk, but no call instance exists.\n");
3071                 ast_mutex_unlock(&chan_lock);
3072                 return -1;
3073         }
3074
3075         CDEBUG(call, ast, "Received send_text from Asterisk. (text=%s)\n", text);
3076         memset(&newparam, 0, sizeof(union parameter));
3077         strncpy(newparam.notifyinfo.display, text, sizeof(newparam.notifyinfo.display)-1);
3078         send_message(MESSAGE_NOTIFY, call->ref, &newparam);
3079         ast_mutex_unlock(&chan_lock);
3080         return 0;
3081 }
3082
3083 /*
3084  * bridge process
3085  */
3086 enum ast_bridge_result lcr_bridge(struct ast_channel *ast1,
3087                                   struct ast_channel *ast2, int flags,
3088                                   struct ast_frame **fo,
3089                                   struct ast_channel **rc, int timeoutms)
3090
3091 {
3092         struct chan_call        *call1, *call2;
3093         struct ast_channel      *carr[2], *who;
3094         int                     to;
3095         struct ast_frame        *f;
3096         int                     bridge_id;
3097
3098         CDEBUG(NULL, NULL, "Received bridging request from Asterisk.\n");
3099
3100         carr[0] = ast1;
3101         carr[1] = ast2;
3102
3103         /* join via dsp (if the channels are currently open) */
3104         ast_mutex_lock(&chan_lock);
3105 #if ASTERISK_VERSION_NUM < 110000
3106         call1 = ast1->tech_pvt;
3107         call2 = ast2->tech_pvt;
3108 #else
3109         call1 = ast_channel_tech_pvt(ast1);
3110         call2 = ast_channel_tech_pvt(ast2);
3111 #endif
3112         if (!call1 || !call2) {
3113                 CDEBUG(NULL, NULL, "Bridge, but we don't have two call instances, exitting.\n");
3114                 ast_mutex_unlock(&chan_lock);
3115                 return AST_BRIDGE_COMPLETE;
3116         }
3117
3118         /* join, if both call instances uses dsp
3119            ignore the case of fax detection here it may be benificial for ISDN fax machines or pass through.
3120         */
3121         CDEBUG(NULL, NULL, "Both calls use DSP, bridging via DSP.\n");
3122
3123         /* get bridge id and join */
3124         bridge_id = new_bridge_id();
3125
3126 #if 0
3127         call1->bridge_id = bridge_id;
3128         if (call1->bchannel)
3129                 bchannel_join(call1->bchannel, bridge_id);
3130
3131         call2->bridge_id = bridge_id;
3132         if (call2->bchannel)
3133                 bchannel_join(call2->bchannel, bridge_id);
3134 #else
3135         printf("FIXME");
3136         exit(0);
3137 #endif
3138
3139         call1->bridge_call = call2;
3140         call2->bridge_call = call1;
3141
3142         if (call1->state == CHAN_LCR_STATE_IN_SETUP
3143          || call1->state == CHAN_LCR_STATE_IN_DIALING
3144          || call1->state == CHAN_LCR_STATE_IN_PROCEEDING
3145          || call1->state == CHAN_LCR_STATE_IN_ALERTING) {
3146                 CDEBUG(call1, ast1, "Bridge established before lcr_answer, so we call it ourself: Calling lcr_answer...\n");
3147                 lcr_answer(ast1);
3148         }
3149         if (call2->state == CHAN_LCR_STATE_IN_SETUP
3150          || call2->state == CHAN_LCR_STATE_IN_DIALING
3151          || call2->state == CHAN_LCR_STATE_IN_PROCEEDING
3152          || call2->state == CHAN_LCR_STATE_IN_ALERTING) {
3153                 CDEBUG(call2, ast2, "Bridge established before lcr_answer, so we call it ourself: Calling lcr_answer...\n");
3154                 lcr_answer(ast2);
3155         }
3156
3157         /* sometimes SIP phones forget to send RETRIEVE before TRANSFER
3158            so let's do it for them. Hmpf.
3159         */
3160
3161         if (call1->on_hold) {
3162                 union parameter newparam;
3163
3164                 memset(&newparam, 0, sizeof(union parameter));
3165                 newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_RETRIEVAL;
3166                 send_message(MESSAGE_NOTIFY, call1->ref, &newparam);
3167
3168                 call1->on_hold = 0;
3169         }
3170
3171         if (call2->on_hold) {
3172                 union parameter newparam;
3173
3174                 memset(&newparam, 0, sizeof(union parameter));
3175                 newparam.notifyinfo.notify = INFO_NOTIFY_REMOTE_RETRIEVAL;
3176                 send_message(MESSAGE_NOTIFY, call2->ref, &newparam);
3177
3178                 call2->on_hold = 0;
3179         }
3180
3181         ast_mutex_unlock(&chan_lock);
3182
3183         while(1) {
3184                 to = -1;
3185                 who = ast_waitfor_n(carr, 2, &to);
3186
3187                 if (!who) {
3188                         CDEBUG(NULL, NULL, "Empty read on bridge, breaking out.\n");
3189                         break;
3190                 }
3191                 f = ast_read(who);
3192
3193                 if (!f || f->frametype == AST_FRAME_CONTROL) {
3194                         if (!f)
3195                                 CDEBUG(NULL, NULL, "Got hangup.\n");
3196                         else
3197                                 CDEBUG(NULL, NULL, "Got CONTROL.\n");
3198                         /* got hangup .. */
3199                         *fo=f;
3200                         *rc=who;
3201                         break;
3202                 }
3203
3204                 if ( f->frametype == AST_FRAME_DTMF ) {
3205                         CDEBUG(NULL, NULL, "Got DTMF.\n");
3206                         *fo=f;
3207                         *rc=who;
3208                         break;
3209                 }
3210
3211
3212                 if (who == ast1) {
3213                         ast_write(ast2,f);
3214                 }
3215                 else {
3216                         ast_write(ast1,f);
3217                 }
3218
3219         }
3220
3221         CDEBUG(NULL, NULL, "Releasing bridge.\n");
3222
3223         /* split channels */
3224         ast_mutex_lock(&chan_lock);
3225 #if ASTERISK_VERSION_NUM < 110000
3226         call1 = ast1->tech_pvt;
3227         call2 = ast2->tech_pvt;
3228 #else
3229         call1 = ast_channel_tech_pvt(ast1);
3230         call2 = ast_channel_tech_pvt(ast2);
3231 #endif
3232         if (call1 && call1->bridge_id) {
3233                 call1->bridge_id = 0;
3234                 if (call1->bridge_call)
3235                         call1->bridge_call->bridge_call = NULL;
3236         }
3237         if (call2 && call1->bridge_id) {
3238                 call2->bridge_id = 0;
3239                 if (call2->bridge_call)
3240                         call2->bridge_call->bridge_call = NULL;
3241         }
3242         call1->bridge_call = NULL;
3243         call2->bridge_call = NULL;
3244
3245         ast_mutex_unlock(&chan_lock);
3246         return AST_BRIDGE_COMPLETE;
3247 }
3248 static struct ast_channel_tech lcr_tech = {
3249         .type= lcr_type,
3250         .description = "Channel driver for connecting to Linux-Call-Router",
3251         #if ASTERISK_VERSION_NUM < 100000
3252         .capabilities = AST_FORMAT_ALAW,
3253         #endif
3254         .requester = lcr_request,
3255
3256         #ifdef LCR_FOR_ASTERISK
3257         .send_digit_begin = lcr_digit_begin,
3258         .send_digit_end = lcr_digit_end,
3259         #endif
3260
3261         #ifdef LCR_FOR_CALLWEAVER
3262         .send_digit = lcr_digit,
3263         #endif
3264
3265         .call = lcr_call,
3266         .bridge = lcr_bridge,
3267         .hangup = lcr_hangup,
3268         .answer = lcr_answer,
3269         .read = lcr_read,
3270         .write = lcr_write,
3271         .indicate = lcr_indicate,
3272         .fixup = lcr_fixup,
3273         .send_text = lcr_send_text,
3274         .properties = 0
3275 };
3276
3277
3278 /*
3279  * cli
3280  */
3281 #if 0
3282 static int lcr_show_lcr (int fd, int argc, char *argv[])
3283 {
3284         return 0;
3285 }
3286
3287 static int lcr_show_calls (int fd, int argc, char *argv[])
3288 {
3289         return 0;
3290 }
3291
3292 static int lcr_reload_routing (int fd, int argc, char *argv[])
3293 {
3294         return 0;
3295 }
3296
3297 static int lcr_reload_interfaces (int fd, int argc, char *argv[])
3298 {
3299         return 0;
3300 }
3301
3302 static int lcr_port_block (int fd, int argc, char *argv[])
3303 {
3304         return 0;
3305 }
3306
3307 static int lcr_port_unblock (int fd, int argc, char *argv[])
3308 {
3309         return 0;
3310 }
3311
3312 static int lcr_port_unload (int fd, int argc, char *argv[])
3313 {
3314         return 0;
3315 }
3316
3317 static struct ast_cli_entry cli_show_lcr =
3318 { {"lcr", "show", "lcr", NULL},
3319  lcr_show_lcr,
3320  "Shows current states of LCR core",
3321  "Usage: lcr show lcr\n",
3322 };
3323
3324 static struct ast_cli_entry cli_show_calls =
3325 { {"lcr", "show", "calls", NULL},
3326  lcr_show_calls,
3327  "Shows current calls made by LCR and Asterisk",
3328  "Usage: lcr show calls\n",
3329 };
3330
3331 static struct ast_cli_entry cli_reload_routing =
3332 { {"lcr", "reload", "routing", NULL},
3333  lcr_reload_routing,
3334  "Reloads routing conf of LCR, current uncomplete calls will be disconnected",
3335  "Usage: lcr reload routing\n",
3336 };
3337
3338 static struct ast_cli_entry cli_reload_interfaces =
3339 { {"lcr", "reload", "interfaces", NULL},
3340  lcr_reload_interfaces,
3341  "Reloads interfaces conf of LCR",
3342  "Usage: lcr reload interfaces\n",
3343 };
3344
3345 static struct ast_cli_entry cli_port_block =
3346 { {"lcr", "port", "block", NULL},
3347  lcr_port_block,
3348  "Blocks LCR port for further calls",
3349  "Usage: lcr port block \"<port>\"\n",
3350 };
3351
3352 static struct ast_cli_entry cli_port_unblock =
3353 { {"lcr", "port", "unblock", NULL},
3354  lcr_port_unblock,
3355  "Unblocks or loads LCR port, port is opened my mISDN",
3356  "Usage: lcr port unblock \"<port>\"\n",
3357 };
3358
3359 static struct ast_cli_entry cli_port_unload =
3360 { {"lcr", "port", "unload", NULL},
3361  lcr_port_unload,