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