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