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