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