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