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