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