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