* removed unneeded bc->state field
[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 }
1223
1224
1225 static int read_config(struct chan_list *ch, int orig) {
1226
1227         if (!ch) {
1228                 ast_log(LOG_WARNING, "Cannot configure without chanlist\n");
1229                 return -1;
1230         }
1231
1232         struct ast_channel *ast=ch->ast;
1233         struct misdn_bchannel *bc=ch->bc;
1234         if (! ast || ! bc ) {
1235                 ast_log(LOG_WARNING, "Cannot configure without ast || bc\n");
1236                 return -1;
1237         }
1238         
1239         int port=bc->port;
1240         
1241         chan_misdn_log(1,port,"read_config: Getting Config\n");
1242
1243         char lang[BUFFERSIZE+1];
1244         
1245
1246         misdn_cfg_get( port, MISDN_CFG_LANGUAGE, lang, BUFFERSIZE);
1247         ast_string_field_set(ast, language, lang);
1248
1249         char localmusicclass[BUFFERSIZE+1];
1250         
1251         misdn_cfg_get( port, MISDN_CFG_MUSICCLASS, localmusicclass, BUFFERSIZE);
1252         ast_string_field_set(ast, musicclass, localmusicclass);
1253         
1254         
1255         misdn_cfg_get( port, MISDN_CFG_TXGAIN, &bc->txgain, sizeof(int));
1256         misdn_cfg_get( port, MISDN_CFG_RXGAIN, &bc->rxgain, sizeof(int));
1257         
1258         misdn_cfg_get( port, MISDN_CFG_INCOMING_EARLY_AUDIO, &ch->incoming_early_audio, sizeof(int));
1259         
1260         misdn_cfg_get( port, MISDN_CFG_SENDDTMF, &bc->send_dtmf, sizeof(int));
1261
1262         misdn_cfg_get( port, MISDN_CFG_NEED_MORE_INFOS, &bc->need_more_infos, sizeof(int));
1263         
1264         int hdlc=0;
1265         misdn_cfg_get( port, MISDN_CFG_HDLC, &hdlc, sizeof(int));
1266         
1267         if (hdlc) {
1268                 switch (bc->capability) {
1269                 case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
1270                 case INFO_CAPABILITY_DIGITAL_RESTRICTED:
1271                         chan_misdn_log(1,bc->port," --> CONF HDLC\n");
1272                         bc->hdlc=1;
1273                         break;
1274                 }
1275                 
1276         }
1277         /*Initialize new Jitterbuffer*/
1278         {
1279                 misdn_cfg_get( port, MISDN_CFG_JITTERBUFFER, &ch->jb_len, sizeof(int));
1280                 misdn_cfg_get( port, MISDN_CFG_JITTERBUFFER_UPPER_THRESHOLD, &ch->jb_upper_threshold, sizeof(int));
1281                 
1282                 config_jitterbuffer(ch);
1283         }
1284         
1285         misdn_cfg_get( bc->port, MISDN_CFG_CONTEXT, ch->context, sizeof(ch->context));
1286         
1287         ast_copy_string (ast->context,ch->context,sizeof(ast->context));
1288         
1289         {
1290                 int ec, ectr;
1291                 
1292                 misdn_cfg_get( port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
1293                 
1294                 misdn_cfg_get( port, MISDN_CFG_ECHOTRAINING, &ectr, sizeof(int));
1295                 if (ec == 1 ) {
1296                         bc->ec_enable=1;
1297                 } else if ( ec > 1 ) {
1298                         bc->ec_enable=1;
1299                         bc->ec_deftaps=ec;
1300                 }
1301                 
1302                 if ( ectr >= 0 ) {
1303                         bc->ec_training=ectr;
1304                 }
1305         }
1306         
1307         
1308         {
1309                 int eb3;
1310                 
1311                 misdn_cfg_get( bc->port, MISDN_CFG_EARLY_BCONNECT, &eb3, sizeof(int));
1312                 bc->early_bconnect=eb3;
1313         }
1314         
1315         port=bc->port;
1316         
1317
1318         {
1319                 char buf[256];
1320                 ast_group_t pg,cg;
1321                 
1322                 misdn_cfg_get(port, MISDN_CFG_PICKUPGROUP, &pg, sizeof(pg));
1323                 misdn_cfg_get(port, MISDN_CFG_CALLGROUP, &cg, sizeof(cg));
1324                 
1325                 chan_misdn_log(2, port, " --> * CallGrp:%s PickupGrp:%s\n",ast_print_group(buf,sizeof(buf),cg),ast_print_group(buf,sizeof(buf),pg));
1326                 ast->pickupgroup=pg;
1327                 ast->callgroup=cg;
1328         }
1329         
1330         
1331         if ( orig  == ORG_AST) {
1332                 misdn_cfg_get( port, MISDN_CFG_TE_CHOOSE_CHANNEL, &(bc->te_choose_channel), sizeof(int));
1333                 
1334                 
1335                 {
1336                         char callerid[BUFFERSIZE+1];
1337                         misdn_cfg_get( port, MISDN_CFG_CALLERID, callerid, BUFFERSIZE);
1338                         if ( ! ast_strlen_zero(callerid) ) {
1339                                 chan_misdn_log(1, port, " --> * Setting Cid to %s\n", callerid);
1340                                 {
1341                                         int l = sizeof(bc->oad);
1342                                         strncpy(bc->oad,callerid, l);
1343                                         bc->oad[l-1] = 0;
1344                                 }
1345
1346                         }
1347
1348                         
1349                         misdn_cfg_get( port, MISDN_CFG_DIALPLAN, &bc->dnumplan, sizeof(int));
1350                         switch (bc->dnumplan) {
1351                         case NUMPLAN_INTERNATIONAL:
1352                                 chan_misdn_log(2, port, " --> TON: International\n");
1353                                 break;
1354                         case NUMPLAN_NATIONAL:
1355                                 chan_misdn_log(2, port, " --> TON: National\n");
1356                                 break;
1357                         case NUMPLAN_SUBSCRIBER:
1358                                 chan_misdn_log(2, port, " --> TON: Subscriber\n");
1359                                 break;
1360                         case NUMPLAN_UNKNOWN:
1361                                 chan_misdn_log(2, port, " --> TON: Unknown\n");
1362                                 break;
1363                                 /* Maybe we should cut off the prefix if present ? */
1364                         default:
1365                                 chan_misdn_log(0, port, " --> !!!! Wrong dialplan setting, please see the misdn.conf sample file\n ");
1366                                 break;
1367                         }
1368
1369
1370                         misdn_cfg_get( port, MISDN_CFG_LOCALDIALPLAN, &bc->onumplan, sizeof(int));
1371                         switch (bc->onumplan) {
1372                         case NUMPLAN_INTERNATIONAL:
1373                                 chan_misdn_log(2, port, " --> LTON: International\n");
1374                                 break;
1375                         case NUMPLAN_NATIONAL:
1376                                 chan_misdn_log(2, port, " --> LTON: National\n");
1377                                 break;
1378                         case NUMPLAN_SUBSCRIBER:
1379                                 chan_misdn_log(2, port, " --> LTON: Subscriber\n");
1380                                 break;
1381                         case NUMPLAN_UNKNOWN:
1382                                 chan_misdn_log(2, port, " --> LTON: Unknown\n");
1383                                 break;
1384                                 /* Maybe we should cut off the prefix if present ? */
1385                         default:
1386                                         chan_misdn_log(0, port, " --> !!!! Wrong dialplan setting, please see the misdn.conf sample file\n ");
1387                                         break;
1388                         }
1389
1390                         misdn_cfg_get( port, MISDN_CFG_CPNDIALPLAN, &bc->cpnnumplan, sizeof(int));
1391
1392                         switch (bc->cpnnumplan) {
1393                         case NUMPLAN_INTERNATIONAL:
1394                                 chan_misdn_log(2, port, " --> CTON: International\n");
1395                                 break;
1396                         case NUMPLAN_NATIONAL:
1397                                 chan_misdn_log(2, port, " --> CTON: National\n");
1398                                 break;
1399                         case NUMPLAN_SUBSCRIBER:
1400                                 chan_misdn_log(2, port, " --> CTON: Subscriber\n");
1401                                 break;
1402                         case NUMPLAN_UNKNOWN:
1403                                 chan_misdn_log(2, port, " --> CTON: Unknown\n");
1404                                 break;
1405                                 /* Maybe we should cut off the prefix if present ? */
1406                         default:
1407                                         chan_misdn_log(0, port, " --> !!!! Wrong dialplan setting, please see the misdn.conf sample file\n ");
1408                                         break;
1409                         }
1410
1411                 }
1412
1413                 
1414                 
1415         } else { /** ORIGINATOR MISDN **/
1416                 
1417                 char prefix[BUFFERSIZE+1]="";
1418                 switch( bc->onumplan ) {
1419                 case NUMPLAN_INTERNATIONAL:
1420                         misdn_cfg_get( bc->port, MISDN_CFG_INTERNATPREFIX, prefix, BUFFERSIZE);
1421                         break;
1422                         
1423                 case NUMPLAN_NATIONAL:
1424                         misdn_cfg_get( bc->port, MISDN_CFG_NATPREFIX, prefix, BUFFERSIZE);
1425                         break;
1426                         
1427                         
1428                 case NUMPLAN_SUBSCRIBER:
1429                         /* dunno what to do here ? */
1430                         break;
1431                         
1432                 case NUMPLAN_UNKNOWN:
1433                                 break;
1434                 default:
1435                         break;
1436                 }
1437                 
1438                 {
1439                         int l = strlen(prefix) + strlen(bc->oad);
1440                         char tmp[l+1];
1441                         strcpy(tmp,prefix);
1442                         strcat(tmp,bc->oad);
1443                         strcpy(bc->oad,tmp);
1444                 }
1445                 
1446                 
1447                 if (!ast_strlen_zero(bc->dad)) {
1448                         ast_copy_string(bc->orig_dad,bc->dad, sizeof(bc->orig_dad));
1449                 }
1450                 
1451                 if ( ast_strlen_zero(bc->dad) && !ast_strlen_zero(bc->keypad)) {
1452                         ast_copy_string(bc->dad,bc->keypad, sizeof(bc->dad));
1453                 }
1454                 prefix[0] = 0;
1455                 
1456                 switch( bc->dnumplan ) {
1457                 case NUMPLAN_INTERNATIONAL:
1458                         misdn_cfg_get( bc->port, MISDN_CFG_INTERNATPREFIX, prefix, BUFFERSIZE);
1459                         break;
1460                         
1461                         case NUMPLAN_NATIONAL:
1462                                 misdn_cfg_get( bc->port, MISDN_CFG_NATPREFIX, prefix, BUFFERSIZE);
1463                                 break;
1464                                 
1465                                 
1466                 case NUMPLAN_SUBSCRIBER:
1467                                 /* dunno what to do here ? */
1468                         break;
1469                         
1470                 case NUMPLAN_UNKNOWN:
1471                         break;
1472                 default:
1473                         break;
1474                 }
1475                 
1476                 {
1477                         int l = strlen(prefix) + strlen(bc->dad);
1478                         char tmp[l+1];
1479                         strcpy(tmp,prefix);
1480                         strcat(tmp,bc->dad);
1481                         strcpy(bc->dad,tmp);
1482                 }
1483                 
1484                 if ( strcmp(bc->dad,ast->exten)) {
1485                         ast_copy_string(ast->exten, bc->dad, sizeof(ast->exten));
1486                 }
1487                 if ( ast->cid.cid_num && strcmp(ast->cid.cid_num, bc->oad)) {
1488                         free(ast->cid.cid_num);
1489                         ast->cid.cid_num=NULL;
1490                         
1491                 }
1492                 if ( !ast->cid.cid_num) {
1493                         ast->cid.cid_num=strdup(bc->oad);
1494                 }
1495                 
1496                 pbx_builtin_setvar_helper(ch->ast,"REDIRECTING_NUMBER",bc->rad);
1497         }
1498         return 0;
1499 }
1500
1501
1502 /*****************************/
1503 /*** AST Indications Start ***/
1504 /*****************************/
1505
1506 static int misdn_call(struct ast_channel *ast, char *dest, int timeout)
1507 {
1508         int port=0;
1509         int r;
1510         struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
1511         struct misdn_bchannel *newbc;
1512         char *opts=NULL, *ext,*tokb;
1513         char dest_cp[256];
1514
1515         {
1516                 strncpy(dest_cp,dest,sizeof(dest_cp)-1);
1517                 dest_cp[sizeof(dest_cp)]=0;
1518                 
1519                 ext=strtok_r(dest_cp,"/",&tokb);
1520                 
1521                 if (ext) {
1522                         ext=strtok_r(NULL,"/",&tokb);
1523                         if (ext) {
1524                                 opts=strtok_r(NULL,"/",&tokb);
1525                         } else {
1526                                 chan_misdn_log(-1,0,"misdn_call: No Extension given!\n");
1527                                 return -1;
1528                         }
1529                         
1530                 }
1531                 
1532                 
1533         }
1534
1535         if (!ast) {
1536                 ast_log(LOG_WARNING, " --> ! misdn_call called on ast_channel *ast where ast == NULL\n");
1537                 return -1;
1538         }
1539
1540         if (((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) || !dest  ) {
1541                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1542                 ast->hangupcause=41;
1543                 ast_setstate(ast, AST_STATE_DOWN);
1544                 return -1;
1545         }
1546
1547
1548         if (!ch) {
1549                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1550                 ast->hangupcause=41;
1551                 ast_setstate(ast, AST_STATE_DOWN);
1552                 return -1;
1553         }
1554         
1555         newbc=ch->bc;
1556         
1557         if (!newbc) {
1558                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1559                 ast->hangupcause=41;
1560                 ast_setstate(ast, AST_STATE_DOWN);
1561                 return -1;
1562         }
1563         
1564         port=newbc->port;
1565         strncpy(newbc->dad,ext,sizeof( newbc->dad));
1566         strncpy(ast->exten,ext,sizeof(ast->exten));
1567         
1568         
1569         chan_misdn_log(1, port, "* CALL: %s\n",dest);
1570         
1571         chan_misdn_log(1, port, " --> * dad:%s tech:%s ctx:%s\n",ast->exten,ast->name, ast->context);
1572         
1573         
1574         
1575         chan_misdn_log(3, port, " --> * adding2newbc ext %s\n",ast->exten);
1576         if (ast->exten) {
1577                 int l = sizeof(newbc->dad);
1578                 strncpy(newbc->dad,ast->exten, l);
1579                 newbc->dad[l-1] = 0;
1580         }
1581         newbc->rad[0]=0;
1582         chan_misdn_log(3, port, " --> * adding2newbc callerid %s\n",AST_CID_P(ast));
1583         if (ast_strlen_zero(newbc->oad) && AST_CID_P(ast) ) {
1584
1585                 if (AST_CID_P(ast)) {
1586                         int l = sizeof(newbc->oad);
1587                         strncpy(newbc->oad,AST_CID_P(ast), l);
1588                         newbc->oad[l-1] = 0;
1589                 }
1590         }
1591         
1592         {
1593                 struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
1594                 if (!ch) { ast_verbose("No chan_list in misdn_call"); return -1;}
1595                 
1596                 newbc->capability=ast->transfercapability;
1597                 pbx_builtin_setvar_helper(ast,"TRANSFERCAPABILITY",ast_transfercapability2str(newbc->capability));
1598                 if ( ast->transfercapability == INFO_CAPABILITY_DIGITAL_UNRESTRICTED) {
1599                         chan_misdn_log(2, port, " --> * Call with flag Digital\n");
1600                 }
1601                 
1602
1603                 /* update screening and presentation */ 
1604                 update_config(ch,ORG_AST);
1605                 
1606                 /* fill in some ies from channel vary*/
1607                 import_ies(ast, newbc);
1608                 
1609                 /* Finally The Options Override Everything */
1610                 if (opts)
1611                         misdn_set_opt_exec(ast,opts);
1612                 else
1613                         chan_misdn_log(2,port,"NO OPTS GIVEN\n");
1614                 
1615                 
1616                 ch->state=MISDN_CALLING;
1617                 
1618                 r=misdn_lib_send_event( newbc, EVENT_SETUP );
1619                 
1620                 /** we should have l3id after sending setup **/
1621                 ch->l3id=newbc->l3_id;
1622         }
1623         
1624         if ( r == -ENOCHAN  ) {
1625                 chan_misdn_log(0, port, " --> * Theres no Channel at the moment .. !\n");
1626                 chan_misdn_log(1, port, " --> * SEND: State Down pid:%d\n",newbc?newbc->pid:-1);
1627                 ast->hangupcause=34;
1628                 ast_setstate(ast, AST_STATE_DOWN);
1629                 return -1;
1630         }
1631         
1632         chan_misdn_log(1, port, " --> * SEND: State Dialing pid:%d\n",newbc?newbc->pid:1);
1633
1634         ast_setstate(ast, AST_STATE_DIALING);
1635         ast->hangupcause=16;
1636         return 0; 
1637 }
1638
1639
1640 static int misdn_answer(struct ast_channel *ast)
1641 {
1642         struct chan_list *p;
1643
1644         
1645         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
1646         
1647         chan_misdn_log(1, p? (p->bc? p->bc->port : 0) : 0, "* ANSWER:\n");
1648         
1649         if (!p) {
1650                 ast_log(LOG_WARNING, " --> Channel not connected ??\n");
1651                 ast_queue_hangup(ast);
1652         }
1653
1654         if (!p->bc) {
1655                 chan_misdn_log(1, 0, " --> Got Answer, but theres no bc obj ??\n");
1656
1657                 ast_queue_hangup(ast);
1658         }
1659
1660         {
1661                 const char *tmp_key = pbx_builtin_getvar_helper(p->ast, "CRYPT_KEY");
1662                 
1663                 if (tmp_key ) {
1664                         chan_misdn_log(1, p->bc->port, " --> Connection will be BF crypted\n");
1665                         {
1666                                 int l = sizeof(p->bc->crypt_key);
1667                                 strncpy(p->bc->crypt_key,tmp_key, l);
1668                                 p->bc->crypt_key[l-1] = 0;
1669                         }
1670                 } else {
1671                         chan_misdn_log(3, p->bc->port, " --> Connection is without BF encryption\n");
1672                 }
1673     
1674         }
1675
1676         {
1677                 const char *nodsp=pbx_builtin_getvar_helper(ast, "MISDN_DIGITAL_TRANS");
1678                 if (nodsp) {
1679                         chan_misdn_log(1, p->bc->port, " --> Connection is transparent digital\n");
1680                         p->bc->nodsp=1;
1681                         p->bc->hdlc=0;
1682                         p->bc->nojitter=1;
1683                 }
1684         }
1685         
1686         p->state = MISDN_CONNECTED;
1687         misdn_lib_send_event( p->bc, EVENT_CONNECT);
1688         start_bc_tones(p);
1689         
1690         return 0;
1691 }
1692
1693 static int misdn_digit(struct ast_channel *ast, char digit )
1694 {
1695         struct chan_list *p;
1696         
1697         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) return -1;
1698
1699         struct misdn_bchannel *bc=p->bc;
1700         chan_misdn_log(1, bc?bc->port:0, "* IND : Digit %c\n",digit);
1701         
1702         if (!bc) {
1703                 ast_log(LOG_WARNING, " --> !! Got Digit Event withut having bchannel Object\n");
1704                 return -1;
1705         }
1706         
1707         switch (p->state ) {
1708                 case MISDN_CALLING:
1709                 {
1710                         
1711                         char buf[8];
1712                         buf[0]=digit;
1713                         buf[1]=0;
1714                         
1715                         int l = sizeof(bc->infos_pending);
1716                         strncat(bc->infos_pending,buf,l);
1717                         bc->infos_pending[l-1] = 0;
1718                 }
1719                 break;
1720                 case MISDN_CALLING_ACKNOWLEDGE:
1721                 {
1722                         bc->info_dad[0]=digit;
1723                         bc->info_dad[1]=0;
1724                         
1725                         {
1726                                 int l = sizeof(bc->dad);
1727                                 strncat(bc->dad,bc->info_dad, l - strlen(bc->dad));
1728                                 bc->dad[l-1] = 0;
1729                 }
1730                         {
1731                                 int l = sizeof(p->ast->exten);
1732                                 strncpy(p->ast->exten, bc->dad, l);
1733                                 p->ast->exten[l-1] = 0;
1734                         }
1735                         
1736                         misdn_lib_send_event( bc, EVENT_INFORMATION);
1737                 }
1738                 break;
1739                 
1740                 default:
1741                         if ( bc->send_dtmf ) {
1742                                 send_digit_to_chan(p,digit);
1743                         }
1744                 break;
1745         }
1746         
1747         return 0;
1748 }
1749
1750
1751 static int misdn_fixup(struct ast_channel *oldast, struct ast_channel *ast)
1752 {
1753         struct chan_list *p;
1754         
1755         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) )) return -1;
1756         
1757         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);
1758         
1759         p->ast = ast ;
1760         p->state=MISDN_CONNECTED;
1761   
1762         return 0;
1763 }
1764
1765
1766
1767 static int misdn_indication(struct ast_channel *ast, int cond)
1768 {
1769         struct chan_list *p;
1770
1771   
1772         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) {
1773                 ast_log(LOG_WARNING, "Returnded -1 in misdn_indication\n");
1774                 return -1;
1775         }
1776         
1777         if (!p->bc ) {
1778                 chan_misdn_log(1, 0, "* IND : Indication from %s\n",ast->exten);
1779                 ast_log(LOG_WARNING, "Private Pointer but no bc ?\n");
1780                 return -1;
1781         }
1782         
1783         chan_misdn_log(1, p->bc->port, "* IND : Indication [%d] from %s\n",cond, ast->exten);
1784         
1785         switch (cond) {
1786         case AST_CONTROL_BUSY:
1787                 chan_misdn_log(1, p->bc->port, "* IND :\tbusy\n");
1788                 chan_misdn_log(1, p->bc->port, " --> * SEND: State Busy pid:%d\n",p->bc?p->bc->pid:-1);
1789                 ast_setstate(ast,AST_STATE_BUSY);
1790                 
1791                 p->bc->out_cause=17;
1792                 if (p->state != MISDN_CONNECTED) {
1793                         misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
1794                         tone_indicate(p, TONE_BUSY);
1795                 } else {
1796
1797                         chan_misdn_log(-1, p->bc->port, " --> !! Got Busy in Connected State !?! ast:%s\n", ast->name);
1798                 }
1799                 break;
1800         case AST_CONTROL_RING:
1801                 chan_misdn_log(1, p->bc->port, " --> * IND :\tring pid:%d\n",p->bc?p->bc->pid:-1);
1802                 break;
1803         case AST_CONTROL_RINGING:
1804                 switch (p->state) {
1805                         case MISDN_ALERTING:
1806                                 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);
1807                                 break;
1808                         case MISDN_CONNECTED:
1809                                 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);
1810                                 tone_indicate(p, TONE_ALERTING);
1811                                 break;
1812                         default:
1813                                 p->state=MISDN_ALERTING;
1814                                 chan_misdn_log(1, p->bc->port, " --> * IND :\tringing pid:%d\n",p->bc?p->bc->pid:-1);
1815                                 misdn_lib_send_event( p->bc, EVENT_ALERTING);
1816                                 
1817                                 if ( !p->bc->nt && (p->orginator==ORG_MISDN) && !p->incoming_early_audio ) 
1818                                         chan_misdn_log(1,p->bc->port, " --> incoming_early_audio off\n");
1819                                  else 
1820                                          tone_indicate(p, TONE_ALERTING);
1821                                 chan_misdn_log(1, p->bc->port, " --> * SEND: State Ring pid:%d\n",p->bc?p->bc->pid:-1);
1822                                 ast_setstate(ast,AST_STATE_RINGING);
1823                 }
1824                 break;
1825         case AST_CONTROL_ANSWER:
1826                 chan_misdn_log(1, p->bc->port, " --> * IND :\tanswer pid:%d\n",p->bc?p->bc->pid:-1);
1827                 start_bc_tones(p);
1828                 break;
1829         case AST_CONTROL_TAKEOFFHOOK:
1830                 chan_misdn_log(1, p->bc->port, " --> *\ttakeoffhook pid:%d\n",p->bc?p->bc->pid:-1);
1831                 break;
1832         case AST_CONTROL_OFFHOOK:
1833                 chan_misdn_log(1, p->bc->port, " --> *\toffhook pid:%d\n",p->bc?p->bc->pid:-1);
1834                 break; 
1835         case AST_CONTROL_FLASH:
1836                 chan_misdn_log(1, p->bc->port, " --> *\tflash pid:%d\n",p->bc?p->bc->pid:-1);
1837                 break;
1838         case AST_CONTROL_PROGRESS:
1839                 chan_misdn_log(1, p->bc->port, " --> * IND :\tprogress pid:%d\n",p->bc?p->bc->pid:-1);
1840                 misdn_lib_send_event( p->bc, EVENT_PROGRESS);
1841                 break;
1842         case AST_CONTROL_PROCEEDING:
1843                 chan_misdn_log(1, p->bc->port, " --> * IND :\tproceeding pid:%d\n",p->bc?p->bc->pid:-1);
1844                 misdn_lib_send_event( p->bc, EVENT_PROCEEDING);
1845                 break;
1846         case AST_CONTROL_CONGESTION:
1847                 chan_misdn_log(1, p->bc->port, " --> * IND :\tcongestion pid:%d\n",p->bc?p->bc->pid:-1);
1848
1849                 p->bc->out_cause=42;
1850                 if (p->state != MISDN_CONNECTED) {
1851                         start_bc_tones(p);
1852                         misdn_lib_send_event( p->bc, EVENT_RELEASE);
1853                 } else {
1854                         misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
1855                 }
1856
1857                 if (p->bc->nt) {
1858                         tone_indicate(p, TONE_BUSY);
1859                 }
1860                 break;
1861         case -1 :
1862                 chan_misdn_log(1, p->bc->port, " --> * IND :\t-1! (stop indication) pid:%d\n",p->bc?p->bc->pid:-1);
1863                 
1864                 if (p->state == MISDN_CONNECTED)
1865                         start_bc_tones(p);
1866                 else 
1867                         tone_indicate(p, TONE_NONE);
1868                 break;
1869
1870         case AST_CONTROL_HOLD:
1871                 chan_misdn_log(1, p->bc->port, " --> *\tHOLD pid:%d\n",p->bc?p->bc->pid:-1);
1872                 break;
1873         case AST_CONTROL_UNHOLD:
1874                 chan_misdn_log(1, p->bc->port, " --> *\tUNHOLD pid:%d\n",p->bc?p->bc->pid:-1);
1875                 break;
1876         default:
1877                 ast_log(LOG_WARNING, " --> * Unknown Indication:%d pid:%d\n",cond,p->bc?p->bc->pid:-1);
1878         }
1879   
1880         return 0;
1881 }
1882
1883 static int misdn_hangup(struct ast_channel *ast)
1884 {
1885         struct chan_list *p;
1886         struct misdn_bchannel *bc=NULL;
1887         
1888         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) ) ) return -1;
1889         
1890         release_lock;
1891
1892         
1893         ast_log(LOG_DEBUG, "misdn_hangup(%s)\n", ast->name);
1894         
1895         if (!p) {
1896                 chan_misdn_log(3, 0, "misdn_hangup called, without chan_list obj.\n");
1897                 release_unlock;
1898                 return 0 ;
1899         }
1900         
1901         bc=p->bc;
1902
1903         if (!bc) {
1904                 release_unlock;
1905                 ast_log(LOG_WARNING,"Hangup with private but no bc ?\n");
1906                 return 0;
1907         }
1908
1909         
1910         MISDN_ASTERISK_TECH_PVT(ast)=NULL;
1911         p->ast=NULL;
1912
1913         bc=p->bc;
1914         
1915         if (ast->_state == AST_STATE_RESERVED) {
1916                 /* between request and call */
1917                 MISDN_ASTERISK_TECH_PVT(ast)=NULL;
1918                 release_unlock;
1919                 
1920                 cl_dequeue_chan(&cl_te, p);
1921                 free(p);
1922                 
1923                 if (bc)
1924                         misdn_lib_release(bc);
1925                 
1926                 return 0;
1927         }
1928
1929         stop_bc_tones(p);
1930         
1931         release_unlock;
1932         
1933         
1934         {
1935                 const char *varcause=NULL;
1936                 bc->cause=ast->hangupcause?ast->hangupcause:16;
1937                 
1938                 if ( (varcause=pbx_builtin_getvar_helper(ast, "HANGUPCAUSE")) ||
1939                      (varcause=pbx_builtin_getvar_helper(ast, "PRI_CAUSE"))) {
1940                         int tmpcause=atoi(varcause);
1941                         bc->out_cause=tmpcause?tmpcause:16;
1942                 }
1943     
1944                 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));
1945                 chan_misdn_log(2, bc->port, " --> l3id:%x\n",p->l3id);
1946                 chan_misdn_log(1, bc->port, " --> cause:%d\n",bc->cause);
1947                 chan_misdn_log(1, bc->port, " --> out_cause:%d\n",bc->out_cause);
1948                 
1949                 switch (p->state) {
1950                 case MISDN_CALLING:
1951                         p->state=MISDN_CLEANING;
1952                         misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
1953                         break;
1954                 case MISDN_HOLDED:
1955                 case MISDN_DIALING:
1956                         start_bc_tones(p);
1957                         tone_indicate(p, TONE_BUSY);
1958                         p->state=MISDN_CLEANING;
1959                         
1960                         misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
1961       
1962                         break;
1963       
1964                 case MISDN_ALERTING:
1965                 case MISDN_PROGRESS:
1966                 case MISDN_PROCEEDING:
1967                         chan_misdn_log(2, bc->port, " --> * State Alerting\n");
1968
1969                         if (p->orginator != ORG_AST) 
1970                                 tone_indicate(p, TONE_BUSY);
1971       
1972                         p->state=MISDN_CLEANING;
1973                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
1974                         break;
1975                 case MISDN_CONNECTED:
1976                         /*  Alerting or Disconect */
1977                         chan_misdn_log(2, bc->port, " --> * State Connected\n");
1978                         start_bc_tones(p);
1979                         tone_indicate(p, TONE_BUSY);
1980                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
1981       
1982                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
1983                         break;
1984                 case MISDN_DISCONNECTED:
1985                         chan_misdn_log(2, bc->port, " --> * State Disconnected\n");
1986                         misdn_lib_send_event( bc, EVENT_RELEASE);
1987                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
1988                         break;
1989
1990                 case MISDN_CLEANING:
1991                         break;
1992       
1993                 case MISDN_HOLD_DISCONNECT:
1994                         /* need to send release here */
1995                         chan_misdn_log(2, bc->port, " --> state HOLD_DISC\n");
1996                         chan_misdn_log(1, bc->port, " --> cause %d\n",bc->cause);
1997                         chan_misdn_log(1, bc->port, " --> out_cause %d\n",bc->out_cause);
1998                         
1999                         bc->out_cause=-1;
2000                         misdn_lib_send_event(bc,EVENT_RELEASE);
2001                         break;
2002                 default:
2003                         /*  Alerting or Disconect */
2004
2005                         if (bc->nt) {
2006                                 bc->out_cause=-1;
2007                                 misdn_lib_send_event(bc, EVENT_RELEASE);
2008                         } else
2009                                 misdn_lib_send_event(bc, EVENT_DISCONNECT);
2010                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2011                 }
2012     
2013         }
2014         
2015         chan_misdn_log(1, bc->port, "Channel: %s hanguped\n",ast->name);
2016         
2017         return 0;
2018 }
2019
2020 static struct ast_frame  *misdn_read(struct ast_channel *ast)
2021 {
2022         struct chan_list *tmp;
2023         
2024         char blah[255];
2025         int len =0 ;
2026         
2027         if (!ast) return NULL;
2028         if (! (tmp=MISDN_ASTERISK_TECH_PVT(ast)) ) return NULL;
2029         if (!tmp->bc) return NULL;
2030         
2031         
2032         read(tmp->pipe[0],blah,sizeof(blah));
2033         
2034         
2035         len = misdn_ibuf_usedcount(tmp->bc->astbuf);
2036
2037         if (!len) {
2038                 chan_misdn_log(4,tmp->bc->port,"misdn_read: ZERO READ\n");
2039
2040                 tmp->frame.frametype = AST_FRAME_NULL;
2041                 tmp->frame.subclass = 0;
2042                 return &tmp->frame;
2043         }
2044
2045         /*shrinken len if necessary, we transmit at maximum 4k*/
2046         len = len<=sizeof(tmp->ast_rd_buf)?len:sizeof(tmp->ast_rd_buf);
2047         
2048         misdn_ibuf_memcpy_r(tmp->ast_rd_buf, tmp->bc->astbuf,len);
2049         
2050         tmp->frame.frametype  = AST_FRAME_VOICE;
2051         tmp->frame.subclass = AST_FORMAT_ALAW;
2052         tmp->frame.datalen = len;
2053         tmp->frame.samples = len ;
2054         tmp->frame.mallocd =0 ;
2055         tmp->frame.offset= 0 ;
2056         tmp->frame.src = NULL;
2057         tmp->frame.data = tmp->ast_rd_buf ;
2058
2059         return &tmp->frame;
2060 }
2061
2062
2063
2064
2065 static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
2066 {
2067         struct chan_list *ch;
2068         int i  = 0;
2069         
2070         if (!ast || ! (ch=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
2071         
2072         if (!ch->bc ) {
2073                 ast_log(LOG_WARNING, "private but no bc\n");
2074                 return -1;
2075         }
2076         
2077         /*if (ch->bc->tone != TONE_NONE)
2078           tone_indicate(ch,TONE_NONE); */
2079         
2080         
2081         if (ch->holded ) {
2082                 chan_misdn_log(5, ch->bc->port, "misdn_write: Returning because holded\n");
2083                 return 0;
2084         }
2085         
2086         if (ch->notxtone) {
2087                 chan_misdn_log(5, ch->bc->port, "misdn_write: Returning because notxone\n");
2088                 return 0;
2089         }
2090
2091
2092         if ( !frame->subclass) {
2093                 chan_misdn_log(4, ch->bc->port, "misdn_write: * prods us\n");
2094                 return 0;
2095         }
2096         
2097         if ( !(frame->subclass & prefformat)) {
2098                 
2099                 chan_misdn_log(-1, ch->bc->port, "Got Unsupported Frame with Format:%d\n", frame->subclass);
2100                 return -1;
2101         }
2102         
2103
2104         if ( !frame->samples ) {
2105                 chan_misdn_log(4, ch->bc->port, "misdn_write: zero write\n");
2106                 return 0;
2107         }
2108
2109         if ( ! ch->bc->addr ) {
2110                 chan_misdn_log(4, ch->bc->port, "misdn_write: no addr for bc dropping:%d\n", frame->samples);
2111                 return 0;
2112         }
2113         
2114 #if MISDN_DEBUG
2115         {
2116                 int i, max=5>frame->samples?frame->samples:5;
2117                 
2118                 printf("write2mISDN %p %d bytes: ", p, frame->samples);
2119                 
2120                 for (i=0; i<  max ; i++) printf("%2.2x ",((char*) frame->data)[i]);
2121                 printf ("\n");
2122         }
2123 #endif
2124
2125
2126         switch (ch->bc->bc_state) {
2127                 case BCHAN_ACTIVATED:
2128                 case BCHAN_BRIDGED:
2129                         break;
2130                 default:
2131                 chan_misdn_log(5, ch->bc->port, "BC not active (nor bridged) droping: %d frames addr:%x\n",frame->samples,ch->bc->addr);
2132                 return 0;
2133         }
2134         
2135         chan_misdn_log(9, ch->bc->port, "Sending :%d bytes 2 MISDN\n",frame->samples);
2136         /*if speech flip bits*/
2137         if ( misdn_cap_is_speech(ch->bc->capability) )
2138                 flip_buf_bits(frame->data,frame->samples);
2139         
2140         
2141         if ( !ch->bc->nojitter && misdn_cap_is_speech(ch->bc->capability) ) {
2142                 /* Buffered Transmit (triggert by read from isdn side)*/
2143                 if (misdn_jb_fill(ch->jb,frame->data,frame->samples) < 0) {
2144                         if (ch->bc->active)
2145                                 cb_log(0,ch->bc->port,"Misdn Jitterbuffer Overflow.\n");
2146                 }
2147                 
2148         } else {
2149                 /*transmit without jitterbuffer*/
2150                 i=misdn_lib_tx2misdn_frm(ch->bc, frame->data, frame->samples);
2151         }
2152
2153         
2154         
2155         return 0;
2156 }
2157
2158
2159
2160
2161 enum ast_bridge_result  misdn_bridge (struct ast_channel *c0,
2162                                       struct ast_channel *c1, int flags,
2163                                       struct ast_frame **fo,
2164                                       struct ast_channel **rc,
2165                                       int timeoutms)
2166
2167 {
2168         struct chan_list *ch1,*ch2;
2169         struct ast_channel *carr[2], *who;
2170         int to=-1;
2171         struct ast_frame *f;
2172   
2173         ch1=get_chan_by_ast(c0);
2174         ch2=get_chan_by_ast(c1);
2175
2176         carr[0]=c0;
2177         carr[1]=c1;
2178   
2179   
2180         if (ch1 && ch2 ) ;
2181         else
2182                 return -1;
2183   
2184
2185         int bridging;
2186         misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
2187         if (bridging) {
2188                 int ecwb;
2189                 misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2190                 if ( !ecwb ) {
2191                         chan_misdn_log(2, ch1->bc->port, "Disabling Echo Cancellor when Bridged\n");
2192                         ch1->bc->ec_enable=0;
2193                 /*      manager_ec_disable(ch1->bc); */
2194                 }
2195                 misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2196                 if ( !ecwb ) {
2197                         chan_misdn_log(2, ch2->bc->port, "Disabling Echo Cancellor when Bridged\n");
2198                         ch2->bc->ec_enable=0;
2199                 /*      manager_ec_disable(ch2->bc); */
2200                 }
2201                 
2202                 /* trying to make a mISDN_dsp conference */
2203                 chan_misdn_log(1, ch1->bc->port, "I SEND: Making conference with Number:%d\n", (ch1->bc->pid<<1) +1);
2204
2205                 misdn_lib_bridge(ch1->bc,ch2->bc);
2206         }
2207         
2208         if (option_verbose > 2) 
2209                 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
2210
2211         chan_misdn_log(1, ch1->bc->port, "* Makeing Native Bridge between %s and %s\n", ch1->bc->oad, ch2->bc->oad);
2212   
2213         while(1) {
2214                 to=-1;
2215                 who = ast_waitfor_n(carr, 2, &to);
2216
2217                 if (!who) {
2218                         ast_log(LOG_DEBUG,"misdn_bridge: empty read\n");
2219                         continue;
2220                 }
2221                 f = ast_read(who);
2222     
2223                 if (!f || f->frametype == AST_FRAME_CONTROL) {
2224                         /* got hangup .. */
2225                         *fo=f;
2226                         *rc=who;
2227       
2228                         break;
2229                 }
2230     
2231     
2232                 if (who == c0) {
2233                         ast_write(c1,f);
2234                 }
2235                 else {
2236                         ast_write(c0,f);
2237                 }
2238     
2239         }
2240   
2241         if (bridging) {
2242                 misdn_lib_split_bridge(ch1->bc,ch2->bc);
2243         }
2244   
2245         return 0;
2246 }
2247
2248 /** AST INDICATIONS END **/
2249
2250 static int tone_indicate( struct chan_list *cl, enum tone_e tone)
2251 {
2252         const struct tone_zone_sound *ts= NULL;
2253         struct ast_channel *ast=cl->ast;
2254         
2255         chan_misdn_log(2,cl->bc->port,"Tone Indicate:\n");
2256         
2257         if (!cl->ast) {
2258                 return 0;
2259         }
2260         
2261         switch (tone) {
2262         case TONE_DIAL:
2263                 chan_misdn_log(2,cl->bc->port," --> Dial\n");
2264                 ts=ast_get_indication_tone(ast->zone,"dial");
2265                 misdn_lib_tone_generator_start(cl->bc);
2266                 break;
2267         case TONE_ALERTING:
2268                 chan_misdn_log(2,cl->bc->port," --> Ring\n");
2269                 ts=ast_get_indication_tone(ast->zone,"ring");
2270                 misdn_lib_tone_generator_stop(cl->bc);
2271                 break;
2272         case TONE_BUSY:
2273                 chan_misdn_log(2,cl->bc->port," --> Busy\n");
2274                 ts=ast_get_indication_tone(ast->zone,"busy");
2275                 misdn_lib_tone_generator_stop(cl->bc);
2276                 break;
2277         case TONE_FILE:
2278                 break;
2279
2280         case TONE_NONE:
2281                 chan_misdn_log(2,cl->bc->port," --> None\n");
2282                 misdn_lib_tone_generator_stop(cl->bc);
2283                 ast_playtones_stop(ast);
2284                 break;
2285         default:
2286                 chan_misdn_log(0,cl->bc->port,"Don't know how to handle tone: %d\n",tone);
2287         }
2288         
2289         cl->ts=ts;      
2290         
2291         if (ts) ast_playtones_start(ast,0, ts->data, 0);
2292         
2293         return 0;
2294 }
2295
2296 static int start_bc_tones(struct chan_list* cl)
2297 {
2298         manager_bchannel_activate(cl->bc);
2299         misdn_lib_tone_generator_stop(cl->bc);
2300         cl->notxtone=0;
2301         cl->norxtone=0;
2302         return 0;
2303 }
2304
2305 static int stop_bc_tones(struct chan_list *cl)
2306 {
2307         if (cl->bc) {
2308                 manager_bchannel_deactivate(cl->bc);
2309         }
2310         cl->notxtone=1;
2311         cl->norxtone=1;
2312         
2313         return 0;
2314 }
2315
2316
2317 static struct chan_list *init_chan_list(void)
2318 {
2319         struct chan_list *cl=malloc(sizeof(struct chan_list));
2320         
2321         if (!cl) {
2322                 chan_misdn_log(-1, 0, "misdn_request: malloc failed!");
2323                 return NULL;
2324         }
2325         
2326         memset(cl,0,sizeof(struct chan_list));
2327         
2328         return cl;
2329         
2330 }
2331
2332 static struct ast_channel *misdn_request(const char *type, int format, void *data, int *cause)
2333
2334 {
2335         struct ast_channel *tmp = NULL;
2336         char group[BUFFERSIZE+1]="";
2337         char buf[128];
2338         char buf2[128], *ext=NULL, *port_str;
2339         char *tokb=NULL, *p=NULL;
2340         int channel=0, port=0;
2341         struct misdn_bchannel *newbc = NULL;
2342         
2343         struct chan_list *cl=init_chan_list();
2344         
2345         sprintf(buf,"%s/%s",misdn_type,(char*)data);
2346         ast_copy_string(buf2,data, 128);
2347         
2348         port_str=strtok_r(buf2,"/", &tokb);
2349
2350         ext=strtok_r(NULL,"/", &tokb);
2351
2352         if (port_str) {
2353                 if (port_str[0]=='g' && port_str[1]==':' ) {
2354                         /* We make a group call lets checkout which ports are in my group */
2355                         port_str += 2;
2356                         strncpy(group, port_str, BUFFERSIZE);
2357                         group[127] = 0;
2358                         chan_misdn_log(2, 0, " --> Group Call group: %s\n",group);
2359                 } 
2360                 else if ((p = strchr(port_str, ':'))) {
2361                         // we have a preselected channel
2362                         *p = 0;
2363                         channel = atoi(++p);
2364                         port = atoi(port_str);
2365                         chan_misdn_log(2, port, " --> Call on preselected Channel (%d).\n", channel);
2366                 }
2367                 else {
2368                         port = atoi(port_str);
2369                 }
2370                 
2371                 
2372         } else {
2373                 ast_log(LOG_WARNING, " --> ! IND : CALL dad:%s WITHOUT PORT/Group, check extension.conf\n",ext);
2374                 return NULL;
2375         }
2376
2377         if (!ast_strlen_zero(group)) {
2378         
2379                 char cfg_group[BUFFERSIZE+1];
2380                 struct robin_list *rr = NULL;
2381
2382                 if (misdn_cfg_is_group_method(group, METHOD_ROUND_ROBIN)) {
2383                         chan_misdn_log(4, port, " --> STARTING ROUND ROBIN...");
2384                         rr = get_robin_position(group);
2385                 }
2386                 
2387                 if (rr) {
2388                         int robin_channel = rr->channel;
2389                         int port_start;
2390                         int next_chan = 1;
2391
2392                         do {
2393                                 port_start = 0;
2394                                 for (port = misdn_cfg_get_next_port_spin(rr->port); port > 0 && port != port_start;
2395                                          port = misdn_cfg_get_next_port_spin(port)) {
2396
2397                                         if (!port_start)
2398                                                 port_start = port;
2399
2400                                         if (port >= port_start)
2401                                                 next_chan = 1;
2402                                         
2403                                         if (port < port_start && next_chan) {
2404                                                 if (++robin_channel >= MAX_BCHANS) {
2405                                                         robin_channel = 1;
2406                                                 }
2407                                                 next_chan = 0;
2408                                         }
2409
2410                                         misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2411                                         
2412                                         if (!strcasecmp(cfg_group, group)) {
2413                                                 int port_up;
2414                                                 int check;
2415                                                 misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
2416                                                 port_up = misdn_lib_port_up(port, check);
2417                                                 
2418                                                 if ( port_up )  {
2419                                                         newbc = misdn_lib_get_free_bc(port, robin_channel);
2420                                                         if (newbc) {
2421                                                                 chan_misdn_log(4, port, " Success! Found port:%d channel:%d\n", newbc->port, newbc->channel);
2422                                                                 if (port_up)
2423                                                                         chan_misdn_log(4, port, "ortup:%d\n",  port_up);
2424                                                                 rr->port = newbc->port;
2425                                                                 rr->channel = newbc->channel;
2426                                                                 break;
2427                                                         }
2428                                                 }
2429                                         }
2430                                 }
2431                         } while (!newbc && robin_channel != rr->channel);
2432                         
2433                         if (!newbc)
2434                                 chan_misdn_log(4, port, " Failed! No free channel in group %d!", group);
2435                 }
2436                 
2437                 else {          
2438                         for (port=misdn_cfg_get_next_port(0); port > 0;
2439                                  port=misdn_cfg_get_next_port(port)) {
2440                                 
2441                                 misdn_cfg_get( port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2442
2443                                 chan_misdn_log(3,port, "Group [%s] Port [%d]\n", group, port);
2444                                 if (!strcasecmp(cfg_group, group)) {
2445                                         int port_up;
2446                                         int check;
2447                                         misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
2448                                         port_up = misdn_lib_port_up(port, check);
2449                                         
2450                                         chan_misdn_log(4, port, "portup:%d\n", port_up);
2451                                         
2452                                         if ( port_up )  {
2453                                                 newbc = misdn_lib_get_free_bc(port, 0);
2454                                                 if (newbc)
2455                                                         break;
2456                                         }
2457                                 }
2458                         }
2459                 }
2460                 
2461         } else {
2462                 if (channel)
2463                         chan_misdn_log(1, port," --> preselected_channel: %d\n",channel);
2464                 newbc = misdn_lib_get_free_bc(port, channel);
2465         }
2466         
2467         if (!newbc) {
2468                 chan_misdn_log(-1, 0, " --> ! No free channel chan ext:%s even after Group Call\n",ext);
2469                 chan_misdn_log(-1, 0, " --> SEND: State Down\n");
2470                 return NULL;
2471         }
2472
2473         /* create ast_channel and link all the objects together */
2474         cl->bc=newbc;
2475         
2476         tmp = misdn_new(cl, AST_STATE_RESERVED, ext, NULL, format, port, channel);
2477         cl->ast=tmp;
2478         
2479         /* register chan in local list */
2480         cl_queue_chan(&cl_te, cl) ;
2481         
2482         /* fill in the config into the objects */
2483         read_config(cl, ORG_AST);
2484         
2485         
2486         return tmp;
2487 }
2488
2489
2490 int misdn_send_text (struct ast_channel *chan, const char *text)
2491 {
2492         struct chan_list *tmp=chan->tech_pvt;
2493         
2494         if (tmp && tmp->bc) {
2495                 ast_copy_string(tmp->bc->display,text,sizeof(tmp->bc->display));
2496                 misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
2497         } else {
2498                 ast_log(LOG_WARNING, "No chan_list but send_text request?\n");
2499                 return -1;
2500         }
2501         
2502         return 0;
2503 }
2504
2505 static struct ast_channel_tech misdn_tech = {
2506         .type="mISDN",
2507         .description="Channel driver for mISDN Support (Bri/Pri)",
2508         .capabilities= AST_FORMAT_ALAW ,
2509         .requester=misdn_request,
2510         .send_digit=misdn_digit,
2511         .call=misdn_call,
2512         .bridge=misdn_bridge, 
2513         .hangup=misdn_hangup,
2514         .answer=misdn_answer,
2515         .read=misdn_read,
2516         .write=misdn_write,
2517         .indicate=misdn_indication,
2518         .fixup=misdn_fixup,
2519         .send_text=misdn_send_text,
2520         .properties=0
2521 };
2522
2523 static struct ast_channel_tech misdn_tech_wo_bridge = {
2524         .type="mISDN",
2525         .description="Channel driver for mISDN Support (Bri/Pri)",
2526         .capabilities=AST_FORMAT_ALAW ,
2527         .requester=misdn_request,
2528         .send_digit=misdn_digit,
2529         .call=misdn_call,
2530         .hangup=misdn_hangup,
2531         .answer=misdn_answer,
2532         .read=misdn_read,
2533         .write=misdn_write,
2534         .indicate=misdn_indication,
2535         .fixup=misdn_fixup,
2536         .send_text=misdn_send_text,
2537         .properties=0
2538 };
2539
2540
2541 static unsigned long glob_channel=0;
2542
2543 static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char *exten, char *callerid, int format, int port, int c)
2544 {
2545         struct ast_channel *tmp;
2546         
2547         tmp = ast_channel_alloc(1);
2548         
2549         if (tmp) {
2550                 chan_misdn_log(2, 0, " --> * NEW CHANNEL dad:%s oad:%s\n",exten,callerid);
2551                 
2552                 
2553                 if (c<=0) {
2554                         c=glob_channel++;
2555                         ast_string_field_build(tmp, name, "%s/%d-u%d",
2556                                  misdn_type, port, c);
2557                 } else {
2558                         ast_string_field_build(tmp, name, "%s/%d-%d",
2559                                  misdn_type, port, c);
2560                 }
2561                 
2562                 tmp->nativeformats = prefformat;
2563
2564                 tmp->readformat = format;
2565                 tmp->writeformat = format;
2566     
2567                 tmp->tech_pvt = chlist;
2568                 
2569                 int bridging;
2570                 misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
2571                 if (bridging)
2572                         tmp->tech = &misdn_tech;
2573                 else
2574                         tmp->tech = &misdn_tech_wo_bridge;
2575                 
2576                 tmp->writeformat = format;
2577                 tmp->readformat = format;
2578                 tmp->priority=1;
2579                 
2580                 if (exten) 
2581                         ast_copy_string(tmp->exten, exten,  sizeof(tmp->exten));
2582                 else
2583                         chan_misdn_log(1,0,"misdn_new: no exten given.\n");
2584                 
2585                 if (callerid) {
2586                         char *cid_name, *cid_num;
2587       
2588                         ast_callerid_parse(callerid, &cid_name, &cid_num);
2589                         if (cid_name)
2590                                 tmp->cid.cid_name=strdup(cid_name);
2591                         if (cid_num)
2592                                 tmp->cid.cid_num=strdup(cid_num);
2593                 }
2594
2595                 {
2596                         if (pipe(chlist->pipe)<0)
2597                                 perror("Pipe failed\n");
2598                         
2599                         tmp->fds[0]=chlist->pipe[0];
2600                         
2601                 }
2602                 
2603                 ast_setstate(tmp, state);
2604                 if (state == AST_STATE_RING)
2605                         tmp->rings = 1;
2606                 else
2607                         tmp->rings = 0;
2608                 
2609                 
2610         } else {
2611                 chan_misdn_log(-1,0,"Unable to allocate channel structure\n");
2612         }
2613         
2614         return tmp;
2615 }
2616
2617
2618
2619 static int misdn_tx2ast_frm(struct chan_list * tmp, char * buf,  int len )
2620 {
2621         struct ast_frame frame;
2622
2623         /* If in hold state we drop frame .. */
2624         if (tmp->holded ) return 0;
2625         
2626         switch(tmp->state) {
2627         case MISDN_CLEANING:
2628         case MISDN_EXTCANTMATCH:
2629                 return 0;
2630                 
2631         case MISDN_WAITING4DIGS:
2632         default:
2633                 break;
2634         }
2635         
2636         if (tmp->norxtone) {
2637                 chan_misdn_log(3, tmp->bc->port, "misdn_tx2ast_frm: Returning because norxtone\n");
2638                 return 0;
2639         }
2640         
2641         frame.frametype  = AST_FRAME_VOICE;
2642         frame.subclass = AST_FORMAT_ALAW;
2643         frame.datalen = len;
2644         frame.samples = len ;
2645         frame.mallocd =0 ;
2646         frame.offset= 0 ;
2647         frame.src = NULL;
2648         frame.data = buf ;
2649         
2650         if (tmp->faxdetect || tmp->ast_dsp ) {
2651                 struct ast_frame *f,*f2;
2652                 if (tmp->trans)
2653                         f2=ast_translate(tmp->trans, &frame,0);
2654                 else {
2655                         chan_misdn_log(0, tmp->bc->port, "No T-Path found\n");
2656                         return 0;
2657                 }
2658                 
2659                 f = ast_dsp_process(tmp->ast, tmp->dsp, f2);
2660                 if (f && (f->frametype == AST_FRAME_DTMF)) {
2661                         ast_log(LOG_DEBUG, "Detected inband DTMF digit: %c", f->subclass);
2662                         if (f->subclass == 'f' && tmp->faxdetect) {
2663                                 /* Fax tone -- Handle and return NULL */
2664                                 struct ast_channel *ast = tmp->ast;
2665                                 if (!tmp->faxhandled) {
2666                                         tmp->faxhandled++;
2667                                         if (strcmp(ast->exten, "fax")) {
2668                                                 if (ast_exists_extension(ast, S_OR(ast->macrocontext, ast->context), "fax", 1, AST_CID_P(ast))) {
2669                                                         if (option_verbose > 2)
2670                                                                 ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension\n", ast->name);
2671                                                         /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
2672                                                         pbx_builtin_setvar_helper(ast,"FAXEXTEN",ast->exten);
2673                                                         if (ast_async_goto(ast, ast->context, "fax", 1))
2674                                                                 ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, ast->context);
2675                                                 } else
2676                                                         ast_log(LOG_NOTICE, "Fax detected, but no fax extension ctx:%s exten:%s\n",ast->context, ast->exten);
2677                                         } else
2678                                                 ast_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
2679                                 } else
2680                                         ast_log(LOG_DEBUG, "Fax already handled\n");
2681                                 frame.frametype = AST_FRAME_NULL;
2682                                 frame.subclass = 0;
2683                                 f = &frame;
2684                         }  else if ( tmp->ast_dsp) {
2685                                 struct ast_frame fr;
2686                                 memset(&fr, 0 , sizeof(fr));
2687                                 fr.frametype = AST_FRAME_DTMF;
2688                                 fr.subclass = f->subclass ;
2689                                 fr.src=NULL;
2690                                 fr.data = NULL ;
2691                                 fr.datalen = 0;
2692                                 fr.samples = 0 ;
2693                                 fr.mallocd =0 ;
2694                                 fr.offset= 0 ;
2695                                 
2696                                 chan_misdn_log(2, tmp->bc->port, " --> * SEND: DTMF (AST_DSP) :%c\n",f->subclass);
2697                                 ast_queue_frame(tmp->ast, &fr);
2698                                 
2699                                 frame.frametype = AST_FRAME_NULL;
2700                                 frame.subclass = 0;
2701                                 f = &frame;
2702                         }
2703                 }
2704         }
2705         
2706         if (tmp && tmp->ast && MISDN_ASTERISK_PVT (tmp->ast) && MISDN_ASTERISK_TECH_PVT(tmp->ast) ) {
2707 #if MISDN_DEBUG
2708                 int i, max=5>len?len:5;
2709     
2710                 printf("write2* %p %d bytes: ",tmp, len);
2711     
2712                 for (i=0; i<  max ; i++) printf("%2.2x ",((char*) frame.data)[i]);
2713                 printf ("\n");
2714 #endif
2715                 chan_misdn_log(9, tmp->bc->port, "Queueing %d bytes 2 Asterisk\n",len);
2716                 ast_queue_frame(tmp->ast,&frame);
2717
2718         }  else {
2719                 ast_log (LOG_WARNING, "No ast || ast->pvt || ch\n");
2720         }
2721         
2722         return 0;
2723 }
2724
2725 /** Channel Queue ***/
2726
2727 static struct chan_list *find_chan_by_l3id(struct chan_list *list, unsigned long l3id)
2728 {
2729         struct chan_list *help=list;
2730         for (;help; help=help->next) {
2731                 if (help->l3id == l3id ) return help;
2732         }
2733   
2734         chan_misdn_log(6, list? (list->bc? list->bc->port : 0) : 0, "$$$ find_chan: No channel found with l3id:%x\n",l3id);
2735   
2736         return NULL;
2737 }
2738
2739 static struct chan_list *find_chan_by_bc(struct chan_list *list, struct misdn_bchannel *bc)
2740 {
2741         struct chan_list *help=list;
2742         for (;help; help=help->next) {
2743                 if (help->bc == bc) return help;
2744         }
2745   
2746         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
2747   
2748         return NULL;
2749 }
2750
2751
2752 static struct chan_list *find_holded(struct chan_list *list, struct misdn_bchannel *bc)
2753 {
2754         struct chan_list *help=list;
2755         
2756         chan_misdn_log(6, bc->port, "$$$ find_holded: channel:%d oad:%s dad:%s\n",bc->channel, bc->oad,bc->dad);
2757         for (;help; help=help->next) {
2758                 chan_misdn_log(4, bc->port, "$$$ find_holded: --> holded:%d channel:%d\n",help->bc->holded, help->bc->channel);
2759                 if (help->bc->port == bc->port
2760                     && help->bc->holded ) return help;
2761         }
2762         
2763         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
2764   
2765         return NULL;
2766 }
2767
2768 static void cl_queue_chan(struct chan_list **list, struct chan_list *chan)
2769 {
2770         chan_misdn_log(4, chan->bc? chan->bc->port : 0, "* Queuing chan %p\n",chan);
2771   
2772         ast_mutex_lock(&cl_te_lock);
2773         if (!*list) {
2774                 *list = chan;
2775         } else {
2776                 struct chan_list *help=*list;
2777                 for (;help->next; help=help->next); 
2778                 help->next=chan;
2779         }
2780         chan->next=NULL;
2781         ast_mutex_unlock(&cl_te_lock);
2782 }
2783
2784 static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan) 
2785 {
2786         if (chan->dsp) 
2787                 ast_dsp_free(chan->dsp);
2788         if (chan->trans)
2789                 ast_translator_free_path(chan->trans);
2790
2791         
2792
2793         ast_mutex_lock(&cl_te_lock);
2794         if (!*list) {
2795                 ast_mutex_unlock(&cl_te_lock);
2796                 return;
2797         }
2798   
2799         if (*list == chan) {
2800                 *list=(*list)->next;
2801                 ast_mutex_unlock(&cl_te_lock);
2802                 return ;
2803         }
2804   
2805         {
2806                 struct chan_list *help=*list;
2807                 for (;help->next; help=help->next) {
2808                         if (help->next == chan) {
2809                                 help->next=help->next->next;
2810                                 ast_mutex_unlock(&cl_te_lock);
2811                                 return;
2812                         }
2813                 }
2814         }
2815         
2816         ast_mutex_unlock(&cl_te_lock);
2817 }
2818
2819 /** Channel Queue End **/
2820
2821
2822
2823 /** Isdn asks us to release channel, pendant to misdn_hangup **/
2824 static void release_chan(struct misdn_bchannel *bc) {
2825         struct ast_channel *ast=NULL;
2826         
2827         {
2828                 struct chan_list *ch=find_chan_by_bc(cl_te, bc);
2829                 if (!ch) ch=find_chan_by_l3id (cl_te, bc->l3_id);
2830                 if (!ch)  {
2831                         chan_misdn_log(0, bc->port, "release_chan: Ch not found!\n");
2832                         return;
2833                 }
2834                 
2835                 release_lock;
2836                 if (ch->ast) {
2837                         ast=ch->ast;
2838                 } 
2839                 release_unlock;
2840                 
2841                 chan_misdn_log(1, bc->port, "Trying to Release bc with l3id: %x\n",bc->l3_id);
2842
2843                 //releaseing jitterbuffer
2844                 if (ch->jb ) {
2845                         misdn_jb_destroy(ch->jb);
2846                         ch->jb=NULL;
2847                 } else {
2848                         if (!bc->nojitter)
2849                                 chan_misdn_log(5,bc->port,"Jitterbuffer already destroyed.\n");
2850                 }
2851                 
2852                 if (ch) {
2853                         
2854                         close(ch->pipe[0]);
2855                         close(ch->pipe[1]);
2856                         
2857                         if (ast && MISDN_ASTERISK_PVT(ast)) {
2858                                 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));
2859                                 chan_misdn_log(3, bc->port, " --> * State Down\n");
2860                                 /* copy cause */
2861                                 send_cause2ast(ast,bc);
2862                                 
2863                                 MISDN_ASTERISK_TECH_PVT(ast)=NULL;
2864                                 
2865       
2866                                 if (ast->_state != AST_STATE_RESERVED) {
2867                                         chan_misdn_log(3, bc->port, " --> Setting AST State to down\n");
2868                                         ast_setstate(ast, AST_STATE_DOWN);
2869                                 }
2870                                 
2871                                 switch(ch->state) {
2872                                 case MISDN_EXTCANTMATCH:
2873                                 case MISDN_WAITING4DIGS:
2874                                 {
2875                                         chan_misdn_log(3,  bc->port, " --> * State Wait4dig | ExtCantMatch\n");
2876                                         ast_hangup(ast);
2877                                 }
2878                                 break;
2879                                 
2880                                 case MISDN_DIALING:
2881                                 case MISDN_CALLING_ACKNOWLEDGE:
2882                                 case MISDN_PROGRESS:
2883                                         chan_misdn_log(2,  bc->port, "* --> In State Dialin\n");
2884                                         chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2885                                         
2886
2887                                         ast_queue_hangup(ast);
2888                                         break;
2889                                 case MISDN_CALLING:
2890                                         
2891                                         chan_misdn_log(2,  bc->port, "* --> In State Callin\n");
2892                                         
2893                                         if (!bc->nt) {
2894                                                 chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2895                                                 ast_queue_hangup(ast);
2896                                         } else {
2897                                                 chan_misdn_log(2,  bc->port, "* --> Hangup\n");
2898                                                 ast_queue_hangup(ast);
2899                                         }
2900                                         break;
2901                                         
2902                                 case MISDN_CLEANING:
2903                                         /* this state comes out of ast so we mustnt call a ast function ! */
2904                                         chan_misdn_log(2,  bc->port, "* --> In StateCleaning\n");
2905                                         break;
2906                                 case MISDN_HOLD_DISCONNECT:
2907                                         chan_misdn_log(2,  bc->port, "* --> In HOLD_DISC\n");
2908                                         break;
2909                                 default:
2910                                         chan_misdn_log(2,  bc->port, "* --> In State Default\n");
2911                                         chan_misdn_log(2,  bc->port, "* --> Queue Hangup\n");
2912                                         if (ast) {
2913                                                 ast_queue_hangup(ast);
2914                                         } else {
2915                                                 chan_misdn_log (0,  bc->port, "!! Not really queued!\n");
2916                                         }
2917                                 }
2918                         }
2919                         cl_dequeue_chan(&cl_te, ch);
2920                         
2921                         free(ch);
2922                 } else {
2923                         /* chan is already cleaned, so exiting  */
2924                 }
2925         }
2926 }
2927 /*** release end **/
2928
2929 static void misdn_transfer_bc(struct chan_list *tmp_ch, struct chan_list *holded_chan)
2930 {
2931         chan_misdn_log(4,0,"TRANSFERING %s to %s\n",holded_chan->ast->name, tmp_ch->ast->name);
2932         
2933         tmp_ch->state=MISDN_HOLD_DISCONNECT;
2934   
2935         ast_moh_stop(AST_BRIDGED_P(holded_chan->ast));
2936
2937         holded_chan->state=MISDN_CONNECTED;
2938         holded_chan->holded=0;
2939         misdn_lib_transfer(holded_chan->bc?holded_chan->bc:holded_chan->holded_bc);
2940         ast_channel_masquerade(holded_chan->ast, AST_BRIDGED_P(tmp_ch->ast));
2941 }
2942
2943
2944 static void do_immediate_setup(struct misdn_bchannel *bc,struct chan_list *ch , struct ast_channel *ast)
2945 {
2946         char predial[256]="";
2947         char *p = predial;
2948   
2949         struct ast_frame fr;
2950   
2951         strncpy(predial, ast->exten, sizeof(predial) -1 );
2952   
2953         ch->state=MISDN_DIALING;
2954
2955         if (bc->nt) {
2956                 int ret; 
2957                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
2958         } else {
2959                 int ret;
2960                 if ( misdn_lib_is_ptp(bc->port)) {
2961                         ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
2962                 } else {
2963                         ret = misdn_lib_send_event(bc, EVENT_PROCEEDING );
2964                 }
2965         }
2966
2967         if ( !bc->nt && (ch->orginator==ORG_MISDN) && !ch->incoming_early_audio ) 
2968                 chan_misdn_log(1,bc->port, " --> incoming_early_audio off\n");
2969          else 
2970                 tone_indicate(ch,TONE_DIAL);  
2971   
2972         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));
2973   
2974         strncpy(ast->exten,"s", 2);
2975   
2976         if (ast_pbx_start(ast)<0) {
2977                 ast=NULL;
2978                 tone_indicate(ch,TONE_BUSY);
2979
2980                 if (bc->nt)
2981                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
2982                 else
2983                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
2984         }
2985   
2986   
2987         while (!ast_strlen_zero(p) ) {
2988                 fr.frametype = AST_FRAME_DTMF;
2989                 fr.subclass = *p ;
2990                 fr.src=NULL;
2991                 fr.data = NULL ;
2992                 fr.datalen = 0;
2993                 fr.samples = 0 ;
2994                 fr.mallocd =0 ;
2995                 fr.offset= 0 ;
2996
2997                 if (ch->ast && MISDN_ASTERISK_PVT(ch->ast) && MISDN_ASTERISK_TECH_PVT(ch->ast)) {
2998                         ast_queue_frame(ch->ast, &fr);
2999                 }
3000                 p++;
3001         }
3002 }
3003
3004
3005
3006 static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc) {
3007         
3008         ast->hangupcause=bc->cause;
3009         
3010         switch ( bc->cause) {
3011                 
3012         case 1: /** Congestion Cases **/
3013         case 2:
3014         case 3:
3015         case 4:
3016         case 22:
3017         case 27:
3018                 /*
3019                  * Not Queueing the Congestion anymore, since we want to hear
3020                  * the inband message
3021                  *
3022                 chan_misdn_log(1, bc?bc->port:0, " --> * SEND: Queue Congestion pid:%d\n", bc?bc->pid:-1);
3023                 
3024                 ast_queue_control(ast, AST_CONTROL_CONGESTION);
3025                 */
3026                 break;
3027                 
3028         case 21:
3029         case 17: /* user busy */
3030                 chan_misdn_log(1,  bc?bc->port:0, " --> * SEND: Queue Busy pid:%d\n", bc?bc->pid:-1);
3031                 
3032                 ast_queue_control(ast, AST_CONTROL_BUSY);
3033                 
3034                 break;
3035         }
3036 }
3037
3038
3039 void import_ies(struct ast_channel *chan, struct misdn_bchannel *bc)
3040 {
3041         const char *tmp;
3042
3043         tmp=pbx_builtin_getvar_helper(chan,"PRI_MODE");
3044         if (tmp) bc->mode=atoi(tmp);
3045
3046         tmp=pbx_builtin_getvar_helper(chan,"PRI_URATE");
3047         if (tmp) bc->urate=atoi(tmp);
3048
3049         tmp=pbx_builtin_getvar_helper(chan,"PRI_RATE");
3050         if (tmp) bc->rate=atoi(tmp);
3051
3052         tmp=pbx_builtin_getvar_helper(chan,"PRI_USER1");
3053         if (tmp) bc->user1=atoi(tmp);
3054         
3055         tmp=pbx_builtin_getvar_helper(chan,"RDNIS");
3056         if (tmp) ast_copy_string(bc->rad,tmp,sizeof(bc->rad));
3057         
3058 }
3059
3060 void export_ies(struct ast_channel *chan, struct misdn_bchannel *bc)
3061 {
3062         char tmp[32];
3063         
3064         sprintf(tmp,"%d",bc->mode);
3065         pbx_builtin_setvar_helper(chan,"PRI_MODE",tmp);
3066
3067         sprintf(tmp,"%d",bc->urate);
3068         pbx_builtin_setvar_helper(chan,"PRI_URATE",tmp);
3069
3070         sprintf(tmp,"%d",bc->rate);
3071         pbx_builtin_setvar_helper(chan,"PRI_RATE",tmp);
3072         
3073         sprintf(tmp,"%d",bc->user1);
3074         pbx_builtin_setvar_helper(chan,"PRI_USER1",tmp);
3075         
3076         pbx_builtin_setvar_helper(chan,"RDNIS",bc->rad);
3077 }
3078
3079
3080
3081 /************************************************************/
3082 /*  Receive Events from isdn_lib  here                     */
3083 /************************************************************/
3084 static enum event_response_e
3085 cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
3086 {
3087         struct chan_list *ch=find_chan_by_bc(cl_te, bc);
3088         
3089         if (!ch)
3090                 ch=find_chan_by_l3id(cl_te, bc->l3_id);
3091         
3092         if (event != EVENT_BCHAN_DATA && event != EVENT_TONE_GENERATE) { /*  Debug Only Non-Bchan */
3093                 chan_misdn_log(1, bc->port, "I IND :%s oad:%s dad:%s\n", manager_isdn_get_info(event), bc->oad, bc->dad);
3094                 misdn_lib_log_ies(bc);
3095                 chan_misdn_log(2,bc->port," --> bc_state:%s\n",bc_state2str(bc->bc_state));
3096         }
3097         
3098         if (event != EVENT_SETUP) {
3099                 if (!ch) {
3100                         if (event != EVENT_CLEANUP )
3101                                 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);
3102                         return -1;
3103                 }
3104         }
3105         
3106         if (ch ) {
3107                 switch (event) {
3108                 case EVENT_RELEASE:
3109                 case EVENT_RELEASE_COMPLETE:
3110                 case EVENT_CLEANUP:
3111                         break;
3112                 default:
3113                         if ( !ch->ast  || !MISDN_ASTERISK_PVT(ch->ast) || !MISDN_ASTERISK_TECH_PVT(ch->ast)) {
3114                                 if (event!=EVENT_BCHAN_DATA)
3115                                         ast_log(LOG_WARNING, "No Ast or No private Pointer in Event (%d:%s)\n", event, manager_isdn_get_info(event));
3116                                 return -1;
3117                         }
3118                 }
3119         }
3120         
3121         
3122         switch (event) {
3123
3124         case EVENT_BCHAN_ACTIVATED:
3125                 break;
3126                 
3127                 
3128         case EVENT_NEW_L3ID:
3129                 ch->l3id=bc->l3_id;
3130                 break;
3131
3132         case EVENT_NEW_BC:
3133                 if (bc)
3134                         ch->bc=bc;
3135                 break;
3136                 
3137         case EVENT_DTMF_TONE:
3138         {
3139                 /*  sending INFOS as DTMF-Frames :) */
3140                 struct ast_frame fr;
3141                 memset(&fr, 0 , sizeof(fr));
3142                 fr.frametype = AST_FRAME_DTMF;
3143                 fr.subclass = bc->dtmf ;
3144                 fr.src=NULL;
3145                 fr.data = NULL ;
3146                 fr.datalen = 0;
3147                 fr.samples = 0 ;
3148                 fr.mallocd =0 ;
3149                 fr.offset= 0 ;
3150                 
3151                 chan_misdn_log(2, bc->port, " --> DTMF:%c\n", bc->dtmf);
3152                 
3153                 ast_queue_frame(ch->ast, &fr);
3154         }
3155         break;
3156         case EVENT_STATUS:
3157                 break;
3158     
3159         case EVENT_INFORMATION:
3160         {
3161                 int stop_tone;
3162                 misdn_cfg_get( 0, MISDN_GEN_STOP_TONE, &stop_tone, sizeof(int));
3163                 if ( stop_tone ) {
3164                         tone_indicate(ch,TONE_NONE);
3165                 }
3166                 
3167                 if (ch->state == MISDN_WAITING4DIGS ) {
3168                         /*  Ok, incomplete Setup, waiting till extension exists */
3169                         {
3170                                 int l = sizeof(bc->dad);
3171                                 strncat(bc->dad,bc->info_dad, l);
3172                                 bc->dad[l-1] = 0;
3173                         }
3174                         
3175                         
3176                         {
3177                                 int l = sizeof(ch->ast->exten);
3178                                 strncpy(ch->ast->exten, bc->dad, l);
3179                                 ch->ast->exten[l-1] = 0;
3180                         }
3181 /*                      chan_misdn_log(5, bc->port, "Can Match Extension: dad:%s oad:%s\n",bc->dad,bc->oad);*/
3182                         
3183                         /* Check for Pickup Request first */
3184                         if (!strcmp(ch->ast->exten, ast_pickup_ext())) {
3185                                 int ret;/** Sending SETUP_ACK**/
3186                                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3187                                 if (ast_pickup_call(ch->ast)) {
3188                                         ast_hangup(ch->ast);
3189                                 } else {
3190                                         struct ast_channel *chan=ch->ast;
3191                                         ch->state = MISDN_CALLING_ACKNOWLEDGE;
3192                                         ch->ast=NULL;
3193                                         ast_setstate(chan, AST_STATE_DOWN);
3194                                         ast_hangup(chan);
3195                                         break;
3196                                 }
3197                         }
3198                         
3199                         if(!ast_canmatch_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3200
3201                                 chan_misdn_log(-1, bc->port, "Extension can never match, so disconnecting\n");
3202                                 tone_indicate(ch,TONE_BUSY);
3203                                 ch->state=MISDN_EXTCANTMATCH;
3204                                 bc->out_cause=1;
3205
3206                                 if (bc->nt)
3207                                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3208                                 else
3209                                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
3210                                 break;
3211                         }
3212                         if (ast_exists_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3213                                 ch->state=MISDN_DIALING;
3214           
3215                                 tone_indicate(ch,TONE_NONE);
3216 /*                              chan_misdn_log(1, bc->port, " --> * Starting Ast ctx:%s\n", ch->context);*/
3217                                 if (ast_pbx_start(ch->ast)<0) {
3218
3219                                         chan_misdn_log(-1, bc->port, "ast_pbx_start returned < 0 in INFO\n");
3220                                         tone_indicate(ch,TONE_BUSY);
3221
3222                                         if (bc->nt)
3223                                                 misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3224                                         else
3225                                                 misdn_lib_send_event(bc, EVENT_DISCONNECT );
3226                                 }
3227                         }
3228         
3229                 } else {
3230                         /*  sending INFOS as DTMF-Frames :) */
3231                         struct ast_frame fr;
3232                         fr.frametype = AST_FRAME_DTMF;
3233                         fr.subclass = bc->info_dad[0] ;
3234                         fr.src=NULL;
3235                         fr.data = NULL ;
3236                         fr.datalen = 0;
3237                         fr.samples = 0 ;
3238                         fr.mallocd =0 ;
3239                         fr.offset= 0 ;
3240
3241                         
3242                         int digits;
3243                         misdn_cfg_get( 0, MISDN_GEN_APPEND_DIGITS2EXTEN, &digits, sizeof(int));
3244                         if (ch->state != MISDN_CONNECTED ) {
3245                                 if (digits) {
3246                                         int l = sizeof(bc->dad);
3247                                         strncat(bc->dad,bc->info_dad, l);
3248                                         bc->dad[l-1] = 0;
3249                                         l = sizeof(ch->ast->exten);
3250                                         strncpy(ch->ast->exten, bc->dad, l);
3251                                         ch->ast->exten[l-1] = 0;
3252
3253                                         ast_cdr_update(ch->ast);
3254                                 }
3255                                 
3256                                 ast_queue_frame(ch->ast, &fr);
3257                         }
3258                         
3259                 }
3260         }
3261         break;
3262         case EVENT_SETUP:
3263         {
3264                 struct chan_list *ch=find_chan_by_bc(cl_te, bc);
3265                 if (ch && ch->state != MISDN_NOTHING ) {
3266                         chan_misdn_log(1, bc->port, " --> Ignoring Call we have already one\n");
3267                         return RESPONSE_IGNORE_SETUP_WITHOUT_CLOSE; /*  Ignore MSNs which are not in our List */
3268                 }
3269         }
3270         
3271
3272         int msn_valid = misdn_cfg_is_msn_valid(bc->port, bc->dad);
3273         if (!bc->nt && ! msn_valid) {
3274                 chan_misdn_log(1, bc->port, " --> Ignoring Call, its not in our MSN List\n");
3275                 return RESPONSE_IGNORE_SETUP; /*  Ignore MSNs which are not in our List */
3276         }
3277         
3278         print_bearer(bc);
3279     
3280         {
3281                 struct chan_list *ch=init_chan_list();
3282                 struct ast_channel *chan;
3283
3284                 if (!ch) { chan_misdn_log(-1, bc->port, "cb_events: malloc for chan_list failed!\n"); return 0;}
3285                 
3286                 ch->bc = bc;
3287                 ch->l3id=bc->l3_id;
3288                 ch->addr=bc->addr;
3289                 ch->orginator = ORG_MISDN;
3290
3291                 chan=misdn_new(ch, AST_STATE_RESERVED,bc->dad, bc->oad, AST_FORMAT_ALAW, bc->port, bc->channel);
3292                 ch->ast = chan;
3293
3294                 read_config(ch, ORG_MISDN);
3295                 
3296                 export_ies(chan, bc);
3297                 
3298                 ch->ast->rings=1;
3299                 ast_setstate(ch->ast, AST_STATE_RINGING);
3300
3301                 if ( bc->pres ) {
3302                         chan->cid.cid_pres=AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
3303                 }  else {
3304                         chan->cid.cid_pres=AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
3305                 }
3306       
3307                 pbx_builtin_setvar_helper(chan, "TRANSFERCAPABILITY", ast_transfercapability2str(bc->capability));
3308                 chan->transfercapability=bc->capability;
3309                 
3310                 switch (bc->capability) {
3311                 case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
3312                         pbx_builtin_setvar_helper(chan,"CALLTYPE","DIGITAL");
3313                         break;
3314                 default:
3315                         pbx_builtin_setvar_helper(chan,"CALLTYPE","SPEECH");
3316                 }
3317
3318                 /** queue new chan **/
3319                 cl_queue_chan(&cl_te, ch) ;
3320                 
3321                 /* Check for Pickup Request first */
3322                 if (!strcmp(chan->exten, ast_pickup_ext())) {
3323                         int ret;/** Sending SETUP_ACK**/
3324                         ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3325                         if (ast_pickup_call(chan)) {
3326                                 ast_hangup(chan);
3327                         } else {
3328                                 ch->state = MISDN_CALLING_ACKNOWLEDGE;
3329                                 ch->ast=NULL;
3330                                 ast_setstate(chan, AST_STATE_DOWN);
3331                                 ast_hangup(chan);
3332                                 break;
3333                         }
3334                 }
3335                 
3336                 /*
3337                   added support for s extension hope it will help those poor cretains
3338                   which haven't overlap dial.
3339                 */
3340                 {
3341                         int ai;
3342                         misdn_cfg_get( bc->port, MISDN_CFG_ALWAYS_IMMEDIATE, &ai, sizeof(ai));
3343                         if ( ai ) {
3344                                 do_immediate_setup(bc, ch , chan);
3345                                 break;
3346                         }
3347                         
3348                         
3349                         
3350                 }
3351
3352                 /* check if we should jump into s when we have no dad */
3353                 {
3354                         int im;
3355                         misdn_cfg_get( bc->port, MISDN_CFG_IMMEDIATE, &im, sizeof(im));
3356                         if ( im && ast_strlen_zero(bc->dad) ) {
3357                                 do_immediate_setup(bc, ch , chan);
3358                                 break;
3359                         }
3360                 }
3361
3362                 
3363                         chan_misdn_log(5,bc->port,"CONTEXT:%s\n",ch->context);
3364                         if(!ast_canmatch_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3365                         
3366                         chan_misdn_log(-1, bc->port, "Extension can never match, so disconnecting\n");
3367
3368                         tone_indicate(ch,TONE_BUSY);
3369                         ch->state=MISDN_EXTCANTMATCH;
3370                         bc->out_cause=1;
3371
3372                         if (bc->nt)
3373                                 misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3374                         else
3375                                 misdn_lib_send_event(bc, EVENT_DISCONNECT );
3376                         break;
3377                 }
3378                 
3379                 if (ast_exists_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
3380                         ch->state=MISDN_DIALING;
3381                         
3382                         if (bc->nt || (bc->need_more_infos && misdn_lib_is_ptp(bc->port)) ) {
3383                                 int ret; 
3384                                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3385                         } else {
3386                                 int ret;
3387                                 ret= misdn_lib_send_event(bc, EVENT_PROCEEDING );
3388                         }
3389         
3390                         if (ast_pbx_start(chan)<0) {
3391
3392                                 chan_misdn_log(-1, bc->port, "ast_pbx_start returned <0 in SETUP\n");
3393                                 chan=NULL;
3394                                 tone_indicate(ch,TONE_BUSY);
3395
3396                                 if (bc->nt)
3397                                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3398                                 else
3399                                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
3400                         }
3401                 } else {
3402                         int ret= misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3403                         if (ret == -ENOCHAN) {
3404                                 ast_log(LOG_WARNING,"Channel was catched, before we could Acknowledge\n");
3405                                 misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
3406                         }
3407                         /*  send tone to phone :) */
3408
3409                         /** ADD IGNOREPAT **/
3410                         
3411                         int stop_tone;
3412                         misdn_cfg_get( 0, MISDN_GEN_STOP_TONE, &stop_tone, sizeof(int));
3413                         if ( (!ast_strlen_zero(bc->dad)) && stop_tone ) 
3414                                 tone_indicate(ch,TONE_NONE);
3415                         else
3416                                 tone_indicate(ch,TONE_DIAL);
3417                         
3418                         ch->state=MISDN_WAITING4DIGS;
3419                 }
3420       
3421         }
3422         break;
3423         case EVENT_SETUP_ACKNOWLEDGE:
3424         {
3425                 ch->state = MISDN_CALLING_ACKNOWLEDGE;
3426                 if (!ast_strlen_zero(bc->infos_pending)) {
3427                         /* TX Pending Infos */
3428                         
3429                         {
3430                                 int l = sizeof(bc->dad);
3431                                 strncat(bc->dad,bc->infos_pending, l - strlen(bc->dad));
3432                                 bc->dad[l-1] = 0;
3433                         }       
3434                         {
3435                                 int l = sizeof(ch->ast->exten);
3436                                 strncpy(ch->ast->exten, bc->dad, l);
3437                                 ch->ast->exten[l-1] = 0;
3438                         }
3439                         {
3440                                 int l = sizeof(bc->info_dad);
3441                                 strncpy(bc->info_dad, bc->infos_pending, l);
3442                                 bc->info_dad[l-1] = 0;
3443                         }
3444                         strncpy(bc->infos_pending,"", 1);
3445
3446                         misdn_lib_send_event(bc, EVENT_INFORMATION);
3447                 }
3448         }
3449         break;
3450         case EVENT_PROCEEDING:
3451         {
3452                 
3453                 if ( misdn_cap_is_speech(bc->capability) &&
3454                      misdn_inband_avail(bc) ) {
3455                         start_bc_tones(ch);
3456                 }
3457
3458                 ch->state = MISDN_PROCEEDING;
3459                 
3460                 ast_queue_control(ch->ast, AST_CONTROL_PROCEEDING);
3461         }
3462         break;
3463         case EVENT_PROGRESS:
3464                 if (!bc->nt ) {
3465                         if ( misdn_cap_is_speech(bc->capability) &&
3466                              misdn_inband_avail(bc)
3467                                 ) {
3468                                 start_bc_tones(ch);
3469                         }
3470                         
3471                         ast_queue_control(ch->ast, AST_CONTROL_PROGRESS);
3472                         
3473                         ch->state=MISDN_PROGRESS;
3474                 }
3475                 break;
3476                 
3477                 
3478         case EVENT_ALERTING:
3479         {
3480                 ch->state = MISDN_ALERTING;
3481                 
3482                 ast_queue_control(ch->ast, AST_CONTROL_RINGING);
3483                 ast_setstate(ch->ast, AST_STATE_RINGING);
3484                 
3485                 cb_log(1,bc->port,"Set State Ringing\n");
3486                 
3487                 if ( misdn_cap_is_speech(bc->capability) && misdn_inband_avail(bc)) {
3488                         start_bc_tones(ch);
3489                 }
3490         }
3491         break;
3492         case EVENT_CONNECT:
3493                 misdn_lib_send_event(bc,EVENT_CONNECT_ACKNOWLEDGE);
3494         case EVENT_CONNECT_ACKNOWLEDGE:
3495         {
3496                 ch->l3id=bc->l3_id;
3497                 ch->addr=bc->addr;
3498                 
3499                 start_bc_tones(ch);
3500                 
3501                 
3502                 ch->state = MISDN_CONNECTED;
3503                 ast_queue_control(ch->ast, AST_CONTROL_ANSWER);
3504         }
3505         break;
3506         case EVENT_DISCONNECT:
3507         {
3508                 
3509                 struct chan_list *holded_ch=find_holded(cl_te, bc);
3510                 
3511                 
3512                 send_cause2ast(ch->ast,bc);
3513
3514                 if (misdn_inband_avail(bc) && ch->state != MISDN_CONNECTED) {
3515                         /* If there's inband information available (e.g. a
3516                            recorded message saying what was wrong with the
3517                            dialled number, or perhaps even giving an
3518                            alternative number, then play it instead of
3519                            immediately releasing the call */
3520                         chan_misdn_log(0,bc->port, " --> Inband Info Avail, not sending RELEASE\n");
3521                         ch->state = MISDN_DISCONNECTED;
3522      &nb