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