don't generate any message for native bridge attempts unless all the basic checks...
[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         if (option_verbose > 2) 
2027                 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
2028
2029         chan_misdn_log(1, ch1->bc->port, "* Makeing Native Bridge between %s and %s\n", ch1->bc->oad, ch2->bc->oad);
2030   
2031         while(1) {
2032                 to=-1;
2033                 who = ast_waitfor_n(carr, 2, &to);
2034
2035                 if (!who) {
2036                         ast_log(LOG_DEBUG,"misdn_bridge: empty read\n");
2037                         continue;
2038                 }
2039                 f = ast_read(who);
2040     
2041                 if (!f || f->frametype == AST_FRAME_CONTROL) {
2042                         /* got hangup .. */
2043                         *fo=f;
2044                         *rc=who;
2045       
2046                         break;
2047                 }
2048     
2049     
2050                 if (who == c0) {
2051                         ast_write(c1,f);
2052                 }
2053                 else {
2054                         ast_write(c0,f);
2055                 }
2056     
2057         }
2058   
2059         if (bridging) {
2060                 misdn_lib_split_bridge(ch1->bc,ch2->bc);
2061         }
2062   
2063         return 0;
2064 }
2065
2066 /** AST INDICATIONS END **/
2067
2068 static int start_bc_tones(struct chan_list* cl)
2069 {
2070         manager_bchannel_activate(cl->bc);
2071         manager_send_tone(cl->bc ,TONE_NONE);
2072         cl->notxtone=0;
2073         cl->norxtone=0;
2074         return 0;
2075 }
2076
2077 static int stop_bc_tones(struct chan_list *cl)
2078 {
2079         if (cl->bc) {
2080                 manager_bchannel_deactivate(cl->bc);
2081         }
2082         cl->notxtone=1;
2083         cl->norxtone=1;
2084         
2085         return 0;
2086 }
2087
2088
2089 static struct chan_list *init_chan_list(void)
2090 {
2091         struct chan_list *cl=malloc(sizeof(struct chan_list));
2092         
2093         if (!cl) {
2094                 chan_misdn_log(-1, 0, "misdn_request: malloc failed!");
2095                 return NULL;
2096         }
2097         
2098         memset(cl,0,sizeof(struct chan_list));
2099         
2100         return cl;
2101         
2102 }
2103
2104 static struct ast_channel *misdn_request(const char *type, int format, void *data, int *cause)
2105
2106 {
2107         struct ast_channel *tmp = NULL;
2108         char group[BUFFERSIZE]="";
2109         char buf[128];
2110         char buf2[128], *ext=NULL, *port_str;
2111         char *tokb=NULL, *p=NULL;
2112         int channel=0, port=0;
2113         struct misdn_bchannel *newbc = NULL;
2114         
2115         struct chan_list *cl=init_chan_list();
2116         
2117         sprintf(buf,"%s/%s",misdn_type,(char*)data);
2118         strncpy(buf2,data, 128);
2119         buf2[127] = 0;
2120         port_str=strtok_r(buf2,"/", &tokb);
2121
2122         ext=strtok_r(NULL,"/", &tokb);
2123
2124         /*
2125           if (!ext) {
2126           ast_log(LOG_WARNING, " --> ! IND : CALL dad:%s WITH WRONG ARGS, check extension.conf\n",ext);
2127           
2128           return NULL;
2129           }
2130         */
2131         
2132         if (port_str) {
2133                 if (port_str[0]=='g' && port_str[1]==':' ) {
2134                         /* We make a group call lets checkout which ports are in my group */
2135                         port_str += 2;
2136                         strncpy(group, port_str, BUFFERSIZE);
2137                         group[127] = 0;
2138                         chan_misdn_log(2, 0, " --> Group Call group: %s\n",group);
2139                 } 
2140                 else if ((p = strchr(port_str, ':'))) {
2141                         // we have a preselected channel
2142                         *p = 0;
2143                         channel = atoi(++p);
2144                         port = atoi(port_str);
2145                         chan_misdn_log(2, port, " --> Call on preselected Channel (%d).\n", channel);
2146                 }
2147                 else {
2148                         port = atoi(port_str);
2149                 }
2150                 
2151                 
2152         } else {
2153                 ast_log(LOG_WARNING, " --> ! IND : CALL dad:%s WITHOUT PORT/Group, check extension.conf\n",ext);
2154                 return NULL;
2155         }
2156
2157         if (!ast_strlen_zero(group)) {
2158         
2159                 char cfg_group[BUFFERSIZE];
2160                 struct robin_list *rr = NULL;
2161
2162                 if (misdn_cfg_is_group_method(group, METHOD_ROUND_ROBIN)) {
2163                         chan_misdn_log(4, port, " --> STARTING ROUND ROBIN...");
2164                         rr = get_robin_position(group);
2165                 }
2166                 
2167                 if (rr) {
2168                         int robin_channel = rr->channel;
2169                         int port_start;
2170                         int next_chan = 1;
2171
2172                         do {
2173                                 port_start = 0;
2174                                 for (port = misdn_cfg_get_next_port_spin(rr->port); port > 0 && port != port_start;
2175                                          port = misdn_cfg_get_next_port_spin(port)) {
2176
2177                                         if (!port_start)
2178                                                 port_start = port;
2179
2180                                         if (port >= port_start)
2181                                                 next_chan = 1;
2182                                         
2183                                         if (port < port_start && next_chan) {
2184                                                 if (++robin_channel >= MAX_BCHANS) {
2185                                                         robin_channel = 1;
2186                                                 }
2187                                                 next_chan = 0;
2188                                         }
2189
2190                                         misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2191                                         
2192                                         if (!strcasecmp(cfg_group, group)) {
2193                                                 int l1, port_up;
2194                                         
2195                                                 misdn_cfg_get( 0, MISDN_GEN_L1_INFO_OK, &l1, sizeof(l1));
2196                                                 port_up = misdn_lib_port_up(port);
2197                                                 
2198                                                 if ((l1 && port_up) || !l1)     {
2199                                                         newbc = misdn_lib_get_free_bc(port, robin_channel);
2200                                                         if (newbc) {
2201                                                                 chan_misdn_log(4, port, " Success! Found port:%d channel:%d\n", newbc->port, newbc->channel);
2202                                                                 if (port_up)
2203                                                                         chan_misdn_log(4, port, "def_l1:%d, portup:%d\n", l1, port_up);
2204                                                                 rr->port = newbc->port;
2205                                                                 rr->channel = newbc->channel;
2206                                                                 break;
2207                                                         }
2208                                                 }
2209                                         }
2210                                 }
2211                         } while (!newbc && robin_channel != rr->channel);
2212                         
2213                         if (!newbc)
2214                                 chan_misdn_log(4, port, " Failed! No free channel in group %d!", group);
2215                 }
2216                 
2217                 else {          
2218                         for (port=misdn_cfg_get_next_port(0); port > 0;
2219                                  port=misdn_cfg_get_next_port(port)) {
2220                                 
2221                                 misdn_cfg_get( port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2222                                 
2223                                 if (!strcasecmp(cfg_group, group)) {
2224                                         int l1, port_up;
2225                                         
2226                                         misdn_cfg_get( 0, MISDN_GEN_L1_INFO_OK, &l1, sizeof(l1));
2227                                         port_up = misdn_lib_port_up(port);
2228
2229                                         chan_misdn_log(4, port, "def_l1:%d, portup:%d\n", l1, port_up);
2230                                         
2231                                         if ((l1 && port_up) || !l1)     {
2232                                                 newbc = misdn_lib_get_free_bc(port, 0);
2233                                                 if (newbc)
2234                                                         break;
2235                                         }
2236                                 }
2237                         }
2238                 }
2239                 
2240         } else {
2241                 if (channel)
2242                         chan_misdn_log(1, port," --> preselected_channel: %d\n",channel);
2243                 newbc = misdn_lib_get_free_bc(port, channel);
2244         }
2245         
2246         if (!newbc) {
2247                 chan_misdn_log(1, 0, " --> ! No free channel chan ext:%s even after Group Call\n",ext);
2248                 chan_misdn_log(1, 0, " --> SEND: State Down\n");
2249                 return NULL;
2250         }
2251
2252         /* create ast_channel and link all the objects together */
2253         cl->bc=newbc;
2254         
2255         tmp = misdn_new(cl, AST_STATE_RESERVED, ext, NULL, format, port, channel);
2256         cl->ast=tmp;
2257         
2258         /* register chan in local list */
2259         cl_queue_chan(&cl_te, cl) ;
2260         
2261         /* fill in the config into the objects */
2262         read_config(cl, ORG_AST);
2263         
2264         
2265         return tmp;
2266 }
2267
2268
2269 static struct ast_channel_tech misdn_tech = {
2270         .type="mISDN",
2271         .description="Channel driver for mISDN Support (Bri/Pri)",
2272         .capabilities= AST_FORMAT_ALAW ,
2273         .requester=misdn_request,
2274         .send_digit=misdn_digit,
2275         .call=misdn_call,
2276         .bridge=misdn_bridge, 
2277         .hangup=misdn_hangup,
2278         .answer=misdn_answer,
2279         .read=misdn_read,
2280         .write=misdn_write,
2281         .indicate=misdn_indication,
2282         .fixup=misdn_fixup,
2283         .properties=0
2284 };
2285
2286 static struct ast_channel_tech misdn_tech_wo_bridge = {
2287         .type="mISDN",
2288         .description="Channel driver for mISDN Support (Bri/Pri)",
2289         .capabilities=AST_FORMAT_ALAW ,
2290         .requester=misdn_request,
2291         .send_digit=misdn_digit,
2292         .call=misdn_call,
2293         .hangup=misdn_hangup,
2294         .answer=misdn_answer,
2295         .read=misdn_read,
2296         .write=misdn_write,
2297         .indicate=misdn_indication,
2298         .fixup=misdn_fixup,
2299         .properties=0
2300 };
2301
2302
2303 static unsigned long glob_channel=0;
2304
2305 static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char *exten, char *callerid, int format, int port, int c)
2306 {
2307         struct ast_channel *tmp;
2308         
2309         tmp = ast_channel_alloc(1);
2310         
2311         if (tmp) {
2312                 chan_misdn_log(2, 0, " --> * NEW CHANNEL dad:%s oad:%s\n",exten,callerid);
2313                 
2314                 
2315                 if (c<=0) {
2316                         c=glob_channel++;
2317                         snprintf(tmp->name, sizeof(tmp->name), "%s/%d-u%d",
2318                                  misdn_type, port, c);
2319                 } else {
2320                         snprintf(tmp->name, sizeof(tmp->name), "%s/%d-%d",
2321                                  misdn_type, port, c);
2322                 }
2323                 
2324                 tmp->type = misdn_type;
2325                 
2326                 tmp->nativeformats = prefformat;
2327
2328                 tmp->readformat = format;
2329                 tmp->writeformat = format;
2330     
2331                 tmp->tech_pvt = chlist;
2332                 
2333                 int bridging;
2334                 misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
2335                 if (bridging)
2336                         tmp->tech = &misdn_tech;
2337                 else
2338                         tmp->tech = &misdn_tech_wo_bridge;
2339                 
2340                 tmp->writeformat = format;
2341                 tmp->readformat = format;
2342                 tmp->priority=1;
2343                 
2344                 if (exten) 
2345                         ast_copy_string(tmp->exten, exten,  sizeof(tmp->exten));
2346                 else
2347                         chan_misdn_log(1,0,"misdn_new: no exten given.\n");
2348                 
2349                 if (callerid) {
2350                         char *cid_name, *cid_num;
2351       
2352                         ast_callerid_parse(callerid, &cid_name, &cid_num);
2353                         if (cid_name)
2354                                 tmp->cid.cid_name=strdup(cid_name);
2355                         if (cid_num)
2356                                 tmp->cid.cid_num=strdup(cid_num);
2357                 }
2358
2359                 {
2360                         if (pipe(chlist->pipe)<0)
2361                                 perror("Pipe failed\n");
2362                         
2363                         tmp->fds[0]=chlist->pipe[0];
2364                         
2365                 }
2366                 
2367                 ast_setstate(tmp, state);
2368                 if (state == AST_STATE_RING)
2369                         tmp->rings = 1;
2370                 else
2371                         tmp->rings = 0;
2372                 
2373                 
2374         } else {
2375                 chan_misdn_log(-1,0,"Unable to allocate channel structure\n");
2376         }
2377         
2378         return tmp;
2379 }
2380
2381
2382
2383 static int misdn_tx2ast_frm(struct chan_list * tmp, char * buf,  int len )
2384 {
2385         struct ast_frame frame;
2386         
2387         /* If in hold state we drop frame .. */
2388         if (tmp->holded ) return 0;
2389
2390         switch(tmp->state) {
2391         case MISDN_CLEANING:
2392         case MISDN_EXTCANTMATCH:
2393         case MISDN_WAITING4DIGS:
2394                 return 0;
2395         default:
2396                 break;
2397         }
2398         
2399         if (tmp->norxtone) {
2400                 chan_misdn_log(3, tmp->bc->port, "misdn_tx2ast_frm: Returning because norxtone\n");
2401                 return 0;
2402         }
2403         
2404         frame.frametype  = AST_FRAME_VOICE;
2405         frame.subclass = AST_FORMAT_ALAW;
2406         frame.datalen = len;
2407         frame.samples = len ;
2408         frame.mallocd =0 ;
2409         frame.offset= 0 ;
2410         frame.src = NULL;
2411         frame.data = buf ;
2412         
2413         if (tmp->faxdetect || tmp->ast_dsp ) {
2414                 struct ast_frame *f,*f2;
2415                 if (tmp->trans)
2416                         f2=ast_translate(tmp->trans, &frame,0);
2417                 else {
2418                         chan_misdn_log(0, tmp->bc->port, "No T-Path found\n");
2419                         return 0;
2420                 }
2421                 
2422                 f = ast_dsp_process(tmp->ast, tmp->dsp, f2);
2423                 if (f && (f->frametype == AST_FRAME_DTMF)) {
2424                         ast_log(LOG_DEBUG, "Detected inband DTMF digit: %c", f->subclass);
2425                         if (f->subclass == 'f' && tmp->faxdetect) {
2426                                 /* Fax tone -- Handle and return NULL */
2427                                 struct ast_channel *ast = tmp->ast;
2428                                 if (!tmp->faxhandled) {
2429                                         tmp->faxhandled++;
2430                                         if (strcmp(ast->exten, "fax")) {
2431                                                 if (ast_exists_extension(ast, ast_strlen_zero(ast->macrocontext)? ast->context : ast->macrocontext, "fax", 1, AST_CID_P(ast))) {
2432                                                         if (option_verbose > 2)
2433                                                                 ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension\n", ast->name);
2434                                                         /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
2435                                                         pbx_builtin_setvar_helper(ast,"FAXEXTEN",ast->exten);
2436                                                         if (ast_async_goto(ast, ast->context, "fax", 1))
2437                                                                 ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, ast->context);
2438                                                 } else
2439                                                         ast_log(LOG_NOTICE, "Fax detected, but no fax extension ctx:%s exten:%s\n",ast->context, ast->exten);
2440                                         } else
2441                                                 ast_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
2442                                 } else
2443                                         ast_log(LOG_DEBUG, "Fax already handled\n");
2444                                 frame.frametype = AST_FRAME_NULL;
2445                                 frame.subclass = 0;
2446                                 f = &frame;
2447                         }  else if ( tmp->ast_dsp) {
2448                                 struct ast_frame fr;
2449                                 memset(&fr, 0 , sizeof(fr));
2450                                 fr.frametype = AST_FRAME_DTMF;
2451                                 fr.subclass = f->subclass ;
2452                                 fr.src=NULL;
2453                                 fr.data = NULL ;
2454                                 fr.datalen = 0;
2455                                 fr.samples = 0 ;
2456                                 fr.mallocd =0 ;
2457                                 fr.offset= 0 ;
2458                                 
2459                                 chan_misdn_log(2, tmp->bc->port, " --> * SEND: DTMF (AST_DSP) :%c\n",f->subclass);
2460                                 ast_queue_frame(tmp->ast, &fr);
2461                                 
2462                                 frame.frametype = AST_FRAME_NULL;
2463                                 frame.subclass = 0;
2464                                 f = &frame;
2465                         }
2466                 }
2467         }
2468         
2469         if (tmp && tmp->ast && MISDN_ASTERISK_PVT (tmp->ast) && MISDN_ASTERISK_TECH_PVT(tmp->ast) ) {
2470 #if MISDN_DEBUG
2471                 int i, max=5>len?len:5;
2472     
2473                 printf("write2* %p %d bytes: ",tmp, len);
2474     
2475                 for (i=0; i<  max ; i++) printf("%2.2x ",((char*) frame.data)[i]);
2476                 printf ("\n");
2477 #endif
2478                 chan_misdn_log(9, tmp->bc->port, "Queueing %d bytes 2 Asterisk\n",len);
2479                 ast_queue_frame(tmp->ast,&frame);
2480                 
2481         }  else {
2482                 ast_log (LOG_WARNING, "No ast || ast->pvt || ch\n");
2483         }
2484         
2485         return 0;
2486 }
2487
2488 /** Channel Queue ***/
2489
2490 static struct chan_list *find_chan_by_l3id(struct chan_list *list, unsigned long l3id)
2491 {
2492         struct chan_list *help=list;
2493         for (;help; help=help->next) {
2494                 if (help->l3id == l3id ) return help;
2495         }
2496   
2497         chan_misdn_log(4, list? (list->bc? list->bc->port : 0) : 0, "$$$ find_chan: No channel found with l3id:%x\n",l3id);
2498   
2499         return NULL;
2500 }
2501
2502 static struct chan_list *find_chan_by_bc(struct chan_list *list, struct misdn_bchannel *bc)
2503 {
2504         struct chan_list *help=list;
2505         for (;help; help=help->next) {
2506                 if (help->bc == bc) return help;
2507         }
2508   
2509         chan_misdn_log(4, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
2510   
2511         return NULL;
2512 }
2513
2514
2515 static struct chan_list *find_holded(struct chan_list *list, struct misdn_bchannel *bc)
2516 {
2517         struct chan_list *help=list;
2518         
2519         chan_misdn_log(4, bc->port, "$$$ find_holded: channel:%d oad:%s dad:%s\n",bc->channel, bc->oad,bc->dad);
2520         for (;help; help=help->next) {
2521                 chan_misdn_log(4, bc->port, "$$$ find_holded: --> holded:%d channel:%d\n",help->bc->holded, help->bc->channel);
2522                 if (help->bc->port == bc->port
2523                     && help->bc->holded ) return help;
2524         }
2525         
2526         chan_misdn_log(4, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
2527   
2528         return NULL;
2529 }
2530
2531 static void cl_queue_chan(struct chan_list **list, struct chan_list *chan)
2532 {
2533         chan_misdn_log(4, chan->bc? chan->bc->port : 0, "* Queuing chan %p\n",chan);
2534   
2535         ast_mutex_lock(&cl_te_lock);
2536         if (!*list) {
2537                 *list = chan;
2538         } else {
2539                 struct chan_list *help=*list;
2540                 for (;help->next; help=help->next); 
2541                 help->next=chan;
2542         }
2543         chan->next=NULL;
2544         ast_mutex_unlock(&cl_te_lock);
2545 }
2546
2547 static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan) 
2548 {
2549         if (chan->dsp) 
2550                 ast_dsp_free(chan->dsp);
2551         if (chan->trans)
2552                 ast_translator_free_path(chan->trans);
2553
2554         
2555
2556         ast_mutex_lock(&cl_te_lock);
2557         if (!*list) {
2558                 ast_mutex_unlock(&cl_te_lock);
2559                 return;
2560         }
2561   
2562         if (*list == chan) {
2563                 *list=(*list)->next;
2564                 ast_mutex_unlock(&cl_te_lock);
2565                 return ;
2566         }
2567   
2568         {
2569                 struct chan_list *help=*list;
2570                 for (;help->next; help=help->next) {
2571                         if (help->next == chan) {
2572                                 help->next=help->next->next;
2573                                 ast_mutex_unlock(&cl_te_lock);
2574                                 return;
2575                         }
2576                 }
2577         }
2578         
2579         ast_mutex_unlock(&cl_te_lock);
2580 }
2581
2582 /** Channel Queue End **/
2583
2584
2585
2586 /** Isdn asks us to release channel, pendant to misdn_hangup **/
2587 static void release_chan(struct misdn_bchannel *bc) {
2588         struct ast_channel *ast=NULL;
2589         
2590         {
2591                 struct chan_list *ch=find_chan_by_bc(cl_te, bc);
2592                 if (!ch) ch=find_chan_by_l3id (cl_te, bc->l3_id);
2593                 
2594                 release_lock;
2595                 if (ch->ast) {
2596                         ast=ch->ast;
2597                 } 
2598                 release_unlock;
2599                 
2600                 chan_misdn_log(1, bc->port, "Trying to Release bc with l3id: %x\n",bc->l3_id);
2601
2602                 //releaseing jitterbuffer
2603                 if (ch->jb ) {
2604                         misdn_jb_destroy(ch->jb);
2605                         ch->jb=NULL;
2606                 } else {
2607                         if (!bc->nojitter)
2608                                 chan_misdn_log(5,bc->port,"Jitterbuffer already destroyed.\n");
2609                 }
2610                 
2611                 if (ch) {
2612                         
2613                         close(ch->pipe[0]);
2614                         close(ch->pipe[1]);
2615                         
2616                         if (ast && MISDN_ASTERISK_PVT(ast)) {
2617                                 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));
2618                                 chan_misdn_log(3, bc->port, " --> * State Down\n");
2619                                 /* copy cause */
2620                                 send_cause2ast(ast,bc);
2621                                 
2622                                 MISDN_ASTERISK_TECH_PVT(ast)=NULL;
2623                                 
2624       
2625                                 if (ast->_state != AST_STATE_RESERVED) {
2626                                         chan_misdn_log(3, bc->port, " --> Setting AST State to down\n");
2627                                         ast_setstate(ast, AST_STATE_DOWN);
2628                                 }
2629                                 
2630                                 switch(ch->state) {
2631                                 case MISDN_EXTCANTMATCH:
2632                                 case MISDN_WAITING4DIGS:
2633                                 {
2634                                         chan_misdn_log(3,  bc->port, " --> * State Wait4dig | ExtCantMatch\n");
2635                                         ast_hangup(ast);
2636                                 }
2637                                 break;
2638                                 
2639                                 case MISDN_DIALING:
2640                                 case MISDN_CALLING_ACKNOWLEDGE:
2641                                 case MISDN_PROGRESS:
2642                                         chan_misdn_log(2,  bc->port, "* --> In State Dialin\n");
2643                                         chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2644                                         
2645
2646                                         ast_queue_hangup(ast);
2647                                         break;
2648                                 case MISDN_CALLING:
2649                                         
2650                                         chan_misdn_log(2,  bc->port, "* --> In State Callin\n");
2651                                         
2652                                         if (!bc->nt) {
2653                                                 chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2654                                                 ast_queue_hangup(ast);
2655                                         } else {
2656                                                 chan_misdn_log(2,  bc->port, "* --> Hangup\n");
2657                                                 ast_queue_hangup(ast);
2658                                                 //ast_hangup(ast);
2659                                         }
2660                                         break;
2661                                         
2662                                 case MISDN_CLEANING:
2663                                         /* this state comes out of ast so we mustnt call a ast function ! */
2664                                         chan_misdn_log(2,  bc->port, "* --> In StateCleaning\n");
2665                                         break;
2666                                 case MISDN_HOLD_DISCONNECT:
2667                                         chan_misdn_log(2,  bc->port, "* --> In HOLD_DISC\n");
2668                                         break;
2669                                 default:
2670                                         chan_misdn_log(2,  bc->port, "* --> In State Default\n");
2671                                         chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2672         
2673                                         
2674                                         if (ast && MISDN_ASTERISK_PVT(ast)) {
2675                                                 ast_queue_hangup(ast);
2676                                         } else {
2677                                                 chan_misdn_log (0,  bc->port, "!! Not really queued!\n");
2678                                         }
2679                                 }
2680                         }
2681                         cl_dequeue_chan(&cl_te, ch);
2682                         
2683                         free(ch);
2684                 } else {
2685                         /* chan is already cleaned, so exiting  */
2686                 }
2687         }
2688 }
2689 /*** release end **/
2690
2691 static void misdn_transfer_bc(struct chan_list *tmp_ch, struct chan_list *holded_chan)
2692 {
2693         chan_misdn_log(4,0,"TRANSFERING %s to %s\n",holded_chan->ast->name, tmp_ch->ast->name);
2694         
2695         tmp_ch->state=MISDN_HOLD_DISCONNECT;
2696   
2697         ast_moh_stop(AST_BRIDGED_P(holded_chan->ast));
2698
2699         holded_chan->state=MISDN_CONNECTED;
2700         holded_chan->holded=0;
2701         misdn_lib_transfer(holded_chan->bc?holded_chan->bc:holded_chan->holded_bc);
2702         
2703         ast_channel_masquerade(holded_chan->ast, AST_BRIDGED_P(tmp_ch->ast));
2704 }
2705
2706
2707 static void do_immediate_setup(struct misdn_bchannel *bc,struct chan_list *ch , struct ast_channel *ast)
2708 {
2709         char predial[256]="";
2710         char *p = predial;
2711   
2712         struct ast_frame fr;
2713   
2714         strncpy(predial, ast->exten, sizeof(predial) -1 );
2715   
2716         ch->state=MISDN_DIALING;
2717         
2718
2719         if (bc->nt) {
2720                 int ret; 
2721                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
2722         } else {
2723                 int ret;
2724                 if ( misdn_lib_is_ptp(bc->port)) {
2725                         ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
2726                 } else {
2727                         ret = misdn_lib_send_event(bc, EVENT_PROCEEDING );
2728                 }
2729         }
2730
2731         manager_send_tone(bc,TONE_DIAL);  
2732   
2733         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));
2734   
2735         strncpy(ast->exten,"s", 2);
2736   
2737         if (ast_pbx_start(ast)<0) {
2738                 ast=NULL;
2739                 manager_send_tone(bc,TONE_BUSY);
2740
2741                 if (bc->nt)
2742                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
2743                 else
2744                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
2745         }
2746   
2747   
2748         while (!ast_strlen_zero(p) ) {
2749                 fr.frametype = AST_FRAME_DTMF;
2750                 fr.subclass = *p ;
2751                 fr.src=NULL;
2752                 fr.data = NULL ;
2753                 fr.datalen = 0;
2754                 fr.samples = 0 ;
2755                 fr.mallocd =0 ;
2756                 fr.offset= 0 ;
2757
2758                 if (ch->ast && MISDN_ASTERISK_PVT(ch->ast) && MISDN_ASTERISK_TECH_PVT(ch->ast)) {
2759                         ast_queue_frame(ch->ast, &fr);
2760                 }
2761                 p++;
2762         }
2763 }
2764
2765
2766
2767 static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc) {
2768         
2769         ast->hangupcause=bc->cause;
2770         
2771         switch ( bc->cause) {
2772                 
2773         case 1: /** Congestion Cases **/
2774         case 2:
2775         case 3:
2776         case 4:
2777         case 22:
2778         case 27:
2779                 chan_misdn_log(1, bc?bc->port:0, " --> * SEND: Queue Congestion pid:%d\n", bc?bc->pid:-1);
2780                 
2781                 ast_queue_control(ast, AST_CONTROL_CONGESTION);
2782                 break;
2783                 
2784         case 21:
2785         case 17: /* user busy */
2786                 chan_misdn_log(1,  bc?bc->port:0, " --> * SEND: Queue Busy pid:%d\n", bc?bc->pid:-1);
2787                 
2788                 ast_queue_control(ast, AST_CONTROL_BUSY);
2789                 
2790                 break;
2791         }
2792 }
2793
2794 /************************************************************/
2795 /*  Receive Events from isdn_lib  here                     */
2796 /************************************************************/
2797 static enum event_response_e
2798 cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
2799 {
2800         struct chan_list *ch=find_chan_by_bc(cl_te, bc);
2801         
2802         if (!ch)
2803                 ch=find_chan_by_l3id(cl_te, bc->l3_id);
2804         
2805         if (event != EVENT_BCHAN_DATA) { /*  Debug Only Non-Bchan */
2806                 chan_misdn_log(1, bc->port, "I IND :%s oad:%s dad:%s\n", manager_isdn_get_info(event), bc->oad, bc->dad);
2807                 misdn_lib_log_ies(bc);
2808         }
2809         
2810         if (event != EVENT_SETUP) {
2811                 if (!ch) {
2812                         if (event != EVENT_CLEANUP )
2813                                 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);
2814                         return -1;
2815                 }
2816         }
2817         
2818         if (ch ) {
2819                 switch (event) {
2820                 case EVENT_RELEASE:
2821                 case EVENT_RELEASE_COMPLETE:
2822                 case EVENT_CLEANUP:
2823                         break;
2824                 default:
2825                         if ( !ch->ast  || !MISDN_ASTERISK_PVT(ch->ast) || !MISDN_ASTERISK_TECH_PVT(ch->ast)) {
2826                                 if (event!=EVENT_BCHAN_DATA)
2827                                         ast_log(LOG_WARNING, "No Ast or No private Pointer in Event (%d:%s)\n", event, manager_isdn_get_info(event));
2828                                 return -1;
2829                         }
2830                 }
2831         }
2832         
2833         
2834         switch (event) {
2835         case EVENT_NEW_L3ID:
2836                 ch->l3id=bc->l3_id;
2837                 break;
2838
2839         case EVENT_NEW_BC:
2840                 if (bc)
2841                         ch->bc=bc;
2842                 break;
2843                 
2844         case EVENT_DTMF_TONE:
2845         {
2846                 /*  sending INFOS as DTMF-Frames :) */
2847                 struct ast_frame fr;
2848                 memset(&fr, 0 , sizeof(fr));
2849                 fr.frametype = AST_FRAME_DTMF;
2850                 fr.subclass = bc->dtmf ;
2851                 fr.src=NULL;
2852                 fr.data = NULL ;
2853                 fr.datalen = 0;
2854                 fr.samples = 0 ;
2855                 fr.mallocd =0 ;
2856                 fr.offset= 0 ;
2857                 
2858                 chan_misdn_log(2, bc->port, " --> DTMF:%c\n", bc->dtmf);
2859                 
2860                 ast_queue_frame(ch->ast, &fr);
2861         }
2862         break;
2863         case EVENT_STATUS:
2864                 break;
2865     
2866         case EVENT_INFORMATION:
2867         {
2868                 int stop_tone;
2869                 misdn_cfg_get( 0, MISDN_GEN_STOP_TONE, &stop_tone, sizeof(int));
2870                 if ( stop_tone && bc->tone != TONE_NONE) {
2871                         manager_send_tone(bc,TONE_NONE);
2872                 }
2873                 
2874                 if (ch->state == MISDN_WAITING4DIGS ) {
2875                         /*  Ok, incomplete Setup, waiting till extension exists */
2876                         {
2877                                 int l = sizeof(bc->dad);
2878                                 strncat(bc->dad,bc->info_dad, l);
2879                                 bc->dad[l-1] = 0;
2880                         }
2881                         
2882                         
2883                         {
2884                                 int l = sizeof(ch->ast->exten);
2885                                 strncpy(ch->ast->exten, bc->dad, l);
2886                                 ch->ast->exten[l-1] = 0;
2887                         }
2888 /*                      chan_misdn_log(5, bc->port, "Can Match Extension: dad:%s oad:%s\n",bc->dad,bc->oad);*/
2889                         
2890                         
2891                         if(!ast_canmatch_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
2892
2893                                 chan_misdn_log(-1, bc->port, "Extension can never match, so disconnecting\n");
2894                                 manager_send_tone(bc,TONE_BUSY);
2895                                 ch->state=MISDN_EXTCANTMATCH;
2896                                 bc->out_cause=1;
2897
2898                                 if (bc->nt)
2899                                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
2900                                 else
2901                                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
2902                                 break;
2903                         }
2904                         if (ast_exists_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
2905                                 ch->state=MISDN_DIALING;
2906           
2907                                 manager_send_tone(bc,TONE_NONE);
2908 /*                              chan_misdn_log(1, bc->port, " --> * Starting Ast ctx:%s\n", ch->context);*/
2909                                 if (ast_pbx_start(ch->ast)<0) {
2910
2911                                         chan_misdn_log(-1, bc->port, "ast_pbx_start returned < 0 in INFO\n");
2912                                         manager_send_tone(bc,TONE_BUSY);
2913
2914                                         if (bc->nt)
2915                                                 misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
2916                                         else
2917                                                 misdn_lib_send_event(bc, EVENT_DISCONNECT );
2918                                 }
2919                         }
2920         
2921                 } else {
2922                         /*  sending INFOS as DTMF-Frames :) */
2923                         struct ast_frame fr;
2924                         fr.frametype = AST_FRAME_DTMF;
2925                         fr.subclass = bc->info_dad[0] ;
2926                         fr.src=NULL;
2927                         fr.data = NULL ;
2928                         fr.datalen = 0;
2929                         fr.samples = 0 ;
2930                         fr.mallocd =0 ;
2931                         fr.offset= 0 ;
2932
2933                         
2934                         int digits;
2935                         misdn_cfg_get( 0, MISDN_GEN_APPEND_DIGITS2EXTEN, &digits, sizeof(int));
2936                         if (ch->state != MISDN_CONNECTED ) {
2937                                 if (digits) {
2938                                         int l = sizeof(bc->dad);
2939                                         strncat(bc->dad,bc->info_dad, l);
2940                                         bc->dad[l-1] = 0;
2941                                         l = sizeof(ch->ast->exten);
2942                                         strncpy(ch->ast->exten, bc->dad, l);
2943                                         ch->ast->exten[l-1] = 0;
2944
2945                                         ast_cdr_update(ch->ast);
2946                                 }
2947                                 
2948                                 ast_queue_frame(ch->ast, &fr);
2949                         }
2950                         
2951                 }
2952         }
2953         break;
2954         case EVENT_SETUP:
2955         {
2956                 struct chan_list *ch=find_chan_by_bc(cl_te, bc);
2957                 if (ch && ch->state != MISDN_NOTHING ) {
2958                         chan_misdn_log(1, bc->port, " --> Ignoring Call we have already one\n");
2959                         return RESPONSE_IGNORE_SETUP_WITHOUT_CLOSE; /*  Ignore MSNs which are not in our List */
2960                 }
2961         }
2962         
2963
2964         int msn_valid = misdn_cfg_is_msn_valid(bc->port, bc->dad);
2965         if (!bc->nt && ! msn_valid) {
2966                 chan_misdn_log(1, bc->port, " --> Ignoring Call, its not in our MSN List\n");
2967                 return RESPONSE_IGNORE_SETUP; /*  Ignore MSNs which are not in our List */
2968         }
2969         
2970         print_bearer(bc);
2971     
2972         {
2973                 struct chan_list *ch=init_chan_list();
2974                 struct ast_channel *chan;
2975
2976                 if (!ch) { chan_misdn_log(-1, bc->port, "cb_events: malloc for chan_list failed!\n"); return 0;}
2977                 
2978                 ch->bc = bc;
2979                 ch->l3id=bc->l3_id;
2980                 ch->addr=bc->addr;
2981                 ch->orginator = ORG_MISDN;
2982                 
2983                 chan=misdn_new(ch, AST_STATE_RESERVED,bc->dad, bc->oad, AST_FORMAT_ALAW, bc->port, bc->channel);
2984         ch->ast = chan;
2985                 
2986                 read_config(ch, ORG_MISDN);
2987                 
2988                 ch->ast->rings=1;
2989                 ast_setstate(ch->ast, AST_STATE_RINGING);
2990
2991                 if ( bc->pres ) {
2992                         chan->cid.cid_pres=AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
2993                 }  else {
2994                         chan->cid.cid_pres=AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
2995                 }
2996       
2997                 pbx_builtin_setvar_helper(chan, "TRANSFERCAPABILITY", ast_transfercapability2str(bc->capability));
2998                 chan->transfercapability=bc->capability;
2999                 
3000                 switch (bc->capability) {
3001                 case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
3002                         pbx_builtin_setvar_helper(chan,"CALLTYPE","DIGITAL");
3003                         break;
3004                 default:
3005                         pbx_builtin_setvar_helper(chan,"CALLTYPE","SPEECH");
3006                 }
3007
3008                 /** queue new chan **/
3009                 cl_queue_chan(&cl_te, ch) ;
3010
3011                 
3012                 /*
3013                   added support for s extension hope it will help those poor cretains
3014                   which haven't overlap dial.
3015                 */
3016                 {
3017                         int ai;
3018                         misdn_cfg_get( bc->port, MISDN_CFG_ALWAYS_IMMEDIATE, &ai, sizeof(ai));
3019                         if ( ai ) {
3020                                 do_immediate_setup(bc, ch , chan);
3021                                 break;
3022                         }
3023                         
3024                         
3025                         
3026                 }
3027
3028                 
3029                         chan_misdn_log(0,bc->port,"CONTEXT:%s\n",ch->context);
3030                         if(!ast_canmatch_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3031                         
3032                         chan_misdn_log(-1, bc->port, "Extension can never match, so disconnecting\n");
3033
3034                         manager_send_tone(bc,TONE_BUSY);
3035                         ch->state=MISDN_EXTCANTMATCH;
3036                         bc->out_cause=1;
3037
3038                         if (bc->nt)
3039                                 misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3040                         else
3041                                 misdn_lib_send_event(bc, EVENT_DISCONNECT );
3042                         break;
3043                 }
3044                 
3045                 if (ast_exists_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3046                         ch->state=MISDN_DIALING;
3047                         
3048                         if (bc->nt) {
3049                                 int ret; 
3050                                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3051                         } else {
3052                                 int ret;
3053                                 ret= misdn_lib_send_event(bc, EVENT_PROCEEDING );
3054                         }
3055         
3056                         if (ast_pbx_start(chan)<0) {
3057
3058                                 chan_misdn_log(-1, bc->port, "ast_pbx_start returned <0 in SETUP\n");
3059                                 chan=NULL;
3060                                 manager_send_tone(bc,TONE_BUSY);
3061
3062                                 if (bc->nt)
3063                                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3064                                 else
3065                                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
3066                         }
3067                 } else {
3068                         int ret= misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3069                         if (ret == -ENOCHAN) {
3070                                 ast_log(LOG_WARNING,"Channel was catched, before we could Acknowledge\n");
3071                                 misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
3072                         }
3073                         /*  send tone to phone :) */
3074
3075                         /** ADD IGNOREPAT **/
3076                         
3077                         int stop_tone;
3078                         misdn_cfg_get( 0, MISDN_GEN_STOP_TONE, &stop_tone, sizeof(int));
3079                         if ( (!ast_strlen_zero(bc->dad)) && stop_tone ) 
3080                                 manager_send_tone(bc,TONE_NONE);
3081                         else
3082                                 manager_send_tone(bc,TONE_DIAL);
3083         
3084                         ch->state=MISDN_WAITING4DIGS;
3085                 }
3086       
3087         }
3088         break;
3089         case EVENT_SETUP_ACKNOWLEDGE:
3090         {
3091                 ch->state = MISDN_CALLING_ACKNOWLEDGE;
3092                 if (!ast_strlen_zero(bc->infos_pending)) {
3093                         /* TX Pending Infos */
3094                         
3095                         {
3096                                 int l = sizeof(bc->dad);
3097                                 strncat(bc->dad,bc->infos_pending, l - strlen(bc->dad));
3098                                 bc->dad[l-1] = 0;
3099                         }       
3100                         {
3101                                 int l = sizeof(ch->ast->exten);
3102                                 strncpy(ch->ast->exten, bc->dad, l);
3103                                 ch->ast->exten[l-1] = 0;
3104                         }
3105                         {
3106                                 int l = sizeof(bc->info_dad);
3107                                 strncpy(bc->info_dad, bc->infos_pending, l);
3108                                 bc->info_dad[l-1] = 0;
3109                         }
3110                         strncpy(bc->infos_pending,"", 1);
3111
3112                         misdn_lib_send_event(bc, EVENT_INFORMATION);
3113                 }
3114         }
3115         break;
3116         case EVENT_PROCEEDING:
3117         {
3118                 
3119                 if ( misdn_cap_is_speech(bc->capability) &&
3120                      misdn_inband_avail(bc) ) {
3121                         start_bc_tones(ch);
3122                 }
3123         }
3124         break;
3125         case EVENT_PROGRESS:
3126                 if (!bc->nt ) {
3127                         if ( misdn_cap_is_speech(bc->capability) &&
3128                              misdn_inband_avail(bc)
3129                                 ) {
3130                                 start_bc_tones(ch);
3131                         }
3132                         
3133                         ast_queue_control(ch->ast, AST_CONTROL_PROGRESS);
3134                         
3135                         ch->state=MISDN_PROGRESS;
3136                 }
3137                 break;
3138                 
3139                 
3140         case EVENT_ALERTING:
3141         {
3142                 ch->state = MISDN_ALERTING;
3143                 
3144                 ast_queue_control(ch->ast, AST_CONTROL_RINGING);
3145                 ast_setstate(ch->ast, AST_STATE_RINGING);
3146                 
3147                 cb_log(1,bc->port,"Set State Ringing\n");
3148                 
3149                 if ( misdn_cap_is_speech(bc->capability) && misdn_inband_avail(bc)) {
3150                          start_bc_tones(ch);
3151                  }
3152         }
3153         break;
3154         case EVENT_CONNECT:
3155                 misdn_lib_send_event(bc,EVENT_CONNECT_ACKNOWLEDGE);
3156         case EVENT_CONNECT_ACKNOWLEDGE:
3157         {
3158                 bc->state=STATE_CONNECTED;
3159                 
3160                 ch->l3id=bc->l3_id;
3161                 ch->addr=bc->addr;
3162                 
3163                 start_bc_tones(ch);
3164                 
3165                 
3166                 ch->state = MISDN_CONNECTED;
3167                 ast_queue_control(ch->ast, AST_CONTROL_ANSWER);
3168         }
3169         break;
3170         case EVENT_DISCONNECT:
3171         {
3172                 
3173                 struct chan_list *holded_ch=find_holded(cl_te, bc);
3174                 
3175                 
3176                 send_cause2ast(ch->ast,bc);
3177
3178                 if (misdn_inband_avail(bc) && ch->state != MISDN_CONNECTED) {
3179                         /* If there's inband information available (e.g. a
3180                            recorded message saying what was wrong with the
3181                            dialled number, or perhaps even giving an
3182                            alternative number, then play it instead of
3183                            immediately releasing the call */
3184                         start_bc_tones(ch);
3185                         break;
3186                 }
3187                 
3188                 /*Check for holded channel, to implement transfer*/
3189                 if (holded_ch ) {
3190                         if  (ch->state == MISDN_CONNECTED ) {
3191                                 misdn_transfer_bc(ch, holded_ch) ;
3192                                 misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
3193                                 break;
3194                         }
3195                 }
3196                 
3197                 stop_bc_tones(ch);
3198                 bc->out_cause=16;
3199                 
3200                 //if (ch->state == MISDN_CONNECTED) 
3201                 //misdn_lib_send_event(bc,EVENT_RELEASE);
3202                 //else
3203                 //misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
3204                 
3205                 misdn_lib_send_event(bc,EVENT_RELEASE);
3206                 
3207         }
3208         break;
3209         
3210         case EVENT_RELEASE:
3211                 {
3212                         
3213                         switch ( bc->cause) {
3214                                 
3215                         case -1:
3216                                 /*
3217                                   OK, it really sucks, this is a RELEASE from NT-Stack So we take
3218                                   it and return easylie, It seems that we've send a DISCONNECT
3219                                   before, so we should RELEASE_COMPLETE after that Disconnect
3220                                   (looks like ALERTING State at misdn_hangup !!
3221                                 */
3222                                 return RESPONSE_OK;
3223                                 break;
3224                         }
3225                         
3226                         
3227                         bc->out_cause=16;
3228                         
3229                         stop_bc_tones(ch);
3230                         release_chan(bc);
3231                 }
3232                 break;
3233         case EVENT_RELEASE_COMPLETE:
3234         {
3235                 stop_bc_tones(ch);
3236                 release_chan(bc);
3237         }
3238         break;
3239         
3240         case EVENT_BCHAN_DATA:
3241         {
3242                 
3243                 if ( !misdn_cap_is_speech(ch->bc->capability) || bc->nojitter) {
3244                         misdn_tx2ast_frm(ch, bc->bframe, bc->bframe_len );
3245                 } else {
3246                         int len=bc->bframe_len;
3247                         int free=misdn_ibuf_freecount(bc->astbuf);
3248                         
3249                         
3250                         if (bc->bframe_len > free) {
3251                                 ast_log(LOG_DEBUG, "sbuf overflow!\n");
3252                                 len=misdn_ibuf_freecount(bc->astbuf);
3253
3254                                 if (len == 0) {
3255                                         ast_log(LOG_WARNING, "BCHAN_DATA: write buffer overflow port:%d channel:%d!\n",bc->port,bc->channel);
3256                                 }
3257                         }
3258                         
3259                         misdn_ibuf_memcpy_w(bc->astbuf, bc->bframe, len);
3260                         
3261                         {
3262                                 char blah[1]="\0";
3263 #ifdef FLATTEN_JITTER
3264                                 {
3265                                         struct timeval tv;
3266                                         gettimeofday(&tv,NULL);
3267                                         
3268                                         if (tv.tv_usec % 10000 > 0 ) {
3269                                                 write(ch->pipe[1], blah,sizeof(blah));
3270                                                 bc->time_usec=tv.tv_usec;
3271                                         }
3272                                 }
3273 #else
3274                                 write(ch->pipe[1], blah,sizeof(blah));
3275 #endif
3276                                 
3277                                 
3278                         }
3279                 }
3280                 
3281         }
3282         break;
3283         case EVENT_TIMEOUT:
3284
3285                 misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
3286                 break;
3287                 {
3288                         switch (ch->state) {
3289                         case MISDN_CALLING:
3290
3291                                 chan_misdn_log(-1, bc?bc->port:0, "GOT TIMOUT AT CALING pid:%d\n", bc?bc->pid:-1);
3292                                         break;
3293                         case MISDN_DIALING:
3294                         case MISDN_PROGRESS:
3295                                 break;
3296                         default:
3297                                 misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
3298                         }
3299                 }
3300                 break;
3301         case EVENT_CLEANUP:
3302         {
3303                 stop_bc_tones(ch);
3304                 release_chan(bc);
3305         }
3306         break;
3307     
3308         /***************************/
3309         /** Suplementary Services **/
3310         /***************************/
3311         case EVENT_RETRIEVE:
3312         {
3313                 struct ast_channel *hold_ast=AST_BRIDGED_P(ch->ast);
3314                 ch->state = MISDN_CONNECTED;
3315                 
3316                 if (hold_ast) {
3317                         ast_moh_stop(hold_ast);
3318                 }
3319                 
3320                 if ( misdn_lib_send_event(bc, EVENT_RETRIEVE_ACKNOWLEDGE) < 0)
3321                         misdn_lib_send_event(bc, EVENT_RETRIEVE_REJECT);
3322                 
3323                 
3324         }
3325         break;
3326     
3327         case EVENT_HOLD:
3328         {
3329                 int hold_allowed;
3330                 misdn_cfg_get( bc->port, MISDN_CFG_HOLD_ALLOWED, &hold_allowed, sizeof(int));
3331                 
3332                 if (!hold_allowed) {
3333
3334                         chan_misdn_log(-1, bc->port, "Hold not allowed this port.\n");
3335                         misdn_lib_send_event(bc, EVENT_HOLD_REJECT);
3336                         break;
3337                 }
3338
3339                 {
3340                         struct chan_list *holded_ch=find_holded(cl_te, bc);
3341                         if (holded_ch) {
3342                                 misdn_lib_send_event(bc, EVENT_HOLD_REJECT);
3343
3344                                 chan_misdn_log(-1, bc->port, "We can't use RETRIEVE at the moment due to mISDN bug!\n");
3345                                 break;
3346                         }
3347                 }
3348                 
3349                 if (AST_BRIDGED_P(ch->ast)){
3350                         ch->state = MISDN_HOLDED;
3351                         ch->l3id = bc->l3_id;
3352                         
3353                         ast_moh_start(AST_BRIDGED_P(ch->ast), NULL);
3354                         misdn_lib_send_event(bc, EVENT_HOLD_ACKNOWLEDGE);
3355                 } else {
3356                         misdn_lib_send_event(bc, EVENT_HOLD_REJECT);
3357                         chan_misdn_log(0, bc->port, "We aren't bridged to anybody\n");
3358                 }
3359         } 
3360         break;
3361         
3362         case EVENT_FACILITY:
3363                 print_facility(bc);
3364                 
3365                 switch (bc->fac_type) {
3366                 case FACILITY_CALLDEFLECT:
3367                 {
3368                         struct ast_channel *bridged=AST_BRIDGED_P(ch->ast);
3369                         struct chan_list *ch;
3370                         
3371                         if (bridged && MISDN_ASTERISK_TECH_PVT(bridged)) {
3372                                 ch=MISDN_ASTERISK_TECH_PVT(bridged);
3373                                 //ch->state=MISDN_FACILITY_DEFLECTED;
3374                                 if (ch->bc) {
3375                                         /* todo */
3376                                 }
3377                                 
3378                         }
3379                         
3380                 } 
3381                 
3382                 break;
3383                 default:
3384                         chan_misdn_log(1,bc->port," --> not yet handled\n");
3385                 }
3386                 
3387                 break;
3388                                 
3389         default:
3390                 ast_log(LOG_WARNING, "Got Unknown Event\n");
3391                 break;
3392         }
3393         
3394         return RESPONSE_OK;
3395 }
3396
3397 /** TE STUFF END **/
3398
3399 /******************************************
3400  *
3401  *   Asterisk Channel Endpoint END
3402  *
3403  *
3404  *******************************************/
3405
3406
3407 static int clearl3_true ( void ) {
3408         int default_clearl3;
3409         misdn_cfg_get( 0, MISDN_GEN_CLEAR_L3, &default_clearl3, sizeof(int));
3410         return default_clearl3;
3411 }
3412
3413 static int g_config_initialized=0;
3414
3415 int load_module(void)
3416 {
3417         int i;
3418         
3419         char ports[256]="";
3420         
3421         max_ports=misdn_lib_maxports_get();
3422         
3423         if (max_ports<=0) {
3424                 ast_log(LOG_ERROR, "Unable to initialize mISDN\n");
3425                 return -1;
3426         }
3427         
3428         
3429         misdn_cfg_init(max_ports);
3430         g_config_initialized=1;
3431         
3432         misdn_debug = (int *)malloc(sizeof(int) * (max_ports+1));
3433         misdn_cfg_get( 0, MISDN_GEN_DEBUG, &misdn_debug[0], sizeof(int));
3434         for (i = 1; i <= max_ports; i++)
3435                 misdn_debug[i] = misdn_debug[0];
3436         misdn_debug_only = (int *)calloc(max_ports + 1, sizeof(int));
3437
3438         
3439         {
3440                 char tempbuf[BUFFERSIZE];
3441                 misdn_cfg_get( 0, MISDN_GEN_TRACEFILE, tempbuf, BUFFERSIZE);
3442                 if (strlen(tempbuf))
3443                         tracing = 1;
3444         }
3445
3446         ast_mutex_init(&cl_te_lock);
3447         ast_mutex_init(&release_lock_mutex);
3448
3449         misdn_cfg_get_ports_string(ports);
3450         if (strlen(ports))
3451                 chan_misdn_log(0, 0, "Got: %s from get_ports\n",ports);
3452         
3453         {
3454                 struct misdn_lib_iface iface = {
3455                         .cb_event = cb_events,
3456                         .cb_log = chan_misdn_log,
3457                         .cb_jb_empty = chan_misdn_jb_empty,
3458                         .cb_clearl3_true = clearl3_true
3459                 };
3460                 if (misdn_lib_init(ports, &iface, NULL))
3461                         chan_misdn_log(0, 0, "No te ports initialized\n");
3462         }
3463
3464
3465         {
3466                 if (ast_channel_register(&misdn_tech)) {
3467                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", misdn_type);
3468                         unload_module();
3469                         return -1;
3470                 }
3471         }
3472   
3473         ast_cli_register(&cli_send_display);
3474         ast_cli_register(&cli_send_cd);
3475         ast_cli_register(&cli_send_digit);
3476         ast_cli_register(&cli_toggle_echocancel);
3477         ast_cli_register(&cli_set_tics);
3478
3479         ast_cli_register(&cli_show_cls);
3480         ast_cli_register(&cli_show_cl);
3481         ast_cli_register(&cli_show_config);
3482         ast_cli_register(&cli_show_port);
3483         ast_cli_register(&cli_show_stacks);
3484
3485         ast_cli_register(&cli_restart_port);
3486         ast_cli_register(&cli_port_up);
3487         ast_cli_register(&cli_set_debug);
3488         ast_cli_register(&cli_set_crypt_debug);
3489         ast_cli_register(&cli_reload);
3490
3491   
3492         ast_register_application("misdn_set_opt", misdn_set_opt_exec, "misdn_set_flags",
3493                                  "misdn_set_opt(:<opt><optarg>:<opt><optarg>..):\n"
3494                                  "Sets mISDN opts. and optargs\n"
3495                                  "\n"
3496                 );
3497
3498         
3499         ast_register_application("misdn_facility", misdn_facility_exec, "misdn_facility",
3500                                  "misdn_facility(<FACILITY_TYPE>|<ARG1>|..)\n"
3501                                  "Sends the Facility Message FACILITY_TYPE with \n"
3502                                  "the given Arguments to the current ISDN Channel\n"
3503   &nbs