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