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