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