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