use set_callerid to update callerid with prefix
[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                 ast_set_callerid(ast, bc->oad, NULL, bc->oad);
1512                 
1513                 if ( !ast_strlen_zero(bc->rad) ) {
1514                         if (ast->cid.cid_rdnis)
1515                                 free(ast->cid.cid_rdnis);
1516                         ast->cid.cid_rdnis = strdup(bc->rad);
1517                 }
1518         }
1519         return 0;
1520 }
1521
1522
1523 /*****************************/
1524 /*** AST Indications Start ***/
1525 /*****************************/
1526
1527 static int misdn_call(struct ast_channel *ast, char *dest, int timeout)
1528 {
1529         int port=0;
1530         int r;
1531         struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
1532         struct misdn_bchannel *newbc;
1533         char *opts=NULL, *ext,*tokb;
1534         char dest_cp[256];
1535
1536         {
1537                 strncpy(dest_cp,dest,sizeof(dest_cp)-1);
1538                 dest_cp[sizeof(dest_cp)]=0;
1539                 
1540                 ext=strtok_r(dest_cp,"/",&tokb);
1541                 
1542                 if (ext) {
1543                         ext=strtok_r(NULL,"/",&tokb);
1544                         if (ext) {
1545                                 opts=strtok_r(NULL,"/",&tokb);
1546                         } else {
1547                                 chan_misdn_log(-1,0,"misdn_call: No Extension given!\n");
1548                                 return -1;
1549                         }
1550                         
1551                 }
1552                 
1553                 
1554         }
1555
1556         if (!ast) {
1557                 ast_log(LOG_WARNING, " --> ! misdn_call called on ast_channel *ast where ast == NULL\n");
1558                 return -1;
1559         }
1560
1561         if (((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) || !dest  ) {
1562                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1563                 ast->hangupcause=41;
1564                 ast_setstate(ast, AST_STATE_DOWN);
1565                 return -1;
1566         }
1567
1568
1569         if (!ch) {
1570                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1571                 ast->hangupcause=41;
1572                 ast_setstate(ast, AST_STATE_DOWN);
1573                 return -1;
1574         }
1575         
1576         newbc=ch->bc;
1577         
1578         if (!newbc) {
1579                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1580                 ast->hangupcause=41;
1581                 ast_setstate(ast, AST_STATE_DOWN);
1582                 return -1;
1583         }
1584         
1585         port=newbc->port;
1586         strncpy(newbc->dad,ext,sizeof( newbc->dad));
1587         strncpy(ast->exten,ext,sizeof(ast->exten));
1588         
1589         
1590         chan_misdn_log(1, port, "* CALL: %s\n",dest);
1591         
1592         chan_misdn_log(1, port, " --> * dad:%s tech:%s ctx:%s\n",ast->exten,ast->name, ast->context);
1593         
1594         
1595         
1596         chan_misdn_log(3, port, " --> * adding2newbc ext %s\n",ast->exten);
1597         if (ast->exten) {
1598                 int l = sizeof(newbc->dad);
1599                 strncpy(newbc->dad,ast->exten, l);
1600                 newbc->dad[l-1] = 0;
1601         }
1602         newbc->rad[0]=0;
1603         chan_misdn_log(3, port, " --> * adding2newbc callerid %s\n",AST_CID_P(ast));
1604         if (ast_strlen_zero(newbc->oad) && AST_CID_P(ast) ) {
1605
1606                 if (AST_CID_P(ast)) {
1607                         int l = sizeof(newbc->oad);
1608                         strncpy(newbc->oad,AST_CID_P(ast), l);
1609                         newbc->oad[l-1] = 0;
1610                 }
1611         }
1612         
1613         {
1614                 struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
1615                 if (!ch) { ast_verbose("No chan_list in misdn_call"); return -1;}
1616                 
1617                 newbc->capability=ast->transfercapability;
1618                 pbx_builtin_setvar_helper(ast,"TRANSFERCAPABILITY",ast_transfercapability2str(newbc->capability));
1619                 if ( ast->transfercapability == INFO_CAPABILITY_DIGITAL_UNRESTRICTED) {
1620                         chan_misdn_log(2, port, " --> * Call with flag Digital\n");
1621                 }
1622                 
1623
1624                 /* update screening and presentation */ 
1625                 update_config(ch,ORG_AST);
1626                 
1627                 /* fill in some ies from channel vary*/
1628                 import_ies(ast, newbc);
1629                 
1630                 /* Finally The Options Override Everything */
1631                 if (opts)
1632                         misdn_set_opt_exec(ast,opts);
1633                 else
1634                         chan_misdn_log(2,port,"NO OPTS GIVEN\n");
1635                 
1636                 
1637                 ch->state=MISDN_CALLING;
1638                 
1639                 r=misdn_lib_send_event( newbc, EVENT_SETUP );
1640                 
1641                 /** we should have l3id after sending setup **/
1642                 ch->l3id=newbc->l3_id;
1643         }
1644         
1645         if ( r == -ENOCHAN  ) {
1646                 chan_misdn_log(0, port, " --> * Theres no Channel at the moment .. !\n");
1647                 chan_misdn_log(1, port, " --> * SEND: State Down pid:%d\n",newbc?newbc->pid:-1);
1648                 ast->hangupcause=34;
1649                 ast_setstate(ast, AST_STATE_DOWN);
1650                 return -1;
1651         }
1652         
1653         chan_misdn_log(1, port, " --> * SEND: State Dialing pid:%d\n",newbc?newbc->pid:1);
1654
1655         ast_setstate(ast, AST_STATE_DIALING);
1656         ast->hangupcause=16;
1657         return 0; 
1658 }
1659
1660
1661 static int misdn_answer(struct ast_channel *ast)
1662 {
1663         struct chan_list *p;
1664
1665         
1666         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
1667         
1668         chan_misdn_log(1, p? (p->bc? p->bc->port : 0) : 0, "* ANSWER:\n");
1669         
1670         if (!p) {
1671                 ast_log(LOG_WARNING, " --> Channel not connected ??\n");
1672                 ast_queue_hangup(ast);
1673         }
1674
1675         if (!p->bc) {
1676                 chan_misdn_log(1, 0, " --> Got Answer, but theres no bc obj ??\n");
1677
1678                 ast_queue_hangup(ast);
1679         }
1680
1681         {
1682                 const char *tmp_key = pbx_builtin_getvar_helper(p->ast, "CRYPT_KEY");
1683                 
1684                 if (tmp_key ) {
1685                         chan_misdn_log(1, p->bc->port, " --> Connection will be BF crypted\n");
1686                         {
1687                                 int l = sizeof(p->bc->crypt_key);
1688                                 strncpy(p->bc->crypt_key,tmp_key, l);
1689                                 p->bc->crypt_key[l-1] = 0;
1690                         }
1691                 } else {
1692                         chan_misdn_log(3, p->bc->port, " --> Connection is without BF encryption\n");
1693                 }
1694     
1695         }
1696
1697         {
1698                 const char *nodsp=pbx_builtin_getvar_helper(ast, "MISDN_DIGITAL_TRANS");
1699                 if (nodsp) {
1700                         chan_misdn_log(1, p->bc->port, " --> Connection is transparent digital\n");
1701                         p->bc->nodsp=1;
1702                         p->bc->hdlc=0;
1703                         p->bc->nojitter=1;
1704                 }
1705         }
1706         
1707         p->state = MISDN_CONNECTED;
1708
1709         if ( ast_strlen_zero(p->bc->cad) ) {
1710                 chan_misdn_log(2,p->bc->port," --> empty cad using dad\n");
1711                 ast_copy_string(p->bc->cad,p->bc->dad,sizeof(p->bc->cad));
1712         }
1713
1714         misdn_lib_send_event( p->bc, EVENT_CONNECT);
1715         start_bc_tones(p);
1716         
1717         return 0;
1718 }
1719
1720 static int misdn_digit(struct ast_channel *ast, char digit )
1721 {
1722         struct chan_list *p;
1723         
1724         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) return -1;
1725
1726         struct misdn_bchannel *bc=p->bc;
1727         chan_misdn_log(1, bc?bc->port:0, "* IND : Digit %c\n",digit);
1728         
1729         if (!bc) {
1730                 ast_log(LOG_WARNING, " --> !! Got Digit Event withut having bchannel Object\n");
1731                 return -1;
1732         }
1733         
1734         switch (p->state ) {
1735                 case MISDN_CALLING:
1736                 {
1737                         
1738                         char buf[8];
1739                         buf[0]=digit;
1740                         buf[1]=0;
1741                         
1742                         int l = sizeof(bc->infos_pending);
1743                         strncat(bc->infos_pending,buf,l);
1744                         bc->infos_pending[l-1] = 0;
1745                 }
1746                 break;
1747                 case MISDN_CALLING_ACKNOWLEDGE:
1748                 {
1749                         bc->info_dad[0]=digit;
1750                         bc->info_dad[1]=0;
1751                         
1752                         {
1753                                 int l = sizeof(bc->dad);
1754                                 strncat(bc->dad,bc->info_dad, l - strlen(bc->dad));
1755                                 bc->dad[l-1] = 0;
1756                 }
1757                         {
1758                                 int l = sizeof(p->ast->exten);
1759                                 strncpy(p->ast->exten, bc->dad, l);
1760                                 p->ast->exten[l-1] = 0;
1761                         }
1762                         
1763                         misdn_lib_send_event( bc, EVENT_INFORMATION);
1764                 }
1765                 break;
1766                 
1767                 default:
1768                         if ( bc->send_dtmf ) {
1769                                 send_digit_to_chan(p,digit);
1770                         }
1771                 break;
1772         }
1773         
1774         return 0;
1775 }
1776
1777
1778 static int misdn_fixup(struct ast_channel *oldast, struct ast_channel *ast)
1779 {
1780         struct chan_list *p;
1781         
1782         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) )) return -1;
1783         
1784         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);
1785         
1786         p->ast = ast ;
1787         p->state=MISDN_CONNECTED;
1788   
1789         return 0;
1790 }
1791
1792
1793
1794 static int misdn_indication(struct ast_channel *ast, int cond)
1795 {
1796         struct chan_list *p;
1797
1798   
1799         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) {
1800                 ast_log(LOG_WARNING, "Returnded -1 in misdn_indication\n");
1801                 return -1;
1802         }
1803         
1804         if (!p->bc ) {
1805                 chan_misdn_log(1, 0, "* IND : Indication from %s\n",ast->exten);
1806                 ast_log(LOG_WARNING, "Private Pointer but no bc ?\n");
1807                 return -1;
1808         }
1809         
1810         chan_misdn_log(1, p->bc->port, "* IND : Indication [%d] from %s\n",cond, ast->exten);
1811         
1812         switch (cond) {
1813         case AST_CONTROL_BUSY:
1814                 chan_misdn_log(1, p->bc->port, "* IND :\tbusy\n");
1815                 chan_misdn_log(1, p->bc->port, " --> * SEND: State Busy pid:%d\n",p->bc?p->bc->pid:-1);
1816                 ast_setstate(ast,AST_STATE_BUSY);
1817                 
1818                 p->bc->out_cause=17;
1819                 if (p->state != MISDN_CONNECTED) {
1820                         misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
1821                         tone_indicate(p, TONE_BUSY);
1822                 } else {
1823
1824                         chan_misdn_log(-1, p->bc->port, " --> !! Got Busy in Connected State !?! ast:%s\n", ast->name);
1825                 }
1826                 break;
1827         case AST_CONTROL_RING:
1828                 chan_misdn_log(1, p->bc->port, " --> * IND :\tring pid:%d\n",p->bc?p->bc->pid:-1);
1829                 break;
1830         case AST_CONTROL_RINGING:
1831                 switch (p->state) {
1832                         case MISDN_ALERTING:
1833                                 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);
1834                                 break;
1835                         case MISDN_CONNECTED:
1836                                 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);
1837                                 tone_indicate(p, TONE_ALERTING);
1838                                 break;
1839                         default:
1840                                 p->state=MISDN_ALERTING;
1841                                 chan_misdn_log(1, p->bc->port, " --> * IND :\tringing pid:%d\n",p->bc?p->bc->pid:-1);
1842                                 misdn_lib_send_event( p->bc, EVENT_ALERTING);
1843                                 
1844                                 if ( !p->bc->nt && (p->orginator==ORG_MISDN) && !p->incoming_early_audio ) 
1845                                         chan_misdn_log(1,p->bc->port, " --> incoming_early_audio off\n");
1846                                  else 
1847                                          tone_indicate(p, TONE_ALERTING);
1848                                 chan_misdn_log(1, p->bc->port, " --> * SEND: State Ring pid:%d\n",p->bc?p->bc->pid:-1);
1849                                 ast_setstate(ast,AST_STATE_RINGING);
1850                 }
1851                 break;
1852         case AST_CONTROL_ANSWER:
1853                 chan_misdn_log(1, p->bc->port, " --> * IND :\tanswer pid:%d\n",p->bc?p->bc->pid:-1);
1854                 start_bc_tones(p);
1855                 break;
1856         case AST_CONTROL_TAKEOFFHOOK:
1857                 chan_misdn_log(1, p->bc->port, " --> *\ttakeoffhook pid:%d\n",p->bc?p->bc->pid:-1);
1858                 break;
1859         case AST_CONTROL_OFFHOOK:
1860                 chan_misdn_log(1, p->bc->port, " --> *\toffhook pid:%d\n",p->bc?p->bc->pid:-1);
1861                 break; 
1862         case AST_CONTROL_FLASH:
1863                 chan_misdn_log(1, p->bc->port, " --> *\tflash pid:%d\n",p->bc?p->bc->pid:-1);
1864                 break;
1865         case AST_CONTROL_PROGRESS:
1866                 chan_misdn_log(1, p->bc->port, " --> * IND :\tprogress pid:%d\n",p->bc?p->bc->pid:-1);
1867                 misdn_lib_send_event( p->bc, EVENT_PROGRESS);
1868                 break;
1869         case AST_CONTROL_PROCEEDING:
1870                 chan_misdn_log(1, p->bc->port, " --> * IND :\tproceeding pid:%d\n",p->bc?p->bc->pid:-1);
1871                 misdn_lib_send_event( p->bc, EVENT_PROCEEDING);
1872                 break;
1873         case AST_CONTROL_CONGESTION:
1874                 chan_misdn_log(1, p->bc->port, " --> * IND :\tcongestion pid:%d\n",p->bc?p->bc->pid:-1);
1875
1876                 p->bc->out_cause=42;
1877                 if (p->state != MISDN_CONNECTED) {
1878                         start_bc_tones(p);
1879                         misdn_lib_send_event( p->bc, EVENT_RELEASE);
1880                 } else {
1881                         misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
1882                 }
1883
1884                 if (p->bc->nt) {
1885                         tone_indicate(p, TONE_BUSY);
1886                 }
1887                 break;
1888         case -1 :
1889                 chan_misdn_log(1, p->bc->port, " --> * IND :\t-1! (stop indication) pid:%d\n",p->bc?p->bc->pid:-1);
1890                 
1891                 if (p->state == MISDN_CONNECTED)
1892                         start_bc_tones(p);
1893                 else 
1894                         tone_indicate(p, TONE_NONE);
1895                 break;
1896
1897         case AST_CONTROL_HOLD:
1898                 chan_misdn_log(1, p->bc->port, " --> *\tHOLD pid:%d\n",p->bc?p->bc->pid:-1);
1899                 break;
1900         case AST_CONTROL_UNHOLD:
1901                 chan_misdn_log(1, p->bc->port, " --> *\tUNHOLD pid:%d\n",p->bc?p->bc->pid:-1);
1902                 break;
1903         default:
1904                 ast_log(LOG_WARNING, " --> * Unknown Indication:%d pid:%d\n",cond,p->bc?p->bc->pid:-1);
1905         }
1906   
1907         return 0;
1908 }
1909
1910 static int misdn_hangup(struct ast_channel *ast)
1911 {
1912         struct chan_list *p;
1913         struct misdn_bchannel *bc=NULL;
1914         
1915         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) ) ) return -1;
1916         
1917         release_lock;
1918
1919         
1920         ast_log(LOG_DEBUG, "misdn_hangup(%s)\n", ast->name);
1921         
1922         if (!p) {
1923                 chan_misdn_log(3, 0, "misdn_hangup called, without chan_list obj.\n");
1924                 release_unlock;
1925                 return 0 ;
1926         }
1927         
1928         bc=p->bc;
1929
1930         if (!bc) {
1931                 release_unlock;
1932                 ast_log(LOG_WARNING,"Hangup with private but no bc ?\n");
1933                 return 0;
1934         }
1935
1936         
1937         MISDN_ASTERISK_TECH_PVT(ast)=NULL;
1938         p->ast=NULL;
1939
1940         bc=p->bc;
1941         
1942         if (ast->_state == AST_STATE_RESERVED) {
1943                 /* between request and call */
1944                 MISDN_ASTERISK_TECH_PVT(ast)=NULL;
1945                 release_unlock;
1946                 
1947                 cl_dequeue_chan(&cl_te, p);
1948                 free(p);
1949                 
1950                 if (bc)
1951                         misdn_lib_release(bc);
1952                 
1953                 return 0;
1954         }
1955
1956         stop_bc_tones(p);
1957         
1958         release_unlock;
1959         
1960         {
1961                 const char *varcause=NULL;
1962                 bc->cause=ast->hangupcause?ast->hangupcause:16;
1963                 
1964                 if ( (varcause=pbx_builtin_getvar_helper(ast, "HANGUPCAUSE")) ||
1965                      (varcause=pbx_builtin_getvar_helper(ast, "PRI_CAUSE"))) {
1966                         int tmpcause=atoi(varcause);
1967                         bc->out_cause=tmpcause?tmpcause:16;
1968                 }
1969     
1970                 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));
1971                 chan_misdn_log(2, bc->port, " --> l3id:%x\n",p->l3id);
1972                 chan_misdn_log(1, bc->port, " --> cause:%d\n",bc->cause);
1973                 chan_misdn_log(1, bc->port, " --> out_cause:%d\n",bc->out_cause);
1974                 
1975                 switch (p->state) {
1976                 case MISDN_CALLING:
1977                         p->state=MISDN_CLEANING;
1978                         misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
1979                         break;
1980                 case MISDN_HOLDED:
1981                 case MISDN_DIALING:
1982                         start_bc_tones(p);
1983                         tone_indicate(p, TONE_BUSY);
1984                         p->state=MISDN_CLEANING;
1985                         
1986                         misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
1987       
1988                         break;
1989       
1990                 case MISDN_ALERTING:
1991                 case MISDN_PROGRESS:
1992                 case MISDN_PROCEEDING:
1993                         chan_misdn_log(2, bc->port, " --> * State Alerting\n");
1994
1995                         if (p->orginator != ORG_AST) 
1996                                 tone_indicate(p, TONE_BUSY);
1997       
1998                         p->state=MISDN_CLEANING;
1999                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
2000                         break;
2001                 case MISDN_CONNECTED:
2002                         /*  Alerting or Disconect */
2003                         chan_misdn_log(2, bc->port, " --> * State Connected\n");
2004                         start_bc_tones(p);
2005                         tone_indicate(p, TONE_BUSY);
2006                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
2007       
2008                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2009                         break;
2010                 case MISDN_DISCONNECTED:
2011                         chan_misdn_log(2, bc->port, " --> * State Disconnected\n");
2012                         misdn_lib_send_event( bc, EVENT_RELEASE);
2013                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2014                         break;
2015
2016                 case MISDN_CLEANING:
2017                         break;
2018       
2019                 case MISDN_HOLD_DISCONNECT:
2020                         /* need to send release here */
2021                         chan_misdn_log(2, bc->port, " --> state HOLD_DISC\n");
2022                         chan_misdn_log(1, bc->port, " --> cause %d\n",bc->cause);
2023                         chan_misdn_log(1, bc->port, " --> out_cause %d\n",bc->out_cause);
2024                         
2025                         bc->out_cause=-1;
2026                         misdn_lib_send_event(bc,EVENT_RELEASE);
2027                         break;
2028                 default:
2029                         /*  Alerting or Disconect */
2030
2031                         if (bc->nt) {
2032                                 bc->out_cause=-1;
2033                                 misdn_lib_send_event(bc, EVENT_RELEASE);
2034                         } else
2035                                 misdn_lib_send_event(bc, EVENT_DISCONNECT);
2036                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2037                 }
2038     
2039         }
2040         
2041
2042         chan_misdn_log(1, bc->port, "Channel: %s hanguped\n",ast->name);
2043         
2044         return 0;
2045 }
2046
2047 static struct ast_frame  *misdn_read(struct ast_channel *ast)
2048 {
2049         struct chan_list *tmp;
2050         
2051         char blah[255];
2052         int len =0 ;
2053         
2054         if (!ast) return NULL;
2055         if (! (tmp=MISDN_ASTERISK_TECH_PVT(ast)) ) return NULL;
2056         if (!tmp->bc) return NULL;
2057         
2058         
2059         read(tmp->pipe[0],blah,sizeof(blah));
2060         
2061         
2062         len = misdn_ibuf_usedcount(tmp->bc->astbuf);
2063
2064         if (!len) {
2065                 struct ast_frame *frame;
2066                 if(!tmp->zero_read_cnt)
2067                         chan_misdn_log(4,tmp->bc->port,"misdn_read: ZERO READ\n");
2068                 tmp->zero_read_cnt++;
2069
2070                 if (tmp->zero_read_cnt > 5000) {
2071                         chan_misdn_log(4,tmp->bc->port,"misdn_read: ZERO READ counted > 5000 times\n");
2072                         tmp->zero_read_cnt=0;
2073
2074                 }
2075
2076                /*faking Voice Frame*/
2077                 tmp->frame.frametype = AST_FRAME_VOICE;
2078                 tmp->frame.subclass = AST_FORMAT_ALAW;
2079                 memset(tmp->ast_rd_buf,0,128);
2080                 tmp->frame.data = tmp->ast_rd_buf ;
2081                 tmp->frame.mallocd =0 ;
2082                 tmp->frame.datalen = 128;
2083                 tmp->frame.samples = 128;
2084
2085                 frame=ast_frisolate(&tmp->frame);
2086                 return frame;
2087         }
2088
2089         /*shrinken len if necessary, we transmit at maximum 4k*/
2090         len = len<=sizeof(tmp->ast_rd_buf)?len:sizeof(tmp->ast_rd_buf);
2091         
2092         misdn_ibuf_memcpy_r(tmp->ast_rd_buf, tmp->bc->astbuf,len);
2093         
2094         tmp->frame.frametype  = AST_FRAME_VOICE;
2095         tmp->frame.subclass = AST_FORMAT_ALAW;
2096         tmp->frame.datalen = len;
2097         tmp->frame.samples = len ;
2098         tmp->frame.mallocd =0 ;
2099         tmp->frame.offset= 0 ;
2100         tmp->frame.src = NULL;
2101         tmp->frame.data = tmp->ast_rd_buf ;
2102
2103         return &tmp->frame;
2104 }
2105
2106
2107
2108
2109 static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
2110 {
2111         struct chan_list *ch;
2112         int i  = 0;
2113         
2114         if (!ast || ! (ch=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
2115         
2116         if (!ch->bc ) {
2117                 ast_log(LOG_WARNING, "private but no bc\n");
2118                 return -1;
2119         }
2120         
2121         /*if (ch->bc->tone != TONE_NONE)
2122           tone_indicate(ch,TONE_NONE); */
2123         
2124         
2125         if (ch->holded ) {
2126                 chan_misdn_log(5, ch->bc->port, "misdn_write: Returning because holded\n");
2127                 return 0;
2128         }
2129         
2130         if (ch->notxtone) {
2131                 chan_misdn_log(5, ch->bc->port, "misdn_write: Returning because notxone\n");
2132                 return 0;
2133         }
2134
2135
2136         if ( !frame->subclass) {
2137                 chan_misdn_log(4, ch->bc->port, "misdn_write: * prods us\n");
2138                 return 0;
2139         }
2140         
2141         if ( !(frame->subclass & prefformat)) {
2142                 
2143                 chan_misdn_log(-1, ch->bc->port, "Got Unsupported Frame with Format:%d\n", frame->subclass);
2144                 return -1;
2145         }
2146         
2147
2148         if ( !frame->samples ) {
2149                 chan_misdn_log(4, ch->bc->port, "misdn_write: zero write\n");
2150                 return 0;
2151         }
2152
2153         if ( ! ch->bc->addr ) {
2154                 chan_misdn_log(8, ch->bc->port, "misdn_write: no addr for bc dropping:%d\n", frame->samples);
2155                 return 0;
2156         }
2157         
2158 #if MISDN_DEBUG
2159         {
2160                 int i, max=5>frame->samples?frame->samples:5;
2161                 
2162                 printf("write2mISDN %p %d bytes: ", p, frame->samples);
2163                 
2164                 for (i=0; i<  max ; i++) printf("%2.2x ",((char*) frame->data)[i]);
2165                 printf ("\n");
2166         }
2167 #endif
2168
2169
2170         switch (ch->bc->bc_state) {
2171                 case BCHAN_ACTIVATED:
2172                 case BCHAN_BRIDGED:
2173                         break;
2174                 default:
2175                 if (!ch->dropped_frame_cnt)
2176                         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);
2177                 
2178                 ch->dropped_frame_cnt++;
2179                 if (ch->dropped_frame_cnt > 100) {
2180                         ch->dropped_frame_cnt=0;
2181                         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);
2182
2183                 }
2184
2185                 return 0;
2186         }
2187         
2188         chan_misdn_log(9, ch->bc->port, "Sending :%d bytes 2 MISDN\n",frame->samples);
2189         /*if speech flip bits*/
2190         if ( misdn_cap_is_speech(ch->bc->capability) )
2191                 flip_buf_bits(frame->data,frame->samples);
2192         
2193         
2194         if ( !ch->bc->nojitter && misdn_cap_is_speech(ch->bc->capability) ) {
2195                 /* Buffered Transmit (triggert by read from isdn side)*/
2196                 if (misdn_jb_fill(ch->jb,frame->data,frame->samples) < 0) {
2197                         if (ch->bc->active)
2198                                 cb_log(0,ch->bc->port,"Misdn Jitterbuffer Overflow.\n");
2199                 }
2200                 
2201         } else {
2202                 /*transmit without jitterbuffer*/
2203                 i=misdn_lib_tx2misdn_frm(ch->bc, frame->data, frame->samples);
2204         }
2205
2206         
2207         
2208         return 0;
2209 }
2210
2211
2212
2213
2214 static enum ast_bridge_result  misdn_bridge (struct ast_channel *c0,
2215                                       struct ast_channel *c1, int flags,
2216                                       struct ast_frame **fo,
2217                                       struct ast_channel **rc,
2218                                       int timeoutms)
2219
2220 {
2221         struct chan_list *ch1,*ch2;
2222         struct ast_channel *carr[2], *who;
2223         int to=-1;
2224         struct ast_frame *f;
2225   
2226         ch1=get_chan_by_ast(c0);
2227         ch2=get_chan_by_ast(c1);
2228
2229         carr[0]=c0;
2230         carr[1]=c1;
2231   
2232   
2233         if (ch1 && ch2 ) ;
2234         else
2235                 return -1;
2236   
2237
2238         int bridging;
2239         misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
2240         if (bridging) {
2241                 int ecwb;
2242                 misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2243                 if ( !ecwb ) {
2244                         chan_misdn_log(2, ch1->bc->port, "Disabling Echo Cancellor when Bridged\n");
2245                         ch1->bc->ec_enable=0;
2246                 /*      manager_ec_disable(ch1->bc); */
2247                 }
2248                 misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2249                 if ( !ecwb ) {
2250                         chan_misdn_log(2, ch2->bc->port, "Disabling Echo Cancellor when Bridged\n");
2251                         ch2->bc->ec_enable=0;
2252                 /*      manager_ec_disable(ch2->bc); */
2253                 }
2254                 
2255                 /* trying to make a mISDN_dsp conference */
2256                 chan_misdn_log(1, ch1->bc->port, "I SEND: Making conference with Number:%d\n", (ch1->bc->pid<<1) +1);
2257
2258                 misdn_lib_bridge(ch1->bc,ch2->bc);
2259         }
2260         
2261         if (option_verbose > 2) 
2262                 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
2263
2264         chan_misdn_log(1, ch1->bc->port, "* Makeing Native Bridge between %s and %s\n", ch1->bc->oad, ch2->bc->oad);
2265   
2266         while(1) {
2267                 to=-1;
2268                 who = ast_waitfor_n(carr, 2, &to);
2269
2270                 if (!who) {
2271                         ast_log(LOG_NOTICE,"misdn_bridge: empty read, breaking out\n");
2272                         break;
2273                 }
2274                 f = ast_read(who);
2275     
2276                 if (!f || f->frametype == AST_FRAME_CONTROL) {
2277                         /* got hangup .. */
2278                         *fo=f;
2279                         *rc=who;
2280       
2281                         break;
2282                 }
2283     
2284     
2285                 if (who == c0) {
2286                         ast_write(c1,f);
2287                 }
2288                 else {
2289                         ast_write(c0,f);
2290                 }
2291     
2292         }
2293   
2294         return 0;
2295 }
2296
2297 /** AST INDICATIONS END **/
2298
2299 static int tone_indicate( struct chan_list *cl, enum tone_e tone)
2300 {
2301         const struct tone_zone_sound *ts= NULL;
2302         struct ast_channel *ast=cl->ast;
2303         
2304         chan_misdn_log(2,cl->bc->port,"Tone Indicate:\n");
2305         
2306         if (!cl->ast) {
2307                 return 0;
2308         }
2309         
2310         switch (tone) {
2311         case TONE_DIAL:
2312                 chan_misdn_log(2,cl->bc->port," --> Dial\n");
2313                 ts=ast_get_indication_tone(ast->zone,"dial");
2314                 misdn_lib_tone_generator_start(cl->bc);
2315                 break;
2316         case TONE_ALERTING:
2317                 chan_misdn_log(2,cl->bc->port," --> Ring\n");
2318                 ts=ast_get_indication_tone(ast->zone,"ring");
2319                 misdn_lib_tone_generator_stop(cl->bc);
2320                 break;
2321         case TONE_BUSY:
2322                 chan_misdn_log(2,cl->bc->port," --> Busy\n");
2323                 ts=ast_get_indication_tone(ast->zone,"busy");
2324                 misdn_lib_tone_generator_stop(cl->bc);
2325                 break;
2326         case TONE_FILE:
2327                 break;
2328
2329         case TONE_NONE:
2330                 chan_misdn_log(2,cl->bc->port," --> None\n");
2331                 misdn_lib_tone_generator_stop(cl->bc);
2332                 ast_playtones_stop(ast);
2333                 break;
2334         default:
2335                 chan_misdn_log(0,cl->bc->port,"Don't know how to handle tone: %d\n",tone);
2336         }
2337         
2338         cl->ts=ts;      
2339         
2340         if (ts) ast_playtones_start(ast,0, ts->data, 0);
2341         
2342         return 0;
2343 }
2344
2345 static int start_bc_tones(struct chan_list* cl)
2346 {
2347         manager_bchannel_activate(cl->bc);
2348         misdn_lib_tone_generator_stop(cl->bc);
2349         cl->notxtone=0;
2350         cl->norxtone=0;
2351         return 0;
2352 }
2353
2354 static int stop_bc_tones(struct chan_list *cl)
2355 {
2356         if (cl->bc) {
2357                 manager_bchannel_deactivate(cl->bc);
2358         }
2359         cl->notxtone=1;
2360         cl->norxtone=1;
2361         
2362         return 0;
2363 }
2364
2365
2366 static struct chan_list *init_chan_list(void)
2367 {
2368         struct chan_list *cl=malloc(sizeof(struct chan_list));
2369         
2370         if (!cl) {
2371                 chan_misdn_log(-1, 0, "misdn_request: malloc failed!");
2372                 return NULL;
2373         }
2374         
2375         memset(cl,0,sizeof(struct chan_list));
2376         
2377         return cl;
2378         
2379 }
2380
2381 static struct ast_channel *misdn_request(const char *type, int format, void *data, int *cause)
2382
2383 {
2384         struct ast_channel *tmp = NULL;
2385         char group[BUFFERSIZE+1]="";
2386         char buf[128];
2387         char buf2[128], *ext=NULL, *port_str;
2388         char *tokb=NULL, *p=NULL;
2389         int channel=0, port=0;
2390         struct misdn_bchannel *newbc = NULL;
2391         
2392         struct chan_list *cl=init_chan_list();
2393         
2394         sprintf(buf,"%s/%s",misdn_type,(char*)data);
2395         ast_copy_string(buf2,data, 128);
2396         
2397         port_str=strtok_r(buf2,"/", &tokb);
2398
2399         ext=strtok_r(NULL,"/", &tokb);
2400
2401         if (port_str) {
2402                 if (port_str[0]=='g' && port_str[1]==':' ) {
2403                         /* We make a group call lets checkout which ports are in my group */
2404                         port_str += 2;
2405                         strncpy(group, port_str, BUFFERSIZE);
2406                         group[127] = 0;
2407                         chan_misdn_log(2, 0, " --> Group Call group: %s\n",group);
2408                 } 
2409                 else if ((p = strchr(port_str, ':'))) {
2410                         // we have a preselected channel
2411                         *p = 0;
2412                         channel = atoi(++p);
2413                         port = atoi(port_str);
2414                         chan_misdn_log(2, port, " --> Call on preselected Channel (%d).\n", channel);
2415                 }
2416                 else {
2417                         port = atoi(port_str);
2418                 }
2419                 
2420                 
2421         } else {
2422                 ast_log(LOG_WARNING, " --> ! IND : CALL dad:%s WITHOUT PORT/Group, check extension.conf\n",ext);
2423                 return NULL;
2424         }
2425
2426         if (!ast_strlen_zero(group)) {
2427         
2428                 char cfg_group[BUFFERSIZE+1];
2429                 struct robin_list *rr = NULL;
2430
2431                 if (misdn_cfg_is_group_method(group, METHOD_ROUND_ROBIN)) {
2432                         chan_misdn_log(4, port, " --> STARTING ROUND ROBIN...");
2433                         rr = get_robin_position(group);
2434                 }
2435                 
2436                 if (rr) {
2437                         int robin_channel = rr->channel;
2438                         int port_start;
2439                         int next_chan = 1;
2440
2441                         do {
2442                                 port_start = 0;
2443                                 for (port = misdn_cfg_get_next_port_spin(rr->port); port > 0 && port != port_start;
2444                                          port = misdn_cfg_get_next_port_spin(port)) {
2445
2446                                         if (!port_start)
2447                                                 port_start = port;
2448
2449                                         if (port >= port_start)
2450                                                 next_chan = 1;
2451                                         
2452                                         if (port < port_start && next_chan) {
2453                                                 if (++robin_channel >= MAX_BCHANS) {
2454                                                         robin_channel = 1;
2455                                                 }
2456                                                 next_chan = 0;
2457                                         }
2458
2459                                         misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2460                                         
2461                                         if (!strcasecmp(cfg_group, group)) {
2462                                                 int port_up;
2463                                                 int check;
2464                                                 misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
2465                                                 port_up = misdn_lib_port_up(port, check);
2466                                                 
2467                                                 if ( port_up )  {
2468                                                         newbc = misdn_lib_get_free_bc(port, robin_channel);
2469                                                         if (newbc) {
2470                                                                 chan_misdn_log(4, port, " Success! Found port:%d channel:%d\n", newbc->port, newbc->channel);
2471                                                                 if (port_up)
2472                                                                         chan_misdn_log(4, port, "ortup:%d\n",  port_up);
2473                                                                 rr->port = newbc->port;
2474                                                                 rr->channel = newbc->channel;
2475                                                                 break;
2476                                                         }
2477                                                 }
2478                                         }
2479                                 }
2480                         } while (!newbc && robin_channel != rr->channel);
2481                         
2482                         if (!newbc)
2483                                 chan_misdn_log(4, port, " Failed! No free channel in group %d!", group);
2484                 }
2485                 
2486                 else {          
2487                         for (port=misdn_cfg_get_next_port(0); port > 0;
2488                                  port=misdn_cfg_get_next_port(port)) {
2489                                 
2490                                 misdn_cfg_get( port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2491
2492                                 chan_misdn_log(3,port, "Group [%s] Port [%d]\n", group, port);
2493                                 if (!strcasecmp(cfg_group, group)) {
2494                                         int port_up;
2495                                         int check;
2496                                         misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
2497                                         port_up = misdn_lib_port_up(port, check);
2498                                         
2499                                         chan_misdn_log(4, port, "portup:%d\n", port_up);
2500                                         
2501                                         if ( port_up )  {
2502                                                 newbc = misdn_lib_get_free_bc(port, 0);
2503                                                 if (newbc)
2504                                                         break;
2505                                         }
2506                                 }
2507                         }
2508                 }
2509                 
2510         } else {
2511                 if (channel)
2512                         chan_misdn_log(1, port," --> preselected_channel: %d\n",channel);
2513                 newbc = misdn_lib_get_free_bc(port, channel);
2514         }
2515         
2516         if (!newbc) {
2517                 chan_misdn_log(-1, 0, " --> ! No free channel chan ext:%s even after Group Call\n",ext);
2518                 chan_misdn_log(-1, 0, " --> SEND: State Down\n");
2519                 return NULL;
2520         }
2521
2522         /* create ast_channel and link all the objects together */
2523         cl->bc=newbc;
2524         
2525         tmp = misdn_new(cl, AST_STATE_RESERVED, ext, NULL, format, port, channel);
2526         cl->ast=tmp;
2527         
2528         /* register chan in local list */
2529         cl_queue_chan(&cl_te, cl) ;
2530         
2531         /* fill in the config into the objects */
2532         read_config(cl, ORG_AST);
2533         
2534         
2535         return tmp;
2536 }
2537
2538
2539 static int misdn_send_text (struct ast_channel *chan, const char *text)
2540 {
2541         struct chan_list *tmp=chan->tech_pvt;
2542         
2543         if (tmp && tmp->bc) {
2544                 ast_copy_string(tmp->bc->display,text,sizeof(tmp->bc->display));
2545                 misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
2546         } else {
2547                 ast_log(LOG_WARNING, "No chan_list but send_text request?\n");
2548                 return -1;
2549         }
2550         
2551         return 0;
2552 }
2553
2554 static struct ast_channel_tech misdn_tech = {
2555         .type="mISDN",
2556         .description="Channel driver for mISDN Support (Bri/Pri)",
2557         .capabilities= AST_FORMAT_ALAW ,
2558         .requester=misdn_request,
2559         .send_digit=misdn_digit,
2560         .call=misdn_call,
2561         .bridge=misdn_bridge, 
2562         .hangup=misdn_hangup,
2563         .answer=misdn_answer,
2564         .read=misdn_read,
2565         .write=misdn_write,
2566         .indicate=misdn_indication,
2567         .fixup=misdn_fixup,
2568         .send_text=misdn_send_text,
2569         .properties=0
2570 };
2571
2572 static struct ast_channel_tech misdn_tech_wo_bridge = {
2573         .type="mISDN",
2574         .description="Channel driver for mISDN Support (Bri/Pri)",
2575         .capabilities=AST_FORMAT_ALAW ,
2576         .requester=misdn_request,
2577         .send_digit=misdn_digit,
2578         .call=misdn_call,
2579         .hangup=misdn_hangup,
2580         .answer=misdn_answer,
2581         .read=misdn_read,
2582         .write=misdn_write,
2583         .indicate=misdn_indication,
2584         .fixup=misdn_fixup,
2585         .send_text=misdn_send_text,
2586         .properties=0
2587 };
2588
2589
2590 static unsigned long glob_channel=0;
2591
2592 static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char *exten, char *callerid, int format, int port, int c)
2593 {
2594         struct ast_channel *tmp;
2595         
2596         tmp = ast_channel_alloc(1);
2597         
2598         if (tmp) {
2599                 chan_misdn_log(2, 0, " --> * NEW CHANNEL dad:%s oad:%s\n",exten,callerid);
2600                 
2601                 
2602                 if (c<=0) {
2603                         c=glob_channel++;
2604                         ast_string_field_build(tmp, name, "%s/%d-u%d",
2605                                  misdn_type, port, c);
2606                 } else {
2607                         ast_string_field_build(tmp, name, "%s/%d-%d",
2608                                  misdn_type, port, c);
2609                 }
2610                 
2611                 tmp->nativeformats = prefformat;
2612
2613                 tmp->readformat = format;
2614                 tmp->writeformat = format;
2615     
2616                 tmp->tech_pvt = chlist;
2617                 
2618                 int bridging;
2619                 misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
2620                 if (bridging)
2621                         tmp->tech = &misdn_tech;
2622                 else
2623                         tmp->tech = &misdn_tech_wo_bridge;
2624                 
2625                 tmp->writeformat = format;
2626                 tmp->readformat = format;
2627                 tmp->priority=1;
2628                 
2629                 if (exten) 
2630                         ast_copy_string(tmp->exten, exten,  sizeof(tmp->exten));
2631                 else
2632                         chan_misdn_log(1,0,"misdn_new: no exten given.\n");
2633                 
2634                 if (callerid) {
2635                         char *cid_name, *cid_num;
2636       
2637                         ast_callerid_parse(callerid, &cid_name, &cid_num);
2638                         ast_set_callerid(tmp, cid_num,cid_name,cid_num);
2639                 } else {
2640                         ast_set_callerid(tmp, NULL,NULL,NULL);
2641                 }
2642
2643                 {
2644                         if (pipe(chlist->pipe)<0)
2645                                 perror("Pipe failed\n");
2646                         
2647                         tmp->fds[0]=chlist->pipe[0];
2648                         
2649                 }
2650                 
2651                 ast_setstate(tmp, state);
2652                 if (state == AST_STATE_RING)
2653                         tmp->rings = 1;
2654                 else
2655                         tmp->rings = 0;
2656                 
2657                 
2658         } else {
2659                 chan_misdn_log(-1,0,"Unable to allocate channel structure\n");
2660         }
2661         
2662         return tmp;
2663 }
2664
2665
2666
2667 static int misdn_tx2ast_frm(struct chan_list * tmp, char * buf,  int len )
2668 {
2669         struct ast_frame frame;
2670
2671         /* If in hold state we drop frame .. */
2672         if (tmp->holded ) return 0;
2673         
2674         switch(tmp->state) {
2675         case MISDN_CLEANING:
2676         case MISDN_EXTCANTMATCH:
2677                 return 0;
2678                 
2679         case MISDN_WAITING4DIGS:
2680         default:
2681                 break;
2682         }
2683         
2684         if (tmp->norxtone) {
2685                 chan_misdn_log(3, tmp->bc->port, "misdn_tx2ast_frm: Returning because norxtone\n");
2686                 return 0;
2687         }
2688         
2689         frame.frametype  = AST_FRAME_VOICE;
2690         frame.subclass = AST_FORMAT_ALAW;
2691         frame.datalen = len;
2692         frame.samples = len ;
2693         frame.mallocd =0 ;
2694         frame.offset= 0 ;
2695         frame.src = NULL;
2696         frame.data = buf ;
2697         
2698         if (tmp->faxdetect || tmp->ast_dsp ) {
2699                 struct ast_frame *f,*f2;
2700                 if (tmp->trans)
2701                         f2=ast_translate(tmp->trans, &frame,0);
2702                 else {
2703                         chan_misdn_log(0, tmp->bc->port, "No T-Path found\n");
2704                         return 0;
2705                 }
2706                 
2707                 f = ast_dsp_process(tmp->ast, tmp->dsp, f2);
2708                 if (f && (f->frametype == AST_FRAME_DTMF)) {
2709                         ast_log(LOG_DEBUG, "Detected inband DTMF digit: %c", f->subclass);
2710                         if (f->subclass == 'f' && tmp->faxdetect) {
2711                                 /* Fax tone -- Handle and return NULL */
2712                                 struct ast_channel *ast = tmp->ast;
2713                                 if (!tmp->faxhandled) {
2714                                         tmp->faxhandled++;
2715                                         if (strcmp(ast->exten, "fax")) {
2716                                                 if (ast_exists_extension(ast, S_OR(ast->macrocontext, ast->context), "fax", 1, AST_CID_P(ast))) {
2717                                                         if (option_verbose > 2)
2718                                                                 ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension\n", ast->name);
2719                                                         /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
2720                                                         pbx_builtin_setvar_helper(ast,"FAXEXTEN",ast->exten);
2721                                                         if (ast_async_goto(ast, ast->context, "fax", 1))
2722                                                                 ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, ast->context);
2723                                                 } else
2724                                                         ast_log(LOG_NOTICE, "Fax detected, but no fax extension ctx:%s exten:%s\n",ast->context, ast->exten);
2725                                         } else
2726                                                 ast_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
2727                                 } else
2728                                         ast_log(LOG_DEBUG, "Fax already handled\n");
2729                                 frame.frametype = AST_FRAME_NULL;
2730                                 frame.subclass = 0;
2731                                 f = &frame;
2732                         }  else if ( tmp->ast_dsp) {
2733                                 struct ast_frame fr;
2734                                 memset(&fr, 0 , sizeof(fr));
2735                                 fr.frametype = AST_FRAME_DTMF;
2736                                 fr.subclass = f->subclass ;
2737                                 fr.src=NULL;
2738                                 fr.data = NULL ;
2739                                 fr.datalen = 0;
2740                                 fr.samples = 0 ;
2741                                 fr.mallocd =0 ;
2742                                 fr.offset= 0 ;
2743                                 
2744                                 chan_misdn_log(2, tmp->bc->port, " --> * SEND: DTMF (AST_DSP) :%c\n",f->subclass);
2745                                 ast_queue_frame(tmp->ast, &fr);
2746                                 
2747                                 frame.frametype = AST_FRAME_NULL;
2748                                 frame.subclass = 0;
2749                                 f = &frame;
2750                         }
2751                 }
2752         }
2753         
2754         if (tmp && tmp->ast && MISDN_ASTERISK_PVT (tmp->ast) && MISDN_ASTERISK_TECH_PVT(tmp->ast) ) {
2755 #if MISDN_DEBUG
2756                 int i, max=5>len?len:5;
2757     
2758                 printf("write2* %p %d bytes: ",tmp, len);
2759     
2760                 for (i=0; i<  max ; i++) printf("%2.2x ",((char*) frame.data)[i]);
2761                 printf ("\n");
2762 #endif
2763                 chan_misdn_log(9, tmp->bc->port, "Queueing %d bytes 2 Asterisk\n",len);
2764                 ast_queue_frame(tmp->ast,&frame);
2765
2766         }  else {
2767                 ast_log (LOG_WARNING, "No ast || ast->pvt || ch\n");
2768         }
2769         
2770         return 0;
2771 }
2772
2773 /** Channel Queue ***/
2774
2775 static struct chan_list *find_chan_by_l3id(struct chan_list *list, unsigned long l3id)
2776 {
2777         struct chan_list *help=list;
2778         for (;help; help=help->next) {
2779                 if (help->l3id == l3id ) return help;
2780         }
2781   
2782         chan_misdn_log(6, list? (list->bc? list->bc->port : 0) : 0, "$$$ find_chan: No channel found with l3id:%x\n",l3id);
2783   
2784         return NULL;
2785 }
2786
2787 static struct chan_list *find_chan_by_bc(struct chan_list *list, struct misdn_bchannel *bc)
2788 {
2789         struct chan_list *help=list;
2790         for (;help; help=help->next) {
2791                 if (help->bc == bc) return help;
2792         }
2793   
2794         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
2795   
2796         return NULL;
2797 }
2798
2799
2800 static struct chan_list *find_holded(struct chan_list *list, struct misdn_bchannel *bc)
2801 {
2802         struct chan_list *help=list;
2803         
2804         chan_misdn_log(6, bc->port, "$$$ find_holded: channel:%d oad:%s dad:%s\n",bc->channel, bc->oad,bc->dad);
2805         for (;help; help=help->next) {
2806                 chan_misdn_log(4, bc->port, "$$$ find_holded: --> holded:%d channel:%d\n",help->bc->holded, help->bc->channel);
2807                 if (help->bc->port == bc->port
2808                     && help->bc->holded ) return help;
2809         }
2810         
2811         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
2812   
2813         return NULL;
2814 }
2815
2816 static void cl_queue_chan(struct chan_list **list, struct chan_list *chan)
2817 {
2818         chan_misdn_log(4, chan->bc? chan->bc->port : 0, "* Queuing chan %p\n",chan);
2819   
2820         ast_mutex_lock(&cl_te_lock);
2821         if (!*list) {
2822                 *list = chan;
2823         } else {
2824                 struct chan_list *help=*list;
2825                 for (;help->next; help=help->next); 
2826                 help->next=chan;
2827         }
2828         chan->next=NULL;
2829         ast_mutex_unlock(&cl_te_lock);
2830 }
2831
2832 static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan) 
2833 {
2834         if (chan->dsp) 
2835                 ast_dsp_free(chan->dsp);
2836         if (chan->trans)
2837                 ast_translator_free_path(chan->trans);
2838
2839         
2840
2841         ast_mutex_lock(&cl_te_lock);
2842         if (!*list) {
2843                 ast_mutex_unlock(&cl_te_lock);
2844                 return;
2845         }
2846   
2847         if (*list == chan) {
2848                 *list=(*list)->next;
2849                 ast_mutex_unlock(&cl_te_lock);
2850                 return ;
2851         }
2852   
2853         {
2854                 struct chan_list *help=*list;
2855                 for (;help->next; help=help->next) {
2856                         if (help->next == chan) {
2857                                 help->next=help->next->next;
2858                                 ast_mutex_unlock(&cl_te_lock);
2859                                 return;
2860                         }
2861                 }
2862         }
2863         
2864         ast_mutex_unlock(&cl_te_lock);
2865 }
2866
2867 /** Channel Queue End **/
2868
2869
2870
2871 /** Isdn asks us to release channel, pendant to misdn_hangup **/
2872 static void release_chan(struct misdn_bchannel *bc) {
2873         struct ast_channel *ast=NULL;
2874         
2875         {
2876                 struct chan_list *ch=find_chan_by_bc(cl_te, bc);
2877                 if (!ch) ch=find_chan_by_l3id (cl_te, bc->l3_id);
2878                 if (!ch)  {
2879                         chan_misdn_log(0, bc->port, "release_chan: Ch not found!\n");
2880                         return;
2881                 }
2882                 
2883                 release_lock;
2884                 if (ch->ast) {
2885                         ast=ch->ast;
2886                 } 
2887                 release_unlock;
2888                 
2889                 chan_misdn_log(1, bc->port, "Trying to Release bc with l3id: %x\n",bc->l3_id);
2890
2891                 //releaseing jitterbuffer
2892                 if (ch->jb ) {
2893                         misdn_jb_destroy(ch->jb);
2894                         ch->jb=NULL;
2895                 } else {
2896                         if (!bc->nojitter)
2897                                 chan_misdn_log(5,bc->port,"Jitterbuffer already destroyed.\n");
2898                 }
2899                 
2900                 if (ch) {
2901                         
2902                         close(ch->pipe[0]);
2903                         close(ch->pipe[1]);
2904                         
2905                         if (ast && MISDN_ASTERISK_TECH_PVT(ast)) {
2906                                 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));
2907                                 chan_misdn_log(3, bc->port, " --> * State Down\n");
2908                                 /* copy cause */
2909                                 send_cause2ast(ast,bc);
2910                                 
2911                                 MISDN_ASTERISK_TECH_PVT(ast)=NULL;
2912                                 
2913       
2914                                 if (ast->_state != AST_STATE_RESERVED) {
2915                                         chan_misdn_log(3, bc->port, " --> Setting AST State to down\n");
2916                                         ast_setstate(ast, AST_STATE_DOWN);
2917                                 }
2918                                 
2919                                 switch(ch->state) {
2920                                 case MISDN_EXTCANTMATCH:
2921                                 case MISDN_WAITING4DIGS:
2922                                 {
2923                                         chan_misdn_log(3,  bc->port, " --> * State Wait4dig | ExtCantMatch\n");
2924                                         ast_hangup(ast);
2925                                 }
2926                                 break;
2927                                 
2928                                 case MISDN_DIALING:
2929                                 case MISDN_CALLING_ACKNOWLEDGE:
2930                                 case MISDN_PROGRESS:
2931                                         chan_misdn_log(2,  bc->port, "* --> In State Dialin\n");
2932                                         chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2933                                         
2934
2935                                         ast_queue_hangup(ast);
2936                                         break;
2937                                 case MISDN_CALLING:
2938                                         
2939                                         chan_misdn_log(2,  bc->port, "* --> In State Callin\n");
2940                                         
2941                                         if (!bc->nt) {
2942                                                 chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2943                                                 ast_queue_hangup(ast);
2944                                         } else {
2945                                                 chan_misdn_log(2,  bc->port, "* --> Hangup\n");
2946                                                 ast_queue_hangup(ast);
2947                                         }
2948                                         break;
2949                                         
2950                                 case MISDN_CLEANING:
2951                                         /* this state comes out of ast so we mustnt call a ast function ! */
2952                                         chan_misdn_log(2,  bc->port, "* --> In StateCleaning\n");
2953                                         break;
2954                                 case MISDN_HOLD_DISCONNECT:
2955                                         chan_misdn_log(2,  bc->port, "* --> In HOLD_DISC\n");
2956                                         break;
2957                                 default:
2958                                         chan_misdn_log(2,  bc->port, "* --> In State Default\n");
2959                                         chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2960                                         if (ast) {
2961                                                 ast_queue_hangup(ast);
2962                                         } else {
2963                                                 chan_misdn_log (0,  bc->port, "!! Not really queued!\n");
2964                                         }
2965                                 }
2966                         }
2967                         cl_dequeue_chan(&cl_te, ch);
2968                         
2969                         free(ch);
2970                 } else {
2971                         /* chan is already cleaned, so exiting  */
2972                 }
2973         }
2974 }
2975 /*** release end **/
2976
2977 static void misdn_transfer_bc(struct chan_list *tmp_ch, struct chan_list *holded_chan)
2978 {
2979         chan_misdn_log(4,0,"TRANSFERING %s to %s\n",holded_chan->ast->name, tmp_ch->ast->name);
2980         
2981         tmp_ch->state=MISDN_HOLD_DISCONNECT;
2982   
2983         ast_moh_stop(AST_BRIDGED_P(holded_chan->ast));
2984
2985         holded_chan->state=MISDN_CONNECTED;
2986         holded_chan->holded=0;
2987         misdn_lib_transfer(holded_chan->bc?holded_chan->bc:holded_chan->holded_bc);
2988         ast_channel_masquerade(holded_chan->ast, AST_BRIDGED_P(tmp_ch->ast));
2989 }
2990
2991
2992 static void do_immediate_setup(struct misdn_bchannel *bc,struct chan_list *ch , struct ast_channel *ast)
2993 {
2994         char predial[256]="";
2995         char *p = predial;
2996   
2997         struct ast_frame fr;
2998   
2999         strncpy(predial, ast->exten, sizeof(predial) -1 );
3000   
3001         ch->state=MISDN_DIALING;
3002
3003         if (bc->nt) {
3004                 int ret; 
3005                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3006         } else {
3007                 int ret;
3008                 if ( misdn_lib_is_ptp(bc->port)) {
3009                         ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3010                 } else {
3011                         ret = misdn_lib_send_event(bc, EVENT_PROCEEDING );
3012                 }
3013         }
3014
3015         if ( !bc->nt && (ch->orginator==ORG_MISDN) && !ch->incoming_early_audio ) 
3016                 chan_misdn_log(1,bc->port, " --> incoming_early_audio off\n");
3017          else 
3018                 tone_indicate(ch,TONE_DIAL);  
3019   
3020         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));
3021   
3022         strncpy(ast->exten,"s", 2);
3023   
3024         if (ast_pbx_start(ast)<0) {
3025                 ast=NULL;
3026                 tone_indicate(ch,TONE_BUSY);
3027
3028                 if (bc->nt)
3029                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3030                 else
3031                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
3032         }
3033   
3034   
3035         while (!ast_strlen_zero(p) ) {
3036                 fr.frametype = AST_FRAME_DTMF;
3037                 fr.subclass = *p ;
3038                 fr.src=NULL;
3039                 fr.data = NULL ;
3040                 fr.datalen = 0;
3041                 fr.samples = 0 ;
3042                 fr.mallocd =0 ;
3043                 fr.offset= 0 ;
3044
3045                 if (ch->ast && MISDN_ASTERISK_PVT(ch->ast) && MISDN_ASTERISK_TECH_PVT(ch->ast)) {
3046                         ast_queue_frame(ch->ast, &fr);
3047                 }
3048                 p++;
3049         }
3050 }
3051
3052
3053
3054 static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc) {
3055         
3056         ast->hangupcause=bc->cause;
3057         
3058         switch ( bc->cause) {
3059                 
3060         case 1: /** Congestion Cases **/
3061         case 2:
3062         case 3:
3063         case 4:
3064         case 22:
3065         case 27:
3066                 /*
3067                  * Not Queueing the Congestion anymore, since we want to hear
3068                  * the inband message
3069                  *
3070                 chan_misdn_log(1, bc?bc->port:0, " --> * SEND: Queue Congestion pid:%d\n", bc?bc->pid:-1);
3071                 
3072                 ast_queue_control(ast, AST_CONTROL_CONGESTION);
3073                 */
3074                 break;
3075                 
3076         case 21:
3077         case 17: /* user busy */
3078                 chan_misdn_log(1,  bc?bc->port:0, " --> * SEND: Queue Busy pid:%d\n", bc?bc->pid:-1);
3079                 
3080                 ast_queue_control(ast, AST_CONTROL_BUSY);
3081                 
3082                 break;
3083         }
3084 }
3085
3086
3087 void import_ies(struct ast_channel *chan, struct misdn_bchannel *bc)
3088 {
3089         const char *tmp;
3090
3091         tmp=pbx_builtin_getvar_helper(chan,"PRI_MODE");
3092         if (tmp) bc->mode=atoi(tmp);
3093
3094         tmp=pbx_builtin_getvar_helper(chan,"PRI_URATE");
3095         if (tmp) bc->urate=atoi(tmp);
3096
3097         tmp=pbx_builtin_getvar_helper(chan,"PRI_RATE");
3098         if (tmp) bc->rate=atoi(tmp);
3099
3100         tmp=pbx_builtin_getvar_helper(chan,"PRI_USER1");
3101         if (tmp) bc->user1=atoi(tmp);
3102         
3103         tmp=pbx_builtin_getvar_helper(chan,"RDNIS");
3104         if (tmp) ast_copy_string(bc->rad,tmp,sizeof(bc->rad));
3105         
3106 }
3107
3108 void export_ies(struct ast_channel *chan, struct misdn_bchannel *bc)
3109 {
3110         char tmp[32];
3111         
3112         sprintf(tmp,"%d",bc->mode);
3113         pbx_builtin_setvar_helper(chan,"PRI_MODE",tmp);
3114
3115         sprintf(tmp,"%d",bc->urate);
3116         pbx_builtin_setvar_helper(chan,"PRI_URATE",tmp);
3117
3118         sprintf(tmp,"%d",bc->rate);
3119         pbx_builtin_setvar_helper(chan,"PRI_RATE",tmp);
3120         
3121         sprintf(tmp,"%d",bc->user1);
3122         pbx_builtin_setvar_helper(chan,"PRI_USER1",tmp);
3123         
3124         pbx_builtin_setvar_helper(chan,"RDNIS",bc->rad);
3125 }
3126
3127
3128
3129 /************************************************************/
3130 /*  Receive Events from isdn_lib  here                     */
3131 /************************************************************/
3132 static enum event_response_e
3133 cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
3134 {
3135         struct chan_list *ch=find_chan_by_bc(cl_te, bc);
3136         
3137         if (!ch)
3138                 ch=find_chan_by_l3id(cl_te, bc->l3_id);
3139         
3140         if (event != EVENT_BCHAN_DATA && event != EVENT_TONE_GENERATE) { /*  Debug Only Non-Bchan */
3141                 chan_misdn_log(1, bc->port, "I IND :%s oad:%s dad:%s\n", manager_isdn_get_info(event), bc->oad, bc->dad);
3142                 misdn_lib_log_ies(bc);
3143                 chan_misdn_log(2,bc->port," --> bc_state:%s\n",bc_state2str(bc->bc_state));
3144         }
3145         
3146         if (event != EVENT_SETUP) {
3147                 if (!ch) {
3148                         if (event != EVENT_CLEANUP )
3149                                 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);
3150                         return -1;
3151                 }
3152         }
3153         
3154         if (ch ) {
3155                 switch (event) {
3156                 case EVENT_RELEASE:
3157                 case EVENT_RELEASE_COMPLETE:
3158                 case EVENT_CLEANUP:
3159                         break;
3160                 default:
3161                         if ( !ch->ast  || !MISDN_ASTERISK_PVT(ch->ast) || !MISDN_ASTERISK_TECH_PVT(ch->ast)) {
3162                                 if (event!=EVENT_BCHAN_DATA)
3163                                         ast_log(LOG_WARNING, "No Ast or No private Pointer in Event (%d:%s)\n", event, manager_isdn_get_info(event));
3164                                 return -1;
3165                         }
3166                 }
3167         }
3168         
3169         
3170         switch (event) {
3171
3172         case EVENT_BCHAN_ACTIVATED:
3173                 break;
3174                 
3175                 
3176         case EVENT_NEW_L3ID:
3177                 ch->l3id=bc->l3_id;
3178                 break;
3179
3180         case EVENT_NEW_BC:
3181                 if (bc)
3182                         ch->bc=bc;
3183                 break;
3184                 
3185         case EVENT_DTMF_TONE:
3186         {
3187                 /*  sending INFOS as DTMF-Frames :) */
3188                 struct ast_frame fr;
3189                 memset(&fr, 0 , sizeof(fr));
3190                 fr.frametype = AST_FRAME_DTMF;
3191                 fr.subclass = bc->dtmf ;
3192                 fr.src=NULL;
3193                 fr.data = NULL ;
3194                 fr.datalen = 0;
3195                 fr.samples = 0 ;
3196                 fr.mallocd =0 ;
3197                 fr.offset= 0 ;
3198                 
3199                 chan_misdn_log(2, bc->port, " --> DTMF:%c\n", bc->dtmf);
3200                 
3201                 ast_queue_frame(ch->ast, &fr);
3202         }
3203         break;
3204         case EVENT_STATUS:
3205                 break;
3206     
3207         case EVENT_INFORMATION:
3208         {
3209                 int stop_tone;
3210                 misdn_cfg_get( 0, MISDN_GEN_STOP_TONE, &stop_tone, sizeof(int));
3211                 if ( stop_tone ) {
3212                         tone_indicate(ch,TONE_NONE);
3213                 }
3214                 
3215                 if (ch->state == MISDN_WAITING4DIGS ) {
3216                         /*  Ok, incomplete Setup, waiting till extension exists */
3217                         {
3218                                 int l = sizeof(bc->dad);
3219                                 strncat(bc->dad,bc->info_dad, l);
3220                                 bc->dad[l-1] = 0;
3221                         }
3222                         
3223                         
3224                         {
3225                                 int l = sizeof(ch->ast->exten);
3226                                 strncpy(ch->ast->exten, bc->dad, l);
3227                                 ch->ast->exten[l-1] = 0;
3228                         }
3229 /*                      chan_misdn_log(5, bc->port, "Can Match Extension: dad:%s oad:%s\n",bc->dad,bc->oad);*/
3230                         
3231                         /* Check for Pickup Request first */
3232                         if (!strcmp(ch->ast->exten, ast_pickup_ext())) {
3233                                 int ret;/** Sending SETUP_ACK**/
3234                                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3235                                 if (ast_pickup_call(ch->ast)) {
3236                                         ast_hangup(ch->ast);
3237                                 } else {
3238                                         struct ast_channel *chan=ch->ast;
3239                                         ch->state = MISDN_CALLING_ACKNOWLEDGE;
3240                                         ch->ast=NULL;
3241                                         ast_setstate(chan, AST_STATE_DOWN);
3242                                         ast_hangup(chan);
3243                                         break;
3244                                 }
3245                         }
3246                         
3247                         if(!ast_canmatch_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3248
3249                                 chan_misdn_log(-1, bc->port, "Extension can never match, so disconnecting\n");
3250                                 tone_indicate(ch,TONE_BUSY);
3251                                 ch->state=MISDN_EXTCANTMATCH;
3252                                 bc->out_cause=1;
3253
3254                                 if (bc->nt)
3255                                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3256                                 else
3257                                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
3258                                 break;
3259                         }
3260                         if (ast_exists_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3261                                 ch->state=MISDN_DIALING;
3262           
3263                                 tone_indicate(ch,TONE_NONE);
3264 /*                              chan_misdn_log(1, bc->port, " --> * Starting Ast ctx:%s\n", ch->context);*/
3265                                 if (ast_pbx_start(ch->ast)<0) {
3266
3267                                         chan_misdn_log(-1, bc->port, "ast_pbx_start returned < 0 in INFO\n");
3268                                         tone_indicate(ch,TONE_BUSY);
3269
3270                                         if (bc->nt)
3271                                                 misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3272                                         else
3273                                                 misdn_lib_send_event(bc, EVENT_DISCONNECT );
3274                                 }
3275                         }
3276         
3277                 } else {
3278                         /*  sending INFOS as DTMF-Frames :) */
3279                         struct ast_frame fr;
3280                         fr.frametype = AST_FRAME_DTMF;
3281                         fr.subclass = bc->info_dad[0] ;
3282                         fr.src=NULL;
3283                         fr.data = NULL ;
3284                         fr.datalen = 0;
3285                         fr.samples = 0 ;
3286                         fr.mallocd =0 ;
3287                         fr.offset= 0 ;
3288
3289                         
3290                         int digits;
3291                         misdn_cfg_get( 0, MISDN_GEN_APPEND_DIGITS2EXTEN, &digits, sizeof(int));
3292                         if (ch->state != MISDN_CONNECTED ) {
3293                                 if (digits) {
3294                                         int l = sizeof(bc->dad);
3295                                         strncat(bc->dad,bc->info_dad, l);
3296                                         bc->dad[l-1] = 0;
3297                                         l = sizeof(ch->ast->exten);
3298                                         strncpy(ch->ast->exten, bc->dad, l);
3299                                         ch->ast->exten[l-1] = 0;
3300
3301                                         ast_cdr_update(ch->ast);
3302                                 }
3303                                 
3304                                 ast_queue_frame(ch->ast, &fr);
3305                         }
3306                         
3307                 }
3308         }
3309         break;
3310         case EVENT_SETUP:
3311         {
3312                 struct chan_list *ch=find_chan_by_bc(cl_te, bc);
3313                 if (ch && ch->state != MISDN_NOTHING ) {
3314                         chan_misdn_log(1, bc->port, " --> Ignoring Call we have already one\n");
3315                         return RESPONSE_IGNORE_SETUP_WITHOUT_CLOSE; /*  Ignore MSNs which are not in our List */
3316                 }
3317         }
3318         
3319
3320         int msn_valid = misdn_cfg_is_msn_valid(bc->port, bc->dad);
3321         if (!bc->nt && ! msn_valid) {
3322                 chan_misdn_log(1, bc->port, " --> Ignoring Call, its not in our MSN List\n");
3323                 return RESPONSE_IGNORE_SETUP; /*  Ignore MSNs which are not in our List */
3324         }
3325         
3326         print_bearer(bc);
3327     
3328         {
3329                 struct chan_list *ch=init_chan_list();
3330                 struct ast_channel *chan;
3331
3332                 if (!ch) { chan_misdn_log(-1, bc->port, "cb_events: malloc for chan_list failed!\n"); return 0;}
3333                 
3334                 ch->bc = bc;
3335                 ch->l3id=bc->l3_id;
3336                 ch->addr=bc->addr;
3337                 ch->orginator = ORG_MISDN;
3338
3339                 chan=misdn_new(ch, AST_STATE_RESERVED,bc->dad, bc->oad, AST_FORMAT_ALAW, bc->port, bc->channel);
3340                 ch->ast = chan;
3341
3342                 read_config(ch, ORG_MISDN);
3343                 
3344                 export_ies(chan, bc);
3345                 
3346                 ch->ast->rings=1;
3347                 ast_setstate(ch->ast, AST_STATE_RINGING);
3348
3349                 if ( bc->pres ) {
3350                         chan->cid.cid_pres=AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
3351                 }  else {
3352                         chan->cid.cid_pres=AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
3353                 }
3354       
3355                 pbx_builtin_setvar_helper(chan, "TRANSFERCAPABILITY", ast_transfercapability2str(bc->capability));
3356                 chan->transfercapability=bc->capability;
3357                 
3358                 switch (bc->capability) {
3359                 case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
3360                         pbx_builtin_setvar_helper(chan,"CALLTYPE","DIGITAL");
3361                         break;
3362                 default:
3363                         pbx_builtin_setvar_helper(chan,"CALLTYPE","SPEECH");
3364                 }
3365
3366                 /** queue new chan **/
3367                 cl_queue_chan(&cl_te, ch) ;
3368                 
3369                 /* Check for Pickup Request first */
3370                 if (!strcmp(chan->exten, ast_pickup_ext())) {
3371                         int ret;/** Sending SETUP_ACK**/
3372                         ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3373                         if (ast_pickup_call(chan)) {
3374                                 ast_hangup(chan);
3375                         } else {
3376                                 ch->state = MISDN_CALLING_ACKNOWLEDGE;
3377                                 ch->ast=NULL;
3378                                 ast_setstate(chan, AST_STATE_DOWN);
3379                                 ast_hangup(chan);
3380                                 break;
3381                         }
3382                 }
3383                 
3384                 /*
3385                   added support for s extension hope it will help those poor cretains
3386                   which haven't overlap dial.
3387                 */
3388                 {
3389                         int ai;
3390                         misdn_cfg_get( bc->port, MISDN_CFG_ALWAYS_IMMEDIATE, &ai, sizeof(ai));
3391                         if ( ai ) {
3392                                 do_immediate_setup(bc, ch , chan);
3393                                 break;
3394                         }
3395                         
3396                         
3397                         
3398                 }
3399
3400                 /* check if we should jump into s when we have no dad */
3401                 {
3402                         int im;
3403                         misdn_cfg_get( bc->port, MISDN_CFG_IMMEDIATE, &im, sizeof(im));
3404                         if ( im && ast_strlen_zero(bc->dad) ) {
3405                                 do_immediate_setup(bc, ch , chan);
3406                                 break;
3407                         }
3408                 }
3409
3410                 
3411                         chan_misdn_log(5,bc->port,"CONTEXT:%s\n",ch->context);
3412                         if(!ast_canmatch_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3413                         
3414                         chan_misdn_log(-1, bc->port, "Extension can never match, so disconnecting\n");
3415
3416                         tone_indicate(ch,TONE_BUSY);
3417                         ch->state=MISDN_EXTCANTMATCH;
3418                         bc->out_cause=1;
3419
3420                         if (bc->nt)
3421                                 misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3422                         else
3423                                 misdn_lib_send_event(bc, EVENT_DISCONNECT );
3424                         break;
3425                 }
3426                 
3427                 if (ast_exists_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3428                         ch->state=MISDN_DIALING;
3429                         
3430                         if (bc->nt || (bc->need_more_infos && misdn_lib_is_ptp(bc->port)) ) {
3431                                 int ret; 
3432                                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3433                         } else {
3434                                 int ret;
3435                                 ret= misdn_lib_send_event(bc, EVENT_PROCEEDING );
3436                         }
3437         
3438                         if (ast_pbx_start(chan)<0) {
3439
3440                                 chan_misdn_log(-1, bc->port, "ast_pbx_start returned <0 in SETUP\n");
3441                                 chan=NULL;
3442                                 tone_indicate(ch,TONE_BUSY);
3443
3444                                 if (bc->nt)
3445                                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3446                                 else
3447                                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
3448                         }
3449                 } else {
3450                         int ret= misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3451                         if (ret == -ENOCHAN) {
3452                                 ast_log(LOG_WARNING,"Channel was catched, before we could Acknowledge\n");
3453                                 misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
3454                         }
3455                         /*  send tone to phone :) */
3456
3457                         /** ADD IGNOREPAT **/
3458                         
3459                         int stop_tone;
3460                         misdn_cfg_get( 0, MISDN_GEN_STOP_TONE, &stop_tone, sizeof(int));
3461                         if ( (!ast_strlen_zero(bc->dad)) && stop_tone ) 
3462                                 tone_indicate(ch,TONE_NONE);
3463                         else
3464                                 tone_indicate(ch,TONE_DIAL);
3465                         
3466                         ch->state=MISDN_WAITING4DIGS;
3467                 }
3468       
3469         }
3470         break;
3471         case EVENT_SETUP_ACKNOWLEDGE:
3472         {
3473                 ch->state = MISDN_CALLING_ACKNOWLEDGE;
3474                 if (!ast_strlen_zero(bc->infos_pending)) {
3475                         /* TX Pending Infos */
3476                         
3477                         {
3478                                 int l = sizeof(bc->dad);
3479                                 strncat(bc->dad,bc->infos_pending, l - strlen(bc->dad));
3480                                 bc->dad[l-1] = 0;
3481                         }       
3482                         {
3483                                 int l = sizeof(ch->ast->exten);
3484                                 strncpy(ch->ast->exten, bc->dad, l);
3485                                 ch->ast->exten[l-1] = 0;
3486                         }
3487                         {
3488                                 int l = sizeof(bc->info_dad);
3489                                 strncpy(bc->info_dad, bc->infos_pending, l);
3490                                 bc->info_dad[l-1] = 0;
3491                         }
3492                         strncpy(bc->infos_pending,"", 1);
3493
3494                         misdn_lib_send_event(bc, EVENT_INFORMATION);
3495                 }
3496         }
3497         break;
3498         case EVENT_PROCEEDING:
3499         {
3500                 
3501                 if ( misdn_cap_is_speech(bc->capability) &&
3502                      misdn_inband_avail(bc) ) {
3503                         start_bc_tones(ch);
3504                 }
3505
3506                 ch->state = MISDN_PROCEEDING;
3507                 
3508                 ast_queue_control(ch->ast, AST_CONTROL_PROCEEDING);
3509         }
3510         break;
3511         case EVENT_PROGRESS:
3512                 if (!bc->nt ) {
3513                         if ( misdn_cap_is_speech(bc->capability) &&
3514                              misdn_inband_avail(bc)
3515                                 ) {
3516                                 start_bc_tones(ch);
3517       &