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