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