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