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