710bb8b1c84944569af27a13a9d4a2b5f01ae72c
[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
92
93 /* allocates the jb-structure and initialise the elements*/
94 struct misdn_jb *misdn_jb_init(int size, int upper_threshold);
95
96 /* frees the data and destroys the given jitterbuffer struct */
97 void misdn_jb_destroy(struct misdn_jb *jb);
98
99 /* fills the jitterbuffer with len data returns < 0 if there was an
100 error (bufferoverun). */
101 int misdn_jb_fill(struct misdn_jb *jb, const char *data, int len);
102
103 /* gets len bytes out of the jitterbuffer if available, else only the
104 available data is returned and the return value indicates the number
105 of data. */
106 int misdn_jb_empty(struct misdn_jb *jb, char *data, int len);
107
108
109
110
111 /* BEGIN: chan_misdn.h */
112
113
114
115 enum misdn_chan_state {
116         MISDN_NOTHING,          /*!< at beginning */
117         MISDN_WAITING4DIGS, /*!<  when waiting for infos */
118         MISDN_EXTCANTMATCH, /*!<  when asterisk couldnt match our ext */
119         MISDN_DIALING, /*!<  when pbx_start */
120         MISDN_PROGRESS, /*!<  we got a progress */
121         MISDN_PROCEEDING, /*!<  we got a progress */
122         MISDN_CALLING, /*!<  when misdn_call is called */
123         MISDN_CALLING_ACKNOWLEDGE, /*!<  when we get SETUP_ACK */
124         MISDN_ALERTING, /*!<  when Alerting */
125         MISDN_BUSY, /*!<  when BUSY */
126         MISDN_CONNECTED, /*!<  when connected */
127         MISDN_PRECONNECTED, /*!<  when connected */
128         MISDN_DISCONNECTED, /*!<  when connected */
129         MISDN_BRIDGED, /*!<  when bridged */
130         MISDN_CLEANING, /*!< when hangup from * but we were connected before */
131         MISDN_HUNGUP_FROM_MISDN, /*!< when DISCONNECT/RELEASE/REL_COMP  cam from misdn */
132         MISDN_HUNGUP_FROM_AST, /*!< when DISCONNECT/RELEASE/REL_COMP came out of */
133         /* misdn_hangup */
134         MISDN_HOLDED, /*!< if this chan is holded */
135         MISDN_HOLD_DISCONNECT /*!< if this chan is holded */
136   
137 };
138
139 #define ORG_AST 1
140 #define ORG_MISDN 2
141
142 struct chan_list {
143   
144         ast_mutex_t lock;
145
146         char allowed_bearers[BUFFERSIZE+1];
147         
148         enum misdn_chan_state state;
149         int holded; 
150         int orginator;
151
152         int norxtone;
153         int notxtone; 
154         
155         int incoming_early_audio;
156
157         int ignore_dtmf;
158
159         int pipe[2];
160         char ast_rd_buf[4096];
161         struct ast_frame frame;
162
163         int faxdetect;
164         int faxhandled;
165
166         int ast_dsp;
167
168         int jb_len;
169         int jb_upper_threshold;
170         struct misdn_jb *jb;
171         
172         struct ast_dsp *dsp;
173         struct ast_trans_pvt *trans;
174   
175         struct ast_channel * ast;
176
177         int dummy;
178   
179         struct misdn_bchannel *bc;
180         struct misdn_bchannel *holded_bc;
181
182         unsigned int l3id;
183         int addr;
184
185         char context[BUFFERSIZE];
186
187         int zero_read_cnt;
188         int dropped_frame_cnt;
189
190         int far_alerting;
191         int other_pid;
192         struct chan_list *other_ch;
193
194         const struct tone_zone_sound *ts;
195         
196         struct chan_list *peer;
197         struct chan_list *next;
198         struct chan_list *prev;
199         struct chan_list *first;
200 };
201
202
203
204 void export_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch);
205 void import_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch);
206
207 struct robin_list {
208         char *group;
209         int port;
210         int channel;
211         struct robin_list *next;
212         struct robin_list *prev;
213 };
214 static struct robin_list *robin = NULL;
215
216
217
218 struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame *frame);
219
220
221
222 static inline void free_robin_list_r (struct robin_list *r)
223 {
224         if (r) {
225                 if (r->next) free_robin_list_r(r->next);
226                 if (r->group) free(r->group);
227                 free(r);
228         }
229 }
230
231 static void free_robin_list ( void )
232 {
233         free_robin_list_r(robin);
234         robin = NULL;
235 }
236
237 static struct robin_list* get_robin_position (char *group) 
238 {
239         struct robin_list *iter = robin;
240         for (; iter; iter = iter->next) {
241                 if (!strcasecmp(iter->group, group))
242                         return iter;
243         }
244         struct robin_list *new = (struct robin_list *)calloc(1, sizeof(struct robin_list));
245         new->group = strndup(group, strlen(group));
246         new->channel = 1;
247         if (robin) {
248                 new->next = robin;
249                 robin->prev = new;
250         }
251         robin = new;
252         return robin;
253 }
254
255
256 static void chan_misdn_log(int level, int port, char *tmpl, ...);
257
258 static struct ast_channel *misdn_new(struct chan_list *cl, int state,  char *exten, char *callerid, int format, int port, int c);
259 static void send_digit_to_chan(struct chan_list *cl, char digit );
260
261
262 #define AST_CID_P(ast) ast->cid.cid_num
263 #define AST_BRIDGED_P(ast) ast_bridged_channel(ast) 
264 #define AST_LOAD_CFG ast_config_load
265 #define AST_DESTROY_CFG ast_config_destroy
266
267 #define MISDN_ASTERISK_TECH_PVT(ast) ast->tech_pvt
268 #define MISDN_ASTERISK_PVT(ast) 1
269
270 #include <asterisk/strings.h>
271
272 /* #define MISDN_DEBUG 1 */
273
274 static char *desc = "Channel driver for mISDN Support (Bri/Pri)";
275 static const char misdn_type[] = "mISDN";
276
277 static int tracing = 0 ;
278
279 static char **misdn_key_vector=NULL;
280 static int misdn_key_vector_size=0;
281
282 /* Only alaw and mulaw is allowed for now */
283 static int prefformat =  AST_FORMAT_ALAW ; /*  AST_FORMAT_SLINEAR ;  AST_FORMAT_ULAW | */
284
285 static int *misdn_debug;
286 static int *misdn_debug_only;
287 static int max_ports;
288
289 static int *misdn_in_calls;
290 static int *misdn_out_calls;
291
292
293 struct chan_list dummy_cl;
294
295 struct chan_list *cl_te=NULL;
296 ast_mutex_t cl_te_lock;
297
298 static enum event_response_e
299 cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data);
300
301 static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc);
302
303 static void cl_queue_chan(struct chan_list **list, struct chan_list *chan);
304 static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan);
305 static struct chan_list *find_chan_by_bc(struct chan_list *list, struct misdn_bchannel *bc);
306 static struct chan_list *find_chan_by_pid(struct chan_list *list, int pid);
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_ch(ast, newbc, ch);
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->other_ch && p->other_ch->bc && misdn_inband_avail(p->other_ch->bc)) {
1857                                         chan_misdn_log(1,p->bc->port, " --> other End is mISDN and has inband info available\n");
1858                                         break;
1859                                 }
1860                         
1861                                 if ( !p->bc->nt && (p->orginator==ORG_MISDN) && !p->incoming_early_audio ) 
1862                                         chan_misdn_log(1,p->bc->port, " --> incoming_early_audio off\n");
1863                                  else 
1864                                          tone_indicate(p, TONE_ALERTING);
1865                                 chan_misdn_log(1, p->bc->port, " --> * SEND: State Ring pid:%d\n",p->bc?p->bc->pid:-1);
1866                                 ast_setstate(ast,AST_STATE_RINGING);
1867                 }
1868                 break;
1869         case AST_CONTROL_ANSWER:
1870                 chan_misdn_log(1, p->bc->port, " --> * IND :\tanswer pid:%d\n",p->bc?p->bc->pid:-1);
1871                 start_bc_tones(p);
1872                 break;
1873         case AST_CONTROL_TAKEOFFHOOK:
1874                 chan_misdn_log(1, p->bc->port, " --> *\ttakeoffhook pid:%d\n",p->bc?p->bc->pid:-1);
1875                 break;
1876         case AST_CONTROL_OFFHOOK:
1877                 chan_misdn_log(1, p->bc->port, " --> *\toffhook pid:%d\n",p->bc?p->bc->pid:-1);
1878                 break; 
1879         case AST_CONTROL_FLASH:
1880                 chan_misdn_log(1, p->bc->port, " --> *\tflash pid:%d\n",p->bc?p->bc->pid:-1);
1881                 break;
1882         case AST_CONTROL_PROGRESS:
1883                 chan_misdn_log(1, p->bc->port, " --> * IND :\tprogress pid:%d\n",p->bc?p->bc->pid:-1);
1884                 misdn_lib_send_event( p->bc, EVENT_PROGRESS);
1885                 break;
1886         case AST_CONTROL_PROCEEDING:
1887                 chan_misdn_log(1, p->bc->port, " --> * IND :\tproceeding pid:%d\n",p->bc?p->bc->pid:-1);
1888                 misdn_lib_send_event( p->bc, EVENT_PROCEEDING);
1889                 break;
1890         case AST_CONTROL_CONGESTION:
1891                 chan_misdn_log(1, p->bc->port, " --> * IND :\tcongestion pid:%d\n",p->bc?p->bc->pid:-1);
1892
1893                 p->bc->out_cause=42;
1894                 if (p->state != MISDN_CONNECTED) {
1895                         start_bc_tones(p);
1896                         misdn_lib_send_event( p->bc, EVENT_RELEASE);
1897                 } else {
1898                         misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
1899                 }
1900
1901                 if (p->bc->nt) {
1902                         tone_indicate(p, TONE_BUSY);
1903                 }
1904                 break;
1905         case -1 :
1906                 chan_misdn_log(1, p->bc->port, " --> * IND :\t-1! (stop indication) pid:%d\n",p->bc?p->bc->pid:-1);
1907                 
1908                 tone_indicate(p, TONE_NONE);
1909
1910                 if (p->state == MISDN_CONNECTED) 
1911                         start_bc_tones(p);
1912
1913                 break;
1914
1915         case AST_CONTROL_HOLD:
1916                 chan_misdn_log(1, p->bc->port, " --> *\tHOLD pid:%d\n",p->bc?p->bc->pid:-1);
1917                 break;
1918         case AST_CONTROL_UNHOLD:
1919                 chan_misdn_log(1, p->bc->port, " --> *\tUNHOLD pid:%d\n",p->bc?p->bc->pid:-1);
1920                 break;
1921         default:
1922                 ast_log(LOG_WARNING, " --> * Unknown Indication:%d pid:%d\n",cond,p->bc?p->bc->pid:-1);
1923         }
1924   
1925         return 0;
1926 }
1927
1928 static int misdn_hangup(struct ast_channel *ast)
1929 {
1930         struct chan_list *p;
1931         struct misdn_bchannel *bc=NULL;
1932         
1933         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) ) ) return -1;
1934         
1935         release_lock;
1936
1937         
1938         ast_log(LOG_DEBUG, "misdn_hangup(%s)\n", ast->name);
1939         
1940         if (!p) {
1941                 chan_misdn_log(3, 0, "misdn_hangup called, without chan_list obj.\n");
1942                 release_unlock;
1943                 return 0 ;
1944         }
1945         
1946         bc=p->bc;
1947
1948         if (!bc) {
1949                 release_unlock;
1950                 ast_log(LOG_WARNING,"Hangup with private but no bc ?\n");
1951                 return 0;
1952         }
1953
1954         
1955         MISDN_ASTERISK_TECH_PVT(ast)=NULL;
1956         p->ast=NULL;
1957
1958         bc=p->bc;
1959         
1960         if (ast->_state == AST_STATE_RESERVED) {
1961                 /* between request and call */
1962                 MISDN_ASTERISK_TECH_PVT(ast)=NULL;
1963                 release_unlock;
1964                 
1965                 cl_dequeue_chan(&cl_te, p);
1966                 free(p);
1967                 
1968                 if (bc)
1969                         misdn_lib_release(bc);
1970                 
1971                 return 0;
1972         }
1973
1974         /*stop_bc_tones(p);*/
1975         
1976         release_unlock;
1977         
1978         {
1979                 const char *varcause=NULL;
1980                 bc->cause=ast->hangupcause?ast->hangupcause:16;
1981                 
1982                 if ( (varcause=pbx_builtin_getvar_helper(ast, "HANGUPCAUSE")) ||
1983                      (varcause=pbx_builtin_getvar_helper(ast, "PRI_CAUSE"))) {
1984                         int tmpcause=atoi(varcause);
1985                         bc->out_cause=tmpcause?tmpcause:16;
1986                 }
1987     
1988                 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));
1989                 chan_misdn_log(2, bc->port, " --> l3id:%x\n",p->l3id);
1990                 chan_misdn_log(1, bc->port, " --> cause:%d\n",bc->cause);
1991                 chan_misdn_log(1, bc->port, " --> out_cause:%d\n",bc->out_cause);
1992                 
1993                 switch (p->state) {
1994                 case MISDN_CALLING:
1995                         p->state=MISDN_CLEANING;
1996                         misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
1997                         break;
1998                 case MISDN_HOLDED:
1999                 case MISDN_DIALING:
2000                         start_bc_tones(p);
2001                         tone_indicate(p, TONE_HANGUP);
2002                         p->state=MISDN_CLEANING;
2003                 
2004                         if (bc->nt)
2005                                 misdn_lib_send_event( bc, EVENT_DISCONNECT);
2006                         else
2007                                 misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
2008       
2009                         break;
2010       
2011                 case MISDN_ALERTING:
2012                 case MISDN_PROGRESS:
2013                 case MISDN_PROCEEDING:
2014                         chan_misdn_log(2, bc->port, " --> * State Alerting\n");
2015
2016                         if (p->orginator != ORG_AST) 
2017                                 tone_indicate(p, TONE_HANGUP);
2018       
2019                         p->state=MISDN_CLEANING;
2020                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
2021                         break;
2022                 case MISDN_CONNECTED:
2023                         /*  Alerting or Disconect */
2024                         chan_misdn_log(2, bc->port, " --> * State Connected\n");
2025                         start_bc_tones(p);
2026                         tone_indicate(p, TONE_HANGUP);
2027                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
2028       
2029                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2030                         break;
2031                 case MISDN_DISCONNECTED:
2032                         chan_misdn_log(2, bc->port, " --> * State Disconnected\n");
2033                         misdn_lib_send_event( bc, EVENT_RELEASE);
2034                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2035                         break;
2036
2037                 case MISDN_CLEANING:
2038                         break;
2039       
2040                 case MISDN_HOLD_DISCONNECT:
2041                         /* need to send release here */
2042                         chan_misdn_log(2, bc->port, " --> state HOLD_DISC\n");
2043                         chan_misdn_log(1, bc->port, " --> cause %d\n",bc->cause);
2044                         chan_misdn_log(1, bc->port, " --> out_cause %d\n",bc->out_cause);
2045                         
2046                         bc->out_cause=-1;
2047                         misdn_lib_send_event(bc,EVENT_RELEASE);
2048                         break;
2049                 default:
2050                         /*  Alerting or Disconect */
2051
2052                         if (bc->nt) {
2053                                 bc->out_cause=-1;
2054                                 misdn_lib_send_event(bc, EVENT_RELEASE);
2055                         } else
2056                                 misdn_lib_send_event(bc, EVENT_DISCONNECT);
2057                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2058                 }
2059     
2060         }
2061         
2062
2063         chan_misdn_log(1, bc->port, "Channel: %s hanguped\n",ast->name);
2064         
2065         return 0;
2066 }
2067
2068
2069 struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame *frame)
2070 {
2071         struct ast_frame *f,*f2;
2072         if (tmp->trans)
2073                 f2=ast_translate(tmp->trans, frame,0);
2074         else {
2075                 chan_misdn_log(0, tmp->bc->port, "No T-Path found\n");
2076                 return NULL;
2077         }
2078         
2079         f = ast_dsp_process(tmp->ast, tmp->dsp, f2);
2080         if (f && (f->frametype == AST_FRAME_DTMF)) {
2081                 ast_log(LOG_DEBUG, "Detected inband DTMF digit: %c", f->subclass);
2082                 if (f->subclass == 'f' && tmp->faxdetect) {
2083                         /* Fax tone -- Handle and return NULL */
2084                         struct ast_channel *ast = tmp->ast;
2085                         if (!tmp->faxhandled) {
2086                                 tmp->faxhandled++;
2087                                 if (strcmp(ast->exten, "fax")) {
2088                                         if (ast_exists_extension(ast, ast_strlen_zero(ast->macrocontext)? ast->context : ast->macrocontext, "fax", 1, AST_CID_P(ast))) {
2089                                                 if (option_verbose > 2)
2090                                                         ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension\n", ast->name);
2091                                                 /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
2092                                                 pbx_builtin_setvar_helper(ast,"FAXEXTEN",ast->exten);
2093                                                 if (ast_async_goto(ast, ast->context, "fax", 1))
2094                                                         ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, ast->context);
2095                                         } else
2096                                                 ast_log(LOG_NOTICE, "Fax detected, but no fax extension ctx:%s exten:%s\n",ast->context, ast->exten);
2097                                 } else
2098                                         ast_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
2099                         } else
2100                                 ast_log(LOG_DEBUG, "Fax already handled\n");
2101                         
2102                 }  else if ( tmp->ast_dsp) {
2103                         chan_misdn_log(2, tmp->bc->port, " --> * SEND: DTMF (AST_DSP) :%c\n",f->subclass);
2104                         return f;
2105                 }
2106         }
2107
2108         frame->frametype = AST_FRAME_NULL;
2109         frame->subclass = 0;
2110         return frame;
2111 }
2112
2113
2114 static struct ast_frame  *misdn_read(struct ast_channel *ast)
2115 {
2116         struct chan_list *tmp;
2117         int len;
2118         
2119         if (!ast) return NULL;
2120         if (! (tmp=MISDN_ASTERISK_TECH_PVT(ast)) ) return NULL;
2121         if (!tmp->bc) return NULL;
2122
2123         len=read(tmp->pipe[0],tmp->ast_rd_buf,sizeof(tmp->ast_rd_buf));
2124
2125         if (len<=0) {
2126                 /* we hangup here, since our pipe is closed */
2127                 chan_misdn_log(2,tmp->bc->port,"misdn_read: Pipe closed, hanging up\n");
2128                 return NULL;
2129         }
2130
2131         tmp->frame.frametype  = AST_FRAME_VOICE;
2132         tmp->frame.subclass = AST_FORMAT_ALAW;
2133         tmp->frame.datalen = len;
2134         tmp->frame.samples = len ;
2135         tmp->frame.mallocd =0 ;
2136         tmp->frame.offset= 0 ;
2137         tmp->frame.src = NULL;
2138         tmp->frame.data = tmp->ast_rd_buf ;
2139         
2140         if (tmp->faxdetect || tmp->ast_dsp ) {
2141                 return process_ast_dsp(tmp, &tmp->frame);
2142         }
2143         
2144         return &tmp->frame;
2145 }
2146
2147
2148 static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
2149 {
2150         struct chan_list *ch;
2151         int i  = 0;
2152         
2153         if (!ast || ! (ch=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
2154         
2155         if (!ch->bc ) {
2156                 ast_log(LOG_WARNING, "private but no bc\n");
2157                 return -1;
2158         }
2159         
2160         if (ch->holded ) {
2161                 chan_misdn_log(5, ch->bc->port, "misdn_write: Returning because holded\n");
2162                 return 0;
2163         }
2164         
2165         if (ch->notxtone) {
2166                 chan_misdn_log(5, ch->bc->port, "misdn_write: Returning because notxone\n");
2167                 return 0;
2168         }
2169
2170
2171         if ( !frame->subclass) {
2172                 chan_misdn_log(4, ch->bc->port, "misdn_write: * prods us\n");
2173                 return 0;
2174         }
2175         
2176         if ( !(frame->subclass & prefformat)) {
2177                 
2178                 chan_misdn_log(-1, ch->bc->port, "Got Unsupported Frame with Format:%d\n", frame->subclass);
2179                 return 0;
2180         }
2181         
2182
2183         if ( !frame->samples ) {
2184                 chan_misdn_log(4, ch->bc->port, "misdn_write: zero write\n");
2185                 return 0;
2186         }
2187
2188         if ( ! ch->bc->addr ) {
2189                 chan_misdn_log(8, ch->bc->port, "misdn_write: no addr for bc dropping:%d\n", frame->samples);
2190                 return 0;
2191         }
2192         
2193 #if MISDN_DEBUG
2194         {
2195                 int i, max=5>frame->samples?frame->samples:5;
2196                 
2197                 printf("write2mISDN %p %d bytes: ", p, frame->samples);
2198                 
2199                 for (i=0; i<  max ; i++) printf("%2.2x ",((char*) frame->data)[i]);
2200                 printf ("\n");
2201         }
2202 #endif
2203
2204
2205         switch (ch->bc->bc_state) {
2206                 case BCHAN_ACTIVATED:
2207                 case BCHAN_BRIDGED:
2208                         break;
2209                 default:
2210                 if (!ch->dropped_frame_cnt)
2211                         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);
2212                 
2213                 ch->dropped_frame_cnt++;
2214                 if (ch->dropped_frame_cnt > 100) {
2215                         ch->dropped_frame_cnt=0;
2216                         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);
2217
2218                 }
2219
2220                 return 0;
2221         }
2222
2223         chan_misdn_log(9, ch->bc->port, "Sending :%d bytes 2 MISDN\n",frame->samples);
2224         
2225         if ( !ch->bc->nojitter && misdn_cap_is_speech(ch->bc->capability) ) {
2226                 /* Buffered Transmit (triggert by read from isdn side)*/
2227                 if (misdn_jb_fill(ch->jb,frame->data,frame->samples) < 0) {
2228                         if (ch->bc->active)
2229                                 cb_log(0,ch->bc->port,"Misdn Jitterbuffer Overflow.\n");
2230                 }
2231                 
2232         } else {
2233                 /*transmit without jitterbuffer*/
2234                 i=misdn_lib_tx2misdn_frm(ch->bc, frame->data, frame->samples);
2235         }
2236
2237         
2238         
2239         return 0;
2240 }
2241
2242
2243
2244
2245 static enum ast_bridge_result  misdn_bridge (struct ast_channel *c0,
2246                                       struct ast_channel *c1, int flags,
2247                                       struct ast_frame **fo,
2248                                       struct ast_channel **rc,
2249                                       int timeoutms)
2250
2251 {
2252         struct chan_list *ch1,*ch2;
2253         struct ast_channel *carr[2], *who;
2254         int to=-1;
2255         struct ast_frame *f;
2256   
2257         ch1=get_chan_by_ast(c0);
2258         ch2=get_chan_by_ast(c1);
2259
2260         carr[0]=c0;
2261         carr[1]=c1;
2262   
2263   
2264         if (ch1 && ch2 ) ;
2265         else
2266                 return -1;
2267   
2268
2269         int bridging;
2270         misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
2271         if (bridging) {
2272                 int ecwb, ec;
2273                 misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2274                 misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
2275                 if ( !ecwb && ec ) {
2276                         chan_misdn_log(2, ch1->bc->port, "Disabling Echo Cancellor when Bridged\n");
2277                         ch1->bc->ec_enable=0;
2278                         manager_ec_disable(ch1->bc);
2279                 }
2280                 misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2281                 misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
2282                 if ( !ecwb && ec) {
2283                         chan_misdn_log(2, ch2->bc->port, "Disabling Echo Cancellor when Bridged\n");
2284                         ch2->bc->ec_enable=0;
2285                         manager_ec_disable(ch2->bc); 
2286                 }
2287                 
2288                 /* trying to make a mISDN_dsp conference */
2289                 chan_misdn_log(1, ch1->bc->port, "I SEND: Making conference with Number:%d\n", ch1->bc->pid +1);
2290
2291                 misdn_lib_bridge(ch1->bc,ch2->bc);
2292         }
2293         
2294         if (option_verbose > 2) 
2295                 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
2296
2297         chan_misdn_log(1, ch1->bc->port, "* Making Native Bridge between %s and %s\n", ch1->bc->oad, ch2->bc->oad);
2298  
2299         if (! (flags&AST_BRIDGE_DTMF_CHANNEL_0) )
2300                 ch1->ignore_dtmf=1;
2301
2302         if (! (flags&AST_BRIDGE_DTMF_CHANNEL_1) )
2303                 ch2->ignore_dtmf=1;
2304
2305         while(1) {
2306                 to=-1;
2307                 who = ast_waitfor_n(carr, 2, &to);
2308
2309                 if (!who) {
2310                         ast_log(LOG_NOTICE,"misdn_bridge: empty read, breaking out\n");
2311                         break;
2312                 }
2313                 f = ast_read(who);
2314     
2315                 if (!f || f->frametype == AST_FRAME_CONTROL) {
2316                         /* got hangup .. */
2317                         *fo=f;
2318                         *rc=who;
2319       
2320                         break;
2321                 }
2322                 
2323                 if ( f->frametype == AST_FRAME_DTMF ) {
2324                         chan_misdn_log(1,0,"Read DTMF %d from %s\n",f->subclass, who->exten);
2325
2326                         *fo=f;
2327                         *rc=who;
2328                         break;
2329                 }
2330                 
2331                 
2332                 if (who == c0) {
2333                         ast_write(c1,f);
2334                 }
2335                 else {
2336                         ast_write(c0,f);
2337                 }
2338     
2339         }
2340         
2341         chan_misdn_log(1, ch1->bc->port, "I SEND: Splitting conference with Number:%d\n", ch1->bc->pid +1);
2342         
2343         misdn_lib_split_bridge(ch1->bc,ch2->bc);
2344         
2345         
2346         return AST_BRIDGE_COMPLETE;
2347 }
2348
2349 /** AST INDICATIONS END **/
2350
2351 static int tone_indicate( struct chan_list *cl, enum tone_e tone)
2352 {
2353         const struct tone_zone_sound *ts= NULL;
2354         struct ast_channel *ast=cl->ast;
2355         
2356         chan_misdn_log(3,cl->bc->port,"Tone Indicate:\n");
2357         
2358         if (!cl->ast) {
2359                 chan_misdn_log(-1,cl->bc->port,"Ast Ptr Not existing anymore.. we need to generate tones ourselves now (tbd)\n");
2360                 
2361                 misdn_lib_send_tone(cl->bc,tone);
2362                 return 0;
2363         }
2364         
2365         switch (tone) {
2366         case TONE_DIAL:
2367                 chan_misdn_log(3,cl->bc->port," --> Dial\n");
2368                 ts=ast_get_indication_tone(ast->zone,"dial");
2369                 misdn_lib_tone_generator_start(cl->bc);
2370                 break;
2371         case TONE_ALERTING:
2372                 chan_misdn_log(3,cl->bc->port," --> Ring\n");
2373                 ts=ast_get_indication_tone(ast->zone,"ring");
2374                 misdn_lib_tone_generator_start(cl->bc);
2375                 break;
2376         case TONE_FAR_ALERTING:
2377         /* VERY UGLY HACK, BECAUSE CHAN_SIP DOES NOT GENERATE TONES */
2378                 chan_misdn_log(3,cl->bc->port," --> Ring\n");
2379                 ts=ast_get_indication_tone(ast->zone,"ring");
2380                 misdn_lib_tone_generator_start(cl->bc);
2381                 misdn_lib_echo(cl->bc,1);
2382                 break;
2383         case TONE_BUSY:
2384                 chan_misdn_log(3,cl->bc->port," --> Busy\n");
2385                 ts=ast_get_indication_tone(ast->zone,"busy");
2386                 misdn_lib_tone_generator_start(cl->bc);
2387                 break;
2388         case TONE_FILE:
2389                 break;
2390         case TONE_NONE:
2391                 chan_misdn_log(3,cl->bc->port," --> None\n");
2392                 misdn_lib_tone_generator_stop(cl->bc);
2393                 ast_playtones_stop(ast);
2394                 break;
2395         default:
2396                 chan_misdn_log(0,cl->bc->port,"Don't know how to handle tone: %d\n",tone);
2397         }
2398         
2399         cl->ts=ts;      
2400         
2401         if (ts) ast_playtones_start(ast,0, ts->data, 0);
2402         
2403         return 0;
2404 }
2405
2406 static int start_bc_tones(struct chan_list* cl)
2407 {
2408         manager_bchannel_activate(cl->bc);
2409         misdn_lib_tone_generator_stop(cl->bc);
2410         cl->notxtone=0;
2411         cl->norxtone=0;
2412         return 0;
2413 }
2414
2415 static int stop_bc_tones(struct chan_list *cl)
2416 {
2417         if (cl->bc) {
2418                 manager_bchannel_deactivate(cl->bc);
2419         }
2420         cl->notxtone=1;
2421         cl->norxtone=1;
2422         
2423         return 0;
2424 }
2425
2426
2427 static struct chan_list *init_chan_list(int orig)
2428 {
2429         struct chan_list *cl=malloc(sizeof(struct chan_list));
2430         
2431         if (!cl) {
2432                 chan_misdn_log(-1, 0, "misdn_request: malloc failed!");
2433                 return NULL;
2434         }
2435         
2436         memset(cl,0,sizeof(struct chan_list));
2437
2438         cl->orginator=orig;
2439         
2440         return cl;
2441         
2442 }
2443
2444 static struct ast_channel *misdn_request(const char *type, int format, void *data, int *cause)
2445
2446 {
2447         struct ast_channel *tmp = NULL;
2448         char group[BUFFERSIZE+1]="";
2449         char buf[128];
2450         char buf2[128], *ext=NULL, *port_str;
2451         char *tokb=NULL, *p=NULL;
2452         int channel=0, port=0;
2453         struct misdn_bchannel *newbc = NULL;
2454         
2455         struct chan_list *cl=init_chan_list(ORG_AST);
2456         
2457         sprintf(buf,"%s/%s",misdn_type,(char*)data);
2458         ast_copy_string(buf2,data, 128);
2459         
2460         port_str=strtok_r(buf2,"/", &tokb);
2461
2462         ext=strtok_r(NULL,"/", &tokb);
2463
2464         if (port_str) {
2465                 if (port_str[0]=='g' && port_str[1]==':' ) {
2466                         /* We make a group call lets checkout which ports are in my group */
2467                         port_str += 2;
2468                         strncpy(group, port_str, BUFFERSIZE);
2469                         group[127] = 0;
2470                         chan_misdn_log(2, 0, " --> Group Call group: %s\n",group);
2471                 } 
2472                 else if ((p = strchr(port_str, ':'))) {
2473                         /* we have a preselected channel */
2474                         *p = 0;
2475                         channel = atoi(++p);
2476                         port = atoi(port_str);
2477                         chan_misdn_log(2, port, " --> Call on preselected Channel (%d).\n", channel);
2478                 }
2479                 else {
2480                         port = atoi(port_str);
2481                 }
2482                 
2483                 
2484         } else {
2485                 ast_log(LOG_WARNING, " --> ! IND : CALL dad:%s WITHOUT PORT/Group, check extension.conf\n",ext);
2486                 return NULL;
2487         }
2488
2489         if (!ast_strlen_zero(group)) {
2490         
2491                 char cfg_group[BUFFERSIZE+1];
2492                 struct robin_list *rr = NULL;
2493
2494                 if (misdn_cfg_is_group_method(group, METHOD_ROUND_ROBIN)) {
2495                         chan_misdn_log(4, port, " --> STARTING ROUND ROBIN...");
2496                         rr = get_robin_position(group);
2497                 }
2498                 
2499                 if (rr) {
2500                         int robin_channel = rr->channel;
2501                         int port_start;
2502                         int next_chan = 1;
2503
2504                         do {
2505                                 port_start = 0;
2506                                 for (port = misdn_cfg_get_next_port_spin(rr->port); port > 0 && port != port_start;
2507                                          port = misdn_cfg_get_next_port_spin(port)) {
2508
2509                                         if (!port_start)
2510                                                 port_start = port;
2511
2512                                         if (port >= port_start)
2513                                                 next_chan = 1;
2514                                         
2515                                         if (port < port_start && next_chan) {
2516                                                 if (++robin_channel >= MAX_BCHANS) {
2517                                                         robin_channel = 1;
2518                                                 }
2519                                                 next_chan = 0;
2520                                         }
2521
2522                                         misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2523                                         
2524                                         if (!strcasecmp(cfg_group, group)) {
2525                                                 int port_up;
2526                                                 int check;
2527                                                 misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
2528                                                 port_up = misdn_lib_port_up(port, check);
2529                                                 
2530                                                 if ( port_up )  {
2531                                                         newbc = misdn_lib_get_free_bc(port, robin_channel);
2532                                                         if (newbc) {
2533                                                                 chan_misdn_log(4, port, " Success! Found port:%d channel:%d\n", newbc->port, newbc->channel);
2534                                                                 if (port_up)
2535                                                                         chan_misdn_log(4, port, "ortup:%d\n",  port_up);
2536                                                                 rr->port = newbc->port;
2537                                                                 rr->channel = newbc->channel;
2538                                                                 break;
2539                                                         }
2540                                                 }
2541                                         }
2542                                 }
2543                         } while (!newbc && robin_channel != rr->channel);
2544                         
2545                         if (!newbc)
2546                                 chan_misdn_log(4, port, " Failed! No free channel in group %d!", group);
2547                 }
2548                 
2549                 else {          
2550                         for (port=misdn_cfg_get_next_port(0); port > 0;
2551                                  port=misdn_cfg_get_next_port(port)) {
2552                                 
2553                                 misdn_cfg_get( port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2554
2555                                 chan_misdn_log(3,port, "Group [%s] Port [%d]\n", group, port);
2556                                 if (!strcasecmp(cfg_group, group)) {
2557                                         int port_up;
2558                                         int check;
2559                                         misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
2560                                         port_up = misdn_lib_port_up(port, check);
2561                                         
2562                                         chan_misdn_log(4, port, "portup:%d\n", port_up);
2563                                         
2564                                         if ( port_up )  {
2565                                                 newbc = misdn_lib_get_free_bc(port, 0);
2566                                                 if (newbc)
2567                                                         break;
2568                                         }
2569                                 }
2570                         }
2571                 }
2572                 
2573         } else {
2574                 if (channel)
2575                         chan_misdn_log(1, port," --> preselected_channel: %d\n",channel);
2576                 newbc = misdn_lib_get_free_bc(port, channel);
2577         }
2578         
2579         if (!newbc) {
2580                 chan_misdn_log(-1, 0, " --> ! No free channel chan ext:%s even after Group Call\n",ext);
2581                 chan_misdn_log(-1, 0, " --> SEND: State Down\n");
2582                 return NULL;
2583         }
2584
2585         /* create ast_channel and link all the objects together */
2586         cl->bc=newbc;
2587         
2588         tmp = misdn_new(cl, AST_STATE_RESERVED, ext, NULL, format, port, channel);
2589         cl->ast=tmp;
2590         
2591         /* register chan in local list */
2592         cl_queue_chan(&cl_te, cl) ;
2593         
2594         /* fill in the config into the objects */
2595         read_config(cl, ORG_AST);
2596         
2597         
2598         return tmp;
2599 }
2600
2601
2602 static int misdn_send_text (struct ast_channel *chan, const char *text)
2603 {
2604         struct chan_list *tmp=chan->tech_pvt;
2605         
2606         if (tmp && tmp->bc) {
2607                 ast_copy_string(tmp->bc->display,text,sizeof(tmp->bc->display));
2608                 misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
2609         } else {
2610                 ast_log(LOG_WARNING, "No chan_list but send_text request?\n");
2611                 return -1;
2612         }
2613         
2614         return 0;
2615 }
2616
2617 static struct ast_channel_tech misdn_tech = {
2618         .type="mISDN",
2619         .description="Channel driver for mISDN Support (Bri/Pri)",
2620         .capabilities= AST_FORMAT_ALAW ,
2621         .requester=misdn_request,
2622         .send_digit=misdn_digit,
2623         .call=misdn_call,
2624         .bridge=misdn_bridge, 
2625         .hangup=misdn_hangup,
2626         .answer=misdn_answer,
2627         .read=misdn_read,
2628         .write=misdn_write,
2629         .indicate=misdn_indication,
2630         .fixup=misdn_fixup,
2631         .send_text=misdn_send_text,
2632         .properties=0
2633 };
2634
2635 static struct ast_channel_tech misdn_tech_wo_bridge = {
2636         .type="mISDN",
2637         .description="Channel driver for mISDN Support (Bri/Pri)",
2638         .capabilities=AST_FORMAT_ALAW ,
2639         .requester=misdn_request,
2640         .send_digit=misdn_digit,
2641         .call=misdn_call,
2642         .hangup=misdn_hangup,
2643         .answer=misdn_answer,
2644         .read=misdn_read,
2645         .write=misdn_write,
2646         .indicate=misdn_indication,
2647         .fixup=misdn_fixup,
2648         .send_text=misdn_send_text,
2649         .properties=0
2650 };
2651
2652
2653 static unsigned long glob_channel=0;
2654
2655 static void update_name(struct ast_channel *tmp, int port, int c) 
2656 {
2657         if (c<=0) {
2658                         c=glob_channel++;
2659                         ast_string_field_build(tmp, name, "%s/%d-u%d",
2660                                  misdn_type, port, c);
2661         } else {
2662                          ast_string_field_build(tmp, name, "%s/%d-%d",
2663                                  misdn_type, port, c);
2664         }
2665
2666         chan_misdn_log(3,port," --> updating channel name to [%s]\n",tmp->name);
2667         
2668 }
2669
2670 static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char *exten, char *callerid, int format, int port, int c)
2671 {
2672         struct ast_channel *tmp;
2673         
2674         tmp = ast_channel_alloc(1);
2675         
2676         if (tmp) {
2677                 chan_misdn_log(2, 0, " --> * NEW CHANNEL dad:%s oad:%s\n",exten,callerid);
2678                 
2679                 update_name(tmp,port,c);
2680         
2681                 tmp->nativeformats = prefformat;
2682
2683                 tmp->readformat = format;
2684                 tmp->rawreadformat = format;
2685                 tmp->writeformat = format;
2686                 tmp->rawwriteformat = format;
2687     
2688                 tmp->tech_pvt = chlist;
2689                 
2690                 int bridging;
2691                 misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
2692                 if (bridging)
2693                         tmp->tech = &misdn_tech;
2694                 else
2695                         tmp->tech = &misdn_tech_wo_bridge;
2696                 
2697                 tmp->writeformat = format;
2698                 tmp->readformat = format;
2699                 tmp->priority=1;
2700                 
2701                 if (exten) 
2702                         ast_copy_string(tmp->exten, exten,  sizeof(tmp->exten));
2703                 else
2704                         chan_misdn_log(1,0,"misdn_new: no exten given.\n");
2705                 
2706                 if (callerid) {
2707                         char *cid_name, *cid_num;
2708       
2709                         ast_callerid_parse(callerid, &cid_name, &cid_num);
2710                         ast_set_callerid(tmp, cid_num,cid_name,cid_num);
2711                 } else {
2712                         ast_set_callerid(tmp, NULL,NULL,NULL);
2713                 }
2714
2715                 {
2716                         if (pipe(chlist->pipe)<0)
2717                                 perror("Pipe failed\n");
2718                         
2719                         tmp->fds[0]=chlist->pipe[0];
2720                         
2721                 }
2722                 
2723                 ast_setstate(tmp, state);
2724                 if (state == AST_STATE_RING)
2725                         tmp->rings = 1;
2726                 else
2727                         tmp->rings = 0;
2728                 
2729                 
2730         } else {
2731                 chan_misdn_log(-1,0,"Unable to allocate channel structure\n");
2732         }
2733         
2734         return tmp;
2735 }
2736
2737 static struct chan_list *find_chan_by_l3id(struct chan_list *list, unsigned long l3id)
2738 {
2739         struct chan_list *help=list;
2740         for (;help; help=help->next) {
2741                 if (help->l3id == l3id ) return help;
2742         }
2743   
2744         chan_misdn_log(6, list? (list->bc? list->bc->port : 0) : 0, "$$$ find_chan: No channel found with l3id:%x\n",l3id);
2745   
2746         return NULL;
2747 }
2748
2749 static struct chan_list *find_chan_by_bc(struct chan_list *list, struct misdn_bchannel *bc)
2750 {
2751         struct chan_list *help=list;
2752         for (;help; help=help->next) {
2753                 if (help->bc == bc) return help;
2754         }
2755   
2756         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
2757   
2758         return NULL;
2759 }
2760
2761 static struct chan_list *find_chan_by_pid(struct chan_list *list, int pid)
2762 {
2763         struct chan_list *help=list;
2764         for (;help; help=help->next) {
2765                 if (help->bc->pid == pid) return help;
2766         }
2767   
2768         chan_misdn_log(6, 0, "$$$ find_chan: No channel found for pid:%d\n",pid);
2769   
2770         return NULL;
2771 }
2772
2773 static struct chan_list *find_holded(struct chan_list *list, struct misdn_bchannel *bc)
2774 {
2775         struct chan_list *help=list;
2776         
2777         chan_misdn_log(6, bc->port, "$$$ find_holded: channel:%d oad:%s dad:%s\n",bc->channel, bc->oad,bc->dad);
2778         for (;help; help=help->next) {
2779                 chan_misdn_log(4, bc->port, "$$$ find_holded: --> holded:%d channel:%d\n",help->bc->holded, help->bc->channel);
2780                 if (help->bc->port == bc->port
2781                     && help->bc->holded ) return help;
2782         }
2783         
2784         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
2785   
2786         return NULL;
2787 }
2788
2789 static void cl_queue_chan(struct chan_list **list, struct chan_list *chan)
2790 {
2791         chan_misdn_log(4, chan->bc? chan->bc->port : 0, "* Queuing chan %p\n",chan);
2792   
2793         ast_mutex_lock(&cl_te_lock);
2794         if (!*list) {
2795                 *list = chan;
2796         } else {
2797                 struct chan_list *help=*list;
2798                 for (;help->next; help=help->next); 
2799                 help->next=chan;
2800         }
2801         chan->next=NULL;
2802         ast_mutex_unlock(&cl_te_lock);
2803 }
2804
2805 static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan) 
2806 {
2807         if (chan->dsp) 
2808                 ast_dsp_free(chan->dsp);
2809         if (chan->trans)
2810                 ast_translator_free_path(chan->trans);
2811
2812         
2813
2814         ast_mutex_lock(&cl_te_lock);
2815         if (!*list) {
2816                 ast_mutex_unlock(&cl_te_lock);
2817                 return;
2818         }
2819   
2820         if (*list == chan) {
2821                 *list=(*list)->next;
2822                 ast_mutex_unlock(&cl_te_lock);
2823                 return ;
2824         }
2825   
2826         {
2827                 struct chan_list *help=*list;
2828                 for (;help->next; help=help->next) {
2829                         if (help->next == chan) {
2830                                 help->next=help->next->next;
2831                                 ast_mutex_unlock(&cl_te_lock);
2832                                 return;
2833                         }
2834                 }
2835         }
2836         
2837         ast_mutex_unlock(&cl_te_lock);
2838 }
2839
2840 /** Channel Queue End **/
2841
2842
2843
2844 /** Isdn asks us to release channel, pendant to misdn_hangup **/
2845 static void release_chan(struct misdn_bchannel *bc) {
2846         struct ast_channel *ast=NULL;
2847         
2848         {
2849                 struct chan_list *ch=find_chan_by_bc(cl_te, bc);
2850                 if (!ch) ch=find_chan_by_l3id (cl_te, bc->l3_id);
2851                 if (!ch)  {
2852                         chan_misdn_log(0, bc->port, "release_chan: Ch not found!\n");
2853                         return;
2854                 }
2855                 
2856                 release_lock;
2857                 if (ch->ast) {
2858                         ast=ch->ast;
2859                 } 
2860                 release_unlock;
2861                 
2862                 chan_misdn_log(1, bc->port, "release_chan: bc with l3id: %x\n",bc->l3_id);
2863 #if 0
2864                 if (ch->dummy) {
2865                         ast_hangup(ast);
2866                         ch->ast=NULL;
2867                         ast=NULL;
2868                 }
2869 #endif
2870                 
2871                 /*releaseing jitterbuffer*/
2872                 if (ch->jb ) {
2873                         misdn_jb_destroy(ch->jb);
2874                         ch->jb=NULL;
2875                 } else {
2876                         if (!bc->nojitter)
2877                                 chan_misdn_log(5,bc->port,"Jitterbuffer already destroyed.\n");
2878                 }
2879
2880
2881                 if (ch->orginator == ORG_AST) {
2882                         misdn_out_calls[bc->port]--;
2883                 } else {
2884                         misdn_in_calls[bc->port]--;
2885                 }
2886                 
2887                 if (ch) {
2888                         
2889                         close(ch->pipe[0]);
2890                         close(ch->pipe[1]);
2891                         
2892                         if (ast && MISDN_ASTERISK_TECH_PVT(ast)) {
2893                                 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));
2894                                 chan_misdn_log(3, bc->port, " --> * State Down\n");
2895                                 /* copy cause */
2896                                 send_cause2ast(ast,bc);
2897                                 
2898                                 MISDN_ASTERISK_TECH_PVT(ast)=NULL;
2899                                 
2900       
2901                                 if (ast->_state != AST_STATE_RESERVED) {
2902                                         chan_misdn_log(3, bc->port, " --> Setting AST State to down\n");
2903                                         ast_setstate(ast, AST_STATE_DOWN);
2904                                 }
2905                                 
2906                                 switch(ch->state) {
2907                                 case MISDN_EXTCANTMATCH:
2908                                 case MISDN_WAITING4DIGS:
2909                                 {
2910                                         chan_misdn_log(3,  bc->port, " --> * State Wait4dig | ExtCantMatch\n");
2911                                         ast_hangup(ast);
2912                                 }
2913                                 break;
2914                                 
2915                                 case MISDN_DIALING:
2916                                 case MISDN_CALLING_ACKNOWLEDGE:
2917                                 case MISDN_PROGRESS:
2918                                         chan_misdn_log(2,  bc->port, "* --> In State Dialin\n");
2919                                         chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2920                                         
2921
2922                                         ast_queue_hangup(ast);
2923                                         break;
2924                                 case MISDN_CALLING:
2925                                         
2926                                         chan_misdn_log(2,  bc->port, "* --> In State Callin\n");
2927                                         
2928                                         if (!bc->nt) {
2929                                                 chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2930                                                 ast_queue_hangup(ast);
2931                                         } else {
2932                                                 chan_misdn_log(2,  bc->port, "* --> Hangup\n");
2933                                                 ast_queue_hangup(ast);
2934                                         }
2935                                         break;
2936                                         
2937                                 case MISDN_CLEANING:
2938                                         /* this state comes out of ast so we mustnt call a ast function ! */
2939                                         chan_misdn_log(2,  bc->port, "* --> In StateCleaning\n");
2940                                         break;
2941                                 case MISDN_HOLD_DISCONNECT:
2942                                         chan_misdn_log(2,  bc->port, "* --> In HOLD_DISC\n");
2943                                         break;
2944                                 default:
2945                                         chan_misdn_log(2,  bc->port, "* --> In State Default\n");
2946                                         chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2947                                         if (ast) {
2948                                                 ast_queue_hangup(ast);
2949                                         } else {
2950                                                 chan_misdn_log (0,  bc->port, "!! Not really queued!\n");
2951                                         }
2952                                 }
2953                         }
2954                         cl_dequeue_chan(&cl_te, ch);
2955                         
2956                         free(ch);
2957                 } else {
2958                         /* chan is already cleaned, so exiting  */
2959                 }
2960         }
2961 }
2962 /*** release end **/
2963
2964 static void misdn_transfer_bc(struct chan_list *tmp_ch, struct chan_list *holded_chan)
2965 {
2966         chan_misdn_log(4,0,"TRANSFERING %s to %s\n",holded_chan->ast->name, tmp_ch->ast->name);
2967         
2968         tmp_ch->state=MISDN_HOLD_DISCONNECT;
2969   
2970         ast_moh_stop(AST_BRIDGED_P(holded_chan->ast));
2971
2972         holded_chan->state=MISDN_CONNECTED;
2973         holded_chan->holded=0;
2974         misdn_lib_transfer(holded_chan->bc?holded_chan->bc:holded_chan->holded_bc);
2975         ast_channel_masquerade(holded_chan->ast, AST_BRIDGED_P(tmp_ch->ast));
2976 }
2977
2978
2979 static void do_immediate_setup(struct misdn_bchannel *bc,struct chan_list *ch , struct ast_channel *ast)
2980 {
2981         char predial[256]="";
2982         char *p = predial;
2983   
2984         struct ast_frame fr;
2985   
2986         strncpy(predial, ast->exten, sizeof(predial) -1 );
2987   
2988         ch->state=MISDN_DIALING;
2989
2990         if (bc->nt) {
2991                 int ret; 
2992                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
2993         } else {
2994                 int ret;
2995                 if ( misdn_lib_is_ptp(bc->port)) {
2996                         ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
2997                 } else {
2998                         ret = misdn_lib_send_event(bc, EVENT_PROCEEDING );
2999                 }
3000         }
3001
3002         if ( !bc->nt && (ch->orginator==ORG_MISDN) && !ch->incoming_early_audio ) 
3003                 chan_misdn_log(1,bc->port, " --> incoming_early_audio off\n");
3004          else 
3005                 tone_indicate(ch,TONE_DIAL);  
3006   
3007         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));
3008   
3009         strncpy(ast->exten,"s", 2);
3010   
3011         if (ast_pbx_start(ast)<0) {
3012                 ast=NULL;
3013                 tone_indicate(ch,TONE_BUSY);
3014
3015                 if (bc->nt)
3016                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3017                 else
3018                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
3019         }
3020   
3021   
3022         while (!ast_strlen_zero(p) ) {
3023                 fr.frametype = AST_FRAME_DTMF;
3024                 fr.subclass = *p ;
3025                 fr.src=NULL;
3026                 fr.data = NULL ;
3027                 fr.datalen = 0;
3028                 fr.samples = 0 ;
3029                 fr.mallocd =0 ;
3030                 fr.offset= 0 ;
3031
3032                 if (ch->ast && MISDN_ASTERISK_PVT(ch->ast) && MISDN_ASTERISK_TECH_PVT(ch->ast)) {
3033                         ast_queue_frame(ch->ast, &fr);
3034                 }
3035                 p++;
3036         }
3037 }
3038
3039
3040
3041 static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc) {
3042         
3043         ast->hangupcause=bc->cause;
3044         
3045         switch ( bc->cause) {
3046                 
3047         case 1: /** Congestion Cases **/
3048         case 2:
3049         case 3:
3050         case 4:
3051         case 22:
3052         case 27:
3053                 /*
3054                  * Not Queueing the Congestion anymore, since we want to hear
3055                  * the inband message
3056                  *
3057                 chan_misdn_log(1, bc?bc->port:0, " --> * SEND: Queue Congestion pid:%d\n", bc?bc->pid:-1);
3058                 
3059                 ast_queue_control(ast, AST_CONTROL_CONGESTION);
3060                 */
3061                 break;
3062                 
3063         case 21:
3064         case 17: /* user busy */
3065                 chan_misdn_log(1,  bc?bc->port:0, " --> * SEND: Queue Busy pid:%d\n", bc?bc->pid:-1);
3066                 
3067                 ast_queue_control(ast, AST_CONTROL_BUSY);
3068                 
3069                 break;
3070         }
3071 }
3072
3073
3074
3075
3076 void import_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
3077 {
3078         char *tmp;
3079         tmp=pbx_builtin_getvar_helper(chan,"MISDN_PID");
3080         if (tmp) {
3081                 ch->other_pid=atoi(tmp);
3082                 chan_misdn_log(1,bc->port,"IMPORT_PID: importing pid:%s\n",tmp);
3083                 if (ch->other_pid >0) {
3084                         ch->other_ch=find_chan_by_pid(cl_te,ch->other_pid);
3085                         if (ch->other_ch) ch->other_ch->other_ch=ch;
3086                 }
3087         }
3088 }
3089
3090 void export_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
3091 {
3092         char tmp[32];
3093         chan_misdn_log(1,bc->port,"EXPORT_PID: pid:%d\n",bc->pid);
3094         sprintf(tmp,"%d",bc->pid);
3095         pbx_builtin_setvar_helper(chan,"_MISDN_PID",tmp);
3096 }
3097
3098 int add_in_calls(int port)
3099 {
3100         int max_in_calls;
3101         
3102         misdn_cfg_get( port, MISDN_CFG_MAX_IN, &max_in_calls, sizeof(max_in_calls));
3103
3104         misdn_in_calls[port]++;
3105
3106         if (max_in_calls >=0 && max_in_calls<misdn_in_calls[port]) {
3107                 ast_log(LOG_NOTICE,"Marking Incoming Call on port[%d]\n",port);
3108                 return misdn_in_calls[port]-max_in_calls;
3109         }
3110         
3111         return 0;
3112 }
3113
3114 int add_out_calls(int port)
3115 {
3116         int max_out_calls;
3117         
3118         misdn_cfg_get( port, MISDN_CFG_MAX_OUT, &max_out_calls, sizeof(max_out_calls));
3119         
3120
3121         if (max_out_calls >=0 && max_out_calls<=misdn_out_calls[port]) {
3122                 ast_log(LOG_NOTICE,"Rejecting Outgoing Call on port[%d]\n",port);
3123                 return (misdn_out_calls[port]+1)-max_out_calls;
3124         }
3125
3126         misdn_out_calls[port]++;
3127         
3128         return 0;
3129 }
3130
3131
3132
3133 /************************************************************/
3134 /*  Receive Events from isdn_lib  here                     */
3135 /************************************************************/
3136 static enum event_response_e
3137 cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
3138 {
3139         struct chan_list *ch=find_chan_by_bc(cl_te, bc);
3140         
3141         if (!ch)
3142                 ch=find_chan_by_l3id(cl_te, bc->l3_id);
3143         
3144         if (event != EVENT_BCHAN_DATA && event != EVENT_TONE_GENERATE) { /*  Debug Only Non-Bchan */
3145                 chan_misdn_log(1, bc->port, "I IND :%s oad:%s dad:%s\n", manager_isdn_get_info(event), bc->oad, bc->dad);
3146                 misdn_lib_log_ies(bc);
3147                 chan_misdn_log(2,bc->port," --> bc_state:%s\n",bc_state2str(bc->bc_state));
3148         }
3149         
3150         if (event != EVENT_SETUP) {
3151                 if (!ch) {
3152                         if (event != EVENT_CLEANUP )
3153                                 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);
3154                         return -1;
3155                 }
3156         }
3157         
3158         if (ch ) {
3159                 switch (event) {
3160                 case EVENT_DISCONNECT:
3161                 case EVENT_RELEASE:
3162                 case EVENT_RELEASE_COMPLETE:
3163                 case EVENT_CLEANUP:
3164                 case EVENT_TIMEOUT:
3165                         chan_misdn_log(3,bc->port,"ast_hangup already called, so we have no ast ptr anymore in event(%s)\n",manager_isdn_get_info(event));
3166                         break;
3167                 default:
3168                         if ( !ch->ast  || !MISDN_ASTERISK_PVT(ch->ast) || !MISDN_ASTERISK_TECH_PVT(ch->ast)) {
3169                                 if (event!=EVENT_BCHAN_DATA)
3170                                         ast_log(LOG_WARNING, "No Ast or No private Pointer in Event (%d:%s)\n", event, manager_isdn_get_info(event));
3171                                 return -1;
3172                         }
3173                 }
3174         }
3175         
3176         
3177         switch (event) {
3178                 
3179         case EVENT_BCHAN_ACTIVATED:
3180                 break;
3181                 
3182         case EVENT_NEW_CHANNEL:
3183                 update_name(ch->ast,bc->port,bc->channel);
3184                 break;
3185                 
3186         case EVENT_NEW_L3ID:
3187                 ch->l3id=bc->l3_id;
3188                 ch->addr=bc->addr;
3189
3190                 if (bc->nt && ch->state == MISDN_PRECONNECTED ) {
3191                         /* OK we've got the very new l3id so we can answer
3192                            now */
3193                         start_bc_tones(ch);
3194                 
3195                         ch->state = MISDN_CONNECTED;
3196                         ast_queue_control(ch->ast, AST_CONTROL_ANSWER);
3197
3198                 }
3199                 break;
3200
3201         case EVENT_NEW_BC:
3202                 if (bc)
3203                         ch->bc=bc;
3204                 break;
3205                 
3206         case EVENT_DTMF_TONE:
3207         {
3208                 /*  sending INFOS as DTMF-Frames :) */
3209                 struct ast_frame fr;
3210                 memset(&fr, 0 , sizeof(fr));
3211                 fr.frametype = AST_FRAME_DTMF;
3212                 fr.subclass = bc->dtmf ;
3213                 fr.src=NULL;
3214                 fr.data = NULL ;
3215                 fr.datalen = 0;
3216                 fr.samples = 0 ;
3217                 fr.mallocd =0 ;
3218                 fr.offset= 0 ;
3219                 
3220                 if (!ch->ignore_dtmf) {
3221                         chan_misdn_log(2, bc->port, " --> DTMF:%c\n", bc->dtmf);
3222                         ast_queue_frame(ch->ast, &fr);
3223                 } else {
3224                         chan_misdn_log(2, bc->port, " --> Ingoring DTMF:%c due to bridge flags\n", bc->dtmf);
3225                 }
3226         }
3227         break;
3228         case EVENT_STATUS:
3229                 break;
3230     
3231         case EVENT_INFORMATION:
3232         {
3233                 int stop_tone;
3234                 misdn_cfg_get( 0, MISDN_GEN_STOP_TONE, &stop_tone, sizeof(int));
3235                 if ( stop_tone ) {
3236                         tone_indicate(ch,TONE_NONE);
3237                 }
3238                 
3239                 if (ch->state == MISDN_WAITING4DIGS ) {
3240                         /*  Ok, incomplete Setup, waiting till extension exists */
3241                         {
3242                                 int l = sizeof(bc->dad);
3243                                 strncat(bc->dad,bc->info_dad, l);
3244                                 bc->dad[l-1] = 0;
3245                         }
3246                         
3247                         
3248                         {
3249                                 int l = sizeof(ch->ast->exten);
3250                                 strncpy(ch->ast->exten, bc->dad, l);
3251                                 ch->ast->exten[l-1] = 0;
3252                         }
3253 /*                      chan_misdn_log(5, bc->port, "Can Match Extension: dad:%s oad:%s\n",bc->dad,bc->oad);*/
3254                         
3255                         /* Check for Pickup Request first */
3256                         if (!strcmp(ch->ast->exten, ast_pickup_ext())) {
3257                                 int ret;/** Sending SETUP_ACK**/
3258                                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3259                                 if (ast_pickup_call(ch->ast)) {
3260                                         ast_hangup(ch->ast);
3261                                 } else {
3262                                         struct ast_channel *chan=ch->ast;
3263                                         ch->state = MISDN_CALLING_ACKNOWLEDGE;
3264                                         ch->ast=NULL;
3265                                         ast_setstate(chan, AST_STATE_DOWN);
3266                                         ast_hangup(chan);
3267                                         break;
3268                                 }
3269                         }
3270                         
3271                         if(!ast_canmatch_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3272
3273                                 chan_misdn_log(-1, bc->port, "Extension can never match, so disconnecting\n");
3274                                 tone_indicate(ch,TONE_BUSY);
3275                                 ch->state=MISDN_EXTCANTMATCH;
3276                                 bc->out_cause=1;
3277
3278                                 if (bc->nt)
3279                                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3280                                 else
3281                                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
3282                                 break;
3283                         }
3284                         if (ast_exists_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3285                                 ch->state=MISDN_DIALING;
3286           
3287                                 tone_indicate(ch,TONE_NONE);
3288 /*                              chan_misdn_log(1, bc->port, " --> * Starting Ast ctx:%s\n", ch->context);*/
3289                                 if (ast_pbx_start(ch->ast)<0) {
3290
3291                                         chan_misdn_log(-1, bc->port, "ast_pbx_start returned < 0 in INFO\n");
3292                                         tone_indicate(ch,TONE_BUSY);
3293
3294                                         if (bc->nt)
3295                                                 misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3296                                         else
3297                                                 misdn_lib_send_event(bc, EVENT_DISCONNECT );
3298                                 }
3299                         }
3300         
3301                 } else {
3302                         /*  sending INFOS as DTMF-Frames :) */
3303                         struct ast_frame fr;
3304                         fr.frametype = AST_FRAME_DTMF;
3305                         fr.subclass = bc->info_dad[0] ;
3306                         fr.src=NULL;
3307                         fr.data = NULL ;
3308                         fr.datalen = 0;
3309                         fr.samples = 0 ;
3310                         fr.mallocd =0 ;
3311                         fr.offset= 0 ;
3312
3313                         
3314                         int digits;
3315                         misdn_cfg_get( 0, MISDN_GEN_APPEND_DIGITS2EXTEN, &digits, sizeof(int));
3316                         if (ch->state != MISDN_CONNECTED ) {
3317                                 if (digits) {
3318                                         int l = sizeof(bc->dad);
3319                                         strncat(bc->dad,bc->info_dad, l);
3320                                         bc->dad[l-1] = 0;
3321                                         l = sizeof(ch->ast->exten);
3322                                         strncpy(ch->ast->exten, bc->dad, l);
3323                                         ch->ast->exten[l-1] = 0;
3324
3325                                         ast_cdr_update(ch->ast);
3326                                 }
3327                                 
3328                                 ast_queue_frame(ch->ast, &fr);
3329                         }
3330                 }
3331         }
3332         break;
3333         case EVENT_SETUP:
3334         {
3335                 struct chan_list *ch=find_chan_by_bc(cl_te, bc);
3336                 if (ch && ch->state != MISDN_NOTHING ) {
3337                         chan_misdn_log(1, bc->port, " --> Ignoring Call we have already one\n");
3338                         return RESPONSE_IGNORE_SETUP_WITHOUT_CLOSE; /*  Ignore MSNs which are not in our List */
3339                 }
3340         }
3341         
3342
3343         int msn_valid = misdn_cfg_is_msn_valid(bc->port, bc->dad);
3344         if (!bc->nt && ! msn_valid) {
3345                 chan_misdn_log(1, bc->port, " --> Ignoring Call, its not in our MSN List\n");
3346                 return RESPONSE_IGNORE_SETUP; /*  Ignore MSNs which are not in our List */
3347         }
3348
3349         
3350         print_bearer(bc);
3351     
3352         {
3353                 struct chan_list *ch=init_chan_list(ORG_MISDN);
3354                 struct ast_channel *chan;
3355                 int exceed;
3356
3357                 if (!ch) { chan_misdn_log(-1, bc->port, "cb_events: malloc for chan_list failed!\n"); return 0;}
3358                 
3359                 ch->bc = bc;
3360                 ch->l3id=bc->l3_id;
3361                 ch->addr=bc->addr;
3362                 ch->orginator = ORG_MISDN;
3363
3364                 chan=misdn_new(ch, AST_STATE_RESERVED,bc->dad, bc->oad, AST_FORMAT_ALAW, bc->port, bc->channel);
3365                 ch->ast = chan;
3366
3367                 if ((exceed=add_in_calls(bc->port))) {
3368                         char tmp[16];
3369                         sprintf(tmp,"%d",exceed);
3370                         pbx_builtin_setvar_helper(chan,"MAX_OVERFLOW",tmp);
3371                 }
3372
3373                 read_config(ch, ORG_MISDN);
3374                 
3375                 export_ch(chan, bc, ch);
3376
3377                 ch->ast->rings=1;
3378                 ast_setstate(ch->ast, AST_STATE_RINGING);
3379
3380                 if ( bc->pres ) {
3381                         chan->cid.cid_pres=AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
3382                 }  else {
3383                         chan->cid.cid_pres=AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
3384                 }
3385       
3386                 pbx_builtin_setvar_helper(chan, "TRANSFERCAPABILITY", ast_transfercapability2str(bc->capability));
3387                 chan->transfercapability=bc->capability;
3388                 
3389                 switch (bc->capability) {
3390                 case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
3391                         pbx_builtin_setvar_helper(chan,"CALLTYPE","DIGITAL");
3392                         break;
3393                 default:
3394                         pbx_builtin_setvar_helper(chan,"CALLTYPE","SPEECH");
3395                 }
3396
3397                 /** queue new chan **/
3398                 cl_queue_chan(&cl_te, ch) ;
3399
3400
3401                 if (!strstr(ch->allowed_bearers,"all")) {
3402                         int i;
3403                         for (i=0; i< sizeof(allowed_bearers_array)/sizeof(struct allowed_bearers); i++) {
3404                                 if (allowed_bearers_array[i].cap == bc->capability) {
3405                                         if (  !strstr( ch->allowed_bearers, allowed_bearers_array[i].name)) {
3406                                                 chan_misdn_log(0,bc->port,"Bearer Not allowed\b");
3407                                                 bc->out_cause=88;
3408                                                 
3409                                                 ch->state=MISDN_EXTCANTMATCH;
3410                                                 misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3411                                                 return RESPONSE_OK;
3412                                         }
3413                                 }
3414                                 
3415                         }
3416                 }
3417                 
3418                 /* Check for Pickup Request first */
3419                 if (!strcmp(chan->exten, ast_pickup_ext())) {
3420                         int ret;/** Sending SETUP_ACK**/
3421                         ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3422                         if (ast_pickup_call(chan)) {
3423                                 ast_hangup(chan);
3424                         } else {
3425                                 ch->state = MISDN_CALLING_ACKNOWLEDGE;
3426                                 ch->ast=NULL;
3427                                 ast_setstate(chan, AST_STATE_DOWN);
3428                                 ast_hangup(chan);
3429                                 break;
3430                         }
3431                 }
3432                 
3433                 /*
3434                   added support for s extension hope it will help those poor cretains
3435                   which haven't overlap dial.
3436                 */
3437                 {
3438                         int ai;
3439                         misdn_cfg_get( bc->port, MISDN_CFG_ALWAYS_IMMEDIATE, &ai, sizeof(ai));
3440                         if ( ai ) {
3441                                 do_immediate_setup(bc, ch , chan);
3442                                 break;
3443                         }
3444                         
3445                         
3446                         
3447                 }
3448
3449                 /* check if we should jump into s when we have no dad */
3450                 {
3451                         int im;
3452                         misdn_cfg_get( bc->port, MISDN_CFG_IMMEDIATE, &im, sizeof(im));
3453                         if ( im && ast_strlen_zero(bc->dad) ) {
3454                                 do_immediate_setup(bc, ch , chan);
3455                                 break;
3456                         }
3457                 }
3458
3459                 
3460                         chan_misdn_log(5,bc->port,"CONTEXT:%s\n",ch->context);
3461                         if(!ast_canmatch_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3462                         
3463                         chan_misdn_log(-1, bc->port, "Extension can never match, so disconnecting\n");
3464
3465                         tone_indicate(ch,TONE_BUSY);
3466                         ch->state=MISDN_EXTCANTMATCH;
3467                         bc->out_cause=1;
3468
3469                         if (bc->nt)
3470                                 misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3471                         else
3472                                 misdn_lib_send_event(bc, EVENT_RELEASE );
3473                                 
3474                         break;
3475                 }
3476                 
3477                 if (ast_exists_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3478                         ch->state=MISDN_DIALING;
3479                         
3480                         if (bc->nt || (bc->need_more_infos && misdn_lib_is_ptp(bc->port)) ) {
3481                                 int ret; 
3482                                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3483                         } else {
3484                                 int ret;
3485                                 ret= misdn_lib_send_event(bc, EVENT_PROCEEDING );
3486                         }
3487         
3488                         if (ast_pbx_start(chan)<0) {
3489
3490                                 chan_misdn_log(-1, bc->port, "ast_pbx_start returned <0 in SETUP\n");
3491                                 chan=NULL;
3492                                 tone_indicate(ch,TONE_BUSY);
3493
3494                                 if (bc->nt)
3495                                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3496                                 else
3497                                         misdn_lib_send_event(bc, EVENT_RELEASE);
3498                         }
3499                 } else {
3500
3501                         if (bc->sending_complete) {
3502                                 ch->state=MISDN_EXTCANTMATCH;
3503                                 bc->out_cause=1;
3504
3505                                 if (bc->nt)  {
3506                                         chan_misdn_log(0,bc->port," --> sending_complete so we never match ..\n");
3507                                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE);
3508                                 } else {
3509                                         chan_misdn_log(0,bc->port," --> sending_complete so we never match ..\n");
3510                                         misdn_lib_send_event(bc, EVENT_RELEASE);
3511                                 }
3512
3513                         } else {
3514                                 
3515                                 int ret= misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3516                                 if (ret == -ENOCHAN) {
3517                                         ast_log(LOG_WARNING,"Channel was catched, before we could Acknowledge\n");
3518                                         misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
3519                                 }
3520                                 /*  send tone to phone :) */
3521                                 
3522                                 /** ADD IGNOREPAT **/
3523                                 
3524                                 int stop_tone;
3525                                 misdn_cfg_get( 0, MISDN_GEN_STOP_TONE, &stop_tone, sizeof(int));
3526                                 if ( (!ast_strlen_zero(bc->dad)) && stop_tone ) 
3527                                         tone_indicate(ch,TONE_NONE);
3528                                 else
3529                                         tone_indicate(ch,TONE_DIAL);
3530                                 
3531                                 ch->state=MISDN_WAITING4DIGS;
3532                         }
3533                 }
3534       
3535         }
3536         break;
3537         case EVENT_SETUP_ACKNOWLEDGE:
3538         {
3539                 ch->state = MISDN_CALLING_ACKNOWLEDGE;
3540
3541                 if (bc->channel) 
3542                         update_name(ch->ast,bc->port,bc->channel);
3543                 
3544                 if (!ast_strlen_zero(bc->infos_pending)) {
3545                         /* TX Pending Infos */
3546                         
3547                         {
3548                                 int l = sizeof(bc->dad);
3549                                 strncat(bc->dad,bc->infos_pending, l - strlen(bc->dad));
3550                                 bc->dad[l-1] = 0;
3551                         }       
3552                         {
3553                                 int l = sizeof(ch->ast->exten);
3554                                 strncpy(ch->ast->exten, bc->dad, l);
3555                                 ch->ast->exten[l-1] = 0;
3556                         }
3557                         {
3558                                 int l = sizeof(bc->info_dad);
3559                                 strncpy(bc->info_dad, bc->infos_pending, l);
3560                                 bc->info_dad[l-1] = 0;
3561                         }
3562                         strncpy(bc->infos_pending,"", 1);
3563
3564                         misdn_lib_send_event(bc, EVENT_INFORMATION);
3565                 }
3566         }
3567         break;