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