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