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