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