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