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