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