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