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