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