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