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