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