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