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