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