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