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