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