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