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