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