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