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