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