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