Merged revisions 47989 via svnmerge from
[asterisk/asterisk.git] / channels / chan_misdn.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  * 
4  * Copyright (C) 2004 - 2006, Christian Richter
5  *
6  * Christian Richter <crich@beronet.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  *
18  */
19
20 /*!
21  * \file
22  *
23  * \brief the chan_misdn channel driver for Asterisk
24  * \author Christian Richter <crich@beronet.com>
25  *
26  * \ingroup channel_drivers
27  */
28
29 /*** MODULEINFO
30         <depend>isdnnet</depend>
31         <depend>misdn</depend>
32         <depend>suppserv</depend>
33  ***/
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 #include <stdio.h>
39 #include <pthread.h>
40 #include <string.h>
41 #include <sys/socket.h>
42 #include <sys/time.h>
43 #include <errno.h>
44 #include <unistd.h>
45 #include <stdlib.h>
46 #include <arpa/inet.h>
47 #include <fcntl.h>
48 #include <sys/ioctl.h>
49 #include <signal.h>
50 #include <sys/file.h>
51 #include <semaphore.h>
52
53 #include "asterisk/channel.h"
54 #include "asterisk/config.h"
55 #include "asterisk/logger.h"
56 #include "asterisk/module.h"
57 #include "asterisk/pbx.h"
58 #include "asterisk/options.h"
59 #include "asterisk/io.h"
60 #include "asterisk/frame.h"
61 #include "asterisk/translate.h"
62 #include "asterisk/cli.h"
63 #include "asterisk/musiconhold.h"
64 #include "asterisk/dsp.h"
65 #include "asterisk/translate.h"
66 #include "asterisk/config.h"
67 #include "asterisk/file.h"
68 #include "asterisk/callerid.h"
69 #include "asterisk/indications.h"
70 #include "asterisk/app.h"
71 #include "asterisk/features.h"
72 #include "asterisk/term.h"
73 #include "asterisk/sched.h"
74 #include "asterisk/stringfields.h"
75
76 #include "chan_misdn_config.h"
77 #include "isdn_lib.h"
78
79 char global_tracefile[BUFFERSIZE+1];
80
81 static int g_config_initialized=0;
82
83 struct misdn_jb{
84         int size;
85         int upper_threshold;
86         char *samples, *ok;
87         int wp,rp;
88         int state_empty;
89         int state_full;
90         int state_buffer;
91         int bytes_wrote;
92         ast_mutex_t mutexjb;
93 };
94
95
96
97 /* allocates the jb-structure and initialise the elements*/
98 struct misdn_jb *misdn_jb_init(int size, int upper_threshold);
99
100 /* frees the data and destroys the given jitterbuffer struct */
101 void misdn_jb_destroy(struct misdn_jb *jb);
102
103 /* fills the jitterbuffer with len data returns < 0 if there was an
104 error (bufferoverun). */
105 int misdn_jb_fill(struct misdn_jb *jb, const char *data, int len);
106
107 /* gets len bytes out of the jitterbuffer if available, else only the
108 available data is returned and the return value indicates the number
109 of data. */
110 int misdn_jb_empty(struct misdn_jb *jb, char *data, int len);
111
112
113 enum misdn_chan_state {
114         MISDN_NOTHING=0,        /*!< at beginning */
115         MISDN_WAITING4DIGS, /*!<  when waiting for infos */
116         MISDN_EXTCANTMATCH, /*!<  when asterisk couldnt match our ext */
117         MISDN_DIALING, /*!<  when pbx_start */
118         MISDN_PROGRESS, /*!<  we got a progress */
119         MISDN_PROCEEDING, /*!<  we got a progress */
120         MISDN_CALLING, /*!<  when misdn_call is called */
121         MISDN_CALLING_ACKNOWLEDGE, /*!<  when we get SETUP_ACK */
122         MISDN_ALERTING, /*!<  when Alerting */
123         MISDN_BUSY, /*!<  when BUSY */
124         MISDN_CONNECTED, /*!<  when connected */
125         MISDN_PRECONNECTED, /*!<  when connected */
126         MISDN_DISCONNECTED, /*!<  when connected */
127         MISDN_RELEASED, /*!<  when connected */
128         MISDN_BRIDGED, /*!<  when bridged */
129         MISDN_CLEANING, /*!< when hangup from * but we were connected before */
130         MISDN_HUNGUP_FROM_MISDN, /*!< when DISCONNECT/RELEASE/REL_COMP  cam from misdn */
131         MISDN_HUNGUP_FROM_AST, /*!< when DISCONNECT/RELEASE/REL_COMP came out of */
132         /* misdn_hangup */
133         MISDN_HOLDED, /*!< if this chan is holded */
134         MISDN_HOLD_DISCONNECT, /*!< if this chan is holded */
135         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(2, 0, "ITS A HOLDED BC:\n");
1049                                 chan_misdn_log(2,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(7,port,"update_config: Getting Config\n");
1448
1449         int hdlc=0;
1450         misdn_cfg_get( port, MISDN_CFG_HDLC, &hdlc, sizeof(int));
1451         
1452         if (hdlc) {
1453                 switch (bc->capability) {
1454                 case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
1455                 case INFO_CAPABILITY_DIGITAL_RESTRICTED:
1456                         chan_misdn_log(1,bc->port," --> CONF HDLC\n");
1457                         bc->hdlc=1;
1458                         break;
1459                 }
1460                 
1461         }
1462         
1463         
1464         int pres, screen;
1465                         
1466         misdn_cfg_get( port, MISDN_CFG_PRES, &pres, sizeof(int));
1467         misdn_cfg_get( port, MISDN_CFG_SCREEN, &screen, sizeof(int));
1468         chan_misdn_log(2,port," --> pres: %d screen: %d\n",pres, screen);
1469                 
1470         if ( (pres + screen) < 0 ) {
1471
1472                 chan_misdn_log(2,port," --> pres: %x\n", ast->cid.cid_pres);
1473                         
1474                 switch (ast->cid.cid_pres & 0x60){
1475                                 
1476                 case AST_PRES_RESTRICTED:
1477                         bc->pres=1;
1478                         chan_misdn_log(2, port, " --> PRES: Restricted (0x1)\n");
1479                         break;
1480                                 
1481                                 
1482                 case AST_PRES_UNAVAILABLE:
1483                         bc->pres=2;
1484                         chan_misdn_log(2, port, " --> PRES: Unavailable (0x2)\n");
1485                         break;
1486                                 
1487                 default:
1488                         bc->pres=0;
1489                         chan_misdn_log(2, port, " --> PRES: Allowed (0x0)\n");
1490                 }
1491                         
1492                 switch (ast->cid.cid_pres & 0x3){
1493                                 
1494                 case AST_PRES_USER_NUMBER_UNSCREENED:
1495                         bc->screen=0;
1496                         chan_misdn_log(2, port, " --> SCREEN: Unscreened (0x0)\n");
1497                         break;
1498
1499                 case AST_PRES_USER_NUMBER_PASSED_SCREEN:
1500                         bc->screen=1;
1501                         chan_misdn_log(2, port, " --> SCREEN: Passed Screen (0x1)\n");
1502                         break;
1503                 case AST_PRES_USER_NUMBER_FAILED_SCREEN:
1504                         bc->screen=2;
1505                         chan_misdn_log(2, port, " --> SCREEN: Failed Screen (0x2)\n");
1506                         break;
1507                                 
1508                 case AST_PRES_NETWORK_NUMBER:
1509                         bc->screen=3;
1510                         chan_misdn_log(2, port, " --> SCREEN: Network Nr. (0x3)\n");
1511                         break;
1512                                 
1513                 default:
1514                         bc->screen=0;
1515                         chan_misdn_log(2, port, " --> SCREEN: Unscreened (0x0)\n");
1516                 }
1517
1518                         
1519         } else {
1520                 bc->screen=screen;
1521                 bc->pres=pres;
1522         }
1523
1524         return 0;
1525         
1526 }
1527
1528
1529
1530
1531 static void config_jitterbuffer(struct chan_list *ch)
1532 {
1533         struct misdn_bchannel *bc=ch->bc;
1534         int len=ch->jb_len, threshold=ch->jb_upper_threshold;
1535         
1536         chan_misdn_log(5,bc->port, "config_jb: Called\n");
1537         
1538         if ( ! len ) {
1539                 chan_misdn_log(1,bc->port, "config_jb: Deactivating Jitterbuffer\n");
1540                 bc->nojitter=1;
1541         } else {
1542                 
1543                 if (len <=100 || len > 8000) {
1544                         chan_misdn_log(0,bc->port,"config_jb: Jitterbuffer out of Bounds, setting to 1000\n");
1545                         len=1000;
1546                 }
1547                 
1548                 if ( threshold > len ) {
1549                         chan_misdn_log(0,bc->port,"config_jb: Jitterbuffer Threshold > Jitterbuffer setting to Jitterbuffer -1\n");
1550                 }
1551                 
1552                 if ( ch->jb) {
1553                         cb_log(0,bc->port,"config_jb: We've got a Jitterbuffer Already on this port.\n");
1554                         misdn_jb_destroy(ch->jb);
1555                         ch->jb=NULL;
1556                 }
1557                 
1558                 ch->jb=misdn_jb_init(len, threshold);
1559
1560                 if (!ch->jb ) 
1561                         bc->nojitter=1;
1562         }
1563 }
1564
1565
1566 void debug_numplan(int port, int numplan, char *type)
1567 {
1568         switch (numplan) {
1569         case NUMPLAN_INTERNATIONAL:
1570                 chan_misdn_log(2, port, " --> %s: International\n",type);
1571                 break;
1572         case NUMPLAN_NATIONAL:
1573                 chan_misdn_log(2, port, " --> %s: National\n",type);
1574                 break;
1575         case NUMPLAN_SUBSCRIBER:
1576                 chan_misdn_log(2, port, " --> %s: Subscriber\n",type);
1577                 break;
1578         case NUMPLAN_UNKNOWN:
1579                 chan_misdn_log(2, port, " --> %s: Unknown\n",type);
1580                 break;
1581                 /* Maybe we should cut off the prefix if present ? */
1582         default:
1583                 chan_misdn_log(0, port, " --> !!!! Wrong dialplan setting, please see the misdn.conf sample file\n ");
1584                 break;
1585         }
1586 }
1587
1588
1589
1590
1591 static int update_ec_config(struct misdn_bchannel *bc)
1592 {
1593         int ec;
1594         int port=bc->port;
1595                 
1596         misdn_cfg_get( port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
1597         
1598         if (ec == 1 ) {
1599                 bc->ec_enable=1;
1600         } else if ( ec > 1 ) {
1601                 bc->ec_enable=1;
1602                 bc->ec_deftaps=ec;
1603         }
1604 #ifdef WITH_ECHOTRAINING 
1605         int ectr;
1606         misdn_cfg_get( port, MISDN_CFG_ECHOTRAINING, &ectr, sizeof(int));
1607         
1608         if ( ectr >= 0 ) {
1609                 bc->ec_training=ectr;
1610         }
1611 #endif
1612
1613         return 0;
1614 }
1615
1616
1617 static int read_config(struct chan_list *ch, int orig) {
1618
1619         if (!ch) {
1620                 ast_log(LOG_WARNING, "Cannot configure without chanlist\n");
1621                 return -1;
1622         }
1623
1624         struct ast_channel *ast=ch->ast;
1625         struct misdn_bchannel *bc=ch->bc;
1626         if (! ast || ! bc ) {
1627                 ast_log(LOG_WARNING, "Cannot configure without ast || bc\n");
1628                 return -1;
1629         }
1630         
1631         int port=bc->port;
1632         
1633         chan_misdn_log(1,port,"read_config: Getting Config\n");
1634
1635         char lang[BUFFERSIZE+1];
1636         
1637
1638         misdn_cfg_get( port, MISDN_CFG_LANGUAGE, lang, BUFFERSIZE);
1639         ast_string_field_set(ast, language, lang);
1640
1641         char localmusicclass[BUFFERSIZE+1];
1642         
1643         misdn_cfg_get( port, MISDN_CFG_MUSICCLASS, localmusicclass, BUFFERSIZE);
1644         ast_string_field_set(ast, musicclass, localmusicclass);
1645         
1646         
1647         misdn_cfg_get( port, MISDN_CFG_TXGAIN, &bc->txgain, sizeof(int));
1648         misdn_cfg_get( port, MISDN_CFG_RXGAIN, &bc->rxgain, sizeof(int));
1649         
1650         misdn_cfg_get( port, MISDN_CFG_INCOMING_EARLY_AUDIO, &ch->incoming_early_audio, sizeof(int));
1651         
1652         misdn_cfg_get( port, MISDN_CFG_SENDDTMF, &bc->send_dtmf, sizeof(int));
1653
1654         misdn_cfg_get( port, MISDN_CFG_NEED_MORE_INFOS, &bc->need_more_infos, sizeof(int));
1655         misdn_cfg_get( port, MISDN_CFG_NTTIMEOUT, &ch->nttimeout, sizeof(int));
1656         
1657         misdn_cfg_get( port, MISDN_CFG_FAR_ALERTING, &ch->far_alerting, sizeof(int));
1658
1659         misdn_cfg_get( port, MISDN_CFG_ALLOWED_BEARERS, &ch->allowed_bearers, BUFFERSIZE);
1660         
1661         char faxdetect[BUFFERSIZE+1];
1662         misdn_cfg_get( port, MISDN_CFG_FAXDETECT, faxdetect, BUFFERSIZE);
1663         
1664         int hdlc=0;
1665         misdn_cfg_get( port, MISDN_CFG_HDLC, &hdlc, sizeof(int));
1666         
1667         if (hdlc) {
1668                 switch (bc->capability) {
1669                 case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
1670                 case INFO_CAPABILITY_DIGITAL_RESTRICTED:
1671                         chan_misdn_log(1,bc->port," --> CONF HDLC\n");
1672                         bc->hdlc=1;
1673                         break;
1674                 }
1675                 
1676         }
1677         /*Initialize new Jitterbuffer*/
1678         {
1679                 misdn_cfg_get( port, MISDN_CFG_JITTERBUFFER, &ch->jb_len, sizeof(int));
1680                 misdn_cfg_get( port, MISDN_CFG_JITTERBUFFER_UPPER_THRESHOLD, &ch->jb_upper_threshold, sizeof(int));
1681                 
1682                 config_jitterbuffer(ch);
1683         }
1684         
1685         misdn_cfg_get( bc->port, MISDN_CFG_CONTEXT, ch->context, sizeof(ch->context));
1686         
1687         ast_copy_string (ast->context,ch->context,sizeof(ast->context));        
1688
1689         update_ec_config(bc);
1690
1691         {
1692                 int eb3;
1693                 
1694                 misdn_cfg_get( bc->port, MISDN_CFG_EARLY_BCONNECT, &eb3, sizeof(int));
1695                 bc->early_bconnect=eb3;
1696         }
1697         
1698         port=bc->port;
1699         
1700         {
1701                 char buf[256];
1702                 ast_group_t pg,cg;
1703                 
1704                 misdn_cfg_get(port, MISDN_CFG_PICKUPGROUP, &pg, sizeof(pg));
1705                 misdn_cfg_get(port, MISDN_CFG_CALLGROUP, &cg, sizeof(cg));
1706                 
1707                 chan_misdn_log(5, port, " --> * CallGrp:%s PickupGrp:%s\n",ast_print_group(buf,sizeof(buf),cg),ast_print_group(buf,sizeof(buf),pg));
1708                 ast->pickupgroup=pg;
1709                 ast->callgroup=cg;
1710         }
1711         
1712         if ( orig  == ORG_AST) {
1713                 misdn_cfg_get( port, MISDN_CFG_TE_CHOOSE_CHANNEL, &(bc->te_choose_channel), sizeof(int));
1714                 
1715                 if (strstr(faxdetect, "outgoing") || strstr(faxdetect, "both")) {
1716                         if (strstr(faxdetect, "nojump"))
1717                                 ch->faxdetect=2;
1718                         else
1719                                 ch->faxdetect=1;
1720                 }
1721
1722                 {
1723                         char callerid[BUFFERSIZE+1];
1724                         misdn_cfg_get( port, MISDN_CFG_CALLERID, callerid, BUFFERSIZE);
1725                         if ( ! ast_strlen_zero(callerid) ) {
1726                                 chan_misdn_log(1, port, " --> * Setting Cid to %s\n", callerid);
1727                                 {
1728                                         int l = sizeof(bc->oad);
1729                                         strncpy(bc->oad,callerid, l);
1730                                         bc->oad[l-1] = 0;
1731                                 }
1732
1733                         }
1734
1735                         
1736                         misdn_cfg_get( port, MISDN_CFG_DIALPLAN, &bc->dnumplan, sizeof(int));
1737                         misdn_cfg_get( port, MISDN_CFG_LOCALDIALPLAN, &bc->onumplan, sizeof(int));
1738                         misdn_cfg_get( port, MISDN_CFG_CPNDIALPLAN, &bc->cpnnumplan, sizeof(int));
1739                         debug_numplan(port, bc->dnumplan,"TON");
1740                         debug_numplan(port, bc->onumplan,"LTON");
1741                         debug_numplan(port, bc->cpnnumplan,"CTON");
1742                 }
1743
1744                 ch->overlap_dial = 0;
1745         } else { /** ORIGINATOR MISDN **/
1746                 if (strstr(faxdetect, "incoming") || strstr(faxdetect, "both")) {
1747                         if (strstr(faxdetect, "nojump"))
1748                                 ch->faxdetect=2;
1749                         else
1750                                 ch->faxdetect=1;
1751                 }
1752         
1753                 misdn_cfg_get( port, MISDN_CFG_CPNDIALPLAN, &bc->cpnnumplan, sizeof(int));
1754                 debug_numplan(port, bc->cpnnumplan,"CTON");
1755                 
1756                 char prefix[BUFFERSIZE+1]="";
1757                 switch( bc->onumplan ) {
1758                 case NUMPLAN_INTERNATIONAL:
1759                         misdn_cfg_get( bc->port, MISDN_CFG_INTERNATPREFIX, prefix, BUFFERSIZE);
1760                         break;
1761                         
1762                 case NUMPLAN_NATIONAL:
1763                         misdn_cfg_get( bc->port, MISDN_CFG_NATPREFIX, prefix, BUFFERSIZE);
1764                         break;
1765                 default:
1766                         break;
1767                 }
1768                 
1769                 {
1770                         int l = strlen(prefix) + strlen(bc->oad);
1771                         char tmp[l+1];
1772                         strcpy(tmp,prefix);
1773                         strcat(tmp,bc->oad);
1774                         strcpy(bc->oad,tmp);
1775                 }
1776                 
1777                 if (!ast_strlen_zero(bc->dad)) {
1778                         ast_copy_string(bc->orig_dad,bc->dad, sizeof(bc->orig_dad));
1779                 }
1780                 
1781                 if ( ast_strlen_zero(bc->dad) && !ast_strlen_zero(bc->keypad)) {
1782                         ast_copy_string(bc->dad,bc->keypad, sizeof(bc->dad));
1783                 }
1784
1785                 prefix[0] = 0;
1786                 
1787                 switch( bc->dnumplan ) {
1788                 case NUMPLAN_INTERNATIONAL:
1789                         misdn_cfg_get( bc->port, MISDN_CFG_INTERNATPREFIX, prefix, BUFFERSIZE);
1790                         break;
1791                 case NUMPLAN_NATIONAL:
1792                         misdn_cfg_get( bc->port, MISDN_CFG_NATPREFIX, prefix, BUFFERSIZE);
1793                         break;
1794                 default:
1795                         break;
1796                 }
1797                 
1798                 {
1799                         int l = strlen(prefix) + strlen(bc->dad);
1800                         char tmp[l+1];
1801                         strcpy(tmp,prefix);
1802                         strcat(tmp,bc->dad);
1803                         strcpy(bc->dad,tmp);
1804                 }
1805                 
1806                 if ( strcmp(bc->dad,ast->exten)) {
1807                         ast_copy_string(ast->exten, bc->dad, sizeof(ast->exten));
1808                 }
1809                 
1810                 ast_set_callerid(ast, bc->oad, NULL, bc->oad);
1811                 
1812                 if ( !ast_strlen_zero(bc->rad) ) {
1813                         if (ast->cid.cid_rdnis)
1814                                 free(ast->cid.cid_rdnis);
1815                         ast->cid.cid_rdnis = strdup(bc->rad);
1816                 }
1817         
1818                 misdn_cfg_get(bc->port, MISDN_CFG_OVERLAP_DIAL, &ch->overlap_dial, sizeof(ch->overlap_dial));
1819                 ast_mutex_init(&ch->overlap_tv_lock);
1820         } /* ORIG MISDN END */
1821
1822         ch->overlap_dial_task = -1;
1823         
1824         if (ch->faxdetect) {
1825                 misdn_cfg_get( port, MISDN_CFG_FAXDETECT_TIMEOUT, &ch->faxdetect_timeout, sizeof(ch->faxdetect_timeout));
1826                 if (!ch->dsp)
1827                         ch->dsp = ast_dsp_new();
1828                 if (ch->dsp)
1829                         ast_dsp_set_features(ch->dsp, DSP_FEATURE_DTMF_DETECT | DSP_FEATURE_FAX_DETECT);
1830                 if (!ch->trans)
1831                         ch->trans=ast_translator_build_path(AST_FORMAT_SLINEAR, AST_FORMAT_ALAW);
1832         }
1833
1834         /* AOCD initialization */
1835         bc->AOCDtype = Fac_None;
1836
1837         return 0;
1838 }
1839
1840
1841 /*****************************/
1842 /*** AST Indications Start ***/
1843 /*****************************/
1844
1845 static int misdn_call(struct ast_channel *ast, char *dest, int timeout)
1846 {
1847         int port=0;
1848         int r;
1849         struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
1850         struct misdn_bchannel *newbc;
1851         char *opts=NULL, *ext,*tokb;
1852         char dest_cp[256];
1853
1854         {
1855                 strncpy(dest_cp,dest,sizeof(dest_cp)-1);
1856                 dest_cp[sizeof(dest_cp)]=0;
1857                 
1858                 ext=strtok_r(dest_cp,"/",&tokb);
1859                 
1860                 if (ext) {
1861                         ext=strtok_r(NULL,"/",&tokb);
1862                         if (ext) {
1863                                 opts=strtok_r(NULL,"/",&tokb);
1864                         } else {
1865                                 chan_misdn_log(0,0,"misdn_call: No Extension given!\n");
1866                                 return -1;
1867                         }
1868                 }
1869         }
1870
1871         if (!ast) {
1872                 ast_log(LOG_WARNING, " --> ! misdn_call called on ast_channel *ast where ast == NULL\n");
1873                 return -1;
1874         }
1875
1876         if (((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) || !dest  ) {
1877                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1878                 ast->hangupcause=41;
1879                 ast_setstate(ast, AST_STATE_DOWN);
1880                 return -1;
1881         }
1882
1883         if (!ch) {
1884                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1885                 ast->hangupcause=41;
1886                 ast_setstate(ast, AST_STATE_DOWN);
1887                 return -1;
1888         }
1889         
1890         newbc=ch->bc;
1891         
1892         if (!newbc) {
1893                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1894                 ast->hangupcause=41;
1895                 ast_setstate(ast, AST_STATE_DOWN);
1896                 return -1;
1897         }
1898         
1899         port=newbc->port;
1900         strncpy(newbc->dad,ext,sizeof( newbc->dad));
1901         strncpy(ast->exten,ext,sizeof(ast->exten));
1902
1903         int exceed;
1904         if ((exceed=add_out_calls(port))) {
1905                 char tmp[16];
1906                 sprintf(tmp,"%d",exceed);
1907                 pbx_builtin_setvar_helper(ast,"MAX_OVERFLOW",tmp);
1908                 return -1;
1909         }
1910         
1911         chan_misdn_log(1, port, "* CALL: %s\n",dest);
1912         
1913         chan_misdn_log(2, port, " --> * dad:%s tech:%s ctx:%s\n",ast->exten,ast->name, ast->context);
1914         
1915         chan_misdn_log(3, port, " --> * adding2newbc ext %s\n",ast->exten);
1916         if (ast->exten) {
1917                 int l = sizeof(newbc->dad);
1918                 strncpy(newbc->dad,ast->exten, l);
1919                 newbc->dad[l-1] = 0;
1920         }
1921         newbc->rad[0]=0;
1922         chan_misdn_log(3, port, " --> * adding2newbc callerid %s\n",AST_CID_P(ast));
1923         if (ast_strlen_zero(newbc->oad) && AST_CID_P(ast) ) {
1924
1925                 if (AST_CID_P(ast)) {
1926                         int l = sizeof(newbc->oad);
1927                         strncpy(newbc->oad,AST_CID_P(ast), l);
1928                         newbc->oad[l-1] = 0;
1929                 }
1930         }
1931         
1932         {
1933                 struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
1934                 if (!ch) { ast_verbose("No chan_list in misdn_call\n"); return -1;}
1935                 
1936                 newbc->capability=ast->transfercapability;
1937                 pbx_builtin_setvar_helper(ast,"TRANSFERCAPABILITY",ast_transfercapability2str(newbc->capability));
1938                 if ( ast->transfercapability == INFO_CAPABILITY_DIGITAL_UNRESTRICTED) {
1939                         chan_misdn_log(2, port, " --> * Call with flag Digital\n");
1940                 }
1941                 
1942
1943                 /* update screening and presentation */ 
1944                 update_config(ch,ORG_AST);
1945                 
1946                 /* fill in some ies from channel vary*/
1947                 import_ch(ast, newbc, ch);
1948                 
1949                 /* Finally The Options Override Everything */
1950                 if (opts)
1951                         misdn_set_opt_exec(ast,opts);
1952                 else
1953                         chan_misdn_log(2,port,"NO OPTS GIVEN\n");
1954                 
1955                 r=misdn_lib_send_event( newbc, EVENT_SETUP );
1956                 
1957                 /** we should have l3id after sending setup **/
1958                 ch->l3id=newbc->l3_id;
1959         }
1960         
1961         if ( r == -ENOCHAN  ) {
1962                 chan_misdn_log(0, port, " --> * Theres no Channel at the moment .. !\n");
1963                 chan_misdn_log(1, port, " --> * SEND: State Down pid:%d\n",newbc?newbc->pid:-1);
1964                 ast->hangupcause=34;
1965                 ast_setstate(ast, AST_STATE_DOWN);
1966                 return -1;
1967         }
1968         
1969         chan_misdn_log(2, port, " --> * SEND: State Dialing pid:%d\n",newbc?newbc->pid:1);
1970
1971         ast_setstate(ast, AST_STATE_DIALING);
1972         ast->hangupcause=16;
1973         
1974         if (newbc->nt) stop_bc_tones(ch);
1975
1976         ch->state=MISDN_CALLING;
1977         
1978         return 0; 
1979 }
1980
1981
1982 static int misdn_answer(struct ast_channel *ast)
1983 {
1984         struct chan_list *p;
1985
1986         
1987         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
1988         
1989         chan_misdn_log(1, p? (p->bc? p->bc->port : 0) : 0, "* ANSWER:\n");
1990         
1991         if (!p) {
1992                 ast_log(LOG_WARNING, " --> Channel not connected ??\n");
1993                 ast_queue_hangup(ast);
1994         }
1995
1996         if (!p->bc) {
1997                 chan_misdn_log(1, 0, " --> Got Answer, but theres no bc obj ??\n");
1998
1999                 ast_queue_hangup(ast);
2000         }
2001
2002         {
2003                 const char *tmp_key = pbx_builtin_getvar_helper(p->ast, "CRYPT_KEY");
2004                 
2005                 if (tmp_key ) {
2006                         chan_misdn_log(1, p->bc->port, " --> Connection will be BF crypted\n");
2007                         {
2008                                 int l = sizeof(p->bc->crypt_key);
2009                                 strncpy(p->bc->crypt_key,tmp_key, l);
2010                                 p->bc->crypt_key[l-1] = 0;
2011                         }
2012                 } else {
2013                         chan_misdn_log(3, p->bc->port, " --> Connection is without BF encryption\n");
2014                 }
2015     
2016         }
2017
2018         {
2019                 const char *nodsp=pbx_builtin_getvar_helper(ast, "MISDN_DIGITAL_TRANS");
2020                 if (nodsp) {
2021                         chan_misdn_log(1, p->bc->port, " --> Connection is transparent digital\n");
2022                         p->bc->nodsp=1;
2023                         p->bc->hdlc=0;
2024                         p->bc->nojitter=1;
2025                 }
2026         }
2027         
2028         p->state = MISDN_CONNECTED;
2029         misdn_lib_echo(p->bc,0);
2030         stop_indicate(p);
2031
2032         if ( ast_strlen_zero(p->bc->cad) ) {
2033                 chan_misdn_log(2,p->bc->port," --> empty cad using dad\n");
2034                 ast_copy_string(p->bc->cad,p->bc->dad,sizeof(p->bc->cad));
2035         }
2036
2037         misdn_lib_send_event( p->bc, EVENT_CONNECT);
2038         start_bc_tones(p);
2039         
2040         return 0;
2041 }
2042
2043 static int misdn_digit_begin(struct ast_channel *chan, char digit)
2044 {
2045         /* XXX Modify this callback to support Asterisk controlling the length of DTMF */
2046         return 0;
2047 }
2048
2049 static int misdn_digit_end(struct ast_channel *ast, char digit )
2050 {
2051         struct chan_list *p;
2052         
2053         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) return -1;
2054
2055         struct misdn_bchannel *bc=p->bc;
2056         chan_misdn_log(1, bc?bc->port:0, "* IND : Digit %c\n",digit);
2057         
2058         if (!bc) {
2059                 ast_log(LOG_WARNING, " --> !! Got Digit Event withut having bchannel Object\n");
2060                 return -1;
2061         }
2062         
2063         switch (p->state ) {
2064                 case MISDN_CALLING:
2065                 {
2066                         
2067                         char buf[8];
2068                         buf[0]=digit;
2069                         buf[1]=0;
2070                         
2071                         int l = sizeof(bc->infos_pending);
2072                         strncat(bc->infos_pending,buf,l);
2073                         bc->infos_pending[l-1] = 0;
2074                 }
2075                 break;
2076                 case MISDN_CALLING_ACKNOWLEDGE:
2077                 {
2078                         bc->info_dad[0]=digit;
2079                         bc->info_dad[1]=0;
2080                         
2081                         {
2082                                 int l = sizeof(bc->dad);
2083                                 strncat(bc->dad,bc->info_dad, l - strlen(bc->dad));
2084                                 bc->dad[l-1] = 0;
2085                 }
2086                         {
2087                                 int l = sizeof(p->ast->exten);
2088                                 strncpy(p->ast->exten, bc->dad, l);
2089                                 p->ast->exten[l-1] = 0;
2090                         }
2091                         
2092                         misdn_lib_send_event( bc, EVENT_INFORMATION);
2093                 }
2094                 break;
2095                 
2096                 default:
2097                         if ( bc->send_dtmf ) {
2098                                 send_digit_to_chan(p,digit);
2099                         }
2100                 break;
2101         }
2102         
2103         return 0;
2104 }
2105
2106
2107 static int misdn_fixup(struct ast_channel *oldast, struct ast_channel *ast)
2108 {
2109         struct chan_list *p;
2110         
2111         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) )) return -1;
2112         
2113         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);
2114         
2115         p->ast = ast ;
2116         p->state=MISDN_FIXUP;
2117   
2118         return 0;
2119 }
2120
2121
2122
2123 static int misdn_indication(struct ast_channel *ast, int cond, const void *data, size_t datalen)
2124 {
2125         struct chan_list *p;
2126
2127   
2128         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) {
2129                 ast_log(LOG_WARNING, "Returnded -1 in misdn_indication\n");
2130                 return -1;
2131         }
2132         
2133         if (!p->bc ) {
2134                 chan_misdn_log(1, 0, "* IND : Indication from %s\n",ast->exten);
2135                 ast_log(LOG_WARNING, "Private Pointer but no bc ?\n");
2136                 return -1;
2137         }
2138         
2139         chan_misdn_log(5, p->bc->port, "* IND : Indication [%d] from %s\n",cond, ast->exten);
2140         
2141         switch (cond) {
2142         case AST_CONTROL_BUSY:
2143                 chan_misdn_log(1, p->bc->port, "* IND :\tbusy pid:%d\n",p->bc?p->bc->pid:-1);
2144                 ast_setstate(ast,AST_STATE_BUSY);
2145
2146                 p->bc->out_cause=17;
2147                 if (p->state != MISDN_CONNECTED) {
2148                         start_bc_tones(p);
2149                         misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
2150                 } else {
2151                         chan_misdn_log(-1, p->bc->port, " --> !! Got Busy in Connected State !?! ast:%s\n", ast->name);
2152                 }
2153                 return -1;
2154                 break;
2155         case AST_CONTROL_RING:
2156                 chan_misdn_log(1, p->bc->port, "* IND :\tring pid:%d\n",p->bc?p->bc->pid:-1);
2157                 return -1;
2158                 break;
2159                 
2160         case AST_CONTROL_RINGING:
2161                 chan_misdn_log(1, p->bc->port, "* IND :\tringing pid:%d\n",p->bc?p->bc->pid:-1);
2162                 switch (p->state) {
2163                         case MISDN_ALERTING:
2164                                 chan_misdn_log(2, p->bc->port, " --> * IND :\tringing pid:%d but I was Ringing before, so ignoreing it\n",p->bc?p->bc->pid:-1);
2165                                 break;
2166                         case MISDN_CONNECTED:
2167                                 chan_misdn_log(2, p->bc->port, " --> * IND :\tringing pid:%d but Connected, so just send TONE_ALERTING without state changes \n",p->bc?p->bc->pid:-1);
2168                                 return -1;
2169                                 break;
2170                         default:
2171                                 p->state=MISDN_ALERTING;
2172                                 chan_misdn_log(2, p->bc->port, " --> * IND :\tringing pid:%d\n",p->bc?p->bc->pid:-1);
2173                                 misdn_lib_send_event( p->bc, EVENT_ALERTING);
2174                         
2175                                 if (p->other_ch && p->other_ch->bc) {
2176                                         if (misdn_inband_avail(p->other_ch->bc)) {
2177                                                 chan_misdn_log(2,p->bc->port, " --> other End is mISDN and has inband info available\n");
2178                                                 break;
2179                                         }
2180
2181                                         if (!p->other_ch->bc->nt) {
2182                                                 chan_misdn_log(2,p->bc->port, " --> other End is mISDN TE so it has inband info for sure (?)\n");
2183                                                 break;
2184                                         }
2185                                 }
2186
2187                                 chan_misdn_log(3, p->bc->port, " --> * SEND: State Ring pid:%d\n",p->bc?p->bc->pid:-1);
2188                                 ast_setstate(ast,AST_STATE_RINGING);
2189                         
2190                                 if ( !p->bc->nt && (p->orginator==ORG_MISDN) && !p->incoming_early_audio ) 
2191                                         chan_misdn_log(2,p->bc->port, " --> incoming_early_audio off\n");
2192                                 else 
2193                                         return -1;
2194                 }
2195                 break;
2196         case AST_CONTROL_ANSWER:
2197                 chan_misdn_log(1, p->bc->port, " --> * IND :\tanswer pid:%d\n",p->bc?p->bc->pid:-1);
2198                 start_bc_tones(p);
2199                 break;
2200         case AST_CONTROL_TAKEOFFHOOK:
2201                 chan_misdn_log(1, p->bc->port, " --> *\ttakeoffhook pid:%d\n",p->bc?p->bc->pid:-1);
2202                 return -1;
2203                 break;
2204         case AST_CONTROL_OFFHOOK:
2205                 chan_misdn_log(1, p->bc->port, " --> *\toffhook pid:%d\n",p->bc?p->bc->pid:-1);
2206                 return -1;
2207                 break; 
2208         case AST_CONTROL_FLASH:
2209                 chan_misdn_log(1, p->bc->port, " --> *\tflash pid:%d\n",p->bc?p->bc->pid:-1);
2210                 break;
2211         case AST_CONTROL_PROGRESS:
2212                 chan_misdn_log(1, p->bc->port, " --> * IND :\tprogress pid:%d\n",p->bc?p->bc->pid:-1);
2213                 misdn_lib_send_event( p->bc, EVENT_PROGRESS);
2214                 break;
2215         case AST_CONTROL_PROCEEDING:
2216                 chan_misdn_log(1, p->bc->port, " --> * IND :\tproceeding pid:%d\n",p->bc?p->bc->pid:-1);
2217                 misdn_lib_send_event( p->bc, EVENT_PROCEEDING);
2218                 break;
2219         case AST_CONTROL_CONGESTION:
2220                 chan_misdn_log(1, p->bc->port, " --> * IND :\tcongestion pid:%d\n",p->bc?p->bc->pid:-1);
2221
2222                 p->bc->out_cause=42;
2223                 if (p->state != MISDN_CONNECTED) {
2224                         start_bc_tones(p);
2225                         misdn_lib_send_event( p->bc, EVENT_RELEASE);
2226                 } else {
2227                         misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
2228                 }
2229
2230                 if (p->bc->nt) {
2231                         hanguptone_indicate(p);
2232                 }
2233                 break;
2234         case -1 :
2235                 chan_misdn_log(1, p->bc->port, " --> * IND :\t-1! (stop indication) pid:%d\n",p->bc?p->bc->pid:-1);
2236                 
2237                 stop_indicate(p);
2238
2239                 if (p->state == MISDN_CONNECTED) 
2240                         start_bc_tones(p);
2241
2242                 break;
2243
2244         case AST_CONTROL_HOLD:
2245                 chan_misdn_log(1, p->bc->port, " --> *\tHOLD pid:%d\n",p->bc?p->bc->pid:-1);
2246                 break;
2247         case AST_CONTROL_UNHOLD:
2248                 chan_misdn_log(1, p->bc->port, " --> *\tUNHOLD pid:%d\n",p->bc?p->bc->pid:-1);
2249                 break;
2250         default:
2251                 ast_log(LOG_NOTICE, " --> * Unknown Indication:%d pid:%d\n",cond,p->bc?p->bc->pid:-1);
2252         }
2253   
2254         return 0;
2255 }
2256
2257 static int misdn_hangup(struct ast_channel *ast)
2258 {
2259         struct chan_list *p;
2260         struct misdn_bchannel *bc=NULL;
2261
2262         if (option_debug)
2263                 ast_log(LOG_DEBUG, "misdn_hangup(%s)\n", ast->name);
2264         
2265         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) ) ) return -1;
2266         
2267         if (!p) {
2268                 chan_misdn_log(3, 0, "misdn_hangup called, without chan_list obj.\n");
2269                 return 0 ;
2270         }
2271         
2272         bc=p->bc;
2273
2274
2275         
2276         MISDN_ASTERISK_TECH_PVT(ast)=NULL;
2277         p->ast=NULL;
2278
2279         bc=p->bc;
2280         
2281         if (ast->_state == AST_STATE_RESERVED || 
2282                 p->state == MISDN_NOTHING || 
2283                 p->state == MISDN_HOLDED || 
2284                 p->state == MISDN_FIXUP || 
2285                 p->state == MISDN_HOLD_DISCONNECT ) {
2286
2287                 CLEAN_CH:
2288                 /* between request and call */
2289                 if (option_debug)
2290                         ast_log(LOG_DEBUG, "State Reserved (or nothing) => chanIsAvail\n");
2291                 MISDN_ASTERISK_TECH_PVT(ast)=NULL;
2292                 
2293                 cl_dequeue_chan(&cl_te, p);
2294                 close(p->pipe[0]);
2295                 close(p->pipe[1]);
2296                 free(p);
2297                 
2298                 if (bc)
2299                         misdn_lib_release(bc);
2300                 
2301                 return 0;
2302         }
2303
2304         if (!bc) {
2305                 ast_log(LOG_WARNING,"Hangup with private but no bc ? state:%s l3id:%x\n", misdn_get_ch_state(p), p->l3id);
2306                 goto CLEAN_CH;
2307         }
2308
2309
2310         p->need_hangup=0;
2311         p->need_queue_hangup=0;
2312         p->need_busy=0;
2313
2314
2315         if (!p->bc->nt) 
2316                 stop_bc_tones(p);
2317
2318         
2319         {
2320                 const char *varcause=NULL;
2321                 bc->out_cause=ast->hangupcause?ast->hangupcause:16;
2322                 
2323                 if ( (varcause=pbx_builtin_getvar_helper(ast, "HANGUPCAUSE")) ||
2324                      (varcause=pbx_builtin_getvar_helper(ast, "PRI_CAUSE"))) {
2325                         int tmpcause=atoi(varcause);
2326                         bc->out_cause=tmpcause?tmpcause:16;
2327                 }
2328     
2329                 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));
2330                 chan_misdn_log(3, bc->port, " --> l3id:%x\n",p->l3id);
2331                 chan_misdn_log(3, bc->port, " --> cause:%d\n",bc->cause);
2332                 chan_misdn_log(2, bc->port, " --> out_cause:%d\n",bc->out_cause);
2333                 chan_misdn_log(2, bc->port, " --> state:%s\n", misdn_get_ch_state(p));
2334                 
2335                 switch (p->state) {
2336                 case MISDN_CALLING:
2337                         p->state=MISDN_CLEANING;
2338                         misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
2339                         break;
2340                 case MISDN_HOLDED:
2341                 case MISDN_DIALING:
2342                         start_bc_tones(p);
2343                         hanguptone_indicate(p);
2344                 
2345                         if (bc->need_disconnect)
2346                                 misdn_lib_send_event( bc, EVENT_DISCONNECT);
2347                         break;
2348
2349                 case MISDN_CALLING_ACKNOWLEDGE:
2350                         start_bc_tones(p);
2351                         hanguptone_indicate(p);
2352                 
2353                         if (bc->need_disconnect)
2354                                 misdn_lib_send_event( bc, EVENT_DISCONNECT);
2355                         break;
2356       
2357                 case MISDN_ALERTING:
2358                 case MISDN_PROGRESS:
2359                 case MISDN_PROCEEDING:
2360                         if (p->orginator != ORG_AST) 
2361                                 hanguptone_indicate(p);
2362       
2363                         /*p->state=MISDN_CLEANING;*/
2364                         if (bc->need_disconnect)
2365                                 misdn_lib_send_event( bc, EVENT_DISCONNECT);
2366                         break;
2367                 case MISDN_CONNECTED:
2368                 case MISDN_PRECONNECTED:
2369                         /*  Alerting or Disconect */
2370                         if (p->bc->nt) {
2371                                 start_bc_tones(p);
2372                                 hanguptone_indicate(p);
2373                                 p->bc->progress_indicator=8;
2374                         }
2375                         if (bc->need_disconnect)
2376                                 misdn_lib_send_event( bc, EVENT_DISCONNECT);
2377
2378                         /*p->state=MISDN_CLEANING;*/
2379                         break;
2380                 case MISDN_DISCONNECTED:
2381                         misdn_lib_send_event( bc, EVENT_RELEASE);
2382                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2383                         break;
2384
2385                 case MISDN_RELEASED:
2386                 case MISDN_CLEANING:
2387                         p->state=MISDN_CLEANING;
2388                         break;
2389
2390                 case MISDN_BUSY:
2391                         break;
2392       
2393                 case MISDN_HOLD_DISCONNECT:
2394                         /* need to send release here */
2395                         chan_misdn_log(1, bc->port, " --> cause %d\n",bc->cause);
2396                         chan_misdn_log(1, bc->port, " --> out_cause %d\n",bc->out_cause);
2397                         
2398                         bc->out_cause=-1;
2399                         misdn_lib_send_event(bc,EVENT_RELEASE);
2400                         p->state=MISDN_CLEANING;
2401                         break;
2402                 default:
2403                         if (bc->nt) {
2404                                 bc->out_cause=-1;
2405                                 misdn_lib_send_event(bc, EVENT_RELEASE);
2406                                 p->state=MISDN_CLEANING; 
2407                         } else {
2408                                 if (bc->need_disconnect)
2409                                         misdn_lib_send_event(bc, EVENT_DISCONNECT);
2410                         }
2411                 }
2412
2413                 p->state=MISDN_CLEANING;
2414     
2415         }
2416         
2417
2418         chan_misdn_log(3, bc->port, " --> Channel: %s hanguped new state:%s\n",ast->name,misdn_get_ch_state(p));
2419         
2420         return 0;
2421 }
2422
2423
2424 static struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame *frame)
2425 {
2426         struct ast_frame *f,*f2;
2427  
2428         if (tmp->trans) {
2429                 f2 = ast_translate(tmp->trans, frame, 0);
2430                 f = ast_dsp_process(tmp->ast, tmp->dsp, f2);
2431         } else {
2432                 chan_misdn_log(0, tmp->bc->port, "No T-Path found\n");
2433                 return NULL;
2434         }
2435
2436  
2437         if (!f || (f->frametype != AST_FRAME_DTMF))
2438                 return frame;
2439  
2440         if (option_debug)
2441                 ast_log(LOG_DEBUG, "Detected inband DTMF digit: %c\n", f->subclass);
2442  
2443         if (tmp->faxdetect && (f->subclass == 'f')) {
2444                 /* Fax tone -- Handle and return NULL */
2445                 if (!tmp->faxhandled) {
2446                         struct ast_channel *ast = tmp->ast;
2447                         tmp->faxhandled++;
2448                         chan_misdn_log(0, tmp->bc->port, "Fax detected, preparing %s for fax transfer.\n", ast->name);
2449                         tmp->bc->rxgain = 0;
2450                         isdn_lib_update_rxgain(tmp->bc);
2451                         tmp->bc->txgain = 0;
2452                         isdn_lib_update_txgain(tmp->bc);
2453                         tmp->bc->ec_enable = 0;
2454                         isdn_lib_update_ec(tmp->bc);
2455                         isdn_lib_stop_dtmf(tmp->bc);
2456                         switch (tmp->faxdetect) {
2457                         case 1:
2458                                 if (strcmp(ast->exten, "fax")) {
2459                                         char *context;
2460                                         char context_tmp[BUFFERSIZE];
2461                                         misdn_cfg_get(tmp->bc->port, MISDN_CFG_FAXDETECT_CONTEXT, &context_tmp, sizeof(context_tmp));
2462                                         context = ast_strlen_zero(context_tmp) ? (ast_strlen_zero(ast->macrocontext) ? ast->context : ast->macrocontext) : context_tmp;
2463                                         if (ast_exists_extension(ast, context, "fax", 1, AST_CID_P(ast))) {
2464                                                 if (option_verbose > 2)
2465                                                         ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension (context:%s)\n", ast->name, context);
2466                                                 /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
2467                                                 pbx_builtin_setvar_helper(ast,"FAXEXTEN",ast->exten);
2468                                                 if (ast_async_goto(ast, context, "fax", 1))
2469                                                         ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, context);
2470                                         } else
2471                                                 ast_log(LOG_NOTICE, "Fax detected, but no fax extension ctx:%s exten:%s\n", context, ast->exten);
2472                                 } else {
2473                                         if (option_debug)
2474                                                 ast_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
2475                                 }
2476                                 break;
2477                         case 2:
2478                                 ast_verbose(VERBOSE_PREFIX_3 "Not redirecting %s to fax extension, nojump is set.\n", ast->name);
2479                                 break;
2480                         }
2481                 } else {
2482                         if (option_debug)
2483                                 ast_log(LOG_DEBUG, "Fax already handled\n");
2484                 }
2485         }
2486         
2487         if (tmp->ast_dsp && (f->subclass != 'f')) {
2488                 chan_misdn_log(2, tmp->bc->port, " --> * SEND: DTMF (AST_DSP) :%c\n", f->subclass);
2489         }
2490
2491         return frame;
2492 }
2493
2494
2495 static struct ast_frame  *misdn_read(struct ast_channel *ast)
2496 {
2497         struct chan_list *tmp;
2498         int len;
2499         
2500         if (!ast) {
2501                 chan_misdn_log(1,0,"misdn_read called without ast\n");
2502                 return NULL;
2503         }
2504         if (!(tmp=MISDN_ASTERISK_TECH_PVT(ast))) {
2505                 chan_misdn_log(1,0,"misdn_read called without ast->pvt\n");
2506                 return NULL;
2507         }
2508         if (!tmp->bc) {
2509                 chan_misdn_log(1,0,"misdn_read called without bc\n");
2510                 return NULL;
2511         }
2512
2513         len=read(tmp->pipe[0],tmp->ast_rd_buf,sizeof(tmp->ast_rd_buf));
2514
2515         if (len<=0) {
2516                 /* we hangup here, since our pipe is closed */
2517                 chan_misdn_log(2,tmp->bc->port,"misdn_read: Pipe closed, hanging up\n");
2518                 return NULL;
2519         }
2520
2521         tmp->frame.frametype  = AST_FRAME_VOICE;
2522         tmp->frame.subclass = AST_FORMAT_ALAW;
2523         tmp->frame.datalen = len;
2524         tmp->frame.samples = len;
2525         tmp->frame.mallocd = 0;
2526         tmp->frame.offset = 0;
2527         tmp->frame.delivery= ast_tv(0,0) ;
2528         tmp->frame.src = NULL;
2529         tmp->frame.data = tmp->ast_rd_buf;
2530
2531         if (tmp->faxdetect && !tmp->faxhandled) {
2532                 if (tmp->faxdetect_timeout) {
2533                         if (ast_tvzero(tmp->faxdetect_tv)) {
2534                                 tmp->faxdetect_tv = ast_tvnow();
2535                                 chan_misdn_log(2,tmp->bc->port,"faxdetect: starting detection with timeout: %ds ...\n", tmp->faxdetect_timeout);
2536                                 return process_ast_dsp(tmp, &tmp->frame);
2537                         } else {
2538                                 struct timeval tv_now = ast_tvnow();
2539                                 int diff = ast_tvdiff_ms(tv_now, tmp->faxdetect_tv);
2540                                 if (diff <= (tmp->faxdetect_timeout * 1000)) {
2541                                         chan_misdn_log(5,tmp->bc->port,"faxdetect: detecting ...\n");
2542                                         return process_ast_dsp(tmp, &tmp->frame);
2543                                 } else {
2544                                         chan_misdn_log(2,tmp->bc->port,"faxdetect: stopping detection (time ran out) ...\n");
2545                                         tmp->faxdetect = 0;
2546                                         return &tmp->frame;
2547                                 }
2548                         }
2549                 } else {
2550                         chan_misdn_log(5,tmp->bc->port,"faxdetect: detecting ... (no timeout)\n");
2551                         return process_ast_dsp(tmp, &tmp->frame);
2552                 }
2553         } else {
2554                 if (tmp->ast_dsp)
2555                         return process_ast_dsp(tmp, &tmp->frame);
2556                 else
2557                         return &tmp->frame;
2558         }
2559 }
2560
2561
2562 static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
2563 {
2564         struct chan_list *ch;
2565         int i  = 0;
2566         
2567         if (!ast || ! (ch=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
2568
2569         if (ch->state == MISDN_HOLDED) {
2570                 chan_misdn_log(7, 0, "misdn_write: Returning because holded\n");
2571                 return 0;
2572         }
2573         
2574         if (!ch->bc ) {
2575                 ast_log(LOG_WARNING, "private but no bc\n");
2576                 return -1;
2577         }
2578         
2579         if (ch->notxtone) {
2580                 chan_misdn_log(7, ch->bc->port, "misdn_write: Returning because notxone\n");
2581                 return 0;
2582         }
2583
2584
2585         if ( !frame->subclass) {
2586                 chan_misdn_log(4, ch->bc->port, "misdn_write: * prods us\n");
2587                 return 0;
2588         }
2589         
2590         if ( !(frame->subclass & prefformat)) {
2591                 
2592                 chan_misdn_log(-1, ch->bc->port, "Got Unsupported Frame with Format:%d\n", frame->subclass);
2593                 return 0;
2594         }
2595         
2596
2597         if ( !frame->samples ) {
2598                 chan_misdn_log(4, ch->bc->port, "misdn_write: zero write\n");
2599                 return 0;
2600         }
2601
2602         if ( ! ch->bc->addr ) {
2603                 chan_misdn_log(8, ch->bc->port, "misdn_write: no addr for bc dropping:%d\n", frame->samples);
2604                 return 0;
2605         }
2606         
2607 #if MISDN_DEBUG
2608         {
2609                 int i, max=5>frame->samples?frame->samples:5;
2610                 
2611                 printf("write2mISDN %p %d bytes: ", p, frame->samples);
2612                 
2613                 for (i=0; i<  max ; i++) printf("%2.2x ",((char*) frame->data)[i]);
2614                 printf ("\n");
2615         }
2616 #endif
2617
2618
2619         switch (ch->bc->bc_state) {
2620                 case BCHAN_ACTIVATED:
2621                 case BCHAN_BRIDGED:
2622                         break;
2623                 default:
2624                 if (!ch->dropped_frame_cnt)
2625                         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);
2626                 
2627                 ch->dropped_frame_cnt++;
2628                 if (ch->dropped_frame_cnt > 100) {
2629                         ch->dropped_frame_cnt=0;
2630                         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);
2631
2632                 }
2633
2634                 return 0;
2635         }
2636
2637         chan_misdn_log(9, ch->bc->port, "Sending :%d bytes 2 MISDN\n",frame->samples);
2638         if ( !ch->bc->nojitter && misdn_cap_is_speech(ch->bc->capability) ) {
2639                 /* Buffered Transmit (triggert by read from isdn side)*/
2640                 if (misdn_jb_fill(ch->jb,frame->data,frame->samples) < 0) {
2641                         if (ch->bc->active)
2642                                 cb_log(0,ch->bc->port,"Misdn Jitterbuffer Overflow.\n");
2643                 }
2644                 
2645         } else {
2646                 /*transmit without jitterbuffer*/
2647                 i=misdn_lib_tx2misdn_frm(ch->bc, frame->data, frame->samples);
2648         }
2649
2650         
2651         
2652         return 0;
2653 }
2654
2655
2656
2657
2658 static enum ast_bridge_result  misdn_bridge (struct ast_channel *c0,
2659                                       struct ast_channel *c1, int flags,
2660                                       struct ast_frame **fo,
2661                                       struct ast_channel **rc,
2662                                       int timeoutms)
2663
2664 {
2665         struct chan_list *ch1,*ch2;
2666         struct ast_channel *carr[2], *who;
2667         int to=-1;
2668         struct ast_frame *f;
2669   
2670         ch1=get_chan_by_ast(c0);
2671         ch2=get_chan_by_ast(c1);
2672
2673         carr[0]=c0;
2674         carr[1]=c1;
2675   
2676         if (ch1 && ch2 ) ;
2677         else
2678                 return -1;
2679   
2680
2681         int bridging;
2682         misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
2683         if (bridging) {
2684                 int ecwb, ec;
2685                 misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2686                 misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
2687                 if ( !ecwb && ec ) {
2688                         chan_misdn_log(2, ch1->bc->port, "Disabling Echo Cancellor when Bridged\n");
2689                         ch1->bc->ec_enable=0;
2690                         manager_ec_disable(ch1->bc);
2691                 }
2692                 misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2693                 misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
2694                 if ( !ecwb && ec) {
2695                         chan_misdn_log(2, ch2->bc->port, "Disabling Echo Cancellor when Bridged\n");
2696                         ch2->bc->ec_enable=0;
2697                         manager_ec_disable(ch2->bc); 
2698                 }
2699                 /* trying to make a mISDN_dsp conference */
2700                 chan_misdn_log(1, ch1->bc->port, "I SEND: Making conference with Number:%d\n", ch1->bc->pid +1);
2701
2702                 misdn_lib_bridge(ch1->bc,ch2->bc);
2703         }
2704         
2705         if (option_verbose > 2) 
2706                 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
2707
2708         chan_misdn_log(1, ch1->bc->port, "* Making Native Bridge between %s and %s\n", ch1->bc->oad, ch2->bc->oad);
2709  
2710         if (! (flags&AST_BRIDGE_DTMF_CHANNEL_0) )
2711                 ch1->ignore_dtmf=1;
2712
2713         if (! (flags&AST_BRIDGE_DTMF_CHANNEL_1) )
2714                 ch2->ignore_dtmf=1;
2715
2716         while(1) {
2717                 to=-1;
2718                 who = ast_waitfor_n(carr, 2, &to);
2719
2720                 if (!who) {
2721                         ast_log(LOG_NOTICE,"misdn_bridge: empty read, breaking out\n");
2722                         break;
2723                 }
2724                 f = ast_read(who);
2725     
2726                 if (!f || f->frametype == AST_FRAME_CONTROL) {
2727                         /* got hangup .. */
2728
2729                         if (!f) 
2730                                 chan_misdn_log(4,ch1->bc->port,"Read Null Frame\n");
2731                         else
2732                                 chan_misdn_log(4,ch1->bc->port,"Read Frame Controll class:%d\n",f->subclass);
2733                         
2734                         *fo=f;
2735                         *rc=who;
2736       
2737                         break;
2738                 }
2739                 
2740                 if ( f->frametype == AST_FRAME_DTMF ) {
2741                         chan_misdn_log(1,0,"Read DTMF %d from %s\n",f->subclass, who->exten);
2742
2743                         *fo=f;
2744                         *rc=who;
2745                         break;
2746                 }
2747         
2748 #if 0
2749                 if (f->frametype == AST_FRAME_VOICE) {
2750                         chan_misdn_log(1, ch1->bc->port, "I SEND: Splitting conference with Number:%d\n", ch1->bc->pid +1);
2751         
2752                         continue;
2753                 }
2754 #endif
2755
2756                 if (who == c0) {
2757                         ast_write(c1,f);
2758                 }
2759                 else {
2760                         ast_write(c0,f);
2761                 }
2762     
2763         }
2764         
2765         chan_misdn_log(1, ch1->bc->port, "I SEND: Splitting conference with Number:%d\n", ch1->bc->pid +1);
2766         
2767         misdn_lib_split_bridge(ch1->bc,ch2->bc);
2768         
2769         
2770         return AST_BRIDGE_COMPLETE;
2771 }
2772
2773 /** AST INDICATIONS END **/
2774
2775 static int dialtone_indicate(struct chan_list *cl)
2776 {
2777         const struct ind_tone_zone_sound *ts= NULL;
2778         struct ast_channel *ast=cl->ast;
2779
2780
2781         int nd=0;
2782         misdn_cfg_get( cl->bc->port, MISDN_CFG_NODIALTONE, &nd, sizeof(nd));
2783
2784         if (nd) {
2785                 chan_misdn_log(1,cl->bc->port,"Not sending Dialtone, because config wants it\n");
2786                 return 0;
2787         }
2788         
2789         chan_misdn_log(3,cl->bc->port," --> Dial\n");
2790         ts=ast_get_indication_tone(ast->zone,"dial");
2791         cl->ts=ts;      
2792         
2793         if (ts) {
2794                 cl->notxtone=0;
2795                 cl->norxtone=0;
2796                 ast_playtones_start(ast,0, ts->data, 0);
2797                 chan_misdn_log(4,cl->bc->port,"Starting Playtones\n");
2798                 misdn_lib_tone_generator_start(cl->bc);
2799         }
2800
2801         return 0;
2802 }
2803
2804 static int hanguptone_indicate(struct chan_list *cl)
2805 {
2806         misdn_lib_send_tone(cl->bc,TONE_HANGUP);
2807         return 0;
2808 }
2809
2810 static int stop_indicate(struct chan_list *cl)
2811 {
2812         struct ast_channel *ast=cl->ast;
2813         chan_misdn_log(3,cl->bc->port," --> None\n");
2814         misdn_lib_tone_generator_stop(cl->bc);
2815         ast_playtones_stop(ast);
2816         /*ast_deactivate_generator(ast);*/
2817         
2818         return 0;
2819 }
2820
2821
2822 static int start_bc_tones(struct chan_list* cl)
2823 {
2824         misdn_lib_tone_generator_stop(cl->bc);
2825         cl->notxtone=0;
2826         cl->norxtone=0;
2827         return 0;
2828 }
2829
2830 static int stop_bc_tones(struct chan_list *cl)
2831 {
2832         if (!cl) return -1;
2833
2834         cl->notxtone=1;
2835         cl->norxtone=1;
2836         
2837         return 0;
2838 }
2839
2840
2841 static struct chan_list *init_chan_list(int orig)
2842 {
2843         struct chan_list *cl=malloc(sizeof(struct chan_list));
2844         
2845         if (!cl) {
2846                 chan_misdn_log(-1, 0, "misdn_request: malloc failed!");
2847                 return NULL;
2848         }
2849         
2850         memset(cl,0,sizeof(struct chan_list));
2851
2852         cl->orginator=orig;
2853         cl->need_queue_hangup=1;
2854         cl->need_hangup=1;
2855         cl->need_busy=1;
2856         cl->overlap_dial_task=-1;
2857         
2858         return cl;
2859         
2860 }
2861
2862 static struct ast_channel *misdn_request(const char *type, int format, void *data, int *cause)
2863
2864 {
2865         struct ast_channel *tmp = NULL;
2866         char group[BUFFERSIZE+1]="";
2867         char buf[128];
2868         char buf2[128], *ext=NULL, *port_str;
2869         char *tokb=NULL, *p=NULL;
2870         int channel=0, port=0;
2871         struct misdn_bchannel *newbc = NULL;
2872         
2873         struct chan_list *cl=init_chan_list(ORG_AST);
2874         
2875         sprintf(buf,"%s/%s",misdn_type,(char*)data);
2876         ast_copy_string(buf2,data, 128);
2877         
2878         port_str=strtok_r(buf2,"/", &tokb);
2879
2880         ext=strtok_r(NULL,"/", &tokb);
2881
2882         if (port_str) {
2883                 if (port_str[0]=='g' && port_str[1]==':' ) {
2884                         /* We make a group call lets checkout which ports are in my group */
2885                         port_str += 2;
2886                         strncpy(group, port_str, BUFFERSIZE);
2887                         group[127] = 0;
2888                         chan_misdn_log(2, 0, " --> Group Call group: %s\n",group);
2889                 } 
2890                 else if ((p = strchr(port_str, ':'))) {
2891                         /* we have a preselected channel */
2892                         *p = 0;
2893                         channel = atoi(++p);
2894                         port = atoi(port_str);
2895                         chan_misdn_log(2, port, " --> Call on preselected Channel (%d).\n", channel);
2896                 }
2897                 else {
2898                         port = atoi(port_str);
2899                 }
2900                 
2901                 
2902         } else {
2903                 ast_log(LOG_WARNING, " --> ! IND : CALL dad:%s WITHOUT PORT/Group, check extension.conf\n",ext);
2904                 return NULL;
2905         }
2906
2907         if (!ast_strlen_zero(group)) {
2908         
2909                 char cfg_group[BUFFERSIZE+1];
2910                 struct robin_list *rr = NULL;
2911
2912                 if (misdn_cfg_is_group_method(group, METHOD_ROUND_ROBIN)) {
2913                         chan_misdn_log(4, port, " --> STARTING ROUND ROBIN...");
2914                         rr = get_robin_position(group);
2915                 }
2916                 
2917                 if (rr) {
2918                         int robin_channel = rr->channel;
2919                         int port_start;
2920                         int next_chan = 1;
2921
2922                         do {
2923                                 port_start = 0;
2924                                 for (port = misdn_cfg_get_next_port_spin(rr->port); port > 0 && port != port_start;
2925                                          port = misdn_cfg_get_next_port_spin(port)) {
2926
2927                                         if (!port_start)
2928                                                 port_start = port;
2929
2930                                         if (port >= port_start)
2931                                                 next_chan = 1;
2932                                         
2933                                         if (port <= port_start && next_chan) {
2934                                                 int maxbchans=misdn_lib_get_maxchans(port);
2935                                                 if (++robin_channel >= maxbchans) {
2936                                                         robin_channel = 1;
2937                                                 }
2938                                                 next_chan = 0;
2939                                         }
2940
2941                                         misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2942                                         
2943                                         if (!strcasecmp(cfg_group, group)) {
2944                                                 int port_up;
2945                                                 int check;
2946                                                 misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
2947                                                 port_up = misdn_lib_port_up(port, check);
2948
2949                                                 if (check && !port_up) 
2950                                                         chan_misdn_log(1,port,"L1 is not Up on this Port\n");
2951                                                 
2952                                                 if (check && port_up<0) {
2953                                                         ast_log(LOG_WARNING,"This port (%d) is blocked\n", port);
2954                                                 }
2955                                                 
2956                                                 
2957                                                 if ( port_up>0 )        {
2958                                                         newbc = misdn_lib_get_free_bc(port, robin_channel,0);
2959                                                         if (newbc) {
2960                                                                 chan_misdn_log(4, port, " Success! Found port:%d channel:%d\n", newbc->port, newbc->channel);
2961                                                                 if (port_up)
2962                                                                         chan_misdn_log(4, port, "portup:%d\n",  port_up);
2963                                                                 rr->port = newbc->port;
2964                                                                 rr->channel = newbc->channel;
2965                                                                 break;
2966                                                         }
2967                                                 }
2968                                         }
2969                                 }
2970                         } while (!newbc && robin_channel != rr->channel);
2971                         
2972                         if (!newbc)
2973                                 chan_misdn_log(-1, port, " Failed! No free channel in group %d!", group);
2974                 }
2975                 
2976                 else {          
2977                         for (port=misdn_cfg_get_next_port(0); port > 0;
2978                                  port=misdn_cfg_get_next_port(port)) {
2979                                 
2980                                 misdn_cfg_get( port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2981
2982                                 chan_misdn_log(3,port, "Group [%s] Port [%d]\n", group, port);
2983                                 if (!strcasecmp(cfg_group, group)) {
2984                                         int port_up;
2985                                         int check;
2986                                         misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
2987                                         port_up = misdn_lib_port_up(port, check);
2988                                         
2989                                         chan_misdn_log(4, port, "portup:%d\n", port_up);
2990                                         
2991                                         if ( port_up>0 ) {
2992                                                 newbc = misdn_lib_get_free_bc(port, 0, 0);
2993                                                 if (newbc)
2994                                                         break;
2995                                         }
2996                                 }
2997                         }
2998                 }
2999                 
3000         } else {
3001                 if (channel)
3002                         chan_misdn_log(1, port," --> preselected_channel: %d\n",channel);
3003                 newbc = misdn_lib_get_free_bc(port, channel, 0);
3004         }
3005         
3006         if (!newbc) {
3007                 chan_misdn_log(-1, 0, "Could not create channel on port:%d with extensions:%s\n",port,ext);
3008                 return NULL;
3009         }
3010
3011         /* create ast_channel and link all the objects together */
3012         cl->bc=newbc;
3013         
3014         tmp = misdn_new(cl, AST_STATE_RESERVED, ext, NULL, format, port, channel);
3015         cl->ast=tmp;
3016         
3017         /* register chan in local list */
3018         cl_queue_chan(&cl_te, cl) ;
3019         
3020         /* fill in the config into the objects */
3021         read_config(cl, ORG_AST);
3022
3023         /* important */
3024         cl->need_hangup=0;
3025         
3026         return tmp;
3027 }
3028
3029
3030 static int misdn_send_text (struct ast_channel *chan, const char *text)
3031 {
3032         struct chan_list *tmp=chan->tech_pvt;
3033         
3034         if (tmp && tmp->bc) {
3035                 ast_copy_string(tmp->bc->display,text,sizeof(tmp->bc->display));
3036                 misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
3037         } else {
3038                 ast_log(LOG_WARNING, "No chan_list but send_text request?\n");
3039                 return -1;
3040         }
3041         
3042         return 0;
3043 }
3044
3045 static struct ast_channel_tech misdn_tech = {
3046         .type="mISDN",
3047         .description="Channel driver for mISDN Support (Bri/Pri)",
3048         .capabilities= AST_FORMAT_ALAW ,
3049         .requester=misdn_request,
3050         .send_digit_begin=misdn_digit_begin,
3051         .send_digit_end=misdn_digit_end,
3052         .call=misdn_call,
3053         .bridge=misdn_bridge, 
3054         .hangup=misdn_hangup,
3055         .answer=misdn_answer,
3056         .read=misdn_read,
3057         .write=misdn_write,
3058         .indicate=misdn_indication,
3059         .fixup=misdn_fixup,
3060         .send_text=misdn_send_text,
3061         .properties=0
3062 };
3063
3064 static struct ast_channel_tech misdn_tech_wo_bridge = {
3065         .type="mISDN",
3066         .description="Channel driver for mISDN Support (Bri/Pri)",
3067         .capabilities=AST_FORMAT_ALAW ,
3068         .requester=misdn_request,
3069         .send_digit_begin=misdn_digit_begin,
3070         .send_digit_end=misdn_digit_end,
3071         .call=misdn_call,
3072         .hangup=misdn_hangup,
3073         .answer=misdn_answer,
3074         .read=misdn_read,
3075         .write=misdn_write,
3076         .indicate=misdn_indication,
3077         .fixup=misdn_fixup,
3078         .send_text=misdn_send_text,
3079         .properties=0
3080 };
3081
3082
3083 static int glob_channel=0;
3084
3085 static void update_name(struct ast_channel *tmp, int port, int c) 
3086 {
3087         int chan_offset=0;
3088         int tmp_port = misdn_cfg_get_next_port(0);
3089         for (; tmp_port > 0; tmp_port=misdn_cfg_get_next_port(tmp_port)) {
3090         if (tmp_port == port) break;
3091                 chan_offset+=misdn_lib_port_is_pri(tmp_port)?30:2;      
3092         }
3093         if (c<0) c=0;
3094
3095         ast_string_field_build(tmp, name, "%s/%d-u%d",
3096                                  misdn_type, chan_offset+c, glob_channel++);
3097
3098         chan_misdn_log(3,port," --> updating channel name to [%s]\n",tmp->name);
3099         
3100 }
3101
3102 static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char *exten, char *callerid, int format, int port, int c)
3103 {
3104         struct ast_channel *tmp;
3105         char *cid_name = 0, *cid_num = 0;
3106         int chan_offset=0;
3107         int tmp_port = misdn_cfg_get_next_port(0);
3108
3109         for (; tmp_port > 0; tmp_port=misdn_cfg_get_next_port(tmp_port)) {
3110         if (tmp_port == port) break;
3111                 chan_offset+=misdn_lib_port_is_pri(tmp_port)?30:2;      
3112         }
3113         if (c<0) c=0;
3114
3115         
3116         if (callerid) 
3117                 ast_callerid_parse(callerid, &cid_name, &cid_num);
3118
3119         tmp = ast_channel_alloc(1, state, cid_num, cid_name, "%s/%d-u%d", misdn_type, chan_offset + c, glob_channel++);
3120         
3121         if (tmp) {
3122                 chan_misdn_log(2, 0, " --> * NEW CHANNEL dad:%s oad:%s\n",exten,callerid);
3123                 
3124                 tmp->nativeformats = prefformat;
3125
3126                 tmp->readformat = format;
3127                 tmp->rawreadformat = format;
3128                 tmp->writeformat = format;
3129                 tmp->rawwriteformat = format;
3130     
3131                 tmp->tech_pvt = chlist;
3132                 
3133                 int bridging;
3134                 misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
3135                 if (bridging)
3136                         tmp->tech = &misdn_tech;
3137                 else
3138                         tmp->tech = &misdn_tech_wo_bridge;
3139                 
3140                 tmp->writeformat = format;
3141                 tmp->readformat = format;
3142                 tmp->priority=1;
3143                 
3144                 if (exten) 
3145                         ast_copy_string(tmp->exten, exten,  sizeof(tmp->exten));
3146                 else
3147                         chan_misdn_log(1,0,"misdn_new: no exten given.\n");
3148                 
3149                 if (callerid) {
3150                         char *cid_name, *cid_num;
3151       
3152                         ast_callerid_parse(callerid, &cid_name, &cid_num);
3153                         /* Don't use ast_set_callerid() here because it will
3154                          * generate a needless NewCallerID event */
3155                         tmp->cid.cid_num = ast_strdup(cid_num);
3156                         tmp->cid.cid_ani = ast_strdup(cid_num);
3157                         tmp->cid.cid_name = ast_strdup(cid_name);
3158                 }
3159
3160                 {
3161                         if (pipe(chlist->pipe)<0)
3162                                 perror("Pipe failed\n");
3163                         
3164                         tmp->fds[0]=chlist->pipe[0];
3165                         
3166                 }
3167                 
3168                 if (state == AST_STATE_RING)
3169                         tmp->rings = 1;
3170                 else
3171                         tmp->rings = 0;
3172                 
3173                 
3174         } else {
3175                 chan_misdn_log(-1,0,"Unable to allocate channel structure\n");
3176         }
3177         
3178         return tmp;
3179 }
3180
3181 static struct chan_list *find_chan_by_bc(struct chan_list *list, struct misdn_bchannel *bc)
3182 {
3183         struct chan_list *help=list;
3184         for (;help; help=help->next) {
3185                 if (help->bc == bc) return help;
3186         }
3187   
3188         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
3189   
3190         return NULL;
3191 }
3192
3193 static struct chan_list *find_chan_by_pid(struct chan_list *list, int pid)
3194 {
3195         struct chan_list *help=list;
3196         for (;help; help=help->next) {
3197                 if ( help->bc && (help->bc->pid == pid) ) return help;
3198         }
3199   
3200         chan_misdn_log(6, 0, "$$$ find_chan: No channel found for pid:%d\n",pid);
3201   
3202         return NULL;
3203 }
3204
3205 static struct chan_list *find_holded(struct chan_list *list, struct misdn_bchannel *bc)
3206 {
3207         struct chan_list *help=list;
3208         
3209         chan_misdn_log(6, bc->port, "$$$ find_holded: channel:%d oad:%s dad:%s\n",bc->channel, bc->oad,bc->dad);
3210         for (;help; help=help->next) {
3211                 chan_misdn_log(4, bc->port, "$$$ find_holded: --> holded:%d channel:%d\n",help->state==MISDN_HOLDED, help->hold_info.channel);
3212                 if (    (help->state == MISDN_HOLDED) && 
3213                         (help->hold_info.port == bc->port) ) 
3214                         return help;
3215         }       
3216         chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
3217   
3218         return NULL;
3219 }
3220
3221
3222 static struct chan_list *find_holded_l3(struct chan_list *list, unsigned long l3_id, int w) 
3223
3224 {
3225         struct chan_list *help=list;
3226
3227         for (;help; help=help->next) {
3228                 if ( (help->state == MISDN_HOLDED) &&
3229                          (help->l3id == l3_id)   
3230                         ) 
3231                         return help;
3232         }
3233
3234         return NULL;
3235 }
3236
3237 static void cl_queue_chan(struct chan_list **list, struct chan_list *chan)
3238 {
3239         chan_misdn_log(4, chan->bc? chan->bc->port : 0, "* Queuing chan %p\n",chan);
3240   
3241         ast_mutex_lock(&cl_te_lock);
3242         if (!*list) {
3243                 *list = chan;
3244         } else {
3245                 struct chan_list *help=*list;
3246                 for (;help->next; help=help->next); 
3247                 help->next=chan;
3248         }
3249         chan->next=NULL;
3250         ast_mutex_unlock(&cl_te_lock);
3251 }
3252
3253 static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan) 
3254 {
3255         if (chan->dsp) 
3256                 ast_dsp_free(chan->dsp);
3257         if (chan->trans)
3258                 ast_translator_free_path(chan->trans);
3259
3260         
3261
3262         ast_mutex_lock(&cl_te_lock);
3263         if (!*list) {
3264                 ast_mutex_unlock(&cl_te_lock);
3265                 return;
3266         }
3267   
3268         if (*list == chan) {
3269                 *list=(*list)->next;
3270                 ast_mutex_unlock(&cl_te_lock);
3271                 return ;
3272         }
3273   
3274         {
3275                 struct chan_list *help=*list;
3276                 for (;help->next; help=help->next) {
3277                         if (help->next == chan) {
3278                                 help->next=help->next->next;
3279                                 ast_mutex_unlock(&cl_te_lock);
3280                                 return;
3281                         }
3282                 }
3283         }
3284         
3285         ast_mutex_unlock(&cl_te_lock);
3286 }
3287
3288 /** Channel Queue End **/
3289
3290
3291 int pbx_start_chan(struct chan_list *ch)
3292 {
3293         int ret=ast_pbx_start(ch->ast); 
3294
3295         if (ret>=0) 
3296                 ch->need_hangup=0;
3297         else
3298                 ch->need_hangup=1;
3299
3300         return ret;
3301 }
3302
3303 static void hangup_chan(struct chan_list *ch)
3304 {
3305         int port=ch?ch->bc?ch->bc->port:0:0;
3306         if (!ch) {
3307                 cb_log(1,0,"Cannot hangup chan, no ch\n");
3308                 return;
3309         }
3310
3311         cb_log(5,port,"hangup_chan called\n");
3312
3313         if (ch->need_hangup) 
3314         {
3315                 cb_log(2,port," --> hangup\n");
3316                 send_cause2ast(ch->ast,ch->bc,ch);
3317                 ch->need_hangup=0;
3318                 ch->need_queue_hangup=0;
3319                 if (ch->ast)
3320                         ast_hangup(ch->ast);
3321                 return;
3322         }
3323
3324         if (!ch->need_queue_hangup) {
3325                 cb_log(2,port," --> No need to queue hangup\n");
3326         }
3327
3328         ch->need_queue_hangup=0;
3329         if (ch->ast) {
3330                 send_cause2ast(ch->ast,ch->bc,ch);
3331
3332                 if (ch->ast)
3333                         ast_queue_hangup(ch->ast);
3334                 cb_log(2,port," --> queue_hangup\n");
3335         } else {
3336                 cb_log(1,port,"Cannot hangup chan, no ast\n");
3337         }
3338 }
3339
3340 /** Isdn asks us to release channel, pendant to misdn_hangup **/
3341 static void release_chan(struct misdn_bchannel *bc) {
3342         struct ast_channel *ast=NULL;
3343         {
3344                 struct chan_list *ch=find_chan_by_bc(cl_te, bc);
3345                 if (!ch)  {
3346                         chan_misdn_log(1, bc->port, "release_chan: Ch not found!\n");
3347                         return;
3348                 }
3349                 
3350                 if (ch->ast) {
3351                         ast=ch->ast;
3352                 } 
3353                 
3354                 chan_misdn_log(5, bc->port, "release_chan: bc with l3id: %x\n",bc->l3_id);
3355                 
3356                 /*releaseing jitterbuffer*/
3357                 if (ch->jb ) {
3358                         misdn_jb_destroy(ch->jb);
3359                         ch->jb=NULL;
3360                 } else {
3361                         if (!bc->nojitter)
3362                                 chan_misdn_log(5,bc->port,"Jitterbuffer already destroyed.\n");
3363                 }
3364
3365                 if (ch->overlap_dial) {
3366                         if (ch->overlap_dial_task != -1) {
3367                                 misdn_tasks_remove(ch->overlap_dial_task);
3368                                 ch->overlap_dial_task = -1;
3369                         }
3370                         ast_mutex_destroy(&ch->overlap_tv_lock);
3371                 }
3372
3373                 if (ch->orginator == ORG_AST) {
3374                         misdn_out_calls[bc->port]--;
3375                 } else {
3376                         misdn_in_calls[bc->port]--;
3377                 }
3378                 
3379                 if (ch) {
3380                         
3381                         close(ch->pipe[0]);
3382                         close(ch->pipe[1]);
3383
3384                         
3385                         if (ast && MISDN_ASTERISK_TECH_PVT(ast)) {
3386                                 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));
3387                                 chan_misdn_log(3, bc->port, " --> * State Down\n");
3388                                 MISDN_ASTERISK_TECH_PVT(ast)=NULL;
3389                                 
3390       
3391                                 if (ast->_state != AST_STATE_RESERVED) {
3392                                         chan_misdn_log(3, bc->port, " --> Setting AST State to down\n");
3393                                         ast_setstate(ast, AST_STATE_DOWN);
3394                                 }
3395                         }
3396                                 
3397                         ch->state=MISDN_CLEANING;
3398                         cl_dequeue_chan(&cl_te, ch);
3399                         
3400                         free(ch);
3401                 } else {
3402                         /* chan is already cleaned, so exiting  */
3403                 }
3404         }
3405 }
3406 /*** release end **/
3407
3408 static void misdn_transfer_bc(struct chan_list *tmp_ch, struct chan_list *holded_chan)
3409 {
3410         chan_misdn_log(4,0,"TRANSFERING %s to %s\n",holded_chan->ast->name, tmp_ch->ast->name);
3411         
3412         tmp_ch->state=MISDN_HOLD_DISCONNECT;
3413   
3414         ast_moh_stop(AST_BRIDGED_P(holded_chan->ast));
3415
3416         holded_chan->state=MISDN_CONNECTED;
3417         //misdn_lib_transfer(holded_chan->bc);
3418         ast_channel_masquerade(holded_chan->ast, AST_BRIDGED_P(tmp_ch->ast));
3419 }
3420
3421
3422 static void do_immediate_setup(struct misdn_bchannel *bc,struct chan_list *ch , struct ast_channel *ast)
3423 {
3424         char predial[256]="";
3425         char *p = predial;
3426   
3427         struct ast_frame fr;
3428   
3429         strncpy(predial, ast->exten, sizeof(predial) -1 );
3430   
3431         ch->state=MISDN_DIALING;
3432
3433         if (bc->nt) {
3434                 int ret; 
3435                 ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3436         } else {
3437                 int ret;
3438                 if ( misdn_lib_is_ptp(bc->port)) {
3439                         ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
3440                 } else {
3441                         ret = misdn_lib_send_event(bc, EVENT_PROCEEDING );
3442                 }
3443         }
3444
3445         if ( !bc->nt && (ch->orginator==ORG_MISDN) && !ch->incoming_early_audio ) 
3446                 chan_misdn_log(1,bc->port, " --> incoming_early_audio off\n");
3447          else  
3448                 dialtone_indicate(ch);
3449   
3450         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));
3451   
3452         strncpy(ast->exten,"s", 2);
3453   
3454         if (pbx_start_chan(ch)<0) {
3455                 ast=NULL;
3456                 hangup_chan(ch);
3457                 hanguptone_indicate(ch);
3458
3459                 if (bc->nt)
3460                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
3461                 else
3462                         misdn_lib_send_event(bc, EVENT_DISCONNECT );
3463         }
3464   
3465   
3466         while (!ast_strlen_zero(p) ) {
3467                 fr.frametype = AST_FRAME_DTMF;
3468                 fr.subclass = *p ;
3469                 fr.src=NULL;
3470                 fr.data = NULL ;
3471                 fr.datalen = 0;
3472                 fr.samples = 0 ;
3473                 fr.mallocd =0 ;
3474                 fr.offset= 0 ;
3475                 fr.delivery= ast_tv(0,0) ;
3476
3477                 if (ch->ast && MISDN_ASTERISK_PVT(ch->ast) && MISDN_ASTERISK_TECH_PVT(ch->ast)) {
3478                         ast_queue_frame(ch->ast, &fr);
3479                 }
3480                 p++;
3481         }
3482 }
3483
3484
3485
3486 static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc, struct chan_list *ch) {
3487         if (!ast) {
3488                 chan_misdn_log(1,0,"send_cause2ast: No Ast\n");
3489                 return;
3490         }
3491         if (!bc) {
3492                 chan_misdn_log(1,0,"send_cause2ast: No BC\n");
3493                 return;
3494         }
3495         if (!ch) {
3496                 chan_misdn_log(1,0,"send_cause2ast: No Ch\n");
3497                 return;
3498         }
3499         
3500         ast->hangupcause=bc->cause;
3501         
3502         switch ( bc->cause) {
3503                 
3504         case 1: /** Congestion Cases **/
3505         case 2:
3506         case 3:
3507         case 4:
3508         case 22:
3509         case 27:
3510                 /*
3511                  * Not Queueing the Congestion anymore, since we want to hear
3512                  * the inband message
3513                  *
3514                 chan_misdn_log(1, bc?bc->port:0, " --> * SEND: Queue Congestion pid:%d\n", bc?bc->pid:-1);
3515                 ch->state=MISDN_BUSY;
3516                 
3517                 ast_queue_control(ast, AST_CONTROL_CONGESTION);
3518                 */
3519                 break;
3520                 
3521         case 21:
3522         case 17: /* user busy */
3523         
3524                 ch->state=MISDN_BUSY;
3525                         
3526                 if (!ch->need_busy) {
3527                         chan_misdn_log(1,bc?bc->port:0, "Queued busy already\n");
3528                         break;
3529                 }
3530                 
3531                 chan_misdn_log(1,  bc?bc->port:0, " --> * SEND: Queue Busy pid:%d\n", bc?bc->pid:-1);
3532                 
3533                 ast_queue_control(ast, AST_CONTROL_BUSY);
3534                 
3535                 ch->need_busy=0;
3536                 
3537                 break;
3538         }
3539 }
3540
3541
3542
3543
3544 void import_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
3545 {
3546         const char *tmp;
3547         tmp=pbx_builtin_getvar_helper(chan,"MISDN_PID");
3548         if (tmp) {
3549                 ch->other_pid=atoi(tmp);
3550                 chan_misdn_log(3,bc->port," --> IMPORT_PID: importing pid:%s\n",tmp);
3551                 if (ch->other_pid >0) {
3552                         ch->other_ch=find_chan_by_pid(cl_te,ch->other_pid);
3553                         if (ch->other_ch) ch->other_ch->other_ch=ch;
3554                 }
3555         }
3556 }
3557
3558 void export_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
3559 {
3560         char tmp[32];
3561         chan_misdn_log(3,bc->port," --> EXPORT_PID: pid:%d\n",bc->pid);
3562         sprintf(tmp,"%d",bc->pid);
3563         pbx_builtin_setvar_helper(chan,"_MISDN_PID",tmp);
3564 }
3565
3566 int add_in_calls(int port)
3567 {
3568         int max_in_calls;
3569         
3570         misdn_cfg_get( port, MISDN_CFG_MAX_IN, &max_in_calls, sizeof(max_in_calls));
3571
3572         misdn_in_calls[port]++;
3573
3574         if (max_in_calls >=0 && max_in_calls<misdn_in_calls[port]) {
3575                 ast_log(LOG_NOTICE,"Marking Incoming Call on port[%d]\n",port);
3576                 return misdn_in_calls[port]-max_in_calls;
3577         }
3578         
3579         return 0;
3580 }