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