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