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