Fixed detection of dtmfs with bridged channels.
[asterisk/asterisk.git] / channels / chan_misdn.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  * 
4  * Copyright (C) 2004 - 2006, Christian Richter
5  *
6  * Christian Richter <crich@beronet.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  *
18  */
19
20 /*!
21  * \file
22  *
23  * \brief the chan_misdn channel driver for Asterisk
24  * \author Christian Richter <crich@beronet.com>
25  *
26  * \ingroup channel_drivers
27  */
28
29 #include "asterisk.h"
30
31 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
32
33 #include <stdio.h>
34 #include <pthread.h>
35 #include <string.h>
36 #include <sys/socket.h>
37 #include <sys/time.h>
38 #include <errno.h>
39 #include <unistd.h>
40 #include <stdlib.h>
41 #include <arpa/inet.h>
42 #include <fcntl.h>
43 #include <sys/ioctl.h>
44 #include <sys/file.h>
45
46 #include "asterisk/channel.h"
47 #include "asterisk/config.h"
48 #include "asterisk/logger.h"
49 #include "asterisk/module.h"
50 #include "asterisk/pbx.h"
51 #include "asterisk/options.h"
52 #include "asterisk/io.h"
53 #include "asterisk/frame.h"
54 #include "asterisk/translate.h"
55 #include "asterisk/cli.h"
56 #include "asterisk/musiconhold.h"
57 #include "asterisk/dsp.h"
58 #include "asterisk/translate.h"
59 #include "asterisk/config.h"
60 #include "asterisk/file.h"
61 #include "asterisk/callerid.h"
62 #include "asterisk/indications.h"
63 #include "asterisk/app.h"
64 #include "asterisk/features.h"
65 #include "asterisk/stringfields.h"
66
67 #include "chan_misdn_config.h"
68 #include "isdn_lib.h"
69
70 ast_mutex_t release_lock_mutex;
71
72 #define release_lock ast_mutex_lock(&release_lock_mutex)
73 #define release_unlock ast_mutex_unlock(&release_lock_mutex)
74
75
76 char global_tracefile[BUFFERSIZE+1];
77
78
79 struct misdn_jb{
80         int size;
81         int upper_threshold;
82         char *samples, *ok;
83         int wp,rp;
84         int state_empty;
85         int state_full;
86         int state_buffer;
87         int bytes_wrote;
88         ast_mutex_t mutexjb;
89 };
90
91 void export_ies(struct ast_channel *chan, struct misdn_bchannel *bc);
92 void import_ies(struct ast_channel *chan, struct misdn_bchannel *bc);
93
94
95 /* allocates the jb-structure and initialise the elements*/
96 struct misdn_jb *misdn_jb_init(int size, int upper_threshold);
97
98 /* frees the data and destroys the given jitterbuffer struct */
99 void misdn_jb_destroy(struct misdn_jb *jb);
100
101 /* fills the jitterbuffer with len data returns < 0 if there was an
102 error (bufferoverun). */
103 int misdn_jb_fill(struct misdn_jb *jb, const char *data, int len);
104
105 /* gets len bytes out of the jitterbuffer if available, else only the
106 available data is returned and the return value indicates the number
107 of data. */
108 int misdn_jb_empty(struct misdn_jb *jb, char *data, int len);
109
110
111
112
113 /* BEGIN: chan_misdn.h */
114
115
116 enum tone_e {
117         TONE_NONE=0,
118         TONE_DIAL,
119         TONE_ALERTING,
120         TONE_FAR_ALERTING,
121         TONE_BUSY,
122         TONE_CUSTOM,
123         TONE_FILE
124 };
125
126
127 enum misdn_chan_state {
128         MISDN_NOTHING,          /*!< at beginning */
129         MISDN_WAITING4DIGS, /*!<  when waiting for infos */
130         MISDN_EXTCANTMATCH, /*!<  when asterisk couldnt match our ext */
131         MISDN_DIALING, /*!<  when pbx_start */
132         MISDN_PROGRESS, /*!<  we got a progress */
133         MISDN_PROCEEDING, /*!<  we got a progress */
134         MISDN_CALLING, /*!<  when misdn_call is called */
135         MISDN_CALLING_ACKNOWLEDGE, /*!<  when we get SETUP_ACK */
136         MISDN_ALERTING, /*!<  when Alerting */
137         MISDN_BUSY, /*!<  when BUSY */
138         MISDN_CONNECTED, /*!<  when connected */
139         MISDN_PRECONNECTED, /*!<  when connected */
140         MISDN_DISCONNECTED, /*!<  when connected */
141         MISDN_BRIDGED, /*!<  when bridged */
142         MISDN_CLEANING, /*!< when hangup from * but we were connected before */
143         MISDN_HUNGUP_FROM_MISDN, /*!< when DISCONNECT/RELEASE/REL_COMP  cam from misdn */
144         MISDN_HUNGUP_FROM_AST, /*!< when DISCONNECT/RELEASE/REL_COMP came out of */
145         /* misdn_hangup */
146         MISDN_HOLDED, /*!< if this chan is holded */
147         MISDN_HOLD_DISCONNECT /*!< if this chan is holded */
148   
149 };
150
151 #define ORG_AST 1
152 #define ORG_MISDN 2
153
154 struct chan_list {
155   
156         ast_mutex_t lock;
157
158         char allowed_bearers[BUFFERSIZE+1];
159         
160         enum misdn_chan_state state;
161         int holded; 
162         int orginator;
163
164         int norxtone;
165         int notxtone; 
166         
167         int incoming_early_audio;
168
169         int ignore_dtmf;
170
171         int pipe[2];
172         char ast_rd_buf[4096];
173         struct ast_frame frame;
174
175         int faxdetect;
176         int faxhandled;
177
178         int ast_dsp;
179
180         int jb_len;
181         int jb_upper_threshold;
182         struct misdn_jb *jb;
183         
184         struct ast_dsp *dsp;
185         struct ast_trans_pvt *trans;
186   
187         struct ast_channel * ast;
188   
189         struct misdn_bchannel *bc;
190         struct misdn_bchannel *holded_bc;
191
192         unsigned int l3id;
193         int addr;
194
195         char context[BUFFERSIZE];
196
197         int zero_read_cnt;
198         int dropped_frame_cnt;
199
200         int far_alerting;
201
202         const struct tone_zone_sound *ts;
203         
204         struct chan_list *peer;
205         struct chan_list *next;
206         struct chan_list *prev;
207         struct chan_list *first;
208 };
209
210 struct robin_list {
211         char *group;
212         int port;
213         int channel;
214         struct robin_list *next;
215         struct robin_list *prev;
216 };
217 static struct robin_list *robin = NULL;
218
219
220
221 struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame *frame);
222
223
224
225 static inline void free_robin_list_r (struct robin_list *r)
226 {
227         if (r) {
228                 if (r->next) free_robin_list_r(r->next);
229                 if (r->group) free(r->group);
230                 free(r);
231         }
232 }
233
234 static void free_robin_list ( void )
235 {
236         free_robin_list_r(robin);
237         robin = NULL;
238 }
239
240 static struct robin_list* get_robin_position (char *group) 
241 {
242         struct robin_list *iter = robin;
243         for (; iter; iter = iter->next) {
244                 if (!strcasecmp(iter->group, group))
245                         return iter;
246         }
247         struct robin_list *new = (struct robin_list *)calloc(1, sizeof(struct robin_list));
248         new->group = strndup(group, strlen(group));
249         new->channel = 1;
250         if (robin) {
251                 new->next = robin;
252                 robin->prev = new;
253         }
254         robin = new;
255         return robin;
256 }
257
258
259 static void chan_misdn_log(int level, int port, char *tmpl, ...);
260
261 static struct ast_channel *misdn_new(struct chan_list *cl, int state,  char *exten, char *callerid, int format, int port, int c);
262 static void send_digit_to_chan(struct chan_list *cl, char digit );
263
264
265 #define AST_CID_P(ast) ast->cid.cid_num
266 #define AST_BRIDGED_P(ast) ast_bridged_channel(ast) 
267 #define AST_LOAD_CFG ast_config_load
268 #define AST_DESTROY_CFG ast_config_destroy
269
270 #define MISDN_ASTERISK_TECH_PVT(ast) ast->tech_pvt
271 #define MISDN_ASTERISK_PVT(ast) 1
272
273 #include <asterisk/strings.h>
274
275 /* #define MISDN_DEBUG 1 */
276
277 static char *desc = "Channel driver for mISDN Support (Bri/Pri)";
278 static const char misdn_type[] = "mISDN";
279
280 static int tracing = 0 ;
281
282 static char **misdn_key_vector=NULL;
283 static int misdn_key_vector_size=0;
284
285 /* Only alaw and mulaw is allowed for now */
286 static int prefformat =  AST_FORMAT_ALAW ; /*  AST_FORMAT_SLINEAR ;  AST_FORMAT_ULAW | */
287
288 static int *misdn_debug;
289 static int *misdn_debug_only;
290 static int max_ports;
291
292 static int *misdn_in_calls;
293 static int *misdn_out_calls;
294
295
296 struct chan_list dummy_cl;
297
298 struct chan_list *cl_te=NULL;
299 ast_mutex_t cl_te_lock;
300
301 static enum event_response_e
302 cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data);
303
304 static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc);
305
306 static void cl_queue_chan(struct chan_list **list, struct chan_list *chan);
307 static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan);
308 static struct chan_list *find_chan_by_bc(struct chan_list *list, struct misdn_bchannel *bc);
309
310
311
312
313 static int tone_indicate( struct chan_list *cl, enum tone_e tone);
314
315 static int start_bc_tones(struct chan_list *cl);
316 static int stop_bc_tones(struct chan_list *cl);
317 static void release_chan(struct misdn_bchannel *bc);
318
319 static int misdn_set_opt_exec(struct ast_channel *chan, void *data);
320 static int misdn_facility_exec(struct ast_channel *chan, void *data);
321
322 int chan_misdn_jb_empty(struct misdn_bchannel *bc, char *buf, int len);
323
324
325 void debug_numplan(int port, int numplan, char *type);
326
327
328 int add_out_calls(int port);
329 int add_in_calls(int port);
330
331
332 /*************** Helpers *****************/
333
334 static struct chan_list * get_chan_by_ast(struct ast_channel *ast)
335 {
336         struct chan_list *tmp;
337   
338         for (tmp=cl_te; tmp; tmp = tmp->next) {
339                 if ( tmp->ast == ast ) return tmp;
340         }
341   
342         return NULL;
343 }
344
345 static struct chan_list * get_chan_by_ast_name(char *name)
346 {
347         struct chan_list *tmp;
348   
349         for (tmp=cl_te; tmp; tmp = tmp->next) {
350                 if ( tmp->ast  && strcmp(tmp->ast->name,name) == 0) return tmp;
351         }
352   
353         return NULL;
354 }
355
356
357
358 struct allowed_bearers {
359         int cap;
360         int val;
361         char *name;
362 };
363
364 struct allowed_bearers allowed_bearers_array[]={
365         {INFO_CAPABILITY_SPEECH,1,"speech"},
366         {INFO_CAPABILITY_AUDIO_3_1K,2,"3_1khz"},
367         {INFO_CAPABILITY_DIGITAL_UNRESTRICTED,4,"digital_unrestricted"},
368         {INFO_CAPABILITY_DIGITAL_RESTRICTED,8,"digital_restriced"},
369         {INFO_CAPABILITY_VIDEO,16,"video"}
370 };
371
372 static char *bearer2str(int cap) {
373         static char *bearers[]={
374                 "Speech",
375                 "Audio 3.1k",
376                 "Unres Digital",
377                 "Res Digital",
378                 "Video",
379                 "Unknown Bearer"
380         };
381         
382         switch (cap) {
383         case INFO_CAPABILITY_SPEECH:
384                 return bearers[0];
385                 break;
386         case INFO_CAPABILITY_AUDIO_3_1K:
387                 return bearers[1];
388                 break;
389         case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
390                 return bearers[2];
391                 break;
392         case INFO_CAPABILITY_DIGITAL_RESTRICTED:
393                 return bearers[3];
394                 break;
395         case INFO_CAPABILITY_VIDEO:
396                 return bearers[4];
397                 break;
398         default:
399                 return bearers[5];
400                 break;
401         }
402 }
403
404
405 static void print_facility( struct misdn_bchannel *bc)
406 {
407         switch (bc->fac_type) {
408         case FACILITY_CALLDEFLECT:
409                 chan_misdn_log(2,bc->port," --> calldeflect: %s\n",
410                                bc->fac.calldeflect_nr);
411                 break;
412         case FACILITY_CENTREX:
413                 chan_misdn_log(2,bc->port," --> centrex: %s\n",
414                                bc->fac.cnip);
415                 break;
416         default:
417                 chan_misdn_log(2,bc->port," --> unknown\n");
418                 
419         }
420 }
421
422 static void print_bearer(struct misdn_bchannel *bc) 
423 {
424         
425         chan_misdn_log(2, bc->port, " --> Bearer: %s\n",bearer2str(bc->capability));
426         
427         switch(bc->law) {
428         case INFO_CODEC_ALAW:
429                 chan_misdn_log(2, bc->port, " --> Codec: Alaw\n");
430                 break;
431         case INFO_CODEC_ULAW:
432                 chan_misdn_log(2, bc->port, " --> Codec: Ulaw\n");
433                 break;
434         }
435 }
436 /*************** Helpers END *************/
437
438 static void send_digit_to_chan(struct chan_list *cl, char digit )
439 {
440         static const char* dtmf_tones[] = {
441                 "!941+1336/100,!0/100", /* 0 */
442                 "!697+1209/100,!0/100", /* 1 */
443                 "!697+1336/100,!0/100", /* 2 */
444                 "!697+1477/100,!0/100", /* 3 */
445                 "!770+1209/100,!0/100", /* 4 */
446                 "!770+1336/100,!0/100", /* 5 */
447                 "!770+1477/100,!0/100", /* 6 */
448                 "!852+1209/100,!0/100", /* 7 */
449                 "!852+1336/100,!0/100", /* 8 */
450                 "!852+1477/100,!0/100", /* 9 */
451                 "!697+1633/100,!0/100", /* A */
452                 "!770+1633/100,!0/100", /* B */
453                 "!852+1633/100,!0/100", /* C */
454                 "!941+1633/100,!0/100", /* D */
455                 "!941+1209/100,!0/100", /* * */
456                 "!941+1477/100,!0/100" };       /* # */
457         struct ast_channel *chan=cl->ast; 
458   
459         if (digit >= '0' && digit <='9')
460                 ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
461         else if (digit >= 'A' && digit <= 'D')
462                 ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
463         else if (digit == '*')
464                 ast_playtones_start(chan,0,dtmf_tones[14], 0);
465         else if (digit == '#')
466                 ast_playtones_start(chan,0,dtmf_tones[15], 0);
467         else {
468                 /* not handled */
469                 ast_log(LOG_DEBUG, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
470     
471     
472         }
473 }
474 /*** CLI HANDLING ***/
475 static int misdn_set_debug(int fd, int argc, char *argv[])
476 {
477         if (argc != 4 && argc != 5 && argc != 6 && argc != 7)
478                 return RESULT_SHOWUSAGE; 
479
480         int level = atoi(argv[3]);
481
482         switch (argc) {
483                 case 4: 
484                 case 5: {
485                                         int only = 0;
486                                         if (argc == 5) {
487                                                 if (strncasecmp(argv[4], "only", strlen(argv[4])))
488                                                         return RESULT_SHOWUSAGE;
489                                                 else
490                                                         only = 1;
491                                         }
492                                         int i;
493                                         for (i=0; i<=max_ports; i++) {
494                                                 misdn_debug[i] = level;
495                                                 misdn_debug_only[i] = only;
496                                         }
497                                         ast_cli(fd, "changing debug level for all ports to %d%s\n",misdn_debug[0], only?" (only)":"");
498                                 }
499                                 break;
500                 case 6: 
501                 case 7: {
502                                         if (strncasecmp(argv[4], "port", strlen(argv[4])))
503                                                 return RESULT_SHOWUSAGE;
504                                         int port = atoi(argv[5]);
505                                         if (port <= 0 || port > max_ports) {
506                                                 switch (max_ports) {
507                                                         case 0:
508                                                                 ast_cli(fd, "port number not valid! no ports available so you won't get lucky with any number here...\n");
509                                                                 break;
510                                                         case 1:
511                                                                 ast_cli(fd, "port number not valid! only port 1 is availble.\n");
512                                                                 break;
513                                                         default:
514                                                                 ast_cli(fd, "port number not valid! only ports 1 to %d are available.\n", max_ports);
515                                                         }
516                                                         return 0;
517                                         }
518                                         if (argc == 7) {
519                                                 if (strncasecmp(argv[6], "only", strlen(argv[6])))
520                                                         return RESULT_SHOWUSAGE;
521                                                 else
522                                                         misdn_debug_only[port] = 1;
523                                         } else
524                                                 misdn_debug_only[port] = 0;
525                                         misdn_debug[port] = level;
526                                         ast_cli(fd, "changing debug level to %d%s for port %d\n", misdn_debug[port], misdn_debug_only[port]?" (only)":"", port);
527                                 }
528         }
529         return 0;
530 }
531
532 static int misdn_set_crypt_debug(int fd, int argc, char *argv[])
533 {
534         if (argc != 5) return RESULT_SHOWUSAGE; 
535
536         return 0;
537 }
538
539
540 static int misdn_restart_port (int fd, int argc, char *argv[])
541 {
542         int port;
543   
544         if (argc != 4)
545                 return RESULT_SHOWUSAGE;
546   
547         port = atoi(argv[3]);
548
549         misdn_lib_port_restart(port);
550
551         return 0;
552 }
553
554 static int misdn_port_up (int fd, int argc, char *argv[])
555 {
556         int port;
557         
558         if (argc != 4)
559                 return RESULT_SHOWUSAGE;
560         
561         port = atoi(argv[3]);
562         
563         misdn_lib_get_port_up(port);
564   
565         return 0;
566 }
567
568 static int misdn_port_down (int fd, int argc, char *argv[])
569 {
570         int port;
571         
572         if (argc != 4)
573                 return RESULT_SHOWUSAGE;
574         
575         port = atoi(argv[3]);
576         
577         misdn_lib_get_port_down(port);
578   
579         return 0;
580 }
581
582
583 static int misdn_show_config (int fd, int argc, char *argv[])
584 {
585         char buffer[BUFFERSIZE];
586         enum misdn_cfg_elements elem;
587         int linebreak;
588
589         int onlyport = -1;
590         if (argc >= 4) {
591                 if (!sscanf(argv[3], "%d", &onlyport) || onlyport < 0) {
592                         ast_cli(fd, "Unknown option: %s\n", argv[3]);
593                         return RESULT_SHOWUSAGE;
594                 }
595         }
596         
597         if (argc == 3 || onlyport == 0) {
598                 ast_cli(fd,"Misdn General-Config: \n"); 
599                 ast_cli(fd," -> Version: chan_misdn-" CHAN_MISDN_VERSION "\n");
600                 for (elem = MISDN_GEN_FIRST + 1, linebreak = 1; elem < MISDN_GEN_LAST; elem++, linebreak++) {
601                         misdn_cfg_get_config_string( 0, elem, buffer, BUFFERSIZE);
602                         ast_cli(fd, "%-36s%s", buffer, !(linebreak % 2) ? "\n" : "");
603                 }
604                 ast_cli(fd, "\n");
605         }
606
607         if (onlyport < 0) {
608                 int port = misdn_cfg_get_next_port(0);
609                 for (; port > 0; port = misdn_cfg_get_next_port(port)) {
610                         ast_cli(fd, "\n[PORT %d]\n", port);
611                         for (elem = MISDN_CFG_FIRST + 1, linebreak = 1; elem < MISDN_CFG_LAST; elem++, linebreak++) {
612                                 misdn_cfg_get_config_string( port, elem, buffer, BUFFERSIZE);
613                                 ast_cli(fd, "%-36s%s", buffer, !(linebreak % 2) ? "\n" : "");
614                         }       
615                         ast_cli(fd, "\n");
616                 }
617         }
618         
619         if (onlyport > 0) {
620                 if (misdn_cfg_is_port_valid(onlyport)) {
621                         ast_cli(fd, "[PORT %d]\n", onlyport);
622                         for (elem = MISDN_CFG_FIRST + 1, linebreak = 1; elem < MISDN_CFG_LAST; elem++, linebreak++) {
623                                 misdn_cfg_get_config_string( onlyport, elem, buffer, BUFFERSIZE);
624                                 ast_cli(fd, "%-36s%s", buffer, !(linebreak % 2) ? "\n" : "");
625                         }       
626                         ast_cli(fd, "\n");
627                 } else {
628                         ast_cli(fd, "Port %d is not active!\n", onlyport);
629                 }
630         }
631         return 0;
632 }
633
634 struct state_struct {
635         enum misdn_chan_state state;
636         char txt[255] ;
637 } ;
638
639 static struct state_struct state_array[] = {
640         {MISDN_NOTHING,"NOTHING"}, /* at beginning */
641         {MISDN_WAITING4DIGS,"WAITING4DIGS"}, /*  when waiting for infos */
642         {MISDN_EXTCANTMATCH,"EXTCANTMATCH"}, /*  when asterisk couldnt match our ext */
643         {MISDN_DIALING,"DIALING"}, /*  when pbx_start */
644         {MISDN_PROGRESS,"PROGRESS"}, /*  when pbx_start */
645         {MISDN_CALLING,"CALLING"}, /*  when misdn_call is called */
646         {MISDN_ALERTING,"ALERTING"}, /*  when Alerting */
647         {MISDN_BUSY,"BUSY"}, /*  when BUSY */
648         {MISDN_CONNECTED,"CONNECTED"}, /*  when connected */
649         {MISDN_BRIDGED,"BRIDGED"}, /*  when bridged */
650         {MISDN_CLEANING,"CLEANING"}, /* when hangup from * but we were connected before */
651         {MISDN_HUNGUP_FROM_MISDN,"HUNGUP_FROM_MISDN"}, /* when DISCONNECT/RELEASE/REL_COMP  cam from misdn */
652         {MISDN_HOLDED,"HOLDED"}, /* when DISCONNECT/RELEASE/REL_COMP  cam from misdn */
653         {MISDN_HOLD_DISCONNECT,"HOLD_DISCONNECT"}, /* when DISCONNECT/RELEASE/REL_COMP  cam from misdn */
654         {MISDN_HUNGUP_FROM_AST,"HUNGUP_FROM_AST"} /* when DISCONNECT/RELEASE/REL_COMP came out of */
655         /* misdn_hangup */
656 };
657
658 static char *misdn_get_ch_state(struct chan_list *p) 
659 {
660         int i;
661         if( !p) return NULL;
662   
663         for (i=0; i< sizeof(state_array)/sizeof(struct state_struct); i++) {
664                 if ( state_array[i].state == p->state) return state_array[i].txt; 
665         }
666   
667         return NULL;
668 }
669
670
671
672 static void reload_config(void)
673 {
674         int i, cfg_debug;
675         chan_misdn_log(-1, 0, "Dynamic Crypting Activation is not support during reload at the moment\n");
676         
677         free_robin_list();
678         misdn_cfg_reload();
679         misdn_cfg_update_ptp();
680         misdn_cfg_get( 0, MISDN_GEN_TRACEFILE, global_tracefile, BUFFERSIZE);
681         misdn_cfg_get( 0, MISDN_GEN_DEBUG, &cfg_debug, sizeof(int));
682
683         for (i = 0;  i <= max_ports; i++) {
684                 misdn_debug[i] = cfg_debug;
685                 misdn_debug_only[i] = 0;
686         }
687 }
688
689 static int misdn_reload (int fd, int argc, char *argv[])
690 {
691         ast_cli(fd, "Reloading mISDN Config\n");
692         reload_config();
693         return 0;
694 }
695
696 static void print_bc_info (int fd, struct chan_list* help, struct misdn_bchannel* bc)
697 {
698         struct ast_channel *ast=help->ast;
699         ast_cli(fd,
700                 "* Pid:%d Prt:%d Ch:%d Mode:%s Org:%s dad:%s oad:%s rad:%s ctx:%s state:%s\n",
701
702                 bc->pid, bc->port, bc->channel,
703                 bc->nt?"NT":"TE",
704                 help->orginator == ORG_AST?"*":"I",
705                 ast?ast->exten:NULL,
706                 ast?AST_CID_P(ast):NULL,
707                 bc->rad,
708                 ast?ast->context:NULL,
709                 misdn_get_ch_state(help)
710                 );
711         if (misdn_debug[bc->port] > 0)
712                 ast_cli(fd,
713                         "  --> astname: %s\n"
714                         "  --> ch_l3id: %x\n"
715                         "  --> ch_addr: %x\n"
716                         "  --> bc_addr: %x\n"
717                         "  --> bc_l3id: %x\n"
718                         "  --> display: %s\n"
719                         "  --> activated: %d\n"
720                         "  --> state: %s\n"
721                         "  --> capability: %s\n"
722                         "  --> echo_cancel: %d\n"
723                         "  --> notone : rx %d tx:%d\n"
724                         "  --> bc_hold: %d holded_bc :%d\n",
725                         help->ast->name,
726                         help->l3id,
727                         help->addr,
728                         bc->addr,
729                         bc?bc->l3_id:-1,
730                         bc->display,
731                         
732                         bc->active,
733                         bc_state2str(bc->bc_state),
734                         bearer2str(bc->capability),
735                         bc->ec_enable,
736                         help->norxtone,help->notxtone,
737                         bc->holded, help->holded_bc?1:0
738                         );
739   
740 }
741
742 static int misdn_show_cls (int fd, int argc, char *argv[])
743 {
744         struct chan_list *help=cl_te;
745   
746         ast_cli(fd,"Chan List: %p\n",cl_te); 
747   
748         for (;help; help=help->next) {
749                 struct misdn_bchannel *bc=help->bc;   
750                 struct ast_channel *ast=help->ast;
751                 if (misdn_debug[0] > 2) ast_cli(fd, "Bc:%p Ast:%p\n", bc, ast);
752                 if (bc) {
753                         print_bc_info(fd, help, bc);
754                 } else if ( (bc=help->holded_bc) ) {
755                         chan_misdn_log(0, 0, "ITS A HOLDED BC:\n");
756                         print_bc_info(fd, help,  bc);
757                 } else {
758                         ast_cli(fd,"* Channel in unknown STATE !!! Exten:%s, Callerid:%s\n", ast->exten, AST_CID_P(ast));
759                 }
760         }
761   
762   
763         return 0;
764 }
765
766 static int misdn_show_cl (int fd, int argc, char *argv[])
767 {
768         struct chan_list *help=cl_te;
769
770         if (argc != 4)
771                 return RESULT_SHOWUSAGE;
772   
773         for (;help; help=help->next) {
774                 struct misdn_bchannel *bc=help->bc;   
775                 struct ast_channel *ast=help->ast;
776     
777                 if (bc && ast) {
778                         if (!strcasecmp(ast->name,argv[3])) {
779                                 print_bc_info(fd, help, bc);
780                                 break; 
781                         }
782                 } 
783         }
784   
785   
786         return 0;
787 }
788
789 ast_mutex_t lock;
790 int MAXTICS=8;
791
792 static int misdn_set_tics (int fd, int argc, char *argv[])
793 {
794         if (argc != 4)
795                 return RESULT_SHOWUSAGE;
796   
797         MAXTICS=atoi(argv[3]);
798   
799         return 0;
800 }
801
802 static int misdn_show_stacks (int fd, int argc, char *argv[])
803 {
804         int port;
805
806         ast_cli(fd, "BEGIN STACK_LIST:\n");
807
808         for (port=misdn_cfg_get_next_port(0); port > 0;
809              port=misdn_cfg_get_next_port(port)) {
810                 char buf[128];
811                 get_show_stack_details(port,buf);
812                 ast_cli(fd,"  %s  Debug:%d%s\n", buf, misdn_debug[port], misdn_debug_only[port]?"(only)":"");
813         }
814                 
815
816         return 0;
817
818 }
819
820
821 static int misdn_show_ports_stats (int fd, int argc, char *argv[])
822 {
823         int port;
824
825         ast_cli(fd, "Port\tin_calls\tout_calls\n");
826         
827         for (port=misdn_cfg_get_next_port(0); port > 0;
828              port=misdn_cfg_get_next_port(port)) {
829                 ast_cli(fd,"%d\t%d\t\t%d\n",port,misdn_in_calls[port],misdn_out_calls[port]);
830         }
831         ast_cli(fd,"\n");
832         
833         return 0;
834
835 }
836
837
838 static int misdn_show_port (int fd, int argc, char *argv[])
839 {
840         int port;
841         
842         if (argc != 4)
843                 return RESULT_SHOWUSAGE;
844   
845         port = atoi(argv[3]);
846   
847         ast_cli(fd, "BEGIN STACK_LIST:\n");
848
849         char buf[128];
850         get_show_stack_details(port,buf);
851         ast_cli(fd,"  %s  Debug:%d%s\n",buf, misdn_debug[port], misdn_debug_only[port]?"(only)":"");
852
853         
854         return 0;
855 }
856
857 static int misdn_send_cd (int fd, int argc, char *argv[])
858 {
859         char *channame; 
860         char *nr; 
861   
862         if (argc != 5)
863                 return RESULT_SHOWUSAGE;
864   
865         channame = argv[3];
866         nr = argv[4];
867         
868         ast_cli(fd, "Sending Calldeflection (%s) to %s\n",nr, channame);
869         
870         {
871                 struct chan_list *tmp=get_chan_by_ast_name(channame);
872                 
873                 if (!tmp) {
874                         ast_cli(fd, "Sending CD with nr %s to %s failed Channel does not exist\n",nr, channame);
875                         return 0; 
876                 } else {
877                         
878                         misdn_lib_send_facility(tmp->bc, FACILITY_CALLDEFLECT, nr);
879                 }
880         }
881   
882         return 0; 
883 }
884
885 static int misdn_send_digit (int fd, int argc, char *argv[])
886 {
887         char *channame; 
888         char *msg; 
889   
890         if (argc != 5)
891                 return RESULT_SHOWUSAGE;
892   
893         channame = argv[3];
894         msg = argv[4];
895
896         ast_cli(fd, "Sending %s to %s\n",msg, channame);
897   
898         {
899                 struct chan_list *tmp=get_chan_by_ast_name(channame);
900     
901                 if (!tmp) {
902                         ast_cli(fd, "Sending %s to %s failed Channel does not exist\n",msg, channame);
903                         return 0; 
904                 } else {
905 #if 1
906                         int i;
907                         int msglen = strlen(msg);
908                         for (i=0; i<msglen; i++) {
909                                 ast_cli(fd, "Sending: %c\n",msg[i]);
910                                 send_digit_to_chan(tmp, msg[i]);
911                                 /* res = ast_safe_sleep(tmp->ast, 250); */
912                                 usleep(250000);
913                                 /* res = ast_waitfor(tmp->ast,100); */
914                         }
915 #else
916                         int res;
917                         res = ast_dtmf_stream(tmp->ast,NULL,msg,250);
918 #endif
919                 }
920         }
921   
922         return 0; 
923 }
924
925 static int misdn_toggle_echocancel (int fd, int argc, char *argv[])
926 {
927         char *channame; 
928
929         if (argc != 4)
930                 return RESULT_SHOWUSAGE;
931         
932         channame = argv[3];
933   
934         ast_cli(fd, "Toggling EchoCancel on %s\n", channame);
935   
936         {
937                 struct chan_list *tmp=get_chan_by_ast_name(channame);
938     
939                 if (!tmp) {
940                         ast_cli(fd, "Toggling EchoCancel %s failed Channel does not exist\n", channame);
941                         return 0; 
942                 } else {
943                         tmp->bc->ec_enable=tmp->bc->ec_enable?0:1;
944
945                         if (tmp->bc->ec_enable) {
946                                 manager_ec_enable(tmp->bc);
947                         } else {
948                                 manager_ec_disable(tmp->bc);
949                         }
950                 }
951         }
952   
953         return 0; 
954 }
955
956 static int misdn_send_display (int fd, int argc, char *argv[])
957 {
958         char *channame; 
959         char *msg; 
960   
961         if (argc != 5)
962                 return RESULT_SHOWUSAGE;
963   
964         channame = argv[3];
965         msg = argv[4];
966
967         ast_cli(fd, "Sending %s to %s\n",msg, channame);
968         {
969                 struct chan_list *tmp;
970                 tmp=get_chan_by_ast_name(channame);
971     
972                 if (tmp && tmp->bc) {
973                         ast_copy_string(tmp->bc->display, msg, sizeof(tmp->bc->display));
974                         misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
975                 } else {
976                         ast_cli(fd,"No such channel %s\n",channame);
977                         return RESULT_FAILURE;
978                 }
979         }
980
981         return RESULT_SUCCESS ;
982 }
983
984 static char *complete_ch_helper(const char *line, const char *word, int pos, int state, int rpos)
985 {
986         struct ast_channel *c;
987         int which=0;
988         char *ret;
989         if (pos != rpos)
990                 return NULL;
991         c = ast_channel_walk_locked(NULL);
992         while(c) {
993                 if (!strncasecmp(word, c->name, strlen(word))) {
994                         if (++which > state)
995                                 break;
996                 }
997                 ast_mutex_unlock(&c->lock);
998                 c = ast_channel_walk_locked(c);
999         }
1000         if (c) {
1001                 ret = strdup(c->name);
1002                 ast_mutex_unlock(&c->lock);
1003         } else
1004                 ret = NULL;
1005         return ret;
1006 }
1007
1008 static char *complete_ch(const char *line, const char *word, int pos, int state)
1009 {
1010         return complete_ch_helper(line, word, pos, state, 3);
1011 }
1012
1013 static char *complete_debug_port (const char *line, const char *word, int pos, int state)
1014 {
1015         if (state)
1016                 return NULL;
1017
1018         switch (pos) {
1019         case 4: if (*word == 'p')
1020                                 return strdup("port");
1021                         else if (*word == 'o')
1022                                 return strdup("only");
1023                         break;
1024         case 6: if (*word == 'o')
1025                                 return strdup("only");
1026                         break;
1027         }
1028         return NULL;
1029 }
1030
1031 static struct ast_cli_entry cli_send_cd =
1032 { {"misdn","send","calldeflect", NULL},
1033   misdn_send_cd,
1034   "Sends CallDeflection to mISDN Channel", 
1035   "Usage: misdn send calldeflect <channel> \"<nr>\" \n",
1036   complete_ch
1037 };
1038
1039 static struct ast_cli_entry cli_send_digit =
1040 { {"misdn","send","digit", NULL},
1041   misdn_send_digit,
1042   "Sends DTMF Digit to mISDN Channel", 
1043   "Usage: misdn send digit <channel> \"<msg>\" \n"
1044   "       Send <digit> to <channel> as DTMF Tone\n"
1045   "       when channel is a mISDN channel\n",
1046   complete_ch
1047 };
1048
1049 static struct ast_cli_entry cli_toggle_echocancel =
1050 { {"misdn","toggle","echocancel", NULL},
1051   misdn_toggle_echocancel,
1052   "Toggles EchoCancel on mISDN Channel", 
1053   "Usage: misdn toggle echocancel <channel>\n", 
1054   complete_ch
1055 };
1056
1057 static struct ast_cli_entry cli_send_display =
1058 { {"misdn","send","display", NULL},
1059   misdn_send_display,
1060   "Sends Text to mISDN Channel", 
1061   "Usage: misdn send display <channel> \"<msg>\" \n"
1062   "       Send <msg> to <channel> as Display Message\n"
1063   "       when channel is a mISDN channel\n",
1064   complete_ch
1065 };
1066
1067 static struct ast_cli_entry cli_show_config =
1068 { {"misdn","show","config", NULL},
1069   misdn_show_config,
1070   "Shows internal mISDN config, read from cfg-file", 
1071   "Usage: misdn show config [port | 0]\n       use 0 to only print the general config.\n"
1072 };
1073  
1074 static struct ast_cli_entry cli_reload =
1075 { {"misdn","reload", NULL},
1076   misdn_reload,
1077   "Reloads internal mISDN config, read from cfg-file", 
1078   "Usage: misdn reload\n"
1079 };
1080
1081 static struct ast_cli_entry cli_set_tics =
1082 { {"misdn","set","tics", NULL},
1083   misdn_set_tics,
1084   "", 
1085   "\n"
1086 };
1087
1088 static struct ast_cli_entry cli_show_cls =
1089 { {"misdn","show","channels", NULL},
1090   misdn_show_cls,
1091   "Shows internal mISDN chan_list", 
1092   "Usage: misdn show channels\n"
1093 };
1094
1095 static struct ast_cli_entry cli_show_cl =
1096 { {"misdn","show","channel", NULL},
1097   misdn_show_cl,
1098   "Shows internal mISDN chan_list", 
1099   "Usage: misdn show channels\n",
1100   complete_ch
1101 };
1102
1103
1104
1105 static struct ast_cli_entry cli_restart_port =
1106 { {"misdn","restart","port", NULL},
1107   misdn_restart_port,
1108   "Restarts the given port", 
1109   "Usage: misdn restart port\n"
1110 };
1111
1112 static struct ast_cli_entry cli_port_up =
1113 { {"misdn","port","up", NULL},
1114   misdn_port_up,
1115   "Tries to establish L1 on the given port", 
1116   "Usage: misdn port up <port>\n"
1117 };
1118
1119 static struct ast_cli_entry cli_port_down =
1120 { {"misdn","port","down", NULL},
1121   misdn_port_down,
1122   "Tries to deacivate the L1 on the given port", 
1123   "Usage: misdn port down <port>\n"
1124 };
1125
1126
1127
1128 static struct ast_cli_entry cli_show_stacks =
1129 { {"misdn","show","stacks", NULL},
1130   misdn_show_stacks,
1131   "Shows internal mISDN stack_list", 
1132   "Usage: misdn show stacks\n"
1133 };
1134
1135 static struct ast_cli_entry cli_show_ports_stats =
1136 { {"misdn","show","ports","stats", NULL},
1137   misdn_show_ports_stats,
1138   "Shows chan_misdns call statistics per port", 
1139   "Usage: misdn show port stats\n"
1140 };
1141
1142
1143 static struct ast_cli_entry cli_show_port =
1144 { {"misdn","show","port", NULL},
1145   misdn_show_port,
1146   "Shows detailed information for given port", 
1147   "Usage: misdn show port <port>\n"
1148 };
1149
1150 static struct ast_cli_entry cli_set_debug =
1151 { {"misdn","set","debug", NULL},
1152   misdn_set_debug,
1153   "Sets Debuglevel of chan_misdn",
1154   "Usage: misdn set debug <level> [only] | [port <port> [only]]\n",
1155   complete_debug_port
1156 };
1157
1158 static struct ast_cli_entry cli_set_crypt_debug =
1159 { {"misdn","set","crypt","debug", NULL},
1160   misdn_set_crypt_debug,
1161   "Sets CryptDebuglevel of chan_misdn, at the moment, level={1,2}", 
1162   "Usage: misdn set crypt debug <level>\n"
1163 };
1164 /*** CLI END ***/
1165
1166
1167 static int update_config (struct chan_list *ch, int orig) 
1168 {
1169         if (!ch) {
1170                 ast_log(LOG_WARNING, "Cannot configure without chanlist\n");
1171                 return -1;
1172         }
1173         
1174         struct ast_channel *ast=ch->ast;
1175         struct misdn_bchannel *bc=ch->bc;
1176         if (! ast || ! bc ) {
1177                 ast_log(LOG_WARNING, "Cannot configure without ast || bc\n");
1178                 return -1;
1179         }
1180         
1181         int port=bc->port;
1182         
1183         chan_misdn_log(5,port,"update_config: Getting Config\n");
1184
1185
1186         int hdlc=0;
1187         misdn_cfg_get( port, MISDN_CFG_HDLC, &hdlc, sizeof(int));
1188         
1189         if (hdlc) {
1190                 switch (bc->capability) {
1191                 case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
1192                 case INFO_CAPABILITY_DIGITAL_RESTRICTED:
1193                         chan_misdn_log(1,bc->port," --> CONF HDLC\n");
1194                         bc->hdlc=1;
1195                         break;
1196                 }
1197                 
1198         }
1199         
1200         
1201         int pres, screen;
1202                         
1203         misdn_cfg_get( port, MISDN_CFG_PRES, &pres, sizeof(int));
1204         misdn_cfg_get( port, MISDN_CFG_SCREEN, &screen, sizeof(int));
1205         chan_misdn_log(2,port," --> pres: %d screen: %d\n",pres, screen);
1206                 
1207         if ( (pres + screen) < 0 ) {
1208
1209                 chan_misdn_log(2,port," --> pres: %x\n", ast->cid.cid_pres);
1210                         
1211                 switch (ast->cid.cid_pres & 0x60){
1212                                 
1213                 case AST_PRES_RESTRICTED:
1214                         bc->pres=1;
1215                         chan_misdn_log(2, port, " --> PRES: Restricted (0x1)\n");
1216                         break;
1217                                 
1218                                 
1219                 case AST_PRES_UNAVAILABLE:
1220                         bc->pres=2;
1221                         chan_misdn_log(2, port, " --> PRES: Unavailable (0x2)\n");
1222                         break;
1223                                 
1224                 default:
1225                         bc->pres=0;
1226                         chan_misdn_log(2, port, " --> PRES: Allowed (0x0)\n");
1227                 }
1228                         
1229                 switch (ast->cid.cid_pres & 0x3){
1230                                 
1231                 case AST_PRES_USER_NUMBER_UNSCREENED:
1232                         bc->screen=0;
1233                         chan_misdn_log(2, port, " --> SCREEN: Unscreened (0x0)\n");
1234                         break;
1235
1236                 case AST_PRES_USER_NUMBER_PASSED_SCREEN:
1237                         bc->screen=1;
1238                         chan_misdn_log(2, port, " --> SCREEN: Passed Screen (0x1)\n");
1239                         break;
1240                 case AST_PRES_USER_NUMBER_FAILED_SCREEN:
1241                         bc->screen=2;
1242                         chan_misdn_log(2, port, " --> SCREEN: Failed Screen (0x2)\n");
1243                         break;
1244                                 
1245                 case AST_PRES_NETWORK_NUMBER:
1246                         bc->screen=3;
1247                         chan_misdn_log(2, port, " --> SCREEN: Network Nr. (0x3)\n");
1248                         break;
1249                                 
1250                 default:
1251                         bc->screen=0;
1252                         chan_misdn_log(2, port, " --> SCREEN: Unscreened (0x0)\n");
1253                 }
1254
1255                         
1256         } else {
1257                 bc->screen=screen;
1258                 bc->pres=pres;
1259         }
1260
1261         return 0;
1262         
1263 }
1264
1265
1266
1267
1268 static void config_jitterbuffer(struct chan_list *ch)
1269 {
1270         struct misdn_bchannel *bc=ch->bc;
1271         int len=ch->jb_len, threshold=ch->jb_upper_threshold;
1272         
1273         chan_misdn_log(5,bc->port, "config_jb: Called\n");
1274         
1275         if ( ! len ) {
1276                 chan_misdn_log(1,bc->port, "config_jb: Deactivating Jitterbuffer\n");
1277                 bc->nojitter=1;
1278         } else {
1279                 
1280                 if (len <=100 || len > 8000) {
1281                         chan_misdn_log(-1,bc->port,"config_jb: Jitterbuffer out of Bounds, setting to 1000\n");
1282                         len=1000;
1283                 }
1284                 
1285                 if ( threshold > len ) {
1286                         chan_misdn_log(-1,bc->port,"config_jb: Jitterbuffer Threshold > Jitterbuffer setting to Jitterbuffer -1\n");
1287                 }
1288                 
1289                 if ( ch->jb) {
1290                         cb_log(0,bc->port,"config_jb: We've got a Jitterbuffer Already on this port.\n");
1291                         misdn_jb_destroy(ch->jb);
1292                         ch->jb=NULL;
1293                 }
1294                 
1295                 ch->jb=misdn_jb_init(len, threshold);
1296
1297                 if (!ch->jb ) 
1298                         bc->nojitter=1;
1299         }
1300 }
1301
1302
1303 void debug_numplan(int port, int numplan, char *type)
1304 {
1305         switch (numplan) {
1306         case NUMPLAN_INTERNATIONAL:
1307                 chan_misdn_log(2, port, " --> %s: International\n",type);
1308                 break;
1309         case NUMPLAN_NATIONAL:
1310                 chan_misdn_log(2, port, " --> %s: National\n",type);
1311                 break;
1312         case NUMPLAN_SUBSCRIBER:
1313                 chan_misdn_log(2, port, " --> %s: Subscriber\n",type);
1314                 break;
1315         case NUMPLAN_UNKNOWN:
1316                 chan_misdn_log(2, port, " --> %s: Unknown\n",type);
1317                 break;
1318                 /* Maybe we should cut off the prefix if present ? */
1319         default:
1320                 chan_misdn_log(0, port, " --> !!!! Wrong dialplan setting, please see the misdn.conf sample file\n ");
1321                 break;
1322         }
1323 }
1324
1325
1326
1327
1328
1329 static int read_config(struct chan_list *ch, int orig) {
1330
1331         if (!ch) {
1332                 ast_log(LOG_WARNING, "Cannot configure without chanlist\n");
1333                 return -1;
1334         }
1335
1336         struct ast_channel *ast=ch->ast;
1337         struct misdn_bchannel *bc=ch->bc;
1338         if (! ast || ! bc ) {
1339                 ast_log(LOG_WARNING, "Cannot configure without ast || bc\n");
1340                 return -1;
1341         }
1342         
1343         int port=bc->port;
1344         
1345         chan_misdn_log(1,port,"read_config: Getting Config\n");
1346
1347         char lang[BUFFERSIZE+1];
1348         
1349
1350         misdn_cfg_get( port, MISDN_CFG_LANGUAGE, lang, BUFFERSIZE);
1351         ast_string_field_set(ast, language, lang);
1352
1353         char localmusicclass[BUFFERSIZE+1];
1354         
1355         misdn_cfg_get( port, MISDN_CFG_MUSICCLASS, localmusicclass, BUFFERSIZE);
1356         ast_string_field_set(ast, musicclass, localmusicclass);
1357         
1358         
1359         misdn_cfg_get( port, MISDN_CFG_TXGAIN, &bc->txgain, sizeof(int));
1360         misdn_cfg_get( port, MISDN_CFG_RXGAIN, &bc->rxgain, sizeof(int));
1361         
1362         misdn_cfg_get( port, MISDN_CFG_INCOMING_EARLY_AUDIO, &ch->incoming_early_audio, sizeof(int));
1363         
1364         misdn_cfg_get( port, MISDN_CFG_SENDDTMF, &bc->send_dtmf, sizeof(int));
1365
1366         misdn_cfg_get( port, MISDN_CFG_NEED_MORE_INFOS, &bc->need_more_infos, sizeof(int));
1367         
1368         misdn_cfg_get( port, MISDN_CFG_FAR_ALERTING, &ch->far_alerting, sizeof(int));
1369
1370         misdn_cfg_get( port, MISDN_CFG_ALLOWED_BEARERS, &ch->allowed_bearers, BUFFERSIZE);
1371         
1372         
1373         int hdlc=0;
1374         misdn_cfg_get( port, MISDN_CFG_HDLC, &hdlc, sizeof(int));
1375         
1376         if (hdlc) {
1377                 switch (bc->capability) {
1378                 case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
1379                 case INFO_CAPABILITY_DIGITAL_RESTRICTED:
1380                         chan_misdn_log(1,bc->port," --> CONF HDLC\n");
1381                         bc->hdlc=1;
1382                         break;
1383                 }
1384                 
1385         }
1386         /*Initialize new Jitterbuffer*/
1387         {
1388                 misdn_cfg_get( port, MISDN_CFG_JITTERBUFFER, &ch->jb_len, sizeof(int));
1389                 misdn_cfg_get( port, MISDN_CFG_JITTERBUFFER_UPPER_THRESHOLD, &ch->jb_upper_threshold, sizeof(int));
1390                 
1391                 config_jitterbuffer(ch);
1392         }
1393         
1394         misdn_cfg_get( bc->port, MISDN_CFG_CONTEXT, ch->context, sizeof(ch->context));
1395         
1396         ast_copy_string (ast->context,ch->context,sizeof(ast->context));        
1397         {
1398                 int ec, ectr;
1399                 
1400                 misdn_cfg_get( port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
1401                 
1402                 misdn_cfg_get( port, MISDN_CFG_ECHOTRAINING, &ectr, sizeof(int));
1403                 if (ec == 1 ) {
1404                         bc->ec_enable=1;
1405                 } else if ( ec > 1 ) {
1406                         bc->ec_enable=1;
1407                         bc->ec_deftaps=ec;
1408                 }
1409                 
1410                 if ( ectr >= 0 ) {
1411                         bc->ec_training=ectr;
1412                 }
1413         }
1414         
1415         {
1416                 int eb3;
1417                 
1418                 misdn_cfg_get( bc->port, MISDN_CFG_EARLY_BCONNECT, &eb3, sizeof(int));
1419                 bc->early_bconnect=eb3;
1420         }
1421         
1422         port=bc->port;
1423         
1424         {
1425                 char buf[256];
1426                 ast_group_t pg,cg;
1427                 
1428                 misdn_cfg_get(port, MISDN_CFG_PICKUPGROUP, &pg, sizeof(pg));
1429                 misdn_cfg_get(port, MISDN_CFG_CALLGROUP, &cg, sizeof(cg));
1430                 
1431                 chan_misdn_log(5, port, " --> * CallGrp:%s PickupGrp:%s\n",ast_print_group(buf,sizeof(buf),cg),ast_print_group(buf,sizeof(buf),pg));
1432                 ast->pickupgroup=pg;
1433                 ast->callgroup=cg;
1434         }
1435         
1436         if ( orig  == ORG_AST) {
1437                 misdn_cfg_get( port, MISDN_CFG_TE_CHOOSE_CHANNEL, &(bc->te_choose_channel), sizeof(int));
1438                 
1439                 {
1440                         char callerid[BUFFERSIZE+1];
1441                         misdn_cfg_get( port, MISDN_CFG_CALLERID, callerid, BUFFERSIZE);
1442                         if ( ! ast_strlen_zero(callerid) ) {
1443                                 chan_misdn_log(1, port, " --> * Setting Cid to %s\n", callerid);
1444                                 {
1445                                         int l = sizeof(bc->oad);
1446                                         strncpy(bc->oad,callerid, l);
1447                                         bc->oad[l-1] = 0;
1448                                 }
1449
1450                         }
1451
1452                         
1453                         misdn_cfg_get( port, MISDN_CFG_DIALPLAN, &bc->dnumplan, sizeof(int));
1454                         misdn_cfg_get( port, MISDN_CFG_LOCALDIALPLAN, &bc->onumplan, sizeof(int));
1455                         misdn_cfg_get( port, MISDN_CFG_CPNDIALPLAN, &bc->cpnnumplan, sizeof(int));
1456                         debug_numplan(port, bc->dnumplan,"TON");
1457                         debug_numplan(port, bc->onumplan,"LTON");
1458                         debug_numplan(port, bc->cpnnumplan,"CTON");
1459                 }
1460
1461                 
1462                 
1463         } else { /** ORIGINATOR MISDN **/
1464         
1465                 misdn_cfg_get( port, MISDN_CFG_CPNDIALPLAN, &bc->cpnnumplan, sizeof(int));
1466                 debug_numplan(port, bc->cpnnumplan,"CTON");
1467                 
1468                 char prefix[BUFFERSIZE+1]="";
1469                 switch( bc->onumplan ) {
1470                 case NUMPLAN_INTERNATIONAL:
1471                         misdn_cfg_get( bc->port, MISDN_CFG_INTERNATPREFIX, prefix, BUFFERSIZE);
1472                         break;
1473                         
1474                 case NUMPLAN_NATIONAL:
1475                         misdn_cfg_get( bc->port, MISDN_CFG_NATPREFIX, prefix, BUFFERSIZE);
1476                         break;
1477                 default:
1478                         break;
1479                 }
1480                 
1481                 {
1482                         int l = strlen(prefix) + strlen(bc->oad);
1483                         char tmp[l+1];
1484                         strcpy(tmp,prefix);
1485                         strcat(tmp,bc->oad);
1486                         strcpy(bc->oad,tmp);
1487                 }
1488                 
1489                 if (!ast_strlen_zero(bc->dad)) {
1490                         ast_copy_string(bc->orig_dad,bc->dad, sizeof(bc->orig_dad));
1491                 }
1492                 
1493                 if ( ast_strlen_zero(bc->dad) && !ast_strlen_zero(bc->keypad)) {
1494                         ast_copy_string(bc->dad,bc->keypad, sizeof(bc->dad));
1495                 }
1496
1497                 prefix[0] = 0;
1498                 
1499                 switch( bc->dnumplan ) {
1500                 case NUMPLAN_INTERNATIONAL:
1501                         misdn_cfg_get( bc->port, MISDN_CFG_INTERNATPREFIX, prefix, BUFFERSIZE);
1502                         break;
1503                 case NUMPLAN_NATIONAL:
1504                         misdn_cfg_get( bc->port, MISDN_CFG_NATPREFIX, prefix, BUFFERSIZE);
1505                         break;
1506                 default:
1507                         break;
1508                 }
1509                 
1510                 {
1511                         int l = strlen(prefix) + strlen(bc->dad);
1512                         char tmp[l+1];
1513                         strcpy(tmp,prefix);
1514                         strcat(tmp,bc->dad);
1515                         strcpy(bc->dad,tmp);
1516                 }
1517                 
1518                 if ( strcmp(bc->dad,ast->exten)) {
1519                         ast_copy_string(ast->exten, bc->dad, sizeof(ast->exten));
1520                 }
1521                 
1522                 ast_set_callerid(ast, bc->oad, NULL, bc->oad);
1523                 
1524                 if ( !ast_strlen_zero(bc->rad) ) {
1525                         if (ast->cid.cid_rdnis)
1526                                 free(ast->cid.cid_rdnis);
1527                         ast->cid.cid_rdnis = strdup(bc->rad);
1528                 }
1529         } /* ORIG MISDN END */
1530
1531         return 0;
1532 }
1533
1534
1535 /*****************************/
1536 /*** AST Indications Start ***/
1537 /*****************************/
1538
1539 static int misdn_call(struct ast_channel *ast, char *dest, int timeout)
1540 {
1541         int port=0;
1542         int r;
1543         struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
1544         struct misdn_bchannel *newbc;
1545         char *opts=NULL, *ext,*tokb;
1546         char dest_cp[256];
1547
1548         {
1549                 strncpy(dest_cp,dest,sizeof(dest_cp)-1);
1550                 dest_cp[sizeof(dest_cp)]=0;
1551                 
1552                 ext=strtok_r(dest_cp,"/",&tokb);
1553                 
1554                 if (ext) {
1555                         ext=strtok_r(NULL,"/",&tokb);
1556                         if (ext) {
1557                                 opts=strtok_r(NULL,"/",&tokb);
1558                         } else {
1559                                 chan_misdn_log(-1,0,"misdn_call: No Extension given!\n");
1560                                 return -1;
1561                         }
1562                 }
1563         }
1564
1565         if (!ast) {
1566                 ast_log(LOG_WARNING, " --> ! misdn_call called on ast_channel *ast where ast == NULL\n");
1567                 return -1;
1568         }
1569
1570         if (((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) || !dest  ) {
1571                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1572                 ast->hangupcause=41;
1573                 ast_setstate(ast, AST_STATE_DOWN);
1574                 return -1;
1575         }
1576
1577         if (!ch) {
1578                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1579                 ast->hangupcause=41;
1580                 ast_setstate(ast, AST_STATE_DOWN);
1581                 return -1;
1582         }
1583         
1584         newbc=ch->bc;
1585         
1586         if (!newbc) {
1587                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1588                 ast->hangupcause=41;
1589                 ast_setstate(ast, AST_STATE_DOWN);
1590                 return -1;
1591         }
1592         
1593         port=newbc->port;
1594         strncpy(newbc->dad,ext,sizeof( newbc->dad));
1595         strncpy(ast->exten,ext,sizeof(ast->exten));
1596
1597         int exceed;
1598         if ((exceed=add_out_calls(port))) {
1599                 char tmp[16];
1600                 sprintf(tmp,"%d",exceed);
1601                 pbx_builtin_setvar_helper(ast,"MAX_OVERFLOW",tmp);
1602                 return -1;
1603         }
1604         
1605         chan_misdn_log(1, port, "* CALL: %s\n",dest);
1606         
1607         chan_misdn_log(1, port, " --> * dad:%s tech:%s ctx:%s\n",ast->exten,ast->name, ast->context);
1608         
1609         chan_misdn_log(3, port, " --> * adding2newbc ext %s\n",ast->exten);
1610         if (ast->exten) {
1611                 int l = sizeof(newbc->dad);
1612                 strncpy(newbc->dad,ast->exten, l);
1613                 newbc->dad[l-1] = 0;
1614         }
1615         newbc->rad[0]=0;
1616         chan_misdn_log(3, port, " --> * adding2newbc callerid %s\n",AST_CID_P(ast));
1617         if (ast_strlen_zero(newbc->oad) && AST_CID_P(ast) ) {
1618
1619                 if (AST_CID_P(ast)) {
1620                         int l = sizeof(newbc->oad);
1621                         strncpy(newbc->oad,AST_CID_P(ast), l);
1622                         newbc->oad[l-1] = 0;
1623                 }
1624         }
1625         
1626         {
1627                 struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
1628                 if (!ch) { ast_verbose("No chan_list in misdn_call"); return -1;}
1629                 
1630                 newbc->capability=ast->transfercapability;
1631                 pbx_builtin_setvar_helper(ast,"TRANSFERCAPABILITY",ast_transfercapability2str(newbc->capability));
1632                 if ( ast->transfercapability == INFO_CAPABILITY_DIGITAL_UNRESTRICTED) {
1633                         chan_misdn_log(2, port, " --> * Call with flag Digital\n");
1634                 }
1635                 
1636
1637                 /* update screening and presentation */ 
1638                 update_config(ch,ORG_AST);
1639                 
1640                 /* fill in some ies from channel vary*/
1641                 import_ies(ast, newbc);
1642                 
1643                 /* Finally The Options Override Everything */
1644                 if (opts)
1645                         misdn_set_opt_exec(ast,opts);
1646                 else
1647                         chan_misdn_log(2,port,"NO OPTS GIVEN\n");
1648                 
1649                 ch->state=MISDN_CALLING;
1650                 
1651                 r=misdn_lib_send_event( newbc, EVENT_SETUP );
1652                 
1653                 /** we should have l3id after sending setup **/
1654                 ch->l3id=newbc->l3_id;
1655         }
1656         
1657         if ( r == -ENOCHAN  ) {
1658                 chan_misdn_log(0, port, " --> * Theres no Channel at the moment .. !\n");
1659                 chan_misdn_log(1, port, " --> * SEND: State Down pid:%d\n",newbc?newbc->pid:-1);
1660                 ast->hangupcause=34;
1661                 ast_setstate(ast, AST_STATE_DOWN);
1662                 return -1;
1663         }
1664         
1665         chan_misdn_log(1, port, " --> * SEND: State Dialing pid:%d\n",newbc?newbc->pid:1);
1666
1667         ast_setstate(ast, AST_STATE_DIALING);
1668         ast->hangupcause=16;
1669         return 0; 
1670 }
1671
1672
1673 static int misdn_answer(struct ast_channel *ast)
1674 {
1675         struct chan_list *p;
1676
1677         
1678         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
1679         
1680         chan_misdn_log(1, p? (p->bc? p->bc->port : 0) : 0, "* ANSWER:\n");
1681         
1682         if (!p) {
1683                 ast_log(LOG_WARNING, " --> Channel not connected ??\n");
1684                 ast_queue_hangup(ast);
1685         }
1686
1687         if (!p->bc) {
1688                 chan_misdn_log(1, 0, " --> Got Answer, but theres no bc obj ??\n");
1689
1690                 ast_queue_hangup(ast);
1691         }
1692
1693         {
1694                 const char *tmp_key = pbx_builtin_getvar_helper(p->ast, "CRYPT_KEY");
1695                 
1696                 if (tmp_key ) {
1697                         chan_misdn_log(1, p->bc->port, " --> Connection will be BF crypted\n");
1698                         {
1699                                 int l = sizeof(p->bc->crypt_key);
1700                                 strncpy(p->bc->crypt_key,tmp_key, l);
1701                                 p->bc->crypt_key[l-1] = 0;
1702                         }
1703                 } else {
1704                         chan_misdn_log(3, p->bc->port, " --> Connection is without BF encryption\n");
1705                 }
1706     
1707         }
1708
1709         {
1710                 const char *nodsp=pbx_builtin_getvar_helper(ast, "MISDN_DIGITAL_TRANS");
1711                 if (nodsp) {
1712                         chan_misdn_log(1, p->bc->port, " --> Connection is transparent digital\n");
1713                         p->bc->nodsp=1;
1714                         p->bc->hdlc=0;
1715                         p->bc->nojitter=1;
1716                 }
1717         }
1718         
1719         p->state = MISDN_CONNECTED;
1720         misdn_lib_echo(p->bc,0);
1721         tone_indicate(p, TONE_NONE);
1722
1723         if ( ast_strlen_zero(p->bc->cad) ) {
1724                 chan_misdn_log(2,p->bc->port," --> empty cad using dad\n");
1725                 ast_copy_string(p->bc->cad,p->bc->dad,sizeof(p->bc->cad));
1726         }
1727
1728         misdn_lib_send_event( p->bc, EVENT_CONNECT);
1729         start_bc_tones(p);
1730         
1731         return 0;
1732 }
1733
1734 static int misdn_digit(struct ast_channel *ast, char digit )
1735 {
1736         struct chan_list *p;
1737         
1738         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) return -1;
1739
1740         struct misdn_bchannel *bc=p->bc;
1741         chan_misdn_log(1, bc?bc->port:0, "* IND : Digit %c\n",digit);
1742         
1743         if (!bc) {
1744                 ast_log(LOG_WARNING, " --> !! Got Digit Event withut having bchannel Object\n");
1745                 return -1;
1746         }
1747         
1748         switch (p->state ) {
1749                 case MISDN_CALLING:
1750                 {
1751                         
1752                         char buf[8];
1753                         buf[0]=digit;
1754                         buf[1]=0;
1755                         
1756                         int l = sizeof(bc->infos_pending);
1757                         strncat(bc->infos_pending,buf,l);
1758                         bc->infos_pending[l-1] = 0;
1759                 }
1760                 break;
1761                 case MISDN_CALLING_ACKNOWLEDGE:
1762                 {
1763                         bc->info_dad[0]=digit;
1764                         bc->info_dad[1]=0;
1765                         
1766                         {
1767                                 int l = sizeof(bc->dad);
1768                                 strncat(bc->dad,bc->info_dad, l - strlen(bc->dad));
1769                                 bc->dad[l-1] = 0;
1770                 }
1771                         {
1772                                 int l = sizeof(p->ast->exten);
1773                                 strncpy(p->ast->exten, bc->dad, l);
1774                                 p->ast->exten[l-1] = 0;
1775                         }
1776                         
1777                         misdn_lib_send_event( bc, EVENT_INFORMATION);
1778                 }
1779                 break;
1780                 
1781                 default:
1782                         if ( bc->send_dtmf ) {
1783                                 send_digit_to_chan(p,digit);
1784                         }
1785                 break;
1786         }
1787         
1788         return 0;
1789 }
1790
1791
1792 static int misdn_fixup(struct ast_channel *oldast, struct ast_channel *ast)
1793 {
1794         struct chan_list *p;
1795         
1796         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) )) return -1;
1797         
1798         chan_misdn_log(1, p->bc?p->bc->port:0, "* IND: Got Fixup State:%s Holded:%d L3id:%x\n", misdn_get_ch_state(p), p->holded, p->l3id);
1799         
1800         p->ast = ast ;
1801         p->state=MISDN_CONNECTED;
1802   
1803         return 0;
1804 }
1805
1806
1807
1808 static int misdn_indication(struct ast_channel *ast, int cond, const void *data, size_t datalen)
1809 {
1810         struct chan_list *p;
1811
1812   
1813         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) {
1814                 ast_log(LOG_WARNING, "Returnded -1 in misdn_indication\n");
1815                 return -1;
1816         }
1817         
1818         if (!p->bc ) {
1819                 chan_misdn_log(1, 0, "* IND : Indication from %s\n",ast->exten);
1820                 ast_log(LOG_WARNING, "Private Pointer but no bc ?\n");
1821                 return -1;
1822         }
1823         
1824         chan_misdn_log(1, p->bc->port, "* IND : Indication [%d] from %s\n",cond, ast->exten);
1825         
1826         switch (cond) {
1827         case AST_CONTROL_BUSY:
1828                 chan_misdn_log(1, p->bc->port, "* IND :\tbusy\n");
1829                 chan_misdn_log(1, p->bc->port, " --> * SEND: State Busy pid:%d\n",p->bc?p->bc->pid:-1);
1830                 ast_setstate(ast,AST_STATE_BUSY);
1831                 
1832                 p->bc->out_cause=17;
1833                 if (p->state != MISDN_CONNECTED) {
1834                         misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
1835                         tone_indicate(p, TONE_BUSY);
1836                 } else {
1837
1838                         chan_misdn_log(-1, p->bc->port, " --> !! Got Busy in Connected State !?! ast:%s\n", ast->name);
1839                 }
1840                 break;
1841         case AST_CONTROL_RING:
1842                 chan_misdn_log(1, p->bc->port, " --> * IND :\tring pid:%d\n",p->bc?p->bc->pid:-1);
1843                 break;
1844         case AST_CONTROL_RINGING:
1845                 switch (p->state) {
1846                         case MISDN_ALERTING:
1847                                 chan_misdn_log(1, p->bc->port, " --> * IND :\tringing pid:%d but I was Ringing before, so ignoreing it\n",p->bc?p->bc->pid:-1);
1848                                 break;
1849                         case MISDN_CONNECTED:
1850                                 chan_misdn_log(1, p->bc->port, " --> * IND :\tringing pid:%d but Connected, so just send TONE_ALERTING without state changes \n",p->bc?p->bc->pid:-1);
1851                                 tone_indicate(p, TONE_ALERTING);
1852                                 break;
1853                         default:
1854                                 p->state=MISDN_ALERTING;
1855                                 chan_misdn_log(1, p->bc->port, " --> * IND :\tringing pid:%d\n",p->bc?p->bc->pid:-1);
1856                                 misdn_lib_send_event( p->bc, EVENT_ALERTING);
1857                                 
1858                                 if ( !p->bc->nt && (p->orginator==ORG_MISDN) && !p->incoming_early_audio ) 
1859                                         chan_misdn_log(1,p->bc->port, " --> incoming_early_audio off\n");
1860                                  else 
1861                                          tone_indicate(p, TONE_ALERTING);
1862                                 chan_misdn_log(1, p->bc->port, " --> * SEND: State Ring pid:%d\n",p->bc?p->bc->pid:-1);
1863                                 ast_setstate(ast,AST_STATE_RINGING);
1864                 }
1865                 break;
1866         case AST_CONTROL_ANSWER:
1867                 chan_misdn_log(1, p->bc->port, " --> * IND :\tanswer pid:%d\n",p->bc?p->bc->pid:-1);
1868                 start_bc_tones(p);
1869                 break;
1870         case AST_CONTROL_TAKEOFFHOOK:
1871                 chan_misdn_log(1, p->bc->port, " --> *\ttakeoffhook pid:%d\n",p->bc?p->bc->pid:-1);
1872                 break;
1873         case AST_CONTROL_OFFHOOK:
1874                 chan_misdn_log(1, p->bc->port, " --> *\toffhook pid:%d\n",p->bc?p->bc->pid:-1);
1875                 break; 
1876         case AST_CONTROL_FLASH:
1877                 chan_misdn_log(1, p->bc->port, " --> *\tflash pid:%d\n",p->bc?p->bc->pid:-1);
1878                 break;
1879         case AST_CONTROL_PROGRESS:
1880                 chan_misdn_log(1, p->bc->port, " --> * IND :\tprogress pid:%d\n",p->bc?p->bc->pid:-1);
1881                 misdn_lib_send_event( p->bc, EVENT_PROGRESS);
1882                 break;
1883         case AST_CONTROL_PROCEEDING:
1884                 chan_misdn_log(1, p->bc->port, " --> * IND :\tproceeding pid:%d\n",p->bc?p->bc->pid:-1);
1885                 misdn_lib_send_event( p->bc, EVENT_PROCEEDING);
1886                 break;
1887         case AST_CONTROL_CONGESTION:
1888                 chan_misdn_log(1, p->bc->port, " --> * IND :\tcongestion pid:%d\n",p->bc?p->bc->pid:-1);
1889
1890                 p->bc->out_cause=42;
1891                 if (p->state != MISDN_CONNECTED) {
1892                         start_bc_tones(p);
1893                         misdn_lib_send_event( p->bc, EVENT_RELEASE);
1894                 } else {
1895                         misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
1896                 }
1897
1898                 if (p->bc->nt) {
1899                         tone_indicate(p, TONE_BUSY);
1900                 }
1901                 break;
1902         case -1 :
1903                 chan_misdn_log(1, p->bc->port, " --> * IND :\t-1! (stop indication) pid:%d\n",p->bc?p->bc->pid:-1);
1904                 
1905                 if (p->state == MISDN_CONNECTED)
1906                         start_bc_tones(p);
1907                 else 
1908                         tone_indicate(p, TONE_NONE);
1909                 break;
1910
1911         case AST_CONTROL_HOLD:
1912                 chan_misdn_log(1, p->bc->port, " --> *\tHOLD pid:%d\n",p->bc?p->bc->pid:-1);
1913                 break;
1914         case AST_CONTROL_UNHOLD:
1915                 chan_misdn_log(1, p->bc->port, " --> *\tUNHOLD pid:%d\n",p->bc?p->bc->pid:-1);
1916                 break;
1917         default:
1918                 ast_log(LOG_WARNING, " --> * Unknown Indication:%d pid:%d\n",cond,p->bc?p->bc->pid:-1);
1919         }
1920   
1921         return 0;
1922 }
1923
1924 static int misdn_hangup(struct ast_channel *ast)
1925 {
1926         struct chan_list *p;
1927         struct misdn_bchannel *bc=NULL;
1928         
1929         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) ) ) return -1;
1930         
1931         release_lock;
1932
1933         
1934         ast_log(LOG_DEBUG, "misdn_hangup(%s)\n", ast->name);
1935         
1936         if (!p) {
1937                 chan_misdn_log(3, 0, "misdn_hangup called, without chan_list obj.\n");
1938                 release_unlock;
1939                 return 0 ;
1940         }
1941         
1942         bc=p->bc;
1943
1944         if (!bc) {
1945                 release_unlock;
1946                 ast_log(LOG_WARNING,"Hangup with private but no bc ?\n");
1947                 return 0;
1948         }
1949
1950         
1951         MISDN_ASTERISK_TECH_PVT(ast)=NULL;
1952         p->ast=NULL;
1953
1954         bc=p->bc;
1955         
1956         if (ast->_state == AST_STATE_RESERVED) {
1957                 /* between request and call */
1958                 MISDN_ASTERISK_TECH_PVT(ast)=NULL;
1959                 release_unlock;
1960                 
1961                 cl_dequeue_chan(&cl_te, p);
1962                 free(p);
1963                 
1964                 if (bc)
1965                         misdn_lib_release(bc);
1966                 
1967                 return 0;
1968         }
1969
1970         stop_bc_tones(p);
1971         
1972         release_unlock;
1973         
1974         {
1975                 const char *varcause=NULL;
1976                 bc->cause=ast->hangupcause?ast->hangupcause:16;
1977                 
1978                 if ( (varcause=pbx_builtin_getvar_helper(ast, "HANGUPCAUSE")) ||
1979                      (varcause=pbx_builtin_getvar_helper(ast, "PRI_CAUSE"))) {
1980                         int tmpcause=atoi(varcause);
1981                         bc->out_cause=tmpcause?tmpcause:16;
1982                 }
1983     
1984                 chan_misdn_log(1, bc->port, "* IND : HANGUP\tpid:%d ctx:%s dad:%s oad:%s State:%s\n",p->bc?p->bc->pid:-1, ast->context, ast->exten, AST_CID_P(ast), misdn_get_ch_state(p));
1985                 chan_misdn_log(2, bc->port, " --> l3id:%x\n",p->l3id);
1986                 chan_misdn_log(1, bc->port, " --> cause:%d\n",bc->cause);
1987                 chan_misdn_log(1, bc->port, " --> out_cause:%d\n",bc->out_cause);
1988                 
1989                 switch (p->state) {
1990                 case MISDN_CALLING:
1991                         p->state=MISDN_CLEANING;
1992                         misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
1993                         break;
1994                 case MISDN_HOLDED:
1995                 case MISDN_DIALING:
1996                         start_bc_tones(p);
1997                         tone_indicate(p, TONE_BUSY);
1998                         p->state=MISDN_CLEANING;
1999                         
2000                         misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
2001       
2002                         break;
2003       
2004                 case MISDN_ALERTING:
2005                 case MISDN_PROGRESS:
2006                 case MISDN_PROCEEDING:
2007                         chan_misdn_log(2, bc->port, " --> * State Alerting\n");
2008
2009                         if (p->orginator != ORG_AST) 
2010                                 tone_indicate(p, TONE_BUSY);
2011       
2012                         p->state=MISDN_CLEANING;
2013                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
2014                         break;
2015                 case MISDN_CONNECTED:
2016                         /*  Alerting or Disconect */
2017                         chan_misdn_log(2, bc->port, " --> * State Connected\n");
2018                         start_bc_tones(p);
2019                         tone_indicate(p, TONE_BUSY);
2020                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
2021       
2022                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2023                         break;
2024                 case MISDN_DISCONNECTED:
2025                         chan_misdn_log(2, bc->port, " --> * State Disconnected\n");
2026                         misdn_lib_send_event( bc, EVENT_RELEASE);
2027                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2028                         break;
2029
2030                 case MISDN_CLEANING:
2031                         break;
2032       
2033                 case MISDN_HOLD_DISCONNECT:
2034                         /* need to send release here */
2035                         chan_misdn_log(2, bc->port, " --> state HOLD_DISC\n");
2036                         chan_misdn_log(1, bc->port, " --> cause %d\n",bc->cause);
2037                         chan_misdn_log(1, bc->port, " --> out_cause %d\n",bc->out_cause);
2038                         
2039                         bc->out_cause=-1;
2040                         misdn_lib_send_event(bc,EVENT_RELEASE);
2041                         break;
2042                 default:
2043                         /*  Alerting or Disconect */
2044
2045                         if (bc->nt) {
2046                                 bc->out_cause=-1;
2047                                 misdn_lib_send_event(bc, EVENT_RELEASE);
2048                         } else
2049                                 misdn_lib_send_event(bc, EVENT_DISCONNECT);
2050                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2051                 }
2052     
2053         }
2054         
2055
2056         chan_misdn_log(1, bc->port, "Channel: %s hanguped\n",ast->name);
2057         
2058         return 0;
2059 }
2060
2061
2062 struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame *frame)
2063 {
2064         struct ast_frame *f,*f2;
2065         if (tmp->trans)
2066                 f2=ast_translate(tmp->trans, frame,0);
2067         else {
2068                 chan_misdn_log(0, tmp->bc->port, "No T-Path found\n");
2069                 return NULL;
2070         }
2071         
2072         f = ast_dsp_process(tmp->ast, tmp->dsp, f2);
2073         if (f && (f->frametype == AST_FRAME_DTMF)) {
2074                 ast_log(LOG_DEBUG, "Detected inband DTMF digit: %c", f->subclass);
2075                 if (f->subclass == 'f' && tmp->faxdetect) {
2076                         /* Fax tone -- Handle and return NULL */
2077                         struct ast_channel *ast = tmp->ast;
2078                         if (!tmp->faxhandled) {
2079                                 tmp->faxhandled++;
2080                                 if (strcmp(ast->exten, "fax")) {
2081                                         if (ast_exists_extension(ast, ast_strlen_zero(ast->macrocontext)? ast->context : ast->macrocontext, "fax", 1, AST_CID_P(ast))) {
2082                                                 if (option_verbose > 2)
2083                                                         ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension\n", ast->name);
2084                                                 /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
2085                                                 pbx_builtin_setvar_helper(ast,"FAXEXTEN",ast->exten);
2086                                                 if (ast_async_goto(ast, ast->context, "fax", 1))
2087                                                         ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, ast->context);
2088                                         } else
2089                                                 ast_log(LOG_NOTICE, "Fax detected, but no fax extension ctx:%s exten:%s\n",ast->context, ast->exten);
2090                                 } else
2091                                         ast_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
2092                         } else
2093                                 ast_log(LOG_DEBUG, "Fax already handled\n");
2094                         
2095                 }  else if ( tmp->ast_dsp) {
2096                         chan_misdn_log(2, tmp->bc->port, " --> * SEND: DTMF (AST_DSP) :%c\n",f->subclass);
2097                         return f;
2098                 }
2099         }
2100
2101         frame->frametype = AST_FRAME_NULL;
2102         frame->subclass = 0;
2103         return frame;
2104 }
2105
2106
2107 static struct ast_frame  *misdn_read(struct ast_channel *ast)
2108 {
2109         struct chan_list *tmp;
2110         int len;
2111         
2112         if (!ast) return NULL;
2113         if (! (tmp=MISDN_ASTERISK_TECH_PVT(ast)) ) return NULL;
2114         if (!tmp->bc) return NULL;
2115         
2116         len=read(tmp->pipe[0],tmp->ast_rd_buf,sizeof(tmp->ast_rd_buf));
2117
2118         if (len<=0) {
2119                 /* we hangup here, since our pipe is closed */
2120                 chan_misdn_log(2,tmp->bc->port,"misdn_read: Pipe closed, hanging up\n");
2121                 return NULL;
2122         }
2123
2124         tmp->frame.frametype  = AST_FRAME_VOICE;
2125         tmp->frame.subclass = AST_FORMAT_ALAW;
2126         tmp->frame.datalen = len;
2127         tmp->frame.samples = len ;
2128         tmp->frame.mallocd =0 ;
2129         tmp->frame.offset= 0 ;
2130         tmp->frame.src = NULL;
2131         tmp->frame.data = tmp->ast_rd_buf ;
2132         
2133         if (tmp->faxdetect || tmp->ast_dsp ) {
2134                 return process_ast_dsp(tmp, &tmp->frame);
2135         }
2136         
2137         return &tmp->frame;
2138 }
2139
2140
2141 static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
2142 {
2143         struct chan_list *ch;
2144         int i  = 0;
2145         
2146         if (!ast || ! (ch=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
2147         
2148         if (!ch->bc ) {
2149                 ast_log(LOG_WARNING, "private but no bc\n");
2150                 return -1;
2151         }
2152         
2153         if (ch->holded ) {
2154                 chan_misdn_log(5, ch->bc->port, "misdn_write: Returning because holded\n");
2155                 return 0;
2156         }
2157         
2158         if (ch->notxtone) {
2159                 chan_misdn_log(5, ch->bc->port, "misdn_write: Returning because notxone\n");
2160                 return 0;
2161         }
2162
2163
2164         if ( !frame->subclass) {
2165                 chan_misdn_log(4, ch->bc->port, "misdn_write: * prods us\n");
2166                 return 0;
2167         }
2168         
2169         if ( !(frame->subclass & prefformat)) {
2170                 
2171                 chan_misdn_log(-1, ch->bc->port, "Got Unsupported Frame with Format:%d\n", frame->subclass);
2172                 return 0;
2173         }
2174         
2175
2176         if ( !frame->samples ) {
2177                 chan_misdn_log(4, ch->bc->port, "misdn_write: zero write\n");
2178                 return 0;
2179         }
2180
2181         if ( ! ch->bc->addr ) {
2182                 chan_misdn_log(8, ch->bc->port, "misdn_write: no addr for bc dropping:%d\n", frame->samples);
2183                 return 0;
2184         }
2185         
2186 #if MISDN_DEBUG
2187         {
2188                 int i, max=5>frame->samples?frame->samples:5;
2189                 
2190                 printf("write2mISDN %p %d bytes: ", p, frame->samples);
2191                 
2192                 for (i=0; i<  max ; i++) printf("%2.2x ",((char*) frame->data)[i]);
2193                 printf ("\n");
2194         }
2195 #endif
2196
2197
2198         switch (ch->bc->bc_state) {
2199                 case BCHAN_ACTIVATED:
2200                 case BCHAN_BRIDGED:
2201                         break;
2202                 default:
2203                 if (!ch->dropped_frame_cnt)
2204                         chan_misdn_log(5, ch->bc->port, "BC not active (nor bridged) droping: %d frames addr:%x exten:%s cid:%s ch->state:%s bc_state:%d\n",frame->samples,ch->bc->addr, ast->exten, ast->cid.cid_num,misdn_get_ch_state( ch), ch->bc->bc_state);
2205                 
2206                 ch->dropped_frame_cnt++;
2207                 if (ch->dropped_frame_cnt > 100) {
2208                         ch->dropped_frame_cnt=0;
2209                         chan_misdn_log(5, ch->bc->port, "BC not active (nor bridged) droping: %d frames addr:%x  dropped > 100 frames!\n",frame->samples,ch->bc->addr);
2210
2211                 }
2212
2213                 return 0;
2214         }
2215
2216         chan_misdn_log(9, ch->bc->port, "Sending :%d bytes 2 MISDN\n",frame->samples);
2217         
2218         if ( !ch->bc->nojitter && misdn_cap_is_speech(ch->bc->capability) ) {
2219                 /* Buffered Transmit (triggert by read from isdn side)*/
2220                 if (misdn_jb_fill(ch->jb,frame->data,frame->samples) < 0) {
2221                         if (ch->bc->active)
2222                                 cb_log(0,ch->bc->port,"Misdn Jitterbuffer Overflow.\n");
2223                 }
2224                 
2225         } else {
2226                 /*transmit without jitterbuffer*/
2227                 i=misdn_lib_tx2misdn_frm(ch->bc, frame->data, frame->samples);
2228         }
2229
2230         
2231         
2232         return 0;
2233 }
2234
2235
2236
2237
2238 static enum ast_bridge_result  misdn_bridge (struct ast_channel *c0,
2239                                       struct ast_channel *c1, int flags,
2240                                       struct ast_frame **fo,
2241                                       struct ast_channel **rc,
2242                                       int timeoutms)
2243
2244 {
2245         struct chan_list *ch1,*ch2;
2246         struct ast_channel *carr[2], *who;
2247         int to=-1;
2248         struct ast_frame *f;
2249   
2250         ch1=get_chan_by_ast(c0);
2251         ch2=get_chan_by_ast(c1);
2252
2253         carr[0]=c0;
2254         carr[1]=c1;
2255   
2256   
2257         if (ch1 && ch2 ) ;
2258         else
2259                 return -1;
2260   
2261
2262         int bridging;
2263         misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
2264         if (bridging) {
2265                 int ecwb, ec;
2266                 misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2267                 misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
2268                 if ( !ecwb && ec ) {
2269                         chan_misdn_log(2, ch1->bc->port, "Disabling Echo Cancellor when Bridged\n");
2270                         ch1->bc->ec_enable=0;
2271                         manager_ec_disable(ch1->bc);
2272                 }
2273                 misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2274                 misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
2275                 if ( !ecwb && ec) {
2276                         chan_misdn_log(2, ch2->bc->port, "Disabling Echo Cancellor when Bridged\n");
2277                         ch2->bc->ec_enable=0;
2278                         manager_ec_disable(ch2->bc); 
2279                 }
2280                 
2281                 /* trying to make a mISDN_dsp conference */
2282                 chan_misdn_log(1, ch1->bc->port, "I SEND: Making conference with Number:%d\n", ch1->bc->pid +1);
2283
2284                 misdn_lib_bridge(ch1->bc,ch2->bc);
2285         }
2286         
2287         if (option_verbose > 2) 
2288                 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
2289
2290         chan_misdn_log(1, ch1->bc->port, "* Making Native Bridge between %s and %s\n", ch1->bc->oad, ch2->bc->oad);
2291  
2292         if (! (flags&AST_BRIDGE_DTMF_CHANNEL_0) )
2293                 ch1->ignore_dtmf=1;
2294
2295         if (! (flags&AST_BRIDGE_DTMF_CHANNEL_1) )
2296                 ch2->ignore_dtmf=1;
2297
2298         while(1) {
2299                 to=-1;
2300                 who = ast_waitfor_n(carr, 2, &to);
2301
2302                 if (!who) {
2303                         ast_log(LOG_NOTICE,"misdn_bridge: empty read, breaking out\n");
2304                         break;
2305                 }
2306                 f = ast_read(who);
2307     
2308                 if (!f || f->frametype == AST_FRAME_CONTROL) {
2309                         /* got hangup .. */
2310                         *fo=f;
2311                         *rc=who;
2312       
2313                         break;
2314                 }
2315                 
2316                 if ( f->frametype == AST_FRAME_DTMF ) {
2317                         chan_misdn_log(1,0,"Read DTMF %d from %s\n",f->subclass, who->exten);
2318
2319                         *fo=f;
2320                         *rc=who;
2321                         break;
2322                 }
2323                 
2324                 
2325                 if (who == c0) {
2326                         ast_write(c1,f);
2327                 }
2328                 else {
2329                         ast_write(c0,f);
2330                 }
2331     
2332         }
2333         
2334         chan_misdn_log(1, ch1->bc->port, "I SEND: Splitting conference with Number:%d\n", ch1->bc->pid +1);
2335         
2336         misdn_lib_split_bridge(ch1->bc,ch2->bc);
2337         
2338         
2339         return AST_BRIDGE_COMPLETE;
2340 }
2341
2342 /** AST INDICATIONS END **/
2343
2344 static int tone_indicate( struct chan_list *cl, enum tone_e tone)
2345 {
2346         const struct tone_zone_sound *ts= NULL;
2347         struct ast_channel *ast=cl->ast;
2348         
2349         chan_misdn_log(3,cl->bc->port,"Tone Indicate:\n");
2350         
2351         if (!cl->ast) {
2352                 return 0;
2353         }
2354         
2355         switch (tone) {
2356         case TONE_DIAL:
2357                 chan_misdn_log(3,cl->bc->port," --> Dial\n");
2358                 ts=ast_get_indication_tone(ast->zone,"dial");
2359                 misdn_lib_tone_generator_start(cl->bc);
2360                 break;
2361         case TONE_ALERTING:
2362                 chan_misdn_log(3,cl->bc->port," --> Ring\n");
2363                 ts=ast_get_indication_tone(ast->zone,"ring");
2364                 misdn_lib_tone_generator_stop(cl->bc);
2365                 break;
2366         case TONE_FAR_ALERTING:
2367         /* VERY UGLY HACK, BECAUSE CHAN_SIP DOES NOT GENERATE TONES */
2368                 chan_misdn_log(3,cl->bc->port," --> Ring\n");
2369                 ts=ast_get_indication_tone(ast->zone,"ring");
2370                 misdn_lib_tone_generator_start(cl->bc);
2371                 misdn_lib_echo(cl->bc,1);
2372                 break;
2373         case TONE_BUSY:
2374                 chan_misdn_log(3,cl->bc->port," --> Busy\n");
2375                 ts=ast_get_indication_tone(ast->zone,"busy");
2376                 misdn_lib_tone_generator_stop(cl->bc);
2377                 break;
2378         case TONE_FILE:
2379                 break;
2380         case TONE_NONE:
2381                 chan_misdn_log(3,cl->bc->port," --> None\n");
2382                 misdn_lib_tone_generator_stop(cl->bc);
2383                 ast_playtones_stop(ast);
2384                 break;
2385         default:
2386                 chan_misdn_log(0,cl->bc->port,"Don't know how to handle tone: %d\n",tone);
2387         }
2388         
2389         cl->ts=ts;      
2390         
2391         if (ts) ast_playtones_start(ast,0, ts->data, 0);
2392         
2393         return 0;
2394 }
2395
2396 static int start_bc_tones(struct chan_list* cl)
2397 {
2398         manager_bchannel_activate(cl->bc);
2399         misdn_lib_tone_generator_stop(cl->bc);
2400         cl->notxtone=0;
2401         cl->norxtone=0;
2402         return 0;
2403 }
2404
2405 static int stop_bc_tones(struct chan_list *cl)
2406 {
2407         if (cl->bc) {
2408                 manager_bchannel_deactivate(cl->bc);
2409         }
2410         cl->notxtone=1;
2411         cl->norxtone=1;
2412         
2413         return 0;
2414 }
2415
2416
2417 static struct chan_list *init_chan_list(int orig)
2418 {
2419         struct chan_list *cl=malloc(sizeof(struct chan_list));
2420         
2421         if (!cl) {
2422                 chan_misdn_log(-1, 0, "misdn_request: malloc failed!");
2423                 return NULL;
2424         }
2425         
2426         memset(cl,0,sizeof(struct chan_list));
2427
2428         cl->orginator=orig;
2429         
2430         return cl;
2431         
2432 }
2433
2434 static struct ast_channel *misdn_request(const char *type, int format, void *data, int *cause)
2435
2436 {
2437         struct ast_channel *tmp = NULL;
2438         char group[BUFFERSIZE+1]="";
2439         char buf[128];
2440         char buf2[128], *ext=NULL, *port_str;
2441         char *tokb=NULL, *p=NULL;
2442         int channel=0, port=0;
2443         struct misdn_bchannel *newbc = NULL;
2444         
2445         struct chan_list *cl=init_chan_list(ORG_AST);
2446         
2447         sprintf(buf,"%s/%s",misdn_type,(char*)data);
2448         ast_copy_string(buf2,data, 128);
2449         
2450         port_str=strtok_r(buf2,"/", &tokb);
2451
2452         ext=strtok_r(NULL,"/", &tokb);
2453
2454         if (port_str) {
2455                 if (port_str[0]=='g' && port_str[1]==':' ) {
2456                         /* We make a group call lets checkout which ports are in my group */
2457                         port_str += 2;
2458                         strncpy(group, port_str, BUFFERSIZE);
2459                         group[127] = 0;
2460                         chan_misdn_log(2, 0, " --> Group Call group: %s\n",group);
2461                 } 
2462                 else if ((p = strchr(port_str, ':'))) {
2463                         // we have a preselected channel
2464                         *p = 0;
2465                         channel = atoi(++p);
2466                         port = atoi(port_str);
2467                         chan_misdn_log(2, port, " --> Call on preselected Channel (%d).\n", channel);
2468                 }
2469                 else {
2470                         port = atoi(port_str);
2471                 }
2472                 
2473                 
2474         } else {
2475                 ast_log(LOG_WARNING, " --> ! IND : CALL dad:%s WITHOUT PORT/Group, check extension.conf\n",ext);
2476                 return NULL;
2477         }
2478
2479         if (!ast_strlen_zero(group)) {
2480         
2481                 char cfg_group[BUFFERSIZE+1];
2482                 struct robin_list *rr = NULL;
2483
2484                 if (misdn_cfg_is_group_method(group, METHOD_ROUND_ROBIN)) {
2485                         chan_misdn_log(4, port, " --> STARTING ROUND ROBIN...");
2486                         rr = get_robin_position(group);
2487                 }
2488                 
2489                 if (rr) {
2490                         int robin_channel = rr->channel;
2491                         int port_start;
2492                         int next_chan = 1;
2493
2494                         do {
2495                                 port_start = 0;
2496                                 for (port = misdn_cfg_get_next_port_spin(rr->port); port > 0 && port != port_start;
2497                                          port = misdn_cfg_get_next_port_spin(port)) {
2498
2499                                         if (!port_start)
2500                                                 port_start = port;
2501
2502                                         if (port >= port_start)
2503                                                 next_chan = 1;
2504                                         
2505                                         if (port < port_start && next_chan) {
2506                                                 if (++robin_channel >= MAX_BCHANS) {
2507                                                         robin_channel = 1;
2508                                                 }
2509                                                 next_chan = 0;
2510                                         }
2511
2512                                         misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2513                                         
2514                                         if (!strcasecmp(cfg_group, group)) {
2515                                                 int port_up;
2516                                                 int check;
2517                                                 misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
2518                                                 port_up = misdn_lib_port_up(port, check);
2519                                                 
2520                                                 if ( port_up )  {
2521                                                         newbc = misdn_lib_get_free_bc(port, robin_channel);
2522                                                         if (newbc) {
2523                                                                 chan_misdn_log(4, port, " Success! Found port:%d channel:%d\n", newbc->port, newbc->channel);
2524                                                                 if (port_up)
2525                                                                         chan_misdn_log(4, port, "ortup:%d\n",  port_up);
2526                                                                 rr->port = newbc->port;
2527                                                                 rr->channel = newbc->channel;
2528                                                                 break;
2529                                                         }
2530                                                 }
2531                                         }
2532                                 }
2533                         } while (!newbc && robin_channel != rr->channel);
2534                         
2535                         if (!newbc)
2536                                 chan_misdn_log(4, port, " Failed! No free channel in group %d!", group);
2537                 }
2538                 
2539                 else {          
2540                         for (port=misdn_cfg_get_next_port(0); port > 0;
2541                                  port=misdn_cfg_get_next_port(port)) {
2542                                 
2543                                 misdn_cfg_get( port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2544
2545                                 chan_misdn_log(3,port, "Group [%s] Port [%d]\n", group, port);
2546                                 if (!strcasecmp(cfg_group, group)) {
2547                                         int port_up;
2548                                         int check;
2549                                         misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
2550                                         port_up = misdn_lib_port_up(port, check);
2551                                         
2552                                         chan_misdn_log(4, port, "portup:%d\n", port_up);
2553                                         
2554                                         if ( port_up )  {
2555                                                 newbc = misdn_lib_get_free_bc(port, 0);
2556                                                 if (newbc)
2557                                                         break;
2558                                         }
2559                                 }
2560                         }
2561                 }
2562                 
2563         } else {
2564                 if (channel)
2565                         chan_misdn_log(1, port," --> preselected_channel: %d\n",channel);
2566                 newbc = misdn_lib_get_free_bc(port, channel);
2567         }
2568         
2569         if (!newbc) {
2570                 chan_misdn_log(-1, 0, " --> ! No free channel chan ext:%s even after Group Call\n",ext);
2571                 chan_misdn_log(-1, 0, " --> SEND: State Down\n");
2572                 return NULL;
2573         }
2574
2575         /* create ast_channel and link all the objects together */
2576         cl->bc=newbc;
2577         
2578         tmp = misdn_new(cl, AST_STATE_RESERVED, ext, NULL, format, port, channel);
2579         cl->ast=tmp;
2580         
2581         /* register chan in local list */
2582         cl_queue_chan(&cl_te, cl) ;
2583         
2584         /* fill in the config into the objects */
2585         read_config(cl, ORG_AST);
2586         
2587         
2588         return tmp;
2589 }
2590
2591
2592 static int misdn_send_text (struct ast_channel *chan, const char *text)
2593 {
2594         struct chan_list *tmp=chan->tech_pvt;
2595         
2596         if (tmp && tmp->bc) {
2597                 ast_copy_string(tmp->bc->display,text,sizeof(tmp->bc->display));
2598                 misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
2599         } else {
2600                 ast_log(LOG_WARNING, "No chan_list but send_text request?\n");
2601                 return -1;
2602         }
2603         
2604         return 0;
2605 }
2606
2607 static struct ast_channel_tech misdn_tech = {
2608         .type="mISDN",
2609         .description="Channel driver for mISDN Support (Bri/Pri)",
2610         .capabilities= AST_FORMAT_ALAW ,
2611         .requester=misdn_request,
2612         .send_digit=misdn_digit,
2613         .call=misdn_call,
2614         .bridge=misdn_bridge, 
2615         .hangup=misdn_hangup,
2616         .answer=misdn_answer,
2617         .read=misdn_read,
2618         .write=misdn_write,
2619         .indicate=misdn_indication,
2620         .fixup=misdn_fixup,
2621         .send_text=misdn_send_text,
2622         .properties=0
2623 };
2624
2625 static struct ast_channel_tech misdn_tech_wo_bridge = {
2626         .type="mISDN",
2627         .description="Channel driver for mISDN Support (Bri/Pri)",
2628         .capabilities=AST_FORMAT_ALAW ,
2629         .requester=misdn_request,
2630         .send_digit=misdn_digit,
2631         .call=misdn_call,
2632         .hangup=misdn_hangup,
2633         .answer=misdn_answer,
2634         .read=misdn_read,
2635         .write=misdn_write,
2636         .indicate=misdn_indication,
2637         .fixup=misdn_fixup,
2638         .send_text=misdn_send_text,
2639         .properties=0
2640 };
2641
2642
2643 static unsigned long glob_channel=0;
2644
2645 static void update_name(struct ast_channel *tmp, int port, int c) 
2646 {
2647         if (c<=0) {
2648                         c=glob_channel++;
2649                         ast_string_field_build(tmp, name, "%s/%d-u%d",
2650                                  misdn_type, port, c);
2651         } else {
2652                          ast_string_field_build(tmp, name, "%s/%d-%d",
2653                                  misdn_type, port, c);
2654         }
2655
2656         chan_misdn_log(3,port," --> updating channel name to [%s]\n",tmp->name);
2657         
2658 }
2659
2660 static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char *exten, char *callerid, int format, int port, int c)
2661 {
2662         struct ast_channel *tmp;
2663         
2664         tmp = ast_channel_alloc(1);
2665         
2666         if (tmp) {
2667                 chan_misdn_log(2, 0, " --> * NEW CHANNEL dad:%s oad:%s\n",exten,callerid);
2668                 
2669                 update_name(tmp,port,c);
2670         
2671                 tmp->nativeformats = prefformat;
2672
2673                 tmp->readformat = format;
2674                 tmp->rawreadformat = format;
2675                 tmp->writeformat = format;
2676                 tmp->rawwriteformat = format;
2677     
2678                 tmp->tech_pvt = chlist;
2679                 
2680                 int bridging;
2681                 misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
2682                 if (bridging)
2683                         tmp->tech = &misdn_tech;
2684                 else
2685                         tmp->tech = &misdn_tech_wo_bridge;
2686                 
2687                 tmp->writeformat = format;
2688                 tmp->readformat = format;
2689                 tmp->priority=1;
2690                 
2691                 if (exten) 
2692                         ast_copy_string(tmp->exten, exten,  sizeof(tmp->exten));
2693                 else
2694                         chan_misdn_log(1,0,"misdn_new: no exten given.\n");
2695                 
2696                 if (callerid) {
2697                         char *cid_name, *cid_num;
2698       
2699                         ast_callerid_parse(callerid, &cid_name, &cid_num);
2700                         ast_set_callerid(tmp, cid_num,cid_name,cid_num);
2701                 } else {
2702                         ast_set_callerid(tmp, NULL,NULL,NULL);
2703                 }
2704
2705                 {
2706                         if (pipe(chlist->pipe)<0)
2707                                 perror("Pipe failed\n");
2708                         
2709                         tmp->fds[0]=chlist->pipe[0];
2710                         
2711                 }
2712                 
2713                 ast_setstate(tmp, state);
2714                 if (state == AST_STATE_RING)
2715                         tmp->rings = 1;
2716                 else
2717                         tmp->rings = 0;
2718                 
2719                 
2720         } else {
2721                 chan_misdn_log(-1,0,"Unable to allocate channel structure\n");
2722         }
2723         
2724         return tmp;
2725 }
2726
2727 static struct chan_list *find_chan_by_l3id(struct chan_list *list, unsigned long l3id)
2728 {
2729         struct chan_list *help=list;
2730         for (;help; help=help->next) {
2731                 if (help->l3id == l3id ) return help;
2732         }
2733   
2734         chan_misdn_log(6, list? (list->bc? list->bc->port : 0) : 0, "$$$ find_chan: No channel found with l3id:%x\n",l3id);
2735   
2736         return NULL;
2737 }
2738
2739 static struct chan_list *find_chan_by_bc(struct chan_list *list, struct misdn_bchannel *bc)
2740 {
2741         struct chan_list *help=list;
2742         for (;help; help=help->next) {
2743                 if (help->bc == bc) return help;
2744         }
2745   
2746         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
2747   
2748         return NULL;
2749 }
2750
2751
2752 static struct chan_list *find_holded(struct chan_list *list, struct misdn_bchannel *bc)
2753 {
2754         struct chan_list *help=list;
2755         
2756         chan_misdn_log(6, bc->port, "$$$ find_holded: channel:%d oad:%s dad:%s\n",bc->channel, bc->oad,bc->dad);
2757         for (;help; help=help->next) {
2758                 chan_misdn_log(4, bc->port, "$$$ find_holded: --> holded:%d channel:%d\n",help->bc->holded, help->bc->channel);
2759                 if (help->bc->port == bc->port
2760                     && help->bc->holded ) return help;
2761         }
2762         
2763         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
2764   
2765         return NULL;
2766 }
2767
2768 static void cl_queue_chan(struct chan_list **list, struct chan_list *chan)
2769 {
2770         chan_misdn_log(4, chan->bc? chan->bc->port : 0, "* Queuing chan %p\n",chan);
2771   
2772         ast_mutex_lock(&cl_te_lock);
2773         if (!*list) {
2774                 *list = chan;
2775         } else {
2776                 struct chan_list *help=*list;
2777                 for (;help->next; help=help->next); 
2778                 help->next=chan;
2779         }
2780         chan->next=NULL;
2781         ast_mutex_unlock(&cl_te_lock);
2782 }
2783
2784 static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan) 
2785 {
2786         if (chan->dsp) 
2787                 ast_dsp_free(chan->dsp);
2788         if (chan->trans)
2789                 ast_translator_free_path(chan->trans);
2790
2791         
2792
2793         ast_mutex_lock(&cl_te_lock);
2794         if (!*list) {
2795                 ast_mutex_unlock(&cl_te_lock);
2796                 return;
2797         }
2798   
2799         if (*list == chan) {
2800                 *list=(*list)->next;
2801                 ast_mutex_unlock(&cl_te_lock);
2802                 return ;
2803         }
2804   
2805         {
2806                 struct chan_list *help=*list;
2807                 for (;help->next; help=help->next) {
2808                         if (help->next == chan) {
2809                                 help->next=help->next->next;
2810                                 ast_mutex_unlock(&cl_te_lock);
2811                                 return;
2812                         }
2813                 }
2814         }
2815         
2816         ast_mutex_unlock(&cl_te_lock);
2817 }
2818
2819 /** Channel Queue End **/
2820
2821
2822
2823 /** Isdn asks us to release channel, pendant to misdn_hangup **/
2824 static void release_chan(struct misdn_bchannel *bc) {
2825         struct ast_channel *ast=NULL;
2826         
2827         {
2828                 struct chan_list *ch=find_chan_by_bc(cl_te, bc);
2829                 if (!ch) ch=find_chan_by_l3id (cl_te, bc->l3_id);
2830                 if (!ch)  {
2831                         chan_misdn_log(0, bc->port, "release_chan: Ch not found!\n");
2832                         return;
2833                 }
2834                 
2835                 release_lock;
2836                 if (ch->ast) {
2837                         ast=ch->ast;
2838                 } 
2839                 release_unlock;
2840                 
2841                 chan_misdn_log(1, bc->port, "release_chan: bc with l3id: %x\n",bc->l3_id);
2842                 
2843                 //releaseing jitterbuffer
2844                 if (ch->jb ) {
2845                         misdn_jb_destroy(ch->jb);
2846                         ch->jb=NULL;
2847                 } else {
2848                         if (!bc->nojitter)
2849                                 chan_misdn_log(5,bc->port,"Jitterbuffer already destroyed.\n");
2850                 }
2851
2852
2853                 if (ch->orginator == ORG_AST) {
2854                         misdn_out_calls[bc->port]--;
2855                 } else {
2856                         misdn_in_calls[bc->port]--;
2857                 }
2858                 
2859                 if (ch) {
2860                         
2861                         close(ch->pipe[0]);
2862                         close(ch->pipe[1]);
2863                         
2864                         if (ast && MISDN_ASTERISK_TECH_PVT(ast)) {
2865                                 chan_misdn_log(1, bc->port, "* RELEASING CHANNEL pid:%d ctx:%s dad:%s oad:%s state: %s\n",bc?bc->pid:-1, ast->context, ast->exten,AST_CID_P(ast),misdn_get_ch_state(ch));
2866                                 chan_misdn_log(3, bc->port, " --> * State Down\n");
2867                                 /* copy cause */
2868                                 send_cause2ast(ast,bc);
2869                                 
2870                                 MISDN_ASTERISK_TECH_PVT(ast)=NULL;
2871                                 
2872       
2873                                 if (ast->_state != AST_STATE_RESERVED) {
2874                                         chan_misdn_log(3, bc->port, " --> Setting AST State to down\n");
2875                                         ast_setstate(ast, AST_STATE_DOWN);
2876                                 }
2877                                 
2878                                 switch(ch->state) {
2879                                 case MISDN_EXTCANTMATCH:
2880                                 case MISDN_WAITING4DIGS:
2881                                 {
2882                                         chan_misdn_log(3,  bc->port, " --> * State Wait4dig | ExtCantMatch\n");
2883                                         ast_hangup(ast);
2884                                 }
2885                                 break;
2886                                 
2887                                 case MISDN_DIALING:
2888                                 case MISDN_CALLING_ACKNOWLEDGE:
2889                                 case MISDN_PROGRESS:
2890                                         chan_misdn_log(2,  bc->port, "* --> In State Dialin\n");
2891                                         chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2892                                         
2893
2894                                         ast_queue_hangup(ast);
2895                                         break;
2896                                 case MISDN_CALLING:
2897                                         
2898                                         chan_misdn_log(2,  bc->port, "* --> In State Callin\n");
2899                                         
2900                                         if (!bc->nt) {
2901                                                 chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2902                                                 ast_queue_hangup(ast);
2903                                         } else {
2904                                                 chan_misdn_log(2,  bc->port, "* --> Hangup\n");
2905                                                 ast_queue_hangup(ast);
2906                                         }
2907                                         break;
2908                                         
2909                                 case MISDN_CLEANING:
2910                                         /* this state comes out of ast so we mustnt call a ast function ! */
2911                                         chan_misdn_log(2,  bc->port, "* --> In StateCleaning\n");
2912                                         break;
2913                                 case MISDN_HOLD_DISCONNECT:
2914                                         chan_misdn_log(2,  bc->port, "* --> In HOLD_DISC\n");
2915                                         break;
2916                                 default:
2917                                         chan_misdn_log(2,  bc->port, "* --> In State Default\n");
2918                                         chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2919                                         if (ast) {
2920                                                 ast_queue_hangup(ast);
2921                                         } else {
2922                                                 chan_misdn_log (0,  bc->port, "!! Not really queued!\n");
2923                                         }
2924                                 }
2925                         }
2926                         cl_dequeue_chan(&cl_te, ch);
2927                         
2928                         free(ch);
2929                 } else {
2930                         /* chan is already cleaned, so exiting  */
2931                 }
2932         }
2933 }
2934 /*** release end **/
2935
2936 static void misdn_transfer_bc(struct chan_list *tmp_ch, struct chan_list *holded_chan)
2937 {
2938         chan_misdn_log(4,0,"TRANSFERING %s to %s\n",holded_chan->ast->name, tmp_ch->ast->name);
2939         
2940         tmp_ch->state=MISDN_HOLD_DISCONNECT;
2941   
2942         ast_moh_stop(AST_BRIDGED_P(holded_chan->ast));
2943
2944         holded_chan->state=MISDN_CONNECTED;
2945         holded_chan->holded=0;
2946         misdn_lib_transfer(holded_chan->bc?holded_chan->bc:holded_chan->holded_bc);
2947         ast_channel_masquerade(holded_chan->ast, AST_BRIDGED_P(tmp_ch->ast));
2948 }
2949
2950
2951 static void do_immediate_setup(struct misdn_bchannel *bc,struct chan_list *ch , struct ast_channel *ast)
2952 {
2953         char predial[256]="";
2954         char *p = predial;
2955   
2956         struct ast_frame fr;
2957   
2958         strncpy(predial, ast->exten, sizeof(predial) -1 );
2959   
2960         ch->state=MISDN_DIALING;
2961
2962         if (bc->nt) {
2963                 int ret; 
2964                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
2965         } else {
2966                 int ret;
2967                 if ( misdn_lib_is_ptp(bc->port)) {
2968                         ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
2969                 } else {
2970                         ret = misdn_lib_send_event(bc, EVENT_PROCEEDING );
2971                 }
2972         }
2973
2974         if ( !bc->nt && (ch->orginator==ORG_MISDN) && !ch->incoming_early_audio ) 
2975                 chan_misdn_log(1,bc->port, " --> incoming_early_audio off\n");
2976          else 
2977                 tone_indicate(ch,TONE_DIAL);  
2978   
2979         chan_misdn_log(1, bc->port, "* Starting Ast ctx:%s dad:%s oad:%s with 's' extension\n", ast->context, ast->exten, AST_CID_P(ast));
2980   
2981         strncpy(ast->exten,"s", 2);
2982   
2983         if (ast_pbx_start(ast)<0) {
2984                 ast=NULL;
2985                 tone_indicate(ch,TONE_BUSY);
2986
2987                 if (bc->nt)
2988                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
2989                 else
2990                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
2991         }
2992   
2993   
2994         while (!ast_strlen_zero(p) ) {
2995                 fr.frametype = AST_FRAME_DTMF;
2996                 fr.subclass = *p ;
2997                 fr.src=NULL;
2998                 fr.data = NULL ;
2999                 fr.datalen = 0;
3000                 fr.samples = 0 ;
3001                 fr.mallocd =0 ;
3002                 fr.offset= 0 ;
3003
3004                 if (ch->ast && MISDN_ASTERISK_PVT(ch->ast) && MISDN_ASTERISK_TECH_PVT(ch->ast)) {
3005                         ast_queue_frame(ch->ast, &fr);
3006                 }
3007                 p++;
3008         }
3009 }
3010
3011
3012
3013 static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc) {
3014         
3015         ast->hangupcause=bc->cause;
3016         
3017         switch ( bc->cause) {
3018                 
3019         case 1: /** Congestion Cases **/
3020         case 2:
3021         case 3:
3022         case 4:
3023         case 22:
3024         case 27:
3025                 /*
3026                  * Not Queueing the Congestion anymore, since we want to hear
3027                  * the inband message
3028                  *
3029                 chan_misdn_log(1, bc?bc->port:0, " --> * SEND: Queue Congestion pid:%d\n", bc?bc->pid:-1);
3030                 
3031                 ast_queue_control(ast, AST_CONTROL_CONGESTION);
3032                 */
3033                 break;
3034                 
3035         case 21:
3036         case 17: /* user busy */
3037                 chan_misdn_log(1,  bc?bc->port:0, " --> * SEND: Queue Busy pid:%d\n", bc?bc->pid:-1);
3038                 
3039                 ast_queue_control(ast, AST_CONTROL_BUSY);
3040                 
3041                 break;
3042         }
3043 }
3044
3045 void import_ies(struct ast_channel *chan, struct misdn_bchannel *bc)
3046 {
3047         const char *tmp;
3048
3049         tmp=pbx_builtin_getvar_helper(chan,"PRI_MODE");
3050         if (tmp) bc->mode=atoi(tmp);
3051
3052         tmp=pbx_builtin_getvar_helper(chan,"PRI_URATE");
3053         if (tmp) bc->urate=atoi(tmp);
3054
3055         tmp=pbx_builtin_getvar_helper(chan,"PRI_RATE");
3056         if (tmp) bc->rate=atoi(tmp);
3057
3058         tmp=pbx_builtin_getvar_helper(chan,"PRI_USER1");
3059         if (tmp) bc->user1=atoi(tmp);
3060
3061         tmp=pbx_builtin_getvar_helper(chan,"PRI_PROGRESS_INDICATOR");
3062         if (tmp) bc->progress_indicator=atoi(tmp);
3063 }
3064
3065 void export_ies(struct ast_channel *chan, struct misdn_bchannel *bc)
3066 {
3067         char tmp[32];
3068         
3069         sprintf(tmp,"%d",bc->mode);
3070         pbx_builtin_setvar_helper(chan,"_PRI_MODE",tmp);
3071
3072         sprintf(tmp,"%d",bc->urate);
3073         pbx_builtin_setvar_helper(chan,"_PRI_URATE",tmp);
3074
3075         sprintf(tmp,"%d",bc->rate);
3076         pbx_builtin_setvar_helper(chan,"_PRI_RATE",tmp);
3077         
3078         sprintf(tmp,"%d",bc->user1);
3079         pbx_builtin_setvar_helper(chan,"_PRI_USER1",tmp);
3080         
3081         sprintf(tmp,"%d",bc->progress_indicator);
3082         pbx_builtin_setvar_helper(chan,"_PRI_PROGRESS_INDICATOR",tmp);
3083 }
3084
3085
3086 int add_in_calls(int port)
3087 {
3088         int max_in_calls;
3089         
3090         misdn_cfg_get( port, MISDN_CFG_MAX_IN, &max_in_calls, sizeof(max_in_calls));
3091
3092         misdn_in_calls[port]++;
3093
3094         if (max_in_calls >=0 && max_in_calls<misdn_in_calls[port]) {
3095                 ast_log(LOG_NOTICE,"Marking Incoming Call on port[%d]\n",port);
3096                 return misdn_in_calls[port]-max_in_calls;
3097         }
3098         
3099         return 0;
3100 }
3101
3102 int add_out_calls(int port)
3103 {
3104         int max_out_calls;
3105         
3106         misdn_cfg_get( port, MISDN_CFG_MAX_OUT, &max_out_calls, sizeof(max_out_calls));
3107         
3108
3109         if (max_out_calls >=0 && max_out_calls<=misdn_out_calls[port]) {
3110                 ast_log(LOG_NOTICE,"Rejecting Outgoing Call on port[%d]\n",port);
3111                 return (misdn_out_calls[port]+1)-max_out_calls;
3112         }
3113
3114         misdn_out_calls[port]++;
3115         
3116         return 0;
3117 }
3118
3119
3120
3121 /************************************************************/
3122 /*  Receive Events from isdn_lib  here                     */
3123 /************************************************************/
3124 static enum event_response_e
3125 cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
3126 {
3127         struct chan_list *ch=find_chan_by_bc(cl_te, bc);
3128         
3129         if (!ch)
3130                 ch=find_chan_by_l3id(cl_te, bc->l3_id);
3131         
3132         if (event != EVENT_BCHAN_DATA && event != EVENT_TONE_GENERATE) { /*  Debug Only Non-Bchan */
3133                 chan_misdn_log(1, bc->port, "I IND :%s oad:%s dad:%s\n", manager_isdn_get_info(event), bc->oad, bc->dad);
3134                 misdn_lib_log_ies(bc);
3135                 chan_misdn_log(2,bc->port," --> bc_state:%s\n",bc_state2str(bc->bc_state));
3136         }
3137         
3138         if (event != EVENT_SETUP) {
3139                 if (!ch) {
3140                         if (event != EVENT_CLEANUP )
3141                                 ast_log(LOG_WARNING, "Chan not existing at the moment bc->l3id:%x bc:%p event:%s port:%d channel:%d\n",bc->l3_id, bc, manager_isdn_get_info( event), bc->port,bc->channel);
3142                         return -1;
3143                 }
3144         }
3145         
3146         if (ch ) {
3147                 switch (event) {
3148                 case EVENT_RELEASE:
3149                 case EVENT_RELEASE_COMPLETE:
3150                 case EVENT_CLEANUP:
3151                         break;
3152                 default:
3153                         if ( !ch->ast  || !MISDN_ASTERISK_PVT(ch->ast) || !MISDN_ASTERISK_TECH_PVT(ch->ast)) {
3154                                 if (event!=EVENT_BCHAN_DATA)
3155                                         ast_log(LOG_WARNING, "No Ast or No private Pointer in Event (%d:%s)\n", event, manager_isdn_get_info(event));
3156                                 return -1;
3157                         }
3158                 }
3159         }
3160         
3161         
3162         switch (event) {
3163                 
3164    &nb