added general Jitterbuffer Implementation. #9960
[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         MISDN_ASTERISK_TECH_PVT(ast) = NULL;
2323         p->ast = NULL;
2324
2325         if (ast->_state == AST_STATE_RESERVED || 
2326                 p->state == MISDN_NOTHING || 
2327                 p->state == MISDN_HOLDED || 
2328                 p->state == MISDN_HOLD_DISCONNECT ) {
2329
2330                 CLEAN_CH:
2331                 /* between request and call */
2332                 ast_debug(1, "State Reserved (or nothing) => chanIsAvail\n");
2333                 MISDN_ASTERISK_TECH_PVT(ast) = NULL;
2334         
2335                 ast_mutex_lock(&release_lock);
2336                 cl_dequeue_chan(&cl_te, p);
2337                 close(p->pipe[0]);
2338                 close(p->pipe[1]);
2339                 ast_free(p);
2340                 ast_mutex_unlock(&release_lock);
2341                 
2342                 if (bc)
2343                         misdn_lib_release(bc);
2344                 
2345                 return 0;
2346         }
2347
2348         if (!bc) {
2349                 ast_log(LOG_WARNING, "Hangup with private but no bc ? state:%s l3id:%x\n", misdn_get_ch_state(p), p->l3id);
2350                 goto CLEAN_CH;
2351         }
2352
2353
2354         p->need_hangup = 0;
2355         p->need_queue_hangup = 0;
2356         p->need_busy = 0;
2357
2358
2359         if (!p->bc->nt) 
2360                 stop_bc_tones(p);
2361
2362         bc->out_cause = ast->hangupcause ? ast->hangupcause : AST_CAUSE_NORMAL_CLEARING;
2363                 
2364         if ( (varcause = pbx_builtin_getvar_helper(ast, "HANGUPCAUSE")) ||
2365              (varcause = pbx_builtin_getvar_helper(ast, "PRI_CAUSE"))) {
2366                 int tmpcause = atoi(varcause);
2367                 bc->out_cause = tmpcause ? tmpcause : AST_CAUSE_NORMAL_CLEARING;
2368         }
2369     
2370         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));
2371         chan_misdn_log(3, bc->port, " --> l3id:%x\n", p->l3id);
2372         chan_misdn_log(3, bc->port, " --> cause:%d\n", bc->cause);
2373         chan_misdn_log(2, bc->port, " --> out_cause:%d\n", bc->out_cause);
2374         chan_misdn_log(2, bc->port, " --> state:%s\n", misdn_get_ch_state(p));
2375
2376         switch (p->state) {
2377         case MISDN_INCOMING_SETUP:
2378         case MISDN_CALLING:
2379                 p->state = MISDN_CLEANING;
2380                 /* This is the only place in misdn_hangup, where we 
2381                  * can call release_chan, else it might create lot's of trouble
2382                  * */
2383                 ast_log(LOG_NOTICE, "release channel, in CALLING/INCOMING_SETUP state.. no other events happened\n");
2384                 release_chan(bc);
2385                 misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
2386                 break;
2387         case MISDN_HOLDED:
2388         case MISDN_DIALING:
2389                 start_bc_tones(p);
2390                 hanguptone_indicate(p);
2391                 
2392                 if (bc->need_disconnect)
2393                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
2394                 break;
2395         case MISDN_CALLING_ACKNOWLEDGE:
2396                 start_bc_tones(p);
2397                 hanguptone_indicate(p);
2398                 
2399                 if (bc->need_disconnect)
2400                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
2401                 break;
2402       
2403         case MISDN_ALERTING:
2404         case MISDN_PROGRESS:
2405         case MISDN_PROCEEDING:
2406                 if (p->originator != ORG_AST) 
2407                         hanguptone_indicate(p);
2408       
2409                 /*p->state=MISDN_CLEANING;*/
2410                 if (bc->need_disconnect)
2411                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
2412                 break;
2413         case MISDN_CONNECTED:
2414         case MISDN_PRECONNECTED:
2415                 /*  Alerting or Disconect */
2416                 if (p->bc->nt) {
2417                         start_bc_tones(p);
2418                         hanguptone_indicate(p);
2419                         p->bc->progress_indicator = 8;
2420                 }
2421                 if (bc->need_disconnect)
2422                         misdn_lib_send_event( bc, EVENT_DISCONNECT);
2423
2424                 /*p->state=MISDN_CLEANING;*/
2425                 break;
2426         case MISDN_DISCONNECTED:
2427                 misdn_lib_send_event( bc, EVENT_RELEASE);
2428                 p->state = MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2429                 break;
2430
2431         case MISDN_RELEASED:
2432         case MISDN_CLEANING:
2433                 p->state = MISDN_CLEANING;
2434                 break;
2435
2436         case MISDN_BUSY:
2437                 break;
2438       
2439         case MISDN_HOLD_DISCONNECT:
2440                 /* need to send release here */
2441                 chan_misdn_log(1, bc->port, " --> cause %d\n", bc->cause);
2442                 chan_misdn_log(1, bc->port, " --> out_cause %d\n", bc->out_cause);
2443
2444                 bc->out_cause = -1;
2445                 misdn_lib_send_event(bc, EVENT_RELEASE);
2446                 p->state = MISDN_CLEANING;
2447                 break;
2448         default:
2449                 if (bc->nt) {
2450                         bc->out_cause = -1;
2451                         misdn_lib_send_event(bc, EVENT_RELEASE);
2452                         p->state = MISDN_CLEANING; 
2453                 } else {
2454                         if (bc->need_disconnect)
2455                                 misdn_lib_send_event(bc, EVENT_DISCONNECT);
2456                 }
2457         }
2458
2459         p->state = MISDN_CLEANING;
2460     
2461         chan_misdn_log(3, bc->port, " --> Channel: %s hanguped new state:%s\n", ast->name, misdn_get_ch_state(p));
2462
2463         return 0;
2464 }
2465
2466
2467 static struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame *frame)
2468 {
2469         struct ast_frame *f,*f2;
2470  
2471         if (tmp->trans) {
2472                 f2 = ast_translate(tmp->trans, frame, 0);
2473                 f = ast_dsp_process(tmp->ast, tmp->dsp, f2);
2474         } else {
2475                 chan_misdn_log(0, tmp->bc->port, "No T-Path found\n");
2476                 return NULL;
2477         }
2478
2479         if (!f || (f->frametype != AST_FRAME_DTMF))
2480                 return frame;
2481  
2482         ast_debug(1, "Detected inband DTMF digit: %c\n", f->subclass);
2483  
2484         if (tmp->faxdetect && (f->subclass == 'f')) {
2485                 /* Fax tone -- Handle and return NULL */
2486                 if (!tmp->faxhandled) {
2487                         struct ast_channel *ast = tmp->ast;
2488                         tmp->faxhandled++;
2489                         chan_misdn_log(0, tmp->bc->port, "Fax detected, preparing %s for fax transfer.\n", ast->name);
2490                         tmp->bc->rxgain = 0;
2491                         isdn_lib_update_rxgain(tmp->bc);
2492                         tmp->bc->txgain = 0;
2493                         isdn_lib_update_txgain(tmp->bc);
2494 #ifdef MISDN_1_2
2495                         *tmp->bc->pipeline = 0;
2496 #else
2497                         tmp->bc->ec_enable = 0;
2498 #endif
2499                         isdn_lib_update_ec(tmp->bc);
2500                         isdn_lib_stop_dtmf(tmp->bc);
2501                         switch (tmp->faxdetect) {
2502                         case 1:
2503                                 if (strcmp(ast->exten, "fax")) {
2504                                         char *context;
2505                                         char context_tmp[BUFFERSIZE];
2506                                         misdn_cfg_get(tmp->bc->port, MISDN_CFG_FAXDETECT_CONTEXT, &context_tmp, sizeof(context_tmp));
2507                                         context = ast_strlen_zero(context_tmp) ? (ast_strlen_zero(ast->macrocontext) ? ast->context : ast->macrocontext) : context_tmp;
2508                                         if (ast_exists_extension(ast, context, "fax", 1, ast->cid.cid_num)) {
2509                                                 if (option_verbose > 2)
2510                                                         ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension (context:%s)\n", ast->name, context);
2511                                                 /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
2512                                                 pbx_builtin_setvar_helper(ast,"FAXEXTEN",ast->exten);
2513                                                 if (ast_async_goto(ast, context, "fax", 1))
2514                                                         ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, context);
2515                                         } else
2516                                                 ast_log(LOG_NOTICE, "Fax detected, but no fax extension ctx:%s exten:%s\n", context, ast->exten);
2517                                 } else {
2518                                         ast_debug(1, "Already in a fax extension, not redirecting\n");
2519                                 }
2520                                 break;
2521                         case 2:
2522                                 ast_verbose(VERBOSE_PREFIX_3 "Not redirecting %s to fax extension, nojump is set.\n", ast->name);
2523                                 break;
2524                         }
2525                 } else {
2526                         ast_debug(1, "Fax already handled\n");
2527                 }
2528         }
2529         
2530         if (tmp->ast_dsp && (f->subclass != 'f')) {
2531                 chan_misdn_log(2, tmp->bc->port, " --> * SEND: DTMF (AST_DSP) :%c\n", f->subclass);
2532         }
2533
2534         return frame;
2535 }
2536
2537
2538 static struct ast_frame *misdn_read(struct ast_channel *ast)
2539 {
2540         struct chan_list *tmp;
2541         int len;
2542         
2543         if (!ast) {
2544                 chan_misdn_log(1, 0, "misdn_read called without ast\n");
2545                 return NULL;
2546         }
2547         if (!(tmp = MISDN_ASTERISK_TECH_PVT(ast))) {
2548                 chan_misdn_log(1, 0, "misdn_read called without ast->pvt\n");
2549                 return NULL;
2550         }
2551
2552         if (!tmp->bc && !(tmp->state == MISDN_HOLDED)) {
2553                 chan_misdn_log(1, 0, "misdn_read called without bc\n");
2554                 return NULL;
2555         }
2556
2557         len = read(tmp->pipe[0], tmp->ast_rd_buf, sizeof(tmp->ast_rd_buf));
2558
2559         if (len <= 0) {
2560                 /* we hangup here, since our pipe is closed */
2561                 chan_misdn_log(2, tmp->bc->port, "misdn_read: Pipe closed, hanging up\n");
2562                 return NULL;
2563         }
2564
2565         tmp->frame.frametype = AST_FRAME_VOICE;
2566         tmp->frame.subclass = AST_FORMAT_ALAW;
2567         tmp->frame.datalen = len;
2568         tmp->frame.samples = len;
2569         tmp->frame.mallocd = 0;
2570         tmp->frame.offset = 0;
2571         tmp->frame.delivery = ast_tv(0,0);
2572         tmp->frame.src = NULL;
2573         tmp->frame.data = tmp->ast_rd_buf;
2574
2575         if (tmp->faxdetect && !tmp->faxhandled) {
2576                 if (tmp->faxdetect_timeout) {
2577                         if (ast_tvzero(tmp->faxdetect_tv)) {
2578                                 tmp->faxdetect_tv = ast_tvnow();
2579                                 chan_misdn_log(2, tmp->bc->port, "faxdetect: starting detection with timeout: %ds ...\n", tmp->faxdetect_timeout);
2580                                 return process_ast_dsp(tmp, &tmp->frame);
2581                         } else {
2582                                 struct timeval tv_now = ast_tvnow();
2583                                 int diff = ast_tvdiff_ms(tv_now, tmp->faxdetect_tv);
2584                                 if (diff <= (tmp->faxdetect_timeout * 1000)) {
2585                                         chan_misdn_log(5, tmp->bc->port, "faxdetect: detecting ...\n");
2586                                         return process_ast_dsp(tmp, &tmp->frame);
2587                                 } else {
2588                                         chan_misdn_log(2, tmp->bc->port, "faxdetect: stopping detection (time ran out) ...\n");
2589                                         tmp->faxdetect = 0;
2590                                         return &tmp->frame;
2591                                 }
2592                         }
2593                 } else {
2594                         chan_misdn_log(5, tmp->bc->port, "faxdetect: detecting ... (no timeout)\n");
2595                         return process_ast_dsp(tmp, &tmp->frame);
2596                 }
2597         } else {
2598                 if (tmp->ast_dsp)
2599                         return process_ast_dsp(tmp, &tmp->frame);
2600                 else
2601                         return &tmp->frame;
2602         }
2603 }
2604
2605
2606 static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
2607 {
2608         struct chan_list *ch;
2609         int i  = 0;
2610         
2611         if (!ast || ! (ch = MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
2612
2613         if (ch->state == MISDN_HOLDED) {
2614                 chan_misdn_log(7, 0, "misdn_write: Returning because holded\n");
2615                 return 0;
2616         }
2617         
2618         if (!ch->bc ) {
2619                 ast_log(LOG_WARNING, "private but no bc\n");
2620                 return -1;
2621         }
2622         
2623         if (ch->notxtone) {
2624                 chan_misdn_log(7, ch->bc->port, "misdn_write: Returning because notxone\n");
2625                 return 0;
2626         }
2627
2628
2629         if (!frame->subclass) {
2630                 chan_misdn_log(4, ch->bc->port, "misdn_write: * prods us\n");
2631                 return 0;
2632         }
2633         
2634         if (!(frame->subclass & prefformat)) {
2635                 
2636                 chan_misdn_log(-1, ch->bc->port, "Got Unsupported Frame with Format:%d\n", frame->subclass);
2637                 return 0;
2638         }
2639         
2640
2641         if (!frame->samples ) {
2642                 chan_misdn_log(4, ch->bc->port, "misdn_write: zero write\n");
2643                 
2644                 if (!strcmp(frame->src,"ast_prod")) {
2645                         chan_misdn_log(1, ch->bc->port, "misdn_write: state (%s) prodded.\n", misdn_get_ch_state(ch));
2646
2647                         if (ch->ts) {
2648                                 chan_misdn_log(4, ch->bc->port, "Starting Playtones\n");
2649                                 misdn_lib_tone_generator_start(ch->bc);
2650                         }
2651                         return 0;
2652                 }
2653
2654                 return -1;
2655         }
2656
2657         if ( ! ch->bc->addr ) {
2658                 chan_misdn_log(8, ch->bc->port, "misdn_write: no addr for bc dropping:%d\n", frame->samples);
2659                 return 0;
2660         }
2661         
2662 #ifdef MISDN_DEBUG
2663         {
2664                 int i, max = 5 > frame->samples ? frame->samples : 5;
2665
2666                 ast_debug(1, "write2mISDN %p %d bytes: ", p, frame->samples);
2667
2668                 for (i = 0; i < max ; i++)
2669                         ast_debug(1, "%2.2x ", ((char*) frame->data)[i]);
2670         }
2671 #endif
2672
2673         switch (ch->bc->bc_state) {
2674         case BCHAN_ACTIVATED:
2675         case BCHAN_BRIDGED:
2676                 break;
2677         default:
2678                 if (!ch->dropped_frame_cnt)
2679                         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);
2680                 
2681                 ch->dropped_frame_cnt++;
2682                 if (ch->dropped_frame_cnt > 100) {
2683                         ch->dropped_frame_cnt = 0;
2684                         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);
2685
2686                 }
2687
2688                 return 0;
2689         }
2690
2691         chan_misdn_log(9, ch->bc->port, "Sending :%d bytes 2 MISDN\n", frame->samples);
2692         if ( !ch->bc->nojitter && misdn_cap_is_speech(ch->bc->capability) ) {
2693                 /* Buffered Transmit (triggert by read from isdn side)*/
2694                 if (misdn_jb_fill(ch->jb, frame->data, frame->samples) < 0) {
2695                         if (ch->bc->active)
2696                                 cb_log(0, ch->bc->port, "Misdn Jitterbuffer Overflow.\n");
2697                 }
2698                 
2699         } else {
2700                 /*transmit without jitterbuffer*/
2701                 i=misdn_lib_tx2misdn_frm(ch->bc, frame->data, frame->samples);
2702         }
2703
2704         return 0;
2705 }
2706
2707
2708
2709
2710 static enum ast_bridge_result  misdn_bridge (struct ast_channel *c0,
2711                                       struct ast_channel *c1, int flags,
2712                                       struct ast_frame **fo,
2713                                       struct ast_channel **rc,
2714                                       int timeoutms)
2715
2716 {
2717         struct chan_list *ch1, *ch2;
2718         struct ast_channel *carr[2], *who;
2719         int to = -1;
2720         struct ast_frame *f;
2721         int p1_b, p2_b;
2722         int bridging;
2723   
2724         ch1 = get_chan_by_ast(c0);
2725         ch2 = get_chan_by_ast(c1);
2726
2727         carr[0] = c0;
2728         carr[1] = c1;
2729   
2730         if (!(ch1 && ch2))
2731                 return -1;
2732
2733         misdn_cfg_get(ch1->bc->port, MISDN_CFG_BRIDGING, &p1_b, sizeof(p1_b));
2734         misdn_cfg_get(ch2->bc->port, MISDN_CFG_BRIDGING, &p2_b, sizeof(p2_b));
2735
2736         if (! p1_b || ! p2_b) {
2737                 ast_log(LOG_NOTICE, "Falling back to Asterisk bridging\n");
2738                 return AST_BRIDGE_FAILED;
2739         }
2740
2741         misdn_cfg_get(0, MISDN_GEN_BRIDGING, &bridging, sizeof(bridging));
2742         if (bridging) {
2743                 /* trying to make a mISDN_dsp conference */
2744                 chan_misdn_log(1, ch1->bc->port, "I SEND: Making conference with Number:%d\n", ch1->bc->pid + 1);
2745                 misdn_lib_bridge(ch1->bc, ch2->bc);
2746         }
2747
2748         if (option_verbose > 2) 
2749                 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
2750
2751         chan_misdn_log(1, ch1->bc->port, "* Making Native Bridge between %s and %s\n", ch1->bc->oad, ch2->bc->oad);
2752  
2753         if (! (flags & AST_BRIDGE_DTMF_CHANNEL_0) )
2754                 ch1->ignore_dtmf = 1;
2755
2756         if (! (flags & AST_BRIDGE_DTMF_CHANNEL_1) )
2757                 ch2->ignore_dtmf = 1;
2758
2759         for (;/*ever*/;) {
2760                 to = -1;
2761                 who = ast_waitfor_n(carr, 2, &to);
2762
2763                 if (!who) {
2764                         ast_log(LOG_NOTICE, "misdn_bridge: empty read, breaking out\n");
2765                         break;
2766                 }
2767                 f = ast_read(who);
2768
2769                 if (!f || f->frametype == AST_FRAME_CONTROL) {
2770                         /* got hangup .. */
2771
2772                         if (!f) 
2773                                 chan_misdn_log(4, ch1->bc->port, "Read Null Frame\n");
2774                         else
2775                                 chan_misdn_log(4, ch1->bc->port, "Read Frame Controll class:%d\n", f->subclass);
2776
2777                         *fo = f;
2778                         *rc = who;
2779
2780                         break;
2781                 }
2782                 
2783                 if ( f->frametype == AST_FRAME_DTMF ) {
2784                         chan_misdn_log(1, 0, "Read DTMF %d from %s\n", f->subclass, who->exten);
2785
2786                         *fo = f;
2787                         *rc = who;
2788                         break;
2789                 }
2790         
2791 #if 0
2792                 if (f->frametype == AST_FRAME_VOICE) {
2793                         chan_misdn_log(1, ch1->bc->port, "I SEND: Splitting conference with Number:%d\n", ch1->bc->pid +1);
2794         
2795                         continue;
2796                 }
2797 #endif
2798
2799                 if (who == c0) {
2800                         ast_write(c1, f);
2801                 }
2802                 else {
2803                         ast_write(c0, f);
2804                 }
2805         }
2806
2807         chan_misdn_log(1, ch1->bc->port, "I SEND: Splitting conference with Number:%d\n", ch1->bc->pid + 1);
2808
2809         misdn_lib_split_bridge(ch1->bc, ch2->bc);
2810
2811         return AST_BRIDGE_COMPLETE;
2812 }
2813
2814 /** AST INDICATIONS END **/
2815
2816 static int dialtone_indicate(struct chan_list *cl)
2817 {
2818         const struct ind_tone_zone_sound *ts = NULL;
2819         struct ast_channel *ast = cl->ast;
2820         int nd = 0;
2821
2822         if (!ast) {
2823                 chan_misdn_log(0, cl->bc->port, "No Ast in dialtone_indicate\n");
2824                 return -1;
2825         }
2826
2827         misdn_cfg_get(cl->bc->port, MISDN_CFG_NODIALTONE, &nd, sizeof(nd));
2828
2829         if (nd) {
2830                 chan_misdn_log(1, cl->bc->port, "Not sending Dialtone, because config wants it\n");
2831                 return 0;
2832         }
2833         
2834         chan_misdn_log(3, cl->bc->port, " --> Dial\n");
2835         ts = ast_get_indication_tone(ast->zone, "dial");
2836         cl->ts = ts;    
2837         
2838         if (ts) {
2839                 cl->notxtone = 0;
2840                 cl->norxtone = 0;
2841                 /* This prods us in misdn_write */
2842                 ast_playtones_start(ast, 0, ts->data, 0);
2843         }
2844
2845         return 0;
2846 }
2847
2848 static int hanguptone_indicate(struct chan_list *cl)
2849 {
2850         misdn_lib_send_tone(cl->bc, TONE_HANGUP);
2851         return 0;
2852 }
2853
2854 static int stop_indicate(struct chan_list *cl)
2855 {
2856         struct ast_channel *ast = cl->ast;
2857
2858         if (!ast) {
2859                 chan_misdn_log(0, cl->bc->port, "No Ast in stop_indicate\n");
2860                 return -1;
2861         }
2862
2863         chan_misdn_log(3, cl->bc->port, " --> None\n");
2864         misdn_lib_tone_generator_stop(cl->bc);
2865         ast_playtones_stop(ast);
2866
2867         cl->ts = NULL;
2868         /*ast_deactivate_generator(ast);*/
2869
2870         return 0;
2871 }
2872
2873
2874 static int start_bc_tones(struct chan_list* cl)
2875 {
2876         misdn_lib_tone_generator_stop(cl->bc);
2877         cl->notxtone = 0;
2878         cl->norxtone = 0;
2879         return 0;
2880 }
2881
2882 static int stop_bc_tones(struct chan_list *cl)
2883 {
2884         if (!cl) return -1;
2885
2886         cl->notxtone = 1;
2887         cl->norxtone = 1;
2888         
2889         return 0;
2890 }
2891
2892
2893 static struct chan_list *init_chan_list(int orig)
2894 {
2895         struct chan_list *cl;
2896
2897         cl = ast_calloc(1, sizeof(*cl));
2898
2899         if (!cl) {
2900                 chan_misdn_log(-1, 0, "misdn_request: malloc failed!");
2901                 return NULL;
2902         }
2903         
2904         cl->originator = orig;
2905         cl->need_queue_hangup = 1;
2906         cl->need_hangup = 1;
2907         cl->need_busy = 1;
2908         cl->overlap_dial_task = -1;
2909
2910         return cl;
2911 }
2912
2913 static struct ast_channel *misdn_request(const char *type, int format, void *data, int *cause)
2914 {
2915         struct ast_channel *tmp = NULL;
2916         char group[BUFFERSIZE + 1] = "";
2917         char buf[128];
2918         char *buf2 = ast_strdupa(data), *ext = NULL, *port_str;
2919         char *tokb = NULL, *p = NULL;
2920         int channel = 0, port = 0;
2921         struct misdn_bchannel *newbc = NULL;
2922         int dec = 0;
2923
2924         struct chan_list *cl = init_chan_list(ORG_AST);
2925
2926         snprintf(buf, sizeof(buf), "%s/%s", misdn_type, (char*)data);
2927
2928         port_str = strtok_r(buf2, "/", &tokb);
2929
2930         ext = strtok_r(NULL, "/", &tokb);
2931
2932         if (port_str) {
2933                 if (port_str[0] == 'g' && port_str[1] == ':' ) {
2934                         /* We make a group call lets checkout which ports are in my group */
2935                         port_str += 2;
2936                         ast_copy_string(group, port_str, sizeof(group));
2937                         chan_misdn_log(2, 0, " --> Group Call group: %s\n", group);
2938                 } else if ((p = strchr(port_str, ':'))) {
2939                         /* we have a preselected channel */
2940                         *p = 0;
2941                         channel = atoi(++p);
2942                         port = atoi(port_str);
2943                         chan_misdn_log(2, port, " --> Call on preselected Channel (%d).\n", channel);
2944                 } else {
2945                         port = atoi(port_str);
2946                 }
2947         } else {
2948                 ast_log(LOG_WARNING, " --> ! IND : CALL dad:%s WITHOUT PORT/Group, check extensions.conf\n", ext);
2949                 return NULL;
2950         }
2951
2952         if (misdn_cfg_is_group_method(group, METHOD_STANDARD_DEC)) {
2953                 chan_misdn_log(4, port, " --> STARTING STANDARDDEC...\n");
2954                 dec = 1;
2955         }
2956
2957         if (!ast_strlen_zero(group)) {
2958                 char cfg_group[BUFFERSIZE + 1];
2959                 struct robin_list *rr = NULL;
2960
2961                 if (misdn_cfg_is_group_method(group, METHOD_ROUND_ROBIN)) {
2962                         chan_misdn_log(4, port, " --> STARTING ROUND ROBIN...\n");
2963                         rr = get_robin_position(group);
2964                 }
2965
2966                 if (rr) {
2967                         int robin_channel = rr->channel;
2968                         int port_start;
2969                         int next_chan = 1;
2970
2971                         do {
2972                                 port_start = 0;
2973                                 for (port = misdn_cfg_get_next_port_spin(rr->port); port > 0 && port != port_start;
2974                                          port = misdn_cfg_get_next_port_spin(port)) {
2975
2976                                         if (!port_start)
2977                                                 port_start = port;
2978
2979                                         if (port >= port_start)
2980                                                 next_chan = 1;
2981                                         
2982                                         if (port <= port_start && next_chan) {
2983                                                 int maxbchans=misdn_lib_get_maxchans(port);
2984                                                 if (++robin_channel >= maxbchans) {
2985                                                         robin_channel = 1;
2986                                                 }
2987                                                 next_chan = 0;
2988                                         }
2989
2990                                         misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, sizeof(cfg_group));
2991
2992                                         if (!strcasecmp(cfg_group, group)) {
2993                                                 int port_up;
2994                                                 int check;
2995                                                 misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(check));
2996                                                 port_up = misdn_lib_port_up(port, check);
2997
2998                                                 if (check && !port_up) 
2999                                                         chan_misdn_log(1, port, "L1 is not Up on this Port\n");
3000                                                 
3001                                                 if (check && port_up < 0) {
3002                                                         ast_log(LOG_WARNING, "This port (%d) is blocked\n", port);
3003                                                 }
3004
3005                                                 if (port_up > 0)        {
3006                                                         newbc = misdn_lib_get_free_bc(port, robin_channel, 0, 0);
3007                                                         if (newbc) {
3008                                                                 chan_misdn_log(4, port, " Success! Found port:%d channel:%d\n", newbc->port, newbc->channel);
3009                                                                 if (port_up)
3010                                                                         chan_misdn_log(4, port, "portup:%d\n",  port_up);
3011                                                                 rr->port = newbc->port;
3012                                                                 rr->channel = newbc->channel;
3013                                                                 break;
3014                                                         }
3015                                                 }
3016                                         }
3017                                 }
3018                         } while (!newbc && robin_channel != rr->channel);
3019                         
3020                 } else {                
3021                         for (port = misdn_cfg_get_next_port(0); port > 0;
3022                                  port = misdn_cfg_get_next_port(port)) {
3023
3024                                 misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, sizeof(cfg_group));
3025
3026                                 chan_misdn_log(3, port, "Group [%s] Port [%d]\n", group, port);
3027                                 if (!strcasecmp(cfg_group, group)) {
3028                                         int port_up;
3029                                         int check;
3030                                         misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(check));
3031                                         port_up = misdn_lib_port_up(port, check);
3032
3033                                         chan_misdn_log(4, port, "portup:%d\n", port_up);
3034
3035                                         if (port_up > 0) {
3036                                                 newbc = misdn_lib_get_free_bc(port, 0, 0, dec);
3037                                                 if (newbc)
3038                                                         break;
3039                                         }
3040                                 }
3041                         }
3042                 }
3043                 
3044                 /* Group dial failed ?*/
3045                 if (!newbc) {
3046                         ast_log(LOG_WARNING, 
3047                                         "Could not Dial out on group '%s'.\n"
3048                                         "\tEither the L2 and L1 on all of these ports where DOWN (see 'show application misdn_check_l2l1')\n"
3049                                         "\tOr there was no free channel on none of the ports\n\n"
3050                                         , group);
3051                         return NULL;
3052                 }
3053         } else { /* 'Normal' Port dial * Port dial */
3054                 if (channel)
3055                         chan_misdn_log(1, port, " --> preselected_channel: %d\n", channel);
3056                 newbc = misdn_lib_get_free_bc(port, channel, 0, dec);
3057
3058                 if (!newbc) {
3059                         ast_log(LOG_WARNING, "Could not create channel on port:%d with extensions:%s\n", port, ext);
3060                         return NULL;
3061                 }
3062         }
3063         
3064
3065         /* create ast_channel and link all the objects together */
3066         cl->bc = newbc;
3067         
3068         tmp = misdn_new(cl, AST_STATE_RESERVED, ext, NULL, format, port, channel);
3069         if (!tmp) {
3070                 ast_log(LOG_ERROR,"Could not create Asterisk object\n");
3071                 return NULL;
3072         }
3073
3074         cl->ast=tmp;
3075         
3076         /* register chan in local list */
3077         cl_queue_chan(&cl_te, cl) ;
3078         
3079         /* fill in the config into the objects */
3080         read_config(cl, ORG_AST);
3081
3082         /* important */
3083         cl->need_hangup = 0;
3084         
3085         return tmp;
3086 }
3087
3088
3089 static int misdn_send_text(struct ast_channel *chan, const char *text)
3090 {
3091         struct chan_list *tmp = chan->tech_pvt;
3092         
3093         if (tmp && tmp->bc) {
3094                 ast_copy_string(tmp->bc->display, text, sizeof(tmp->bc->display));
3095                 misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
3096         } else {
3097                 ast_log(LOG_WARNING, "No chan_list but send_text request?\n");
3098                 return -1;
3099         }
3100         
3101         return 0;
3102 }
3103
3104 static struct ast_channel_tech misdn_tech = {
3105         .type = "mISDN",
3106         .description = "Channel driver for mISDN Support (Bri/Pri)",
3107         .capabilities = AST_FORMAT_ALAW ,
3108         .requester = misdn_request,
3109         .send_digit_begin = misdn_digit_begin,
3110         .send_digit_end = misdn_digit_end,
3111         .call = misdn_call,
3112         .bridge = misdn_bridge, 
3113         .hangup = misdn_hangup,
3114         .answer = misdn_answer,
3115         .read = misdn_read,
3116         .write = misdn_write,
3117         .indicate = misdn_indication,
3118         .fixup = misdn_fixup,
3119         .send_text = misdn_send_text,
3120         .properties = 0
3121 };
3122
3123 static struct ast_channel_tech misdn_tech_wo_bridge = {
3124         .type = "mISDN",
3125         .description = "Channel driver for mISDN Support (Bri/Pri)",
3126         .capabilities = AST_FORMAT_ALAW ,
3127         .requester = misdn_request,
3128         .send_digit_begin = misdn_digit_begin,
3129         .send_digit_end = misdn_digit_end,
3130         .call = misdn_call,
3131         .hangup = misdn_hangup,
3132         .answer = misdn_answer,
3133         .read = misdn_read,
3134         .write = misdn_write,
3135         .indicate = misdn_indication,
3136         .fixup = misdn_fixup,
3137         .send_text = misdn_send_text,
3138         .properties = 0
3139 };
3140
3141
3142 static int glob_channel = 0;
3143
3144 static void update_name(struct ast_channel *tmp, int port, int c) 
3145 {
3146         int chan_offset = 0;
3147         int tmp_port = misdn_cfg_get_next_port(0);
3148         for (; tmp_port > 0; tmp_port = misdn_cfg_get_next_port(tmp_port)) {
3149                 if (tmp_port == port)
3150                         break;
3151                 chan_offset += misdn_lib_port_is_pri(tmp_port) ? 30 : 2;        
3152         }
3153         if (c < 0)
3154                 c = 0;
3155
3156         ast_string_field_build(tmp, name, "%s/%d-u%d",
3157                                  misdn_type, chan_offset+c, glob_channel++);
3158
3159         chan_misdn_log(3 , port, " --> updating channel name to [%s]\n", tmp->name);
3160 }
3161
3162 static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char *exten, char *callerid, int format, int port, int c)
3163 {
3164         struct ast_channel *tmp;
3165         char *cid_name = 0, *cid_num = 0;
3166         int chan_offset = 0;
3167         int tmp_port = misdn_cfg_get_next_port(0);
3168         int bridging;
3169
3170         for (; tmp_port > 0; tmp_port = misdn_cfg_get_next_port(tmp_port)) {
3171                 if (tmp_port == port)
3172                         break;
3173                 chan_offset += misdn_lib_port_is_pri(tmp_port) ? 30 : 2;        
3174         }
3175         if (c < 0)
3176                 c = 0;
3177
3178         if (callerid) 
3179                 ast_callerid_parse(callerid, &cid_name, &cid_num);
3180
3181         tmp = ast_channel_alloc(1, state, cid_num, cid_name, "", exten, "", 0, "%s/%d-u%d", misdn_type, chan_offset + c, glob_channel++);
3182
3183         if (tmp) {
3184                 chan_misdn_log(2, 0, " --> * NEW CHANNEL dad:%s oad:%s\n", exten, callerid);
3185
3186                 tmp->nativeformats = prefformat;
3187
3188                 tmp->readformat = format;
3189                 tmp->rawreadformat = format;
3190                 tmp->writeformat = format;
3191                 tmp->rawwriteformat = format;
3192     
3193                 tmp->tech_pvt = chlist;
3194
3195                 misdn_cfg_get(0, MISDN_GEN_BRIDGING, &bridging, sizeof(bridging));
3196
3197                 if (bridging)
3198                         tmp->tech = &misdn_tech;
3199                 else
3200                         tmp->tech = &misdn_tech_wo_bridge;
3201
3202                 tmp->writeformat = format;
3203                 tmp->readformat = format;
3204                 tmp->priority=1;
3205
3206                 if (exten) 
3207                         ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
3208                 else
3209                         chan_misdn_log(1, 0, "misdn_new: no exten given.\n");
3210
3211                 if (callerid) {
3212                         char *cid_name, *cid_num;
3213       
3214                         ast_callerid_parse(callerid, &cid_name, &cid_num);
3215                         /* Don't use ast_set_callerid() here because it will
3216                          * generate a needless NewCallerID event */
3217                         tmp->cid.cid_num = ast_strdup(cid_num);
3218                         tmp->cid.cid_ani = ast_strdup(cid_num);
3219                         tmp->cid.cid_name = ast_strdup(cid_name);
3220                 }
3221
3222                 if (pipe(chlist->pipe) < 0)
3223                         ast_log(LOG_ERROR, "Pipe failed\n");
3224
3225                 tmp->fds[0] = chlist->pipe[0];
3226
3227                 if (state == AST_STATE_RING)
3228                         tmp->rings = 1;
3229                 else
3230                         tmp->rings = 0;
3231                 
3232                 ast_jb_configure(tmp, misdn_get_global_jbconf());
3233         } else {
3234                 chan_misdn_log(-1, 0, "Unable to allocate channel structure\n");
3235         }
3236         
3237         return tmp;
3238 }
3239
3240 static struct chan_list *find_chan_by_bc(struct chan_list *list, struct misdn_bchannel *bc)
3241 {
3242         struct chan_list *help = list;
3243         for (; help; help = help->next) {
3244                 if (help->bc == bc) return help;
3245         }
3246
3247         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n", bc->oad, bc->dad);
3248
3249         return NULL;
3250 }
3251
3252 static struct chan_list *find_chan_by_pid(struct chan_list *list, int pid)
3253 {
3254         struct chan_list *help = list;
3255         for (; help; help = help->next) {
3256                 if ( help->bc && (help->bc->pid == pid) ) return help;
3257         }
3258
3259         chan_misdn_log(6, 0, "$$$ find_chan: No channel found for pid:%d\n", pid);
3260
3261         return NULL;
3262 }
3263
3264 static struct chan_list *find_holded(struct chan_list *list, struct misdn_bchannel *bc)
3265 {
3266         struct chan_list *help = list;
3267
3268         if (bc->pri) return NULL;
3269
3270         chan_misdn_log(6, bc->port, "$$$ find_holded: channel:%d oad:%s dad:%s\n", bc->channel, bc->oad, bc->dad);
3271         for (;help; help = help->next) {
3272                 chan_misdn_log(4, bc->port, "$$$ find_holded: --> holded:%d channel:%d\n", help->state==MISDN_HOLDED, help->hold_info.channel);
3273                 if (    (help->state == MISDN_HOLDED) && 
3274                         (help->hold_info.port == bc->port) ) 
3275                         return help;
3276         }
3277         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n", bc->oad, bc->dad);
3278
3279         return NULL;
3280 }
3281
3282
3283 static struct chan_list *find_holded_l3(struct chan_list *list, unsigned long l3_id, int w) 
3284 {
3285         struct chan_list *help = list;
3286
3287         for (; help; help = help->next) {
3288                 if ( (help->state == MISDN_HOLDED) &&
3289                          (help->l3id == l3_id)   
3290                         ) 
3291                         return help;
3292         }
3293
3294         return NULL;
3295 }
3296
3297 static void cl_queue_chan(struct chan_list **list, struct chan_list *chan)
3298 {
3299         chan_misdn_log(4, chan->bc ? chan->bc->port : 0, "* Queuing chan %p\n", chan);
3300   
3301         ast_mutex_lock(&cl_te_lock);
3302         if (!*list) {
3303                 *list = chan;
3304         } else {
3305                 struct chan_list *help = *list;
3306                 for (; help->next; help = help->next); 
3307                 help->next = chan;
3308         }
3309         chan->next = NULL;
3310         ast_mutex_unlock(&cl_te_lock);
3311 }
3312
3313 static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan) 
3314 {
3315         struct chan_list *help;
3316
3317         if (chan->dsp) 
3318                 ast_dsp_free(chan->dsp);
3319         if (chan->trans)
3320                 ast_translator_free_path(chan->trans);
3321
3322         ast_mutex_lock(&cl_te_lock);
3323         if (!*list) {
3324                 ast_mutex_unlock(&cl_te_lock);
3325                 return;
3326         }
3327   
3328         if (*list == chan) {
3329                 *list = (*list)->next;
3330                 ast_mutex_unlock(&cl_te_lock);
3331                 return;
3332         }
3333   
3334         for (help = *list; help->next; help = help->next) {
3335                 if (help->next == chan) {
3336                         help->next = help->next->next;
3337                         ast_mutex_unlock(&cl_te_lock);
3338                         return;
3339                 }
3340         }
3341         
3342         ast_mutex_unlock(&cl_te_lock);
3343 }
3344
3345 /** Channel Queue End **/
3346
3347
3348 int pbx_start_chan(struct chan_list *ch)
3349 {
3350         int ret = ast_pbx_start(ch->ast);       
3351
3352         if (ret >= 0) 
3353                 ch->need_hangup = 0;
3354         else
3355                 ch->need_hangup = 1;
3356
3357         return ret;
3358 }
3359
3360 static void hangup_chan(struct chan_list *ch)
3361 {
3362         int port = ch ? (ch->bc ? ch->bc->port : 0) : 0;
3363         if (!ch) {
3364                 cb_log(1, 0, "Cannot hangup chan, no ch\n");
3365                 return;
3366         }
3367
3368         cb_log(5, port, "hangup_chan called\n");
3369
3370         if (ch->need_hangup) {
3371                 cb_log(2, port, " --> hangup\n");
3372                 send_cause2ast(ch->ast, ch->bc, ch);
3373                 ch->need_hangup = 0;
3374                 ch->need_queue_hangup = 0;
3375                 if (ch->ast)
3376                         ast_hangup(ch->ast);
3377                 return;
3378         }
3379
3380         if (!ch->need_queue_hangup) {
3381                 cb_log(2, port, " --> No need to queue hangup\n");
3382         }
3383
3384         ch->need_queue_hangup = 0;
3385         if (ch->ast) {
3386                 send_cause2ast(ch->ast, ch->bc, ch);
3387
3388                 if (ch->ast)
3389                         ast_queue_hangup(ch->ast);
3390                 cb_log(2, port, " --> queue_hangup\n");
3391         } else {
3392                 cb_log(1, port, "Cannot hangup chan, no ast\n");
3393         }
3394 }
3395
3396 /** Isdn asks us to release channel, pendant to misdn_hangup **/
3397 static void release_chan(struct misdn_bchannel *bc) {
3398         struct ast_channel *ast=NULL;
3399
3400         ast_mutex_lock(&release_lock);
3401         {
3402                 struct chan_list *ch=find_chan_by_bc(cl_te, bc);
3403                 if (!ch)  {
3404                         chan_misdn_log(1, bc->port, "release_chan: Ch not found!\n");
3405                         ast_mutex_unlock(&release_lock);
3406                         return;
3407                 }
3408
3409                 if (ch->ast) {
3410                         ast = ch->ast;
3411                 } 
3412
3413                 chan_misdn_log(5, bc->port, "release_chan: bc with l3id: %x\n", bc->l3_id);
3414
3415                 /*releaseing jitterbuffer*/
3416                 if (ch->jb ) {
3417                         misdn_jb_destroy(ch->jb);
3418                         ch->jb = NULL;
3419                 } else {
3420                         if (!bc->nojitter)
3421                                 chan_misdn_log(5, bc->port, "Jitterbuffer already destroyed.\n");
3422                 }
3423
3424                 if (ch->overlap_dial) {
3425                         if (ch->overlap_dial_task != -1) {
3426                                 misdn_tasks_remove(ch->overlap_dial_task);
3427                                 ch->overlap_dial_task = -1;
3428                         }
3429                         ast_mutex_destroy(&ch->overlap_tv_lock);
3430                 }
3431
3432                 if (ch->originator == ORG_AST) {
3433                         misdn_out_calls[bc->port]--;
3434                 } else {
3435                         misdn_in_calls[bc->port]--;
3436                 }
3437
3438                 if (ch) {
3439                         close(ch->pipe[0]);
3440                         close(ch->pipe[1]);
3441
3442                         if (ast && MISDN_ASTERISK_TECH_PVT(ast)) {
3443                                 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));
3444                                 chan_misdn_log(3, bc->port, " --> * State Down\n");
3445                                 MISDN_ASTERISK_TECH_PVT(ast) = NULL;
3446
3447                                 if (ast->_state != AST_STATE_RESERVED) {
3448                                         chan_misdn_log(3, bc->port, " --> Setting AST State to down\n");
3449                                         ast_setstate(ast, AST_STATE_DOWN);
3450                                 }
3451                         }
3452
3453                         ch->state = MISDN_CLEANING;
3454                         cl_dequeue_chan(&cl_te, ch);
3455
3456                         ast_free(ch);
3457                 } else {
3458                         /* chan is already cleaned, so exiting  */
3459                 }
3460
3461                 ast_mutex_unlock(&release_lock);
3462         }
3463 /*** release end **/
3464 }
3465
3466 static void misdn_transfer_bc(struct chan_list *tmp_ch, struct chan_list *holded_chan)
3467 {
3468         chan_misdn_log(4, 0, "TRANSFERING %s to %s\n", holded_chan->ast->name, tmp_ch->ast->name);
3469
3470         tmp_ch->state = MISDN_HOLD_DISCONNECT;
3471
3472         ast_moh_stop(ast_bridged_channel(holded_chan->ast));
3473
3474         holded_chan->state=MISDN_CONNECTED;
3475         /* misdn_lib_transfer(holded_chan->bc); */
3476         ast_channel_masquerade(holded_chan->ast, ast_bridged_channel(tmp_ch->ast));
3477 }
3478
3479
3480 static void do_immediate_setup(struct misdn_bchannel *bc, struct chan_list *ch, struct ast_channel *ast)
3481 {
3482         char *predial;
3483         struct ast_frame fr;
3484
3485         predial = ast_strdupa(ast->exten);
3486
3487         ch->state = MISDN_DIALING;
3488
3489         if (!ch->noautorespond_on_setup) {
3490                 if (bc->nt) {
3491                         int ret; 
3492                         ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3493                 } else {
3494                         int ret;
3495                         if ( misdn_lib_is_ptp(bc->port)) {
3496                                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3497                         } else {
3498                                 ret = misdn_lib_send_event(bc, EVENT_PROCEEDING );
3499                         }
3500                 }
3501         } else {
3502                 ch->state = MISDN_INCOMING_SETUP;
3503         }
3504
3505         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);
3506   
3507         strncpy(ast->exten, "s", 2);
3508   
3509         if (pbx_start_chan(ch) < 0) {
3510                 ast = NULL;
3511                 hangup_chan(ch);
3512                 hanguptone_indicate(ch);
3513
3514                 if (bc->nt)
3515                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3516                 else
3517                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
3518         }
3519   
3520   
3521         while (!ast_strlen_zero(predial) ) {
3522                 fr.frametype = AST_FRAME_DTMF;
3523                 fr.subclass = *predial;
3524                 fr.src = NULL;
3525                 fr.data = NULL;
3526                 fr.datalen = 0;
3527                 fr.samples = 0;
3528                 fr.mallocd = 0;
3529                 fr.offset = 0;
3530                 fr.delivery = ast_tv(0,0);
3531
3532                 if (ch->ast && MISDN_ASTERISK_PVT(ch->ast) && MISDN_ASTERISK_TECH_PVT(ch->ast)) {
3533                         ast_queue_frame(ch->ast, &fr);
3534                 }
3535                 predial++;
3536         }
3537 }
3538
3539
3540
3541 static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel *bc, struct chan_list *ch) {
3542         if (!ast) {
3543                 chan_misdn_log(1, 0, "send_cause2ast: No Ast\n");
3544                 return;
3545         }
3546         if (!bc) {
3547                 chan_misdn_log(1, 0, "send_cause2ast: No BC\n");
3548                 return;
3549         }
3550         if (!ch) {
3551                 chan_misdn_log(1, 0, "send_cause2ast: No Ch\n");
3552                 return;
3553         }
3554
3555         ast->hangupcause = bc->cause;
3556
3557         switch (bc->cause) {
3558
3559         case 1: /** Congestion Cases **/
3560         case 2:
3561         case 3:
3562         case 4:
3563         case 22:
3564         case 27:
3565                 /*
3566                  * Not Queueing the Congestion anymore, since we want to hear
3567                  * the inband message
3568                  *
3569                 chan_misdn_log(1, bc ? bc->port : 0, " --> * SEND: Queue Congestion pid:%d\n", bc ? bc->pid : -1);
3570                 ch->state = MISDN_BUSY;
3571                 
3572                 ast_queue_control(ast, AST_CONTROL_CONGESTION);
3573                 */
3574                 break;
3575
3576         case 21:
3577         case 17: /* user busy */
3578
3579                 ch->state = MISDN_BUSY;
3580
3581                 if (!ch->need_busy) {
3582                         chan_misdn_log(1, bc ? bc->port : 0, "Queued busy already\n");
3583                         break;
3584                 }
3585
3586                 chan_misdn_log(1, bc ? bc->port : 0, " --> * SEND: Queue Busy pid:%d\n", bc ? bc->pid : -1);
3587                 
3588                 ast_queue_control(ast, AST_CONTROL_BUSY);
3589                 
3590                 ch->need_busy = 0;
3591                 
3592                 break;
3593         }
3594 }
3595
3596
3597 void import_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
3598 {
3599         const char *tmp = pbx_builtin_getvar_helper(chan, "MISDN_PID");
3600         if (tmp) {
3601                 ch->other_pid = atoi(tmp);
3602                 chan_misdn_log(3, bc->port, " --> IMPORT_PID: importing pid:%s\n", tmp);
3603                 if (ch->other_pid > 0) {
3604                         ch->other_ch = find_chan_by_pid(cl_te, ch->other_pid);
3605                         if (ch->other_ch)
3606                                 ch->other_ch->other_ch = ch;
3607                 }
3608         }
3609
3610         tmp = pbx_builtin_getvar_helper(chan, "MISDN_ADDRESS_COMPLETE");
3611         if (tmp && (atoi(tmp) == 1)) {
3612                 bc->sending_complete = 1;
3613         }
3614
3615         tmp = pbx_builtin_getvar_helper(chan, "MISDN_USERUSER");
3616         if (tmp) {
3617                 ast_log(LOG_NOTICE, "MISDN_USERUSER: %s\n", tmp);
3618                 ast_copy_string(bc->uu, tmp, sizeof(bc->uu));
3619                 bc->uulen = strlen(bc->uu);
3620         }
3621
3622         tmp = pbx_builtin_getvar_helper(chan, "MISDN_KEYPAD");
3623         if (tmp)
3624                 ast_copy_string(bc->keypad, tmp, sizeof(bc->keypad));
3625 }
3626
3627 void export_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
3628 {
3629         char tmp[32];
3630         chan_misdn_log(3, bc->port, " --> EXPORT_PID: pid:%d\n", bc->pid);
3631         snprintf(tmp, sizeof(tmp), "%d", bc->pid);
3632         pbx_builtin_setvar_helper(chan, "_MISDN_PID", tmp);
3633
3634         if (bc->sending_complete) {
3635                 snprintf(tmp, sizeof(tmp), "%d", bc->sending_complete);
3636                 pbx_builtin_setvar_helper(chan, "MISDN_ADDRESS_COMPLETE", tmp);
3637         }
3638
3639         if (bc->urate) {
3640                 snprintf(tmp, sizeof(tmp), "%d", bc->urate);
3641                 pbx_builtin_setvar_helper(chan, "MISDN_URATE", tmp);
3642         }
3643
3644         if (bc->uulen)
3645                 pbx_builtin_setvar_helper(chan, "MISDN_USERUSER", bc->uu);
3646
3647         if (!ast_strlen_zero(bc->keypad)) 
3648                 pbx_builtin_setvar_helper(chan, "MISDN_KEYPAD", bc->keypad);
3649 }
3650
3651 int add_in_calls(int port)
3652 {
3653         int max_in_calls;