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