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