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