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