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