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