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