when we get a disconnect, we should stop the tones on te side..
[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         if (!p->bc->nt) 
1975                 stop_bc_tones(p);
1976
1977         
1978         release_unlock;
1979         
1980         {
1981                 const char *varcause=NULL;
1982                 bc->cause=ast->hangupcause?ast->hangupcause:16;
1983                 
1984                 if ( (varcause=pbx_builtin_getvar_helper(ast, "HANGUPCAUSE")) ||
1985                      (varcause=pbx_builtin_getvar_helper(ast, "PRI_CAUSE"))) {
1986                         int tmpcause=atoi(varcause);
1987                         bc->out_cause=tmpcause?tmpcause:16;
1988                 }
1989     
1990                 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));
1991                 chan_misdn_log(2, bc->port, " --> l3id:%x\n",p->l3id);
1992                 chan_misdn_log(1, bc->port, " --> cause:%d\n",bc->cause);
1993                 chan_misdn_log(1, bc->port, " --> out_cause:%d\n",bc->out_cause);
1994                 
1995                 switch (p->state) {
1996                 case MISDN_CALLING:
1997                         p->state=MISDN_CLEANING;
1998                         misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
1999                         break;
2000                 case MISDN_HOLDED:
2001                 case MISDN_DIALING:
2002                         start_bc_tones(p);
2003                         tone_indicate(p, TONE_HANGUP);
2004                         p->state=MISDN_CLEANING;
2005                 
2006                         if (bc->nt)
2007                                 misdn_lib_send_event( bc, EVENT_DISCONNECT);
2008                         else
2009                                 misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
2010       
2011                         break;
2012       
2013                 case MISDN_ALERTING:
2014                 case MISDN_PROGRESS:
2015                 case MISDN_PROCEEDING:
2016                         chan_misdn_log(2, bc->port, " --> * State Alerting\n");
2017
2018                         if (p->orginator != ORG_AST) 
2019                                 tone_indicate(p, TONE_HANGUP);
2020       
2021                         p->state=MISDN_CLEANING;
2022                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
2023                         break;
2024                 case MISDN_CONNECTED:
2025                         /*  Alerting or Disconect */
2026                         chan_misdn_log(2, bc->port, " --> * State Connected\n");
2027                         start_bc_tones(p);
2028                         tone_indicate(p, TONE_HANGUP);
2029                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
2030       
2031                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2032                         break;
2033                 case MISDN_DISCONNECTED:
2034                         chan_misdn_log(2, bc->port, " --> * State Disconnected\n");
2035                         misdn_lib_send_event( bc, EVENT_RELEASE);
2036                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2037                         break;
2038
2039                 case MISDN_CLEANING:
2040                         break;
2041       
2042                 case MISDN_HOLD_DISCONNECT:
2043                         /* need to send release here */
2044                         chan_misdn_log(2, bc->port, " --> state HOLD_DISC\n");
2045                         chan_misdn_log(1, bc->port, " --> cause %d\n",bc->cause);
2046                         chan_misdn_log(1, bc->port, " --> out_cause %d\n",bc->out_cause);
2047                         
2048                         bc->out_cause=-1;
2049                         misdn_lib_send_event(bc,EVENT_RELEASE);
2050                         break;
2051                 default:
2052                         /*  Alerting or Disconect */
2053
2054                         if (bc->nt) {
2055                                 bc->out_cause=-1;
2056                                 misdn_lib_send_event(bc, EVENT_RELEASE);
2057                         } else
2058                                 misdn_lib_send_event(bc, EVENT_DISCONNECT);
2059                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2060                 }
2061     
2062         }
2063         
2064
2065         chan_misdn_log(1, bc->port, "Channel: %s hanguped\n",ast->name);
2066         
2067         return 0;
2068 }
2069
2070
2071 struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame *frame)
2072 {
2073         struct ast_frame *f,*f2;
2074         if (tmp->trans)
2075                 f2=ast_translate(tmp->trans, frame,0);
2076         else {
2077                 chan_misdn_log(0, tmp->bc->port, "No T-Path found\n");
2078                 return NULL;
2079         }
2080         
2081         f = ast_dsp_process(tmp->ast, tmp->dsp, f2);
2082         if (f && (f->frametype == AST_FRAME_DTMF)) {
2083                 ast_log(LOG_DEBUG, "Detected inband DTMF digit: %c", f->subclass);
2084                 if (f->subclass == 'f' && tmp->faxdetect) {
2085                         /* Fax tone -- Handle and return NULL */
2086                         struct ast_channel *ast = tmp->ast;
2087                         if (!tmp->faxhandled) {
2088                                 tmp->faxhandled++;
2089                                 if (strcmp(ast->exten, "fax")) {
2090                                         if (ast_exists_extension(ast, ast_strlen_zero(ast->macrocontext)? ast->context : ast->macrocontext, "fax", 1, AST_CID_P(ast))) {
2091                                                 if (option_verbose > 2)
2092                                                         ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension\n", ast->name);
2093                                                 /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
2094                                                 pbx_builtin_setvar_helper(ast,"FAXEXTEN",ast->exten);
2095                                                 if (ast_async_goto(ast, ast->context, "fax", 1))
2096                                                         ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, ast->context);
2097                                         } else
2098                                                 ast_log(LOG_NOTICE, "Fax detected, but no fax extension ctx:%s exten:%s\n",ast->context, ast->exten);
2099                                 } else
2100                                         ast_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
2101                         } else
2102                                 ast_log(LOG_DEBUG, "Fax already handled\n");
2103                         
2104                 }  else if ( tmp->ast_dsp) {
2105                         chan_misdn_log(2, tmp->bc->port, " --> * SEND: DTMF (AST_DSP) :%c\n",f->subclass);
2106                         return f;
2107                 }
2108         }
2109
2110         frame->frametype = AST_FRAME_NULL;
2111         frame->subclass = 0;
2112         return frame;
2113 }
2114
2115
2116 static struct ast_frame  *misdn_read(struct ast_channel *ast)
2117 {
2118         struct chan_list *tmp;
2119         int len;
2120         
2121         if (!ast) return NULL;
2122         if (! (tmp=MISDN_ASTERISK_TECH_PVT(ast)) ) return NULL;
2123         if (!tmp->bc) return NULL;
2124
2125         len=read(tmp->pipe[0],tmp->ast_rd_buf,sizeof(tmp->ast_rd_buf));
2126
2127         if (len<=0) {
2128                 /* we hangup here, since our pipe is closed */
2129                 chan_misdn_log(2,tmp->bc->port,"misdn_read: Pipe closed, hanging up\n");
2130                 return NULL;
2131         }
2132
2133         tmp->frame.frametype  = AST_FRAME_VOICE;
2134         tmp->frame.subclass = AST_FORMAT_ALAW;
2135         tmp->frame.datalen = len;
2136         tmp->frame.samples = len ;
2137         tmp->frame.mallocd =0 ;
2138         tmp->frame.offset= 0 ;
2139         tmp->frame.src = NULL;
2140         tmp->frame.data = tmp->ast_rd_buf ;
2141         
2142         if (tmp->faxdetect || tmp->ast_dsp ) {
2143                 return process_ast_dsp(tmp, &tmp->frame);
2144         }
2145         
2146         return &tmp->frame;
2147 }
2148
2149
2150 static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
2151 {
2152         struct chan_list *ch;
2153         int i  = 0;
2154         
2155         if (!ast || ! (ch=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
2156         
2157         if (!ch->bc ) {
2158                 ast_log(LOG_WARNING, "private but no bc\n");
2159                 return -1;
2160         }
2161         
2162         if (ch->holded ) {
2163                 chan_misdn_log(5, ch->bc->port, "misdn_write: Returning because holded\n");
2164                 return 0;
2165         }
2166         
2167         if (ch->notxtone) {
2168                 chan_misdn_log(5, ch->bc->port, "misdn_write: Returning because notxone\n");
2169                 return 0;
2170         }
2171
2172
2173         if ( !frame->subclass) {
2174                 chan_misdn_log(4, ch->bc->port, "misdn_write: * prods us\n");
2175                 return 0;
2176         }
2177         
2178         if ( !(frame->subclass & prefformat)) {
2179                 
2180                 chan_misdn_log(-1, ch->bc->port, "Got Unsupported Frame with Format:%d\n", frame->subclass);
2181                 return 0;
2182         }
2183         
2184
2185         if ( !frame->samples ) {
2186                 chan_misdn_log(4, ch->bc->port, "misdn_write: zero write\n");
2187                 return 0;
2188         }
2189
2190         if ( ! ch->bc->addr ) {
2191                 chan_misdn_log(8, ch->bc->port, "misdn_write: no addr for bc dropping:%d\n", frame->samples);
2192                 return 0;
2193         }
2194         
2195 #if MISDN_DEBUG
2196         {
2197                 int i, max=5>frame->samples?frame->samples:5;
2198                 
2199                 printf("write2mISDN %p %d bytes: ", p, frame->samples);
2200                 
2201                 for (i=0; i<  max ; i++) printf("%2.2x ",((char*) frame->data)[i]);
2202                 printf ("\n");
2203         }
2204 #endif
2205
2206
2207         switch (ch->bc->bc_state) {
2208                 case BCHAN_ACTIVATED:
2209                 case BCHAN_BRIDGED:
2210                         break;
2211                 default:
2212                 if (!ch->dropped_frame_cnt)
2213                         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);
2214                 
2215                 ch->dropped_frame_cnt++;
2216                 if (ch->dropped_frame_cnt > 100) {
2217                         ch->dropped_frame_cnt=0;
2218                         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);
2219
2220                 }
2221
2222                 return 0;
2223         }
2224
2225         chan_misdn_log(9, ch->bc->port, "Sending :%d bytes 2 MISDN\n",frame->samples);
2226         
2227         if ( !ch->bc->nojitter && misdn_cap_is_speech(ch->bc->capability) ) {
2228                 /* Buffered Transmit (triggert by read from isdn side)*/
2229                 if (misdn_jb_fill(ch->jb,frame->data,frame->samples) < 0) {
2230                         if (ch->bc->active)
2231                                 cb_log(0,ch->bc->port,"Misdn Jitterbuffer Overflow.\n");
2232                 }
2233                 
2234         } else {
2235                 /*transmit without jitterbuffer*/
2236                 i=misdn_lib_tx2misdn_frm(ch->bc, frame->data, frame->samples);
2237         }
2238
2239         
2240         
2241         return 0;
2242 }
2243
2244
2245
2246
2247 static enum ast_bridge_result  misdn_bridge (struct ast_channel *c0,
2248                                       struct ast_channel *c1, int flags,
2249                                       struct ast_frame **fo,
2250                                       struct ast_channel **rc,
2251                                       int timeoutms)
2252
2253 {
2254         struct chan_list *ch1,*ch2;
2255         struct ast_channel *carr[2], *who;
2256         int to=-1;
2257         struct ast_frame *f;
2258   
2259         ch1=get_chan_by_ast(c0);
2260         ch2=get_chan_by_ast(c1);
2261
2262         carr[0]=c0;
2263         carr[1]=c1;
2264   
2265   
2266         if (ch1 && ch2 ) ;
2267         else
2268                 return -1;
2269   
2270
2271         int bridging;
2272         misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
2273         if (bridging) {
2274                 int ecwb, ec;
2275                 misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2276                 misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
2277                 if ( !ecwb && ec ) {
2278                         chan_misdn_log(2, ch1->bc->port, "Disabling Echo Cancellor when Bridged\n");
2279                         ch1->bc->ec_enable=0;
2280                         manager_ec_disable(ch1->bc);
2281                 }
2282                 misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2283                 misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
2284                 if ( !ecwb && ec) {
2285                         chan_misdn_log(2, ch2->bc->port, "Disabling Echo Cancellor when Bridged\n");
2286                         ch2->bc->ec_enable=0;
2287                         manager_ec_disable(ch2->bc); 
2288                 }
2289                 
2290                 /* trying to make a mISDN_dsp conference */
2291                 chan_misdn_log(1, ch1->bc->port, "I SEND: Making conference with Number:%d\n", ch1->bc->pid +1);
2292
2293                 misdn_lib_bridge(ch1->bc,ch2->bc);
2294         }
2295         
2296         if (option_verbose > 2) 
2297                 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
2298
2299         chan_misdn_log(1, ch1->bc->port, "* Making Native Bridge between %s and %s\n", ch1->bc->oad, ch2->bc->oad);
2300  
2301         if (! (flags&AST_BRIDGE_DTMF_CHANNEL_0) )
2302                 ch1->ignore_dtmf=1;
2303
2304         if (! (flags&AST_BRIDGE_DTMF_CHANNEL_1) )
2305                 ch2->ignore_dtmf=1;
2306
2307         while(1) {
2308                 to=-1;
2309                 who = ast_waitfor_n(carr, 2, &to);
2310
2311                 if (!who) {
2312                         ast_log(LOG_NOTICE,"misdn_bridge: empty read, breaking out\n");
2313                         break;
2314                 }
2315                 f = ast_read(who);
2316     
2317                 if (!f || f->frametype == AST_FRAME_CONTROL) {
2318                         /* got hangup .. */
2319                         *fo=f;
2320                         *rc=who;
2321       
2322                         break;
2323                 }
2324                 
2325                 if ( f->frametype == AST_FRAME_DTMF ) {
2326                         chan_misdn_log(1,0,"Read DTMF %d from %s\n",f->subclass, who->exten);
2327
2328                         *fo=f;
2329                         *rc=who;
2330                         break;
2331                 }
2332                 
2333                 
2334                 if (who == c0) {
2335                         ast_write(c1,f);
2336                 }
2337                 else {
2338                         ast_write(c0,f);
2339                 }
2340     
2341         }
2342         
2343         chan_misdn_log(1, ch1->bc->port, "I SEND: Splitting conference with Number:%d\n", ch1->bc->pid +1);
2344         
2345         misdn_lib_split_bridge(ch1->bc,ch2->bc);
2346         
2347         
2348         return AST_BRIDGE_COMPLETE;
2349 }
2350
2351 /** AST INDICATIONS END **/
2352
2353 static int tone_indicate( struct chan_list *cl, enum tone_e tone)
2354 {
2355         const struct tone_zone_sound *ts= NULL;
2356         struct ast_channel *ast=cl->ast;
2357         
2358         chan_misdn_log(3,cl->bc->port,"Tone Indicate:\n");
2359         
2360         if (!cl->ast) {
2361                 chan_misdn_log(-1,cl->bc->port,"Ast Ptr Not existing anymore.. we need to generate tones ourselves now (tbd)\n");
2362                 
2363                 misdn_lib_send_tone(cl->bc,tone);
2364                 return 0;
2365         }
2366         
2367         switch (tone) {
2368         case TONE_DIAL:
2369                 chan_misdn_log(3,cl->bc->port," --> Dial\n");
2370                 ts=ast_get_indication_tone(ast->zone,"dial");
2371                 misdn_lib_tone_generator_start(cl->bc);
2372                 break;
2373         case TONE_ALERTING:
2374                 chan_misdn_log(3,cl->bc->port," --> Ring\n");
2375                 ts=ast_get_indication_tone(ast->zone,"ring");
2376                 misdn_lib_tone_generator_start(cl->bc);
2377                 break;
2378         case TONE_FAR_ALERTING:
2379         /* VERY UGLY HACK, BECAUSE CHAN_SIP DOES NOT GENERATE TONES */
2380                 chan_misdn_log(3,cl->bc->port," --> Ring\n");
2381                 ts=ast_get_indication_tone(ast->zone,"ring");
2382                 misdn_lib_tone_generator_start(cl->bc);
2383                 misdn_lib_echo(cl->bc,1);
2384                 break;
2385         case TONE_BUSY:
2386                 chan_misdn_log(3,cl->bc->port," --> Busy\n");
2387                 ts=ast_get_indication_tone(ast->zone,"busy");
2388                 misdn_lib_tone_generator_start(cl->bc);
2389                 break;
2390         case TONE_FILE:
2391                 break;
2392         case TONE_NONE:
2393                 chan_misdn_log(3,cl->bc->port," --> None\n");
2394                 misdn_lib_tone_generator_stop(cl->bc);
2395                 ast_playtones_stop(ast);
2396                 break;
2397         default:
2398                 chan_misdn_log(0,cl->bc->port,"Don't know how to handle tone: %d\n",tone);
2399         }
2400         
2401         cl->ts=ts;      
2402         
2403         if (ts) ast_playtones_start(ast,0, ts->data, 0);
2404         
2405         return 0;
2406 }
2407
2408 static int start_bc_tones(struct chan_list* cl)
2409 {
2410         manager_bchannel_activate(cl->bc);
2411         misdn_lib_tone_generator_stop(cl->bc);
2412         cl->notxtone=0;
2413         cl->norxtone=0;
2414         return 0;
2415 }
2416
2417 static int stop_bc_tones(struct chan_list *cl)
2418 {
2419         if (cl->bc) {
2420                 manager_bchannel_deactivate(cl->bc);
2421         }
2422         cl->notxtone=1;
2423         cl->norxtone=1;
2424         
2425         return 0;
2426 }
2427
2428
2429 static struct chan_list *init_chan_list(int orig)
2430 {
2431         struct chan_list *cl=malloc(sizeof(struct chan_list));
2432         
2433         if (!cl) {
2434                 chan_misdn_log(-1, 0, "misdn_request: malloc failed!");
2435                 return NULL;
2436         }
2437         
2438         memset(cl,0,sizeof(struct chan_list));
2439
2440         cl->orginator=orig;
2441         
2442         return cl;
2443         
2444 }
2445
2446 static struct ast_channel *misdn_request(const char *type, int format, void *data, int *cause)
2447
2448 {
2449         struct ast_channel *tmp = NULL;
2450         char group[BUFFERSIZE+1]="";
2451         char buf[128];
2452         char buf2[128], *ext=NULL, *port_str;
2453         char *tokb=NULL, *p=NULL;
2454         int channel=0, port=0;
2455         struct misdn_bchannel *newbc = NULL;
2456         
2457         struct chan_list *cl=init_chan_list(ORG_AST);
2458         
2459         sprintf(buf,"%s/%s",misdn_type,(char*)data);
2460         ast_copy_string(buf2,data, 128);
2461         
2462         port_str=strtok_r(buf2,"/", &tokb);
2463
2464         ext=strtok_r(NULL,"/", &tokb);
2465
2466         if (port_str) {
2467                 if (port_str[0]=='g' && port_str[1]==':' ) {
2468                         /* We make a group call lets checkout which ports are in my group */
2469                         port_str += 2;
2470                         strncpy(group, port_str, BUFFERSIZE);
2471                         group[127] = 0;
2472                         chan_misdn_log(2, 0, " --> Group Call group: %s\n",group);
2473                 } 
2474                 else if ((p = strchr(port_str, ':'))) {
2475                         /* we have a preselected channel */
2476                         *p = 0;
2477                         channel = atoi(++p);
2478                         port = atoi(port_str);
2479                         chan_misdn_log(2, port, " --> Call on preselected Channel (%d).\n", channel);
2480                 }
2481                 else {
2482                         port = atoi(port_str);
2483                 }
2484                 
2485                 
2486         } else {
2487                 ast_log(LOG_WARNING, " --> ! IND : CALL dad:%s WITHOUT PORT/Group, check extension.conf\n",ext);
2488                 return NULL;
2489         }
2490
2491         if (!ast_strlen_zero(group)) {
2492         
2493                 char cfg_group[BUFFERSIZE+1];
2494                 struct robin_list *rr = NULL;
2495
2496                 if (misdn_cfg_is_group_method(group, METHOD_ROUND_ROBIN)) {
2497                         chan_misdn_log(4, port, " --> STARTING ROUND ROBIN...");
2498                         rr = get_robin_position(group);
2499                 }
2500                 
2501                 if (rr) {
2502                         int robin_channel = rr->channel;
2503                         int port_start;
2504                         int next_chan = 1;
2505
2506                         do {
2507                                 port_start = 0;
2508                                 for (port = misdn_cfg_get_next_port_spin(rr->port); port > 0 && port != port_start;
2509                                          port = misdn_cfg_get_next_port_spin(port)) {
2510
2511                                         if (!port_start)
2512                                                 port_start = port;
2513
2514                                         if (port >= port_start)
2515                                                 next_chan = 1;
2516                                         
2517                                         if (port < port_start && next_chan) {
2518                                                 if (++robin_channel >= MAX_BCHANS) {
2519                                                         robin_channel = 1;
2520                                                 }
2521                                                 next_chan = 0;
2522                                         }
2523
2524                                         misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2525                                         
2526                                         if (!strcasecmp(cfg_group, group)) {
2527                                                 int port_up;
2528                                                 int check;
2529                                                 misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
2530                                                 port_up = misdn_lib_port_up(port, check);
2531                                                 
2532                                                 if ( port_up )  {
2533                                                         newbc = misdn_lib_get_free_bc(port, robin_channel);
2534                                                         if (newbc) {
2535                                                                 chan_misdn_log(4, port, " Success! Found port:%d channel:%d\n", newbc->port, newbc->channel);
2536                                                                 if (port_up)
2537                                                                         chan_misdn_log(4, port, "ortup:%d\n",  port_up);
2538                                                                 rr->port = newbc->port;
2539                                                                 rr->channel = newbc->channel;
2540                                                                 break;
2541                                                         }
2542                                                 }
2543                                         }
2544                                 }
2545                         } while (!newbc && robin_channel != rr->channel);
2546                         
2547                         if (!newbc)
2548                                 chan_misdn_log(4, port, " Failed! No free channel in group %d!", group);
2549                 }
2550                 
2551                 else {          
2552                         for (port=misdn_cfg_get_next_port(0); port > 0;
2553                                  port=misdn_cfg_get_next_port(port)) {
2554                                 
2555                                 misdn_cfg_get( port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2556
2557                                 chan_misdn_log(3,port, "Group [%s] Port [%d]\n", group, port);
2558                                 if (!strcasecmp(cfg_group, group)) {
2559                                         int port_up;
2560                                         int check;
2561                                         misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
2562                                         port_up = misdn_lib_port_up(port, check);
2563                                         
2564                                         chan_misdn_log(4, port, "portup:%d\n", port_up);
2565                                         
2566                                         if ( port_up )  {
2567                                                 newbc = misdn_lib_get_free_bc(port, 0);
2568                                                 if (newbc)
2569                                                         break;
2570                                         }
2571                                 }
2572                         }
2573                 }
2574                 
2575         } else {
2576                 if (channel)
2577                         chan_misdn_log(1, port," --> preselected_channel: %d\n",channel);
2578                 newbc = misdn_lib_get_free_bc(port, channel);
2579         }
2580         
2581         if (!newbc) {
2582                 chan_misdn_log(-1, 0, " --> ! No free channel chan ext:%s even after Group Call\n",ext);
2583                 chan_misdn_log(-1, 0, " --> SEND: State Down\n");
2584                 return NULL;
2585         }
2586
2587         /* create ast_channel and link all the objects together */
2588         cl->bc=newbc;
2589         
2590         tmp = misdn_new(cl, AST_STATE_RESERVED, ext, NULL, format, port, channel);
2591         cl->ast=tmp;
2592         
2593         /* register chan in local list */
2594         cl_queue_chan(&cl_te, cl) ;
2595         
2596         /* fill in the config into the objects */
2597         read_config(cl, ORG_AST);
2598         
2599         
2600         return tmp;
2601 }
2602
2603
2604 static int misdn_send_text (struct ast_channel *chan, const char *text)
2605 {
2606         struct chan_list *tmp=chan->tech_pvt;
2607         
2608         if (tmp && tmp->bc) {
2609                 ast_copy_string(tmp->bc->display,text,sizeof(tmp->bc->display));
2610                 misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
2611         } else {
2612                 ast_log(LOG_WARNING, "No chan_list but send_text request?\n");
2613                 return -1;
2614         }
2615         
2616         return 0;
2617 }
2618
2619 static struct ast_channel_tech misdn_tech = {
2620         .type="mISDN",
2621         .description="Channel driver for mISDN Support (Bri/Pri)",
2622         .capabilities= AST_FORMAT_ALAW ,
2623         .requester=misdn_request,
2624         .send_digit=misdn_digit,
2625         .call=misdn_call,
2626         .bridge=misdn_bridge, 
2627         .hangup=misdn_hangup,
2628         .answer=misdn_answer,
2629         .read=misdn_read,
2630         .write=misdn_write,
2631         .indicate=misdn_indication,
2632         .fixup=misdn_fixup,
2633         .send_text=misdn_send_text,
2634         .properties=0
2635 };
2636
2637 static struct ast_channel_tech misdn_tech_wo_bridge = {
2638         .type="mISDN",
2639         .description="Channel driver for mISDN Support (Bri/Pri)",
2640         .capabilities=AST_FORMAT_ALAW ,
2641         .requester=misdn_request,
2642         .send_digit=misdn_digit,
2643         .call=misdn_call,
2644         .hangup=misdn_hangup,
2645         .answer=misdn_answer,
2646         .read=misdn_read,
2647         .write=misdn_write,
2648         .indicate=misdn_indication,
2649         .fixup=misdn_fixup,
2650         .send_text=misdn_send_text,
2651         .properties=0
2652 };
2653
2654
2655 static unsigned long glob_channel=0;
2656
2657 static void update_name(struct ast_channel *tmp, int port, int c) 
2658 {
2659         if (c<=0) {
2660                         c=glob_channel++;
2661                         ast_string_field_build(tmp, name, "%s/%d-u%d",
2662                                  misdn_type, port, c);
2663         } else {
2664                          ast_string_field_build(tmp, name, "%s/%d-%d",
2665                                  misdn_type, port, c);
2666         }
2667
2668         chan_misdn_log(3,port," --> updating channel name to [%s]\n",tmp->name);
2669         
2670 }
2671
2672 static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char *exten, char *callerid, int format, int port, int c)
2673 {
2674         struct ast_channel *tmp;
2675         
2676         tmp = ast_channel_alloc(1);
2677         
2678         if (tmp) {
2679                 chan_misdn_log(2, 0, " --> * NEW CHANNEL dad:%s oad:%s\n",exten,callerid);
2680                 
2681                 update_name(tmp,port,c);
2682         
2683                 tmp->nativeformats = prefformat;
2684
2685                 tmp->readformat = format;
2686                 tmp->rawreadformat = format;
2687                 tmp->writeformat = format;
2688                 tmp->rawwriteformat = format;
2689     
2690                 tmp->tech_pvt = chlist;
2691                 
2692                 int bridging;
2693                 misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
2694                 if (bridging)
2695                         tmp->tech = &misdn_tech;
2696                 else
2697                         tmp->tech = &misdn_tech_wo_bridge;
2698                 
2699                 tmp->writeformat = format;
2700                 tmp->readformat = format;
2701                 tmp->priority=1;
2702                 
2703                 if (exten) 
2704                         ast_copy_string(tmp->exten, exten,  sizeof(tmp->exten));
2705                 else
2706                         chan_misdn_log(1,0,"misdn_new: no exten given.\n");
2707                 
2708                 if (callerid) {
2709                         char *cid_name, *cid_num;
2710       
2711                         ast_callerid_parse(callerid, &cid_name, &cid_num);
2712                         ast_set_callerid(tmp, cid_num,cid_name,cid_num);
2713                 } else {
2714                         ast_set_callerid(tmp, NULL,NULL,NULL);
2715                 }
2716
2717                 {
2718                         if (pipe(chlist->pipe)<0)
2719                                 perror("Pipe failed\n");
2720                         
2721                         tmp->fds[0]=chlist->pipe[0];
2722                         
2723                 }
2724                 
2725                 ast_setstate(tmp, state);
2726                 if (state == AST_STATE_RING)
2727                         tmp->rings = 1;
2728                 else
2729                         tmp->rings = 0;
2730                 
2731                 
2732         } else {
2733                 chan_misdn_log(-1,0,"Unable to allocate channel structure\n");
2734         }
2735         
2736         return tmp;
2737 }
2738
2739 static struct chan_list *find_chan_by_l3id(struct chan_list *list, unsigned long l3id)
2740 {
2741         struct chan_list *help=list;
2742         for (;help; help=help->next) {
2743                 if (help->l3id == l3id ) return help;
2744         }
2745   
2746         chan_misdn_log(6, list? (list->bc? list->bc->port : 0) : 0, "$$$ find_chan: No channel found with l3id:%x\n",l3id);
2747   
2748         return NULL;
2749 }
2750
2751 static struct chan_list *find_chan_by_bc(struct chan_list *list, struct misdn_bchannel *bc)
2752 {
2753         struct chan_list *help=list;
2754         for (;help; help=help->next) {
2755                 if (help->bc == bc) return help;
2756         }
2757   
2758         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
2759   
2760         return NULL;
2761 }
2762
2763 static struct chan_list *find_chan_by_pid(struct chan_list *list, int pid)
2764 {
2765         struct chan_list *help=list;
2766         for (;help; help=help->next) {
2767                 if (help->bc->pid == pid) return help;
2768         }
2769   
2770         chan_misdn_log(6, 0, "$$$ find_chan: No channel found for pid:%d\n",pid);
2771   
2772         return NULL;
2773 }
2774
2775 static struct chan_list *find_holded(struct chan_list *list, struct misdn_bchannel *bc)
2776 {
2777         struct chan_list *help=list;
2778         
2779         chan_misdn_log(6, bc->port, "$$$ find_holded: channel:%d oad:%s dad:%s\n",bc->channel, bc->oad,bc->dad);
2780         for (;help; help=help->next) {
2781                 chan_misdn_log(4, bc->port, "$$$ find_holded: --> holded:%d channel:%d\n",help->bc->holded, help->bc->channel);
2782                 if (help->bc->port == bc->port
2783                     && help->bc->holded ) return help;
2784         }
2785         
2786         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
2787   
2788         return NULL;
2789 }
2790
2791 static void cl_queue_chan(struct chan_list **list, struct chan_list *chan)
2792 {
2793         chan_misdn_log(4, chan->bc? chan->bc->port : 0, "* Queuing chan %p\n",chan);
2794   
2795         ast_mutex_lock(&cl_te_lock);
2796         if (!*list) {
2797                 *list = chan;
2798         } else {
2799                 struct chan_list *help=*list;
2800                 for (;help->next; help=help->next); 
2801                 help->next=chan;
2802         }
2803         chan->next=NULL;
2804         ast_mutex_unlock(&cl_te_lock);
2805 }
2806
2807 static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan) 
2808 {
2809         if (chan->dsp) 
2810                 ast_dsp_free(chan->dsp);
2811         if (chan->trans)
2812                 ast_translator_free_path(chan->trans);
2813
2814         
2815
2816         ast_mutex_lock(&cl_te_lock);
2817         if (!*list) {
2818                 ast_mutex_unlock(&cl_te_lock);
2819                 return;
2820         }
2821   
2822         if (*list == chan) {
2823                 *list=(*list)->next;
2824                 ast_mutex_unlock(&cl_te_lock);
2825                 return ;
2826         }
2827   
2828         {
2829                 struct chan_list *help=*list;
2830                 for (;help->next; help=help->next) {
2831                         if (help->next == chan) {
2832                                 help->next=help->next->next;
2833                                 ast_mutex_unlock(&cl_te_lock);
2834                                 return;
2835                         }
2836                 }
2837         }
2838         
2839         ast_mutex_unlock(&cl_te_lock);
2840 }
2841
2842 /** Channel Queue End **/
2843
2844
2845
2846 /** Isdn asks us to release channel, pendant to misdn_hangup **/
2847 static void release_chan(struct misdn_bchannel *bc) {
2848         struct ast_channel *ast=NULL;
2849         
2850         {
2851                 struct chan_list *ch=find_chan_by_bc(cl_te, bc);
2852                 if (!ch) ch=find_chan_by_l3id (cl_te, bc->l3_id);
2853                 if (!ch)  {
2854                         chan_misdn_log(0, bc->port, "release_chan: Ch not found!\n");
2855                         return;
2856                 }
2857                 
2858                 release_lock;
2859                 if (ch->ast) {
2860                         ast=ch->ast;
2861                 } 
2862                 release_unlock;
2863                 
2864                 chan_misdn_log(1, bc->port, "release_chan: bc with l3id: %x\n",bc->l3_id);
2865 #if 0
2866                 if (ch->dummy) {
2867                         ast_hangup(ast);
2868                         ch->ast=NULL;
2869                         ast=NULL;
2870                 }
2871 #endif
2872                 
2873                 /*releaseing jitterbuffer*/
2874                 if (ch->jb ) {
2875                         misdn_jb_destroy(ch->jb);
2876                         ch->jb=NULL;
2877                 } else {
2878                         if (!bc->nojitter)
2879                                 chan_misdn_log(5,bc->port,"Jitterbuffer already destroyed.\n");
2880                 }
2881
2882
2883                 if (ch->orginator == ORG_AST) {
2884                         misdn_out_calls[bc->port]--;
2885                 } else {
2886                         misdn_in_calls[bc->port]--;
2887                 }
2888                 
2889                 if (ch) {
2890                         
2891                         close(ch->pipe[0]);
2892                         close(ch->pipe[1]);
2893                         
2894                         if (ast && MISDN_ASTERISK_TECH_PVT(ast)) {
2895                                 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));
2896                                 chan_misdn_log(3, bc->port, " --> * State Down\n");
2897                                 /* copy cause */
2898                                 send_cause2ast(ast,bc);
2899                                 
2900                                 MISDN_ASTERISK_TECH_PVT(ast)=NULL;
2901                                 
2902       
2903                                 if (ast->_state != AST_STATE_RESERVED) {
2904                                         chan_misdn_log(3, bc->port, " --> Setting AST State to down\n");
2905                                         ast_setstate(ast, AST_STATE_DOWN);
2906                                 }
2907                                 
2908                                 switch(ch->state) {
2909                                 case MISDN_EXTCANTMATCH:
2910                                 case MISDN_WAITING4DIGS:
2911                                 {
2912                                         chan_misdn_log(3,  bc->port, " --> * State Wait4dig | ExtCantMatch\n");
2913                                         ast_hangup(ast);
2914                                 }
2915                                 break;
2916                                 
2917                                 case MISDN_DIALING:
2918                                 case MISDN_CALLING_ACKNOWLEDGE:
2919                                 case MISDN_PROGRESS:
2920                                         chan_misdn_log(2,  bc->port, "* --> In State Dialin\n");
2921                                         chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2922                                         
2923
2924                                         ast_queue_hangup(ast);
2925                                         break;
2926                                 case MISDN_CALLING:
2927                                         
2928                                         chan_misdn_log(2,  bc->port, "* --> In State Callin\n");
2929                                         
2930                                         if (!bc->nt) {
2931                                                 chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2932                                                 ast_queue_hangup(ast);
2933                                         } else {
2934                                                 chan_misdn_log(2,  bc->port, "* --> Hangup\n");
2935                                                 ast_queue_hangup(ast);
2936                                         }
2937                                         break;
2938                                         
2939                                 case MISDN_CLEANING:
2940                                         /* this state comes out of ast so we mustnt call a ast function ! */
2941                                         chan_misdn_log(2,  bc->port, "* --> In StateCleaning\n");
2942                                         break;
2943                                 case MISDN_HOLD_DISCONNECT:
2944                                         chan_misdn_log(2,  bc->port, "* --> In HOLD_DISC\n");
2945                                         break;
2946                                 default:
2947                                         chan_misdn_log(2,  bc->port, "* --> In State Default\n");
2948                                         chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2949                                         if (ast) {
2950                                                 ast_queue_hangup(ast);
2951                                         } else {
2952                                                 chan_misdn_log (0,  bc->port, "!! Not really queued!\n");
2953                                         }
2954                                 }
2955                         }
2956                         cl_dequeue_chan(&cl_te, ch);
2957                         
2958                         free(ch);
2959                 } else {
2960                         /* chan is already cleaned, so exiting  */
2961                 }
2962         }
2963 }
2964 /*** release end **/
2965
2966 static void misdn_transfer_bc(struct chan_list *tmp_ch, struct chan_list *holded_chan)
2967 {
2968         chan_misdn_log(4,0,"TRANSFERING %s to %s\n",holded_chan->ast->name, tmp_ch->ast->name);
2969         
2970         tmp_ch->state=MISDN_HOLD_DISCONNECT;
2971   
2972         ast_moh_stop(AST_BRIDGED_P(holded_chan->ast));
2973
2974         holded_chan->state=MISDN_CONNECTED;
2975         holded_chan->holded=0;
2976         misdn_lib_transfer(holded_chan->bc?holded_chan->bc:holded_chan->holded_bc);
2977         ast_channel_masquerade(holded_chan->ast, AST_BRIDGED_P(tmp_ch->ast));
2978 }
2979
2980
2981 static void do_immediate_setup(struct misdn_bchannel *bc,struct chan_list *ch , struct ast_channel *ast)
2982 {
2983         char predial[256]="";
2984         char *p = predial;
2985   
2986         struct ast_frame fr;
2987   
2988         strncpy(predial, ast->exten, sizeof(predial) -1 );
2989   
2990         ch->state=MISDN_DIALING;
2991
2992         if (bc->nt) {
2993                 int ret; 
2994                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
2995         } else {
2996                 int ret;
2997                 if ( misdn_lib_is_ptp(bc->port)) {
2998                         ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
2999                 } else {
3000                         ret = misdn_lib_send_event(bc, EVENT_PROCEEDING );
3001                 }
3002         }
3003
3004         if ( !bc->nt && (ch->orginator==ORG_MISDN) && !ch->incoming_early_audio ) 
3005                 chan_misdn_log(1,bc->port, " --> incoming_early_audio off\n");
3006          else 
3007                 tone_indicate(ch,TONE_DIAL);  
3008   
3009         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));
3010   
3011         strncpy(ast->exten,"s", 2);
3012   
3013         if (ast_pbx_start(ast)<0) {
3014                 ast=NULL;
3015                 tone_indicate(ch,TONE_BUSY);
3016
3017                 if (bc->nt)
3018                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3019                 else
3020                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
3021         }
3022   
3023   
3024         while (!ast_strlen_zero(p) ) {
3025                 fr.frametype = AST_FRAME_DTMF;
3026                 fr.subclass = *p ;
3027                 fr.src=NULL;
3028                 fr.data = NULL ;
3029                 fr.datalen = 0;
3030                 fr.samples = 0 ;
3031                 fr.mallocd =0 ;
3032                 fr.offset= 0 ;
3033
3034                 if (ch->ast && MISDN_ASTERISK_PVT(ch->ast) && MISDN_ASTERISK_TECH_PVT(ch->ast)) {
3035                         ast_queue_frame(ch->ast, &fr);
3036                 }
3037                 p++;
3038         }
3039 }
3040
3041
3042
3043 static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc) {
3044         
3045         ast->hangupcause=bc->cause;
3046         
3047         switch ( bc->cause) {
3048                 
3049         case 1: /** Congestion Cases **/
3050         case 2:
3051         case 3:
3052         case 4:
3053         case 22:
3054         case 27:
3055                 /*
3056                  * Not Queueing the Congestion anymore, since we want to hear
3057                  * the inband message
3058                  *
3059                 chan_misdn_log(1, bc?bc->port:0, " --> * SEND: Queue Congestion pid:%d\n", bc?bc->pid:-1);
3060                 
3061                 ast_queue_control(ast, AST_CONTROL_CONGESTION);
3062                 */
3063                 break;
3064                 
3065         case 21:
3066         case 17: /* user busy */
3067                 chan_misdn_log(1,  bc?bc->port:0, " --> * SEND: Queue Busy pid:%d\n", bc?bc->pid:-1);
3068                 
3069                 ast_queue_control(ast, AST_CONTROL_BUSY);
3070                 
3071                 break;
3072         }
3073 }
3074
3075
3076
3077
3078 void import_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
3079 {
3080         char *tmp;
3081         tmp=pbx_builtin_getvar_helper(chan,"MISDN_PID");
3082         if (tmp) {
3083                 ch->other_pid=atoi(tmp);
3084                 chan_misdn_log(1,bc->port,"IMPORT_PID: importing pid:%s\n",tmp);
3085                 if (ch->other_pid >0) {
3086                         ch->other_ch=find_chan_by_pid(cl_te,ch->other_pid);
3087                         if (ch->other_ch) ch->other_ch->other_ch=ch;
3088                 }
3089         }
3090 }
3091
3092 void export_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
3093 {
3094         char tmp[32];
3095         chan_misdn_log(1,bc->port,"EXPORT_PID: pid:%d\n",bc->pid);
3096         sprintf(tmp,"%d",bc->pid);
3097         pbx_builtin_setvar_helper(chan,"_MISDN_PID",tmp);
3098 }
3099
3100 int add_in_calls(int port)
3101 {
3102         int max_in_calls;
3103         
3104         misdn_cfg_get( port, MISDN_CFG_MAX_IN, &max_in_calls, sizeof(max_in_calls));
3105
3106         misdn_in_calls[port]++;
3107
3108         if (max_in_calls >=0 && max_in_calls<misdn_in_calls[port]) {
3109                 ast_log(LOG_NOTICE,"Marking Incoming Call on port[%d]\n",port);
3110                 return misdn_in_calls[port]-max_in_calls;
3111         }
3112         
3113         return 0;
3114 }
3115
3116 int add_out_calls(int port)
3117 {
3118         int max_out_calls;
3119         
3120         misdn_cfg_get( port, MISDN_CFG_MAX_OUT, &max_out_calls, sizeof(max_out_calls));
3121         
3122
3123         if (max_out_calls >=0 && max_out_calls<=misdn_out_calls[port]) {
3124                 ast_log(LOG_NOTICE,"Rejecting Outgoing Call on port[%d]\n",port);
3125                 return (misdn_out_calls[port]+1)-max_out_calls;
3126         }
3127
3128         misdn_out_calls[port]++;
3129         
3130         return 0;
3131 }
3132
3133
3134
3135 /************************************************************/
3136 /*  Receive Events from isdn_lib  here                     */
3137 /************************************************************/
3138 static enum event_response_e
3139 cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
3140 {
3141         struct chan_list *ch=find_chan_by_bc(cl_te, bc);
3142         
3143         if (!ch)
3144                 ch=find_chan_by_l3id(cl_te, bc->l3_id);
3145         
3146         if (event != EVENT_BCHAN_DATA && event != EVENT_TONE_GENERATE) { /*  Debug Only Non-Bchan */
3147                 chan_misdn_log(1, bc->port, "I IND :%s oad:%s dad:%s\n", manager_isdn_get_info(event), bc->oad, bc->dad);
3148                 misdn_lib_log_ies(bc);
3149                 chan_misdn_log(2,bc->port," --> bc_state:%s\n",bc_state2str(bc->bc_state));
3150         }
3151         
3152         if (event != EVENT_SETUP) {
3153                 if (!ch) {
3154                         if (event != EVENT_CLEANUP )
3155                                 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);
3156                         return -1;
3157                 }
3158         }
3159         
3160         if (ch ) {