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