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