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