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