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