adding support for AOCD facility messages.
[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 cli_send_cd =
1345 { {"misdn","send","calldeflect", NULL},
1346   misdn_send_cd,
1347   "Sends CallDeflection to mISDN Channel", 
1348   "Usage: misdn send calldeflect <channel> \"<nr>\" \n",
1349   complete_ch
1350 };
1351
1352 static struct ast_cli_entry cli_send_digit =
1353 { {"misdn","send","digit", NULL},
1354   misdn_send_digit,
1355   "Sends DTMF Digit to mISDN Channel", 
1356   "Usage: misdn send digit <channel> \"<msg>\" \n"
1357   "       Send <digit> to <channel> as DTMF Tone\n"
1358   "       when channel is a mISDN channel\n",
1359   complete_ch
1360 };
1361
1362 static struct ast_cli_entry cli_toggle_echocancel =
1363 { {"misdn","toggle","echocancel", NULL},
1364   misdn_toggle_echocancel,
1365   "Toggles EchoCancel on mISDN Channel", 
1366   "Usage: misdn toggle echocancel <channel>\n", 
1367   complete_ch
1368 };
1369
1370 static struct ast_cli_entry cli_send_display =
1371 { {"misdn","send","display", NULL},
1372   misdn_send_display,
1373   "Sends Text to mISDN Channel", 
1374   "Usage: misdn send display <channel> \"<msg>\" \n"
1375   "       Send <msg> to <channel> as Display Message\n"
1376   "       when channel is a mISDN channel\n",
1377   complete_ch
1378 };
1379
1380 static struct ast_cli_entry cli_show_config =
1381 { {"misdn","show","config", NULL},
1382   misdn_show_config,
1383   "Shows internal mISDN config, read from cfg-file", 
1384   "Usage: misdn show config [<port> | description <config element> | descriptions [general|ports]]\n"
1385   "       Use 0 for <port> to only print the general config.\n",
1386   complete_show_config
1387 };
1388  
1389 static struct ast_cli_entry cli_reload =
1390 { {"misdn","reload", NULL},
1391   misdn_reload,
1392   "Reloads internal mISDN config, read from cfg-file", 
1393   "Usage: misdn reload\n"
1394 };
1395
1396 static struct ast_cli_entry cli_set_tics =
1397 { {"misdn","set","tics", NULL},
1398   misdn_set_tics,
1399   "", 
1400   "\n"
1401 };
1402
1403 static struct ast_cli_entry cli_show_cls =
1404 { {"misdn","show","channels", NULL},
1405   misdn_show_cls,
1406   "Shows internal mISDN chan_list", 
1407   "Usage: misdn show channels\n"
1408 };
1409
1410 static struct ast_cli_entry cli_show_cl =
1411 { {"misdn","show","channel", NULL},
1412   misdn_show_cl,
1413   "Shows internal mISDN chan_list", 
1414   "Usage: misdn show channels\n",
1415   complete_ch
1416 };
1417
1418 static struct ast_cli_entry cli_port_block=
1419 { {"misdn","port","block", NULL},
1420   misdn_port_block,
1421   "Blocks the given port", 
1422   "Usage: misdn port block\n"
1423 };
1424
1425 static struct ast_cli_entry cli_port_unblock=
1426 { {"misdn","port","unblock", NULL},
1427   misdn_port_unblock,
1428   "Unblocks the given port", 
1429   "Usage: misdn port unblock\n"
1430 };
1431
1432
1433 static struct ast_cli_entry cli_restart_port =
1434 { {"misdn","restart","port", NULL},
1435   misdn_restart_port,
1436   "Restarts the given port", 
1437   "Usage: misdn restart port\n"
1438 };
1439
1440 static struct ast_cli_entry cli_port_up =
1441 { {"misdn","port","up", NULL},
1442   misdn_port_up,
1443   "Tries to establish L1 on the given port", 
1444   "Usage: misdn port up <port>\n"
1445 };
1446
1447 static struct ast_cli_entry cli_port_down =
1448 { {"misdn","port","down", NULL},
1449   misdn_port_down,
1450   "Tries to deacivate the L1 on the given port", 
1451   "Usage: misdn port down <port>\n"
1452 };
1453
1454
1455
1456 static struct ast_cli_entry cli_show_stacks =
1457 { {"misdn","show","stacks", NULL},
1458   misdn_show_stacks,
1459   "Shows internal mISDN stack_list", 
1460   "Usage: misdn show stacks\n"
1461 };
1462
1463 static struct ast_cli_entry cli_show_ports_stats =
1464 { {"misdn","show","ports","stats", NULL},
1465   misdn_show_ports_stats,
1466   "Shows chan_misdns call statistics per port", 
1467   "Usage: misdn show port stats\n"
1468 };
1469
1470
1471 static struct ast_cli_entry cli_show_port =
1472 { {"misdn","show","port", NULL},
1473   misdn_show_port,
1474   "Shows detailed information for given port", 
1475   "Usage: misdn show port <port>\n"
1476 };
1477
1478 static struct ast_cli_entry cli_set_debug =
1479 { {"misdn","set","debug", NULL},
1480   misdn_set_debug,
1481   "Sets Debuglevel of chan_misdn",
1482   "Usage: misdn set debug <level> [only] | [port <port> [only]]\n",
1483   complete_debug_port
1484 };
1485
1486 static struct ast_cli_entry cli_set_crypt_debug =
1487 { {"misdn","set","crypt","debug", NULL},
1488   misdn_set_crypt_debug,
1489   "Sets CryptDebuglevel of chan_misdn, at the moment, level={1,2}", 
1490   "Usage: misdn set crypt debug <level>\n"
1491 };
1492 /*** CLI END ***/
1493
1494
1495 static int update_config (struct chan_list *ch, int orig) 
1496 {
1497         if (!ch) {
1498                 ast_log(LOG_WARNING, "Cannot configure without chanlist\n");
1499                 return -1;
1500         }
1501         
1502         struct ast_channel *ast=ch->ast;
1503         struct misdn_bchannel *bc=ch->bc;
1504         if (! ast || ! bc ) {
1505                 ast_log(LOG_WARNING, "Cannot configure without ast || bc\n");
1506                 return -1;
1507         }
1508         
1509         int port=bc->port;
1510         
1511         chan_misdn_log(5,port,"update_config: Getting Config\n");
1512
1513
1514         int hdlc=0;
1515         misdn_cfg_get( port, MISDN_CFG_HDLC, &hdlc, sizeof(int));
1516         
1517         if (hdlc) {
1518                 switch (bc->capability) {
1519                 case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
1520                 case INFO_CAPABILITY_DIGITAL_RESTRICTED:
1521                         chan_misdn_log(1,bc->port," --> CONF HDLC\n");
1522                         bc->hdlc=1;
1523                         break;
1524                 }
1525                 
1526         }
1527         
1528         
1529         int pres, screen;
1530                         
1531         misdn_cfg_get( port, MISDN_CFG_PRES, &pres, sizeof(int));
1532         misdn_cfg_get( port, MISDN_CFG_SCREEN, &screen, sizeof(int));
1533         chan_misdn_log(2,port," --> pres: %d screen: %d\n",pres, screen);
1534                 
1535         if ( (pres + screen) < 0 ) {
1536
1537                 chan_misdn_log(2,port," --> pres: %x\n", ast->cid.cid_pres);
1538                         
1539                 switch (ast->cid.cid_pres & 0x60){
1540                                 
1541                 case AST_PRES_RESTRICTED:
1542                         bc->pres=1;
1543                         chan_misdn_log(2, port, " --> PRES: Restricted (0x1)\n");
1544                         break;
1545                                 
1546                                 
1547                 case AST_PRES_UNAVAILABLE:
1548                         bc->pres=2;
1549                         chan_misdn_log(2, port, " --> PRES: Unavailable (0x2)\n");
1550                         break;
1551                                 
1552                 default:
1553                         bc->pres=0;
1554                         chan_misdn_log(2, port, " --> PRES: Allowed (0x0)\n");
1555                 }
1556                         
1557                 switch (ast->cid.cid_pres & 0x3){
1558                                 
1559                 case AST_PRES_USER_NUMBER_UNSCREENED:
1560                         bc->screen=0;
1561                         chan_misdn_log(2, port, " --> SCREEN: Unscreened (0x0)\n");
1562                         break;
1563
1564                 case AST_PRES_USER_NUMBER_PASSED_SCREEN:
1565                         bc->screen=1;
1566                         chan_misdn_log(2, port, " --> SCREEN: Passed Screen (0x1)\n");
1567                         break;
1568                 case AST_PRES_USER_NUMBER_FAILED_SCREEN:
1569                         bc->screen=2;
1570                         chan_misdn_log(2, port, " --> SCREEN: Failed Screen (0x2)\n");
1571                         break;
1572                                 
1573                 case AST_PRES_NETWORK_NUMBER:
1574                         bc->screen=3;
1575                         chan_misdn_log(2, port, " --> SCREEN: Network Nr. (0x3)\n");
1576                         break;
1577                                 
1578                 default:
1579                         bc->screen=0;
1580                         chan_misdn_log(2, port, " --> SCREEN: Unscreened (0x0)\n");
1581                 }
1582
1583                         
1584         } else {
1585                 bc->screen=screen;
1586                 bc->pres=pres;
1587         }
1588
1589         return 0;
1590         
1591 }
1592
1593
1594
1595
1596 static void config_jitterbuffer(struct chan_list *ch)
1597 {
1598         struct misdn_bchannel *bc=ch->bc;
1599         int len=ch->jb_len, threshold=ch->jb_upper_threshold;
1600         
1601         chan_misdn_log(5,bc->port, "config_jb: Called\n");
1602         
1603         if ( ! len ) {
1604                 chan_misdn_log(1,bc->port, "config_jb: Deactivating Jitterbuffer\n");
1605                 bc->nojitter=1;
1606         } else {
1607                 
1608                 if (len <=100 || len > 8000) {
1609                         chan_misdn_log(0,bc->port,"config_jb: Jitterbuffer out of Bounds, setting to 1000\n");
1610                         len=1000;
1611                 }
1612                 
1613                 if ( threshold > len ) {
1614                         chan_misdn_log(0,bc->port,"config_jb: Jitterbuffer Threshold > Jitterbuffer setting to Jitterbuffer -1\n");
1615                 }
1616                 
1617                 if ( ch->jb) {
1618                         cb_log(0,bc->port,"config_jb: We've got a Jitterbuffer Already on this port.\n");
1619                         misdn_jb_destroy(ch->jb);
1620                         ch->jb=NULL;
1621                 }
1622                 
1623                 ch->jb=misdn_jb_init(len, threshold);
1624
1625                 if (!ch->jb ) 
1626                         bc->nojitter=1;
1627         }
1628 }
1629
1630
1631 void debug_numplan(int port, int numplan, char *type)
1632 {
1633         switch (numplan) {
1634         case NUMPLAN_INTERNATIONAL:
1635                 chan_misdn_log(2, port, " --> %s: International\n",type);
1636                 break;
1637         case NUMPLAN_NATIONAL:
1638                 chan_misdn_log(2, port, " --> %s: National\n",type);
1639                 break;
1640         case NUMPLAN_SUBSCRIBER:
1641                 chan_misdn_log(2, port, " --> %s: Subscriber\n",type);
1642                 break;
1643         case NUMPLAN_UNKNOWN:
1644                 chan_misdn_log(2, port, " --> %s: Unknown\n",type);
1645                 break;
1646                 /* Maybe we should cut off the prefix if present ? */
1647         default:
1648                 chan_misdn_log(0, port, " --> !!!! Wrong dialplan setting, please see the misdn.conf sample file\n ");
1649                 break;
1650         }
1651 }
1652
1653
1654
1655
1656 static int update_ec_config(struct misdn_bchannel *bc)
1657 {
1658         int ec;
1659         int port=bc->port;
1660                 
1661         misdn_cfg_get( port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
1662         
1663         if (ec == 1 ) {
1664                 bc->ec_enable=1;
1665         } else if ( ec > 1 ) {
1666                 bc->ec_enable=1;
1667                 bc->ec_deftaps=ec;
1668         }
1669 #ifdef WITH_ECHOTRAINING 
1670         int ectr;
1671         misdn_cfg_get( port, MISDN_CFG_ECHOTRAINING, &ectr, sizeof(int));
1672         
1673         if ( ectr >= 0 ) {
1674                 bc->ec_training=ectr;
1675         }
1676 #endif
1677
1678         return 0;
1679 }
1680
1681
1682 static int read_config(struct chan_list *ch, int orig) {
1683
1684         if (!ch) {
1685                 ast_log(LOG_WARNING, "Cannot configure without chanlist\n");
1686                 return -1;
1687         }
1688
1689         struct ast_channel *ast=ch->ast;
1690         struct misdn_bchannel *bc=ch->bc;
1691         if (! ast || ! bc ) {
1692                 ast_log(LOG_WARNING, "Cannot configure without ast || bc\n");
1693                 return -1;
1694         }
1695         
1696         int port=bc->port;
1697         
1698         chan_misdn_log(1,port,"read_config: Getting Config\n");
1699
1700         char lang[BUFFERSIZE+1];
1701         
1702
1703         misdn_cfg_get( port, MISDN_CFG_LANGUAGE, lang, BUFFERSIZE);
1704         ast_string_field_set(ast, language, lang);
1705
1706         char localmusicclass[BUFFERSIZE+1];
1707         
1708         misdn_cfg_get( port, MISDN_CFG_MUSICCLASS, localmusicclass, BUFFERSIZE);
1709         ast_string_field_set(ast, musicclass, localmusicclass);
1710         
1711         
1712         misdn_cfg_get( port, MISDN_CFG_TXGAIN, &bc->txgain, sizeof(int));
1713         misdn_cfg_get( port, MISDN_CFG_RXGAIN, &bc->rxgain, sizeof(int));
1714         
1715         misdn_cfg_get( port, MISDN_CFG_INCOMING_EARLY_AUDIO, &ch->incoming_early_audio, sizeof(int));
1716         
1717         misdn_cfg_get( port, MISDN_CFG_SENDDTMF, &bc->send_dtmf, sizeof(int));
1718
1719         misdn_cfg_get( port, MISDN_CFG_NEED_MORE_INFOS, &bc->need_more_infos, sizeof(int));
1720         
1721         misdn_cfg_get( port, MISDN_CFG_FAR_ALERTING, &ch->far_alerting, sizeof(int));
1722
1723         misdn_cfg_get( port, MISDN_CFG_ALLOWED_BEARERS, &ch->allowed_bearers, BUFFERSIZE);
1724         
1725         char faxdetect[BUFFERSIZE+1];
1726         misdn_cfg_get( port, MISDN_CFG_FAXDETECT, faxdetect, BUFFERSIZE);
1727         
1728         int hdlc=0;
1729         misdn_cfg_get( port, MISDN_CFG_HDLC, &hdlc, sizeof(int));
1730         
1731         if (hdlc) {
1732                 switch (bc->capability) {
1733                 case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
1734                 case INFO_CAPABILITY_DIGITAL_RESTRICTED:
1735                         chan_misdn_log(1,bc->port," --> CONF HDLC\n");
1736                         bc->hdlc=1;
1737                         break;
1738                 }
1739                 
1740         }
1741         /*Initialize new Jitterbuffer*/
1742         {
1743                 misdn_cfg_get( port, MISDN_CFG_JITTERBUFFER, &ch->jb_len, sizeof(int));
1744                 misdn_cfg_get( port, MISDN_CFG_JITTERBUFFER_UPPER_THRESHOLD, &ch->jb_upper_threshold, sizeof(int));
1745                 
1746                 config_jitterbuffer(ch);
1747         }
1748         
1749         misdn_cfg_get( bc->port, MISDN_CFG_CONTEXT, ch->context, sizeof(ch->context));
1750         
1751         ast_copy_string (ast->context,ch->context,sizeof(ast->context));        
1752
1753         update_ec_config(bc);
1754
1755         {
1756                 int eb3;
1757                 
1758                 misdn_cfg_get( bc->port, MISDN_CFG_EARLY_BCONNECT, &eb3, sizeof(int));
1759                 bc->early_bconnect=eb3;
1760         }
1761         
1762         port=bc->port;
1763         
1764         {
1765                 char buf[256];
1766                 ast_group_t pg,cg;
1767                 
1768                 misdn_cfg_get(port, MISDN_CFG_PICKUPGROUP, &pg, sizeof(pg));
1769                 misdn_cfg_get(port, MISDN_CFG_CALLGROUP, &cg, sizeof(cg));
1770                 
1771                 chan_misdn_log(5, port, " --> * CallGrp:%s PickupGrp:%s\n",ast_print_group(buf,sizeof(buf),cg),ast_print_group(buf,sizeof(buf),pg));
1772                 ast->pickupgroup=pg;
1773                 ast->callgroup=cg;
1774         }
1775         
1776         if ( orig  == ORG_AST) {
1777                 misdn_cfg_get( port, MISDN_CFG_TE_CHOOSE_CHANNEL, &(bc->te_choose_channel), sizeof(int));
1778                 
1779                 if (strstr(faxdetect, "outgoing") || strstr(faxdetect, "both")) {
1780                         if (strstr(faxdetect, "nojump"))
1781                                 ch->faxdetect=2;
1782                         else
1783                                 ch->faxdetect=1;
1784                 }
1785
1786                 {
1787                         char callerid[BUFFERSIZE+1];
1788                         misdn_cfg_get( port, MISDN_CFG_CALLERID, callerid, BUFFERSIZE);
1789                         if ( ! ast_strlen_zero(callerid) ) {
1790                                 chan_misdn_log(1, port, " --> * Setting Cid to %s\n", callerid);
1791                                 {
1792                                         int l = sizeof(bc->oad);
1793                                         strncpy(bc->oad,callerid, l);
1794                                         bc->oad[l-1] = 0;
1795                                 }
1796
1797                         }
1798
1799                         
1800                         misdn_cfg_get( port, MISDN_CFG_DIALPLAN, &bc->dnumplan, sizeof(int));
1801                         misdn_cfg_get( port, MISDN_CFG_LOCALDIALPLAN, &bc->onumplan, sizeof(int));
1802                         misdn_cfg_get( port, MISDN_CFG_CPNDIALPLAN, &bc->cpnnumplan, sizeof(int));
1803                         debug_numplan(port, bc->dnumplan,"TON");
1804                         debug_numplan(port, bc->onumplan,"LTON");
1805                         debug_numplan(port, bc->cpnnumplan,"CTON");
1806                 }
1807
1808                 ch->overlap_dial = 0;
1809         } else { /** ORIGINATOR MISDN **/
1810                 if (strstr(faxdetect, "incoming") || strstr(faxdetect, "both")) {
1811                         if (strstr(faxdetect, "nojump"))
1812                                 ch->faxdetect=2;
1813                         else
1814                                 ch->faxdetect=1;
1815                 }
1816         
1817                 misdn_cfg_get( port, MISDN_CFG_CPNDIALPLAN, &bc->cpnnumplan, sizeof(int));
1818                 debug_numplan(port, bc->cpnnumplan,"CTON");
1819                 
1820                 char prefix[BUFFERSIZE+1]="";
1821                 switch( bc->onumplan ) {
1822                 case NUMPLAN_INTERNATIONAL:
1823                         misdn_cfg_get( bc->port, MISDN_CFG_INTERNATPREFIX, prefix, BUFFERSIZE);
1824                         break;
1825                         
1826                 case NUMPLAN_NATIONAL:
1827                         misdn_cfg_get( bc->port, MISDN_CFG_NATPREFIX, prefix, BUFFERSIZE);
1828                         break;
1829                 default:
1830                         break;
1831                 }
1832                 
1833                 {
1834                         int l = strlen(prefix) + strlen(bc->oad);
1835                         char tmp[l+1];
1836                         strcpy(tmp,prefix);
1837                         strcat(tmp,bc->oad);
1838                         strcpy(bc->oad,tmp);
1839                 }
1840                 
1841                 if (!ast_strlen_zero(bc->dad)) {
1842                         ast_copy_string(bc->orig_dad,bc->dad, sizeof(bc->orig_dad));
1843                 }
1844                 
1845                 if ( ast_strlen_zero(bc->dad) && !ast_strlen_zero(bc->keypad)) {
1846                         ast_copy_string(bc->dad,bc->keypad, sizeof(bc->dad));
1847                 }
1848
1849                 prefix[0] = 0;
1850                 
1851                 switch( bc->dnumplan ) {
1852                 case NUMPLAN_INTERNATIONAL:
1853                         misdn_cfg_get( bc->port, MISDN_CFG_INTERNATPREFIX, prefix, BUFFERSIZE);
1854                         break;
1855                 case NUMPLAN_NATIONAL:
1856                         misdn_cfg_get( bc->port, MISDN_CFG_NATPREFIX, prefix, BUFFERSIZE);
1857                         break;
1858                 default:
1859                         break;
1860                 }
1861                 
1862                 {
1863                         int l = strlen(prefix) + strlen(bc->dad);
1864                         char tmp[l+1];
1865                         strcpy(tmp,prefix);
1866                         strcat(tmp,bc->dad);
1867                         strcpy(bc->dad,tmp);
1868                 }
1869                 
1870                 if ( strcmp(bc->dad,ast->exten)) {
1871                         ast_copy_string(ast->exten, bc->dad, sizeof(ast->exten));
1872                 }
1873                 
1874                 ast_set_callerid(ast, bc->oad, NULL, bc->oad);
1875                 
1876                 if ( !ast_strlen_zero(bc->rad) ) {
1877                         if (ast->cid.cid_rdnis)
1878                                 free(ast->cid.cid_rdnis);
1879                         ast->cid.cid_rdnis = strdup(bc->rad);
1880                 }
1881         
1882                 misdn_cfg_get(bc->port, MISDN_CFG_OVERLAP_DIAL, &ch->overlap_dial, sizeof(ch->overlap_dial));
1883                 ast_mutex_init(&ch->overlap_tv_lock);
1884         } /* ORIG MISDN END */
1885
1886         ch->overlap_dial_task = -1;
1887         
1888         if (ch->faxdetect) {
1889                 misdn_cfg_get( port, MISDN_CFG_FAXDETECT_TIMEOUT, &ch->faxdetect_timeout, sizeof(ch->faxdetect_timeout));
1890                 if (!ch->dsp)
1891                         ch->dsp = ast_dsp_new();
1892                 if (ch->dsp)
1893                         ast_dsp_set_features(ch->dsp, DSP_FEATURE_DTMF_DETECT | DSP_FEATURE_FAX_DETECT);
1894                 if (!ch->trans)
1895                         ch->trans=ast_translator_build_path(AST_FORMAT_SLINEAR, AST_FORMAT_ALAW);
1896         }
1897
1898         /* AOCD initialization */
1899         bc->AOCDtype = Fac_None;
1900
1901         return 0;
1902 }
1903
1904
1905 /*****************************/
1906 /*** AST Indications Start ***/
1907 /*****************************/
1908
1909 static int misdn_call(struct ast_channel *ast, char *dest, int timeout)
1910 {
1911         int port=0;
1912         int r;
1913         struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
1914         struct misdn_bchannel *newbc;
1915         char *opts=NULL, *ext,*tokb;
1916         char dest_cp[256];
1917
1918         {
1919                 strncpy(dest_cp,dest,sizeof(dest_cp)-1);
1920                 dest_cp[sizeof(dest_cp)]=0;
1921                 
1922                 ext=strtok_r(dest_cp,"/",&tokb);
1923                 
1924                 if (ext) {
1925                         ext=strtok_r(NULL,"/",&tokb);
1926                         if (ext) {
1927                                 opts=strtok_r(NULL,"/",&tokb);
1928                         } else {
1929                                 chan_misdn_log(0,0,"misdn_call: No Extension given!\n");
1930                                 return -1;
1931                         }
1932                 }
1933         }
1934
1935         if (!ast) {
1936                 ast_log(LOG_WARNING, " --> ! misdn_call called on ast_channel *ast where ast == NULL\n");
1937                 return -1;
1938         }
1939
1940         if (((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) || !dest  ) {
1941                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1942                 ast->hangupcause=41;
1943                 ast_setstate(ast, AST_STATE_DOWN);
1944                 return -1;
1945         }
1946
1947         if (!ch) {
1948                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1949                 ast->hangupcause=41;
1950                 ast_setstate(ast, AST_STATE_DOWN);
1951                 return -1;
1952         }
1953         
1954         newbc=ch->bc;
1955         
1956         if (!newbc) {
1957                 ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
1958                 ast->hangupcause=41;
1959                 ast_setstate(ast, AST_STATE_DOWN);
1960                 return -1;
1961         }
1962         
1963         port=newbc->port;
1964         strncpy(newbc->dad,ext,sizeof( newbc->dad));
1965         strncpy(ast->exten,ext,sizeof(ast->exten));
1966
1967         int exceed;
1968         if ((exceed=add_out_calls(port))) {
1969                 char tmp[16];
1970                 sprintf(tmp,"%d",exceed);
1971                 pbx_builtin_setvar_helper(ast,"MAX_OVERFLOW",tmp);
1972                 return -1;
1973         }
1974         
1975         chan_misdn_log(1, port, "* CALL: %s\n",dest);
1976         
1977         chan_misdn_log(1, port, " --> * dad:%s tech:%s ctx:%s\n",ast->exten,ast->name, ast->context);
1978         
1979         chan_misdn_log(3, port, " --> * adding2newbc ext %s\n",ast->exten);
1980         if (ast->exten) {
1981                 int l = sizeof(newbc->dad);
1982                 strncpy(newbc->dad,ast->exten, l);
1983                 newbc->dad[l-1] = 0;
1984         }
1985         newbc->rad[0]=0;
1986         chan_misdn_log(3, port, " --> * adding2newbc callerid %s\n",AST_CID_P(ast));
1987         if (ast_strlen_zero(newbc->oad) && AST_CID_P(ast) ) {
1988
1989                 if (AST_CID_P(ast)) {
1990                         int l = sizeof(newbc->oad);
1991                         strncpy(newbc->oad,AST_CID_P(ast), l);
1992                         newbc->oad[l-1] = 0;
1993                 }
1994         }
1995         
1996         {
1997                 struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
1998                 if (!ch) { ast_verbose("No chan_list in misdn_call"); return -1;}
1999                 
2000                 newbc->capability=ast->transfercapability;
2001                 pbx_builtin_setvar_helper(ast,"TRANSFERCAPABILITY",ast_transfercapability2str(newbc->capability));
2002                 if ( ast->transfercapability == INFO_CAPABILITY_DIGITAL_UNRESTRICTED) {
2003                         chan_misdn_log(2, port, " --> * Call with flag Digital\n");
2004                 }
2005                 
2006
2007                 /* update screening and presentation */ 
2008                 update_config(ch,ORG_AST);
2009                 
2010                 /* fill in some ies from channel vary*/
2011                 import_ch(ast, newbc, ch);
2012                 
2013                 /* Finally The Options Override Everything */
2014                 if (opts)
2015                         misdn_set_opt_exec(ast,opts);
2016                 else
2017                         chan_misdn_log(2,port,"NO OPTS GIVEN\n");
2018                 
2019                 ch->state=MISDN_CALLING;
2020                 
2021                 r=misdn_lib_send_event( newbc, EVENT_SETUP );
2022                 
2023                 /** we should have l3id after sending setup **/
2024                 ch->l3id=newbc->l3_id;
2025         }
2026         
2027         if ( r == -ENOCHAN  ) {
2028                 chan_misdn_log(0, port, " --> * Theres no Channel at the moment .. !\n");
2029                 chan_misdn_log(1, port, " --> * SEND: State Down pid:%d\n",newbc?newbc->pid:-1);
2030                 ast->hangupcause=34;
2031                 ast_setstate(ast, AST_STATE_DOWN);
2032                 return -1;
2033         }
2034         
2035         chan_misdn_log(1, port, " --> * SEND: State Dialing pid:%d\n",newbc?newbc->pid:1);
2036
2037         ast_setstate(ast, AST_STATE_DIALING);
2038         ast->hangupcause=16;
2039         
2040         if (newbc->nt) stop_bc_tones(ch);
2041         
2042         return 0; 
2043 }
2044
2045
2046 static int misdn_answer(struct ast_channel *ast)
2047 {
2048         struct chan_list *p;
2049
2050         
2051         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
2052         
2053         chan_misdn_log(1, p? (p->bc? p->bc->port : 0) : 0, "* ANSWER:\n");
2054         
2055         if (!p) {
2056                 ast_log(LOG_WARNING, " --> Channel not connected ??\n");
2057                 ast_queue_hangup(ast);
2058         }
2059
2060         if (!p->bc) {
2061                 chan_misdn_log(1, 0, " --> Got Answer, but theres no bc obj ??\n");
2062
2063                 ast_queue_hangup(ast);
2064         }
2065
2066         {
2067                 const char *tmp_key = pbx_builtin_getvar_helper(p->ast, "CRYPT_KEY");
2068                 
2069                 if (tmp_key ) {
2070                         chan_misdn_log(1, p->bc->port, " --> Connection will be BF crypted\n");
2071                         {
2072                                 int l = sizeof(p->bc->crypt_key);
2073                                 strncpy(p->bc->crypt_key,tmp_key, l);
2074                                 p->bc->crypt_key[l-1] = 0;
2075                         }
2076                 } else {
2077                         chan_misdn_log(3, p->bc->port, " --> Connection is without BF encryption\n");
2078                 }
2079     
2080         }
2081
2082         {
2083                 const char *nodsp=pbx_builtin_getvar_helper(ast, "MISDN_DIGITAL_TRANS");
2084                 if (nodsp) {
2085                         chan_misdn_log(1, p->bc->port, " --> Connection is transparent digital\n");
2086                         p->bc->nodsp=1;
2087                         p->bc->hdlc=0;
2088                         p->bc->nojitter=1;
2089                 }
2090         }
2091         
2092         p->state = MISDN_CONNECTED;
2093         misdn_lib_echo(p->bc,0);
2094         stop_indicate(p);
2095
2096         if ( ast_strlen_zero(p->bc->cad) ) {
2097                 chan_misdn_log(2,p->bc->port," --> empty cad using dad\n");
2098                 ast_copy_string(p->bc->cad,p->bc->dad,sizeof(p->bc->cad));
2099         }
2100
2101         misdn_lib_send_event( p->bc, EVENT_CONNECT);
2102         start_bc_tones(p);
2103         
2104         return 0;
2105 }
2106
2107 static int misdn_digit(struct ast_channel *ast, char digit )
2108 {
2109         struct chan_list *p;
2110         
2111         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) return -1;
2112
2113         struct misdn_bchannel *bc=p->bc;
2114         chan_misdn_log(1, bc?bc->port:0, "* IND : Digit %c\n",digit);
2115         
2116         if (!bc) {
2117                 ast_log(LOG_WARNING, " --> !! Got Digit Event withut having bchannel Object\n");
2118                 return -1;
2119         }
2120         
2121         switch (p->state ) {
2122                 case MISDN_CALLING:
2123                 {
2124                         
2125                         char buf[8];
2126                         buf[0]=digit;
2127                         buf[1]=0;
2128                         
2129                         int l = sizeof(bc->infos_pending);
2130                         strncat(bc->infos_pending,buf,l);
2131                         bc->infos_pending[l-1] = 0;
2132                 }
2133                 break;
2134                 case MISDN_CALLING_ACKNOWLEDGE:
2135                 {
2136                         bc->info_dad[0]=digit;
2137                         bc->info_dad[1]=0;
2138                         
2139                         {
2140                                 int l = sizeof(bc->dad);
2141                                 strncat(bc->dad,bc->info_dad, l - strlen(bc->dad));
2142                                 bc->dad[l-1] = 0;
2143                 }
2144                         {
2145                                 int l = sizeof(p->ast->exten);
2146                                 strncpy(p->ast->exten, bc->dad, l);
2147                                 p->ast->exten[l-1] = 0;
2148                         }
2149                         
2150                         misdn_lib_send_event( bc, EVENT_INFORMATION);
2151                 }
2152                 break;
2153                 
2154                 default:
2155                         if ( bc->send_dtmf ) {
2156                                 send_digit_to_chan(p,digit);
2157                         }
2158                 break;
2159         }
2160         
2161         return 0;
2162 }
2163
2164
2165 static int misdn_fixup(struct ast_channel *oldast, struct ast_channel *ast)
2166 {
2167         struct chan_list *p;
2168         
2169         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) )) return -1;
2170         
2171         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);
2172         
2173         p->ast = ast ;
2174         p->state=MISDN_CONNECTED;
2175   
2176         return 0;
2177 }
2178
2179
2180
2181 static int misdn_indication(struct ast_channel *ast, int cond, const void *data, size_t datalen)
2182 {
2183         struct chan_list *p;
2184
2185   
2186         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) {
2187                 ast_log(LOG_WARNING, "Returnded -1 in misdn_indication\n");
2188                 return -1;
2189         }
2190         
2191         if (!p->bc ) {
2192                 chan_misdn_log(1, 0, "* IND : Indication from %s\n",ast->exten);
2193                 ast_log(LOG_WARNING, "Private Pointer but no bc ?\n");
2194                 return -1;
2195         }
2196         
2197         chan_misdn_log(1, p->bc->port, "* IND : Indication [%d] from %s\n",cond, ast->exten);
2198         
2199         switch (cond) {
2200         case AST_CONTROL_BUSY:
2201                 chan_misdn_log(1, p->bc->port, "* IND :\tbusy\n");
2202                 chan_misdn_log(1, p->bc->port, " --> * SEND: State Busy pid:%d\n",p->bc?p->bc->pid:-1);
2203                 ast_setstate(ast,AST_STATE_BUSY);
2204
2205                 p->bc->out_cause=17;
2206                 if (p->state != MISDN_CONNECTED) {
2207                         start_bc_tones(p);
2208                         misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
2209                 } else {
2210                         chan_misdn_log(-1, p->bc->port, " --> !! Got Busy in Connected State !?! ast:%s\n", ast->name);
2211                 }
2212                 return -1;
2213                 break;
2214         case AST_CONTROL_RING:
2215                 chan_misdn_log(1, p->bc->port, " --> * IND :\tring pid:%d\n",p->bc?p->bc->pid:-1);
2216                 return -1;
2217                 break;
2218                 
2219         case AST_CONTROL_RINGING:
2220                 switch (p->state) {
2221                         case MISDN_ALERTING:
2222                                 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);
2223                                 break;
2224                         case MISDN_CONNECTED:
2225                                 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);
2226                                 return -1;
2227                                 break;
2228                         default:
2229                                 p->state=MISDN_ALERTING;
2230                                 chan_misdn_log(1, p->bc->port, " --> * IND :\tringing pid:%d\n",p->bc?p->bc->pid:-1);
2231                                 misdn_lib_send_event( p->bc, EVENT_ALERTING);
2232                         
2233                                 if (p->other_ch && p->other_ch->bc) {
2234                                         if (misdn_inband_avail(p->other_ch->bc)) {
2235                                                 chan_misdn_log(1,p->bc->port, " --> other End is mISDN and has inband info available\n");
2236                                                 break;
2237                                         }
2238
2239                                         if (!p->other_ch->bc->nt) {
2240                                                 chan_misdn_log(1,p->bc->port, " --> other End is mISDN TE so it has inband info for sure (?)\n");
2241                                                 break;
2242                                         }
2243                                 }
2244
2245                                 chan_misdn_log(1, p->bc->port, " --> * SEND: State Ring pid:%d\n",p->bc?p->bc->pid:-1);
2246                                 ast_setstate(ast,AST_STATE_RINGING);
2247                         
2248                                 if ( !p->bc->nt && (p->orginator==ORG_MISDN) && !p->incoming_early_audio ) 
2249                                         chan_misdn_log(1,p->bc->port, " --> incoming_early_audio off\n");
2250                                 else 
2251                                         return -1;
2252                 }
2253                 break;
2254         case AST_CONTROL_ANSWER:
2255                 chan_misdn_log(1, p->bc->port, " --> * IND :\tanswer pid:%d\n",p->bc?p->bc->pid:-1);
2256                 start_bc_tones(p);
2257                 break;
2258         case AST_CONTROL_TAKEOFFHOOK:
2259                 chan_misdn_log(1, p->bc->port, " --> *\ttakeoffhook pid:%d\n",p->bc?p->bc->pid:-1);
2260                 return -1;
2261                 break;
2262         case AST_CONTROL_OFFHOOK:
2263                 chan_misdn_log(1, p->bc->port, " --> *\toffhook pid:%d\n",p->bc?p->bc->pid:-1);
2264                 return -1;
2265                 break; 
2266         case AST_CONTROL_FLASH:
2267                 chan_misdn_log(1, p->bc->port, " --> *\tflash pid:%d\n",p->bc?p->bc->pid:-1);
2268                 break;
2269         case AST_CONTROL_PROGRESS:
2270                 chan_misdn_log(1, p->bc->port, " --> * IND :\tprogress pid:%d\n",p->bc?p->bc->pid:-1);
2271                 misdn_lib_send_event( p->bc, EVENT_PROGRESS);
2272                 break;
2273         case AST_CONTROL_PROCEEDING:
2274                 chan_misdn_log(1, p->bc->port, " --> * IND :\tproceeding pid:%d\n",p->bc?p->bc->pid:-1);
2275                 misdn_lib_send_event( p->bc, EVENT_PROCEEDING);
2276                 break;
2277         case AST_CONTROL_CONGESTION:
2278                 chan_misdn_log(1, p->bc->port, " --> * IND :\tcongestion pid:%d\n",p->bc?p->bc->pid:-1);
2279
2280                 p->bc->out_cause=42;
2281                 if (p->state != MISDN_CONNECTED) {
2282                         start_bc_tones(p);
2283                         misdn_lib_send_event( p->bc, EVENT_RELEASE);
2284                 } else {
2285                         misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
2286                 }
2287
2288                 if (p->bc->nt) {
2289                         hanguptone_indicate(p);
2290                 }
2291                 break;
2292         case -1 :
2293                 chan_misdn_log(1, p->bc->port, " --> * IND :\t-1! (stop indication) pid:%d\n",p->bc?p->bc->pid:-1);
2294                 
2295                 stop_indicate(p);
2296
2297                 if (p->state == MISDN_CONNECTED) 
2298                         start_bc_tones(p);
2299
2300                 break;
2301
2302         case AST_CONTROL_HOLD:
2303                 chan_misdn_log(1, p->bc->port, " --> *\tHOLD pid:%d\n",p->bc?p->bc->pid:-1);
2304                 break;
2305         case AST_CONTROL_UNHOLD:
2306                 chan_misdn_log(1, p->bc->port, " --> *\tUNHOLD pid:%d\n",p->bc?p->bc->pid:-1);
2307                 break;
2308         default:
2309                 ast_log(LOG_NOTICE, " --> * Unknown Indication:%d pid:%d\n",cond,p->bc?p->bc->pid:-1);
2310         }
2311   
2312         return 0;
2313 }
2314
2315 static int misdn_hangup(struct ast_channel *ast)
2316 {
2317         struct chan_list *p;
2318         struct misdn_bchannel *bc=NULL;
2319         
2320         if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) ) ) return -1;
2321         
2322         ast_log(LOG_DEBUG, "misdn_hangup(%s)\n", ast->name);
2323         
2324         if (!p) {
2325                 chan_misdn_log(3, 0, "misdn_hangup called, without chan_list obj.\n");
2326                 return 0 ;
2327         }
2328         
2329         bc=p->bc;
2330
2331         if (!bc) {
2332                 ast_log(LOG_WARNING,"Hangup with private but no bc ?\n");
2333                 return 0;
2334         }
2335
2336         
2337         MISDN_ASTERISK_TECH_PVT(ast)=NULL;
2338         p->ast=NULL;
2339
2340         bc=p->bc;
2341         
2342         if (ast->_state == AST_STATE_RESERVED) {
2343                 /* between request and call */
2344                 MISDN_ASTERISK_TECH_PVT(ast)=NULL;
2345                 
2346                 cl_dequeue_chan(&cl_te, p);
2347                 free(p);
2348                 
2349                 if (bc)
2350                         misdn_lib_release(bc);
2351                 
2352                 return 0;
2353         }
2354
2355         p->need_hangup=0;
2356         p->need_queue_hangup=0;
2357         p->need_busy=0;
2358
2359
2360         if (!p->bc->nt) 
2361                 stop_bc_tones(p);
2362
2363         
2364         {
2365                 const char *varcause=NULL;
2366                 bc->out_cause=ast->hangupcause?ast->hangupcause:16;
2367                 
2368                 if ( (varcause=pbx_builtin_getvar_helper(ast, "HANGUPCAUSE")) ||
2369                      (varcause=pbx_builtin_getvar_helper(ast, "PRI_CAUSE"))) {
2370                         int tmpcause=atoi(varcause);
2371                         bc->out_cause=tmpcause?tmpcause:16;
2372                 }
2373     
2374                 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));
2375                 chan_misdn_log(2, bc->port, " --> l3id:%x\n",p->l3id);
2376                 chan_misdn_log(1, bc->port, " --> cause:%d\n",bc->cause);
2377                 chan_misdn_log(1, bc->port, " --> out_cause:%d\n",bc->out_cause);
2378                 chan_misdn_log(1, bc->port, " --> state:%s\n", misdn_get_ch_state(p));
2379                 
2380                 switch (p->state) {
2381                 case MISDN_CALLING:
2382                         p->state=MISDN_CLEANING;
2383                         misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
2384                         break;
2385                 case MISDN_HOLDED:
2386                 case MISDN_DIALING:
2387                         start_bc_tones(p);
2388                         hanguptone_indicate(p);
2389                 
2390                         if (bc->need_disconnect)
2391                                 misdn_lib_send_event( bc, EVENT_DISCONNECT);
2392                         break;
2393
2394                 case MISDN_CALLING_ACKNOWLEDGE:
2395                         start_bc_tones(p);
2396                         hanguptone_indicate(p);
2397                 
2398                         if (bc->need_disconnect)
2399                                 misdn_lib_send_event( bc, EVENT_DISCONNECT);
2400                         break;
2401       
2402                 case MISDN_ALERTING:
2403                 case MISDN_PROGRESS:
2404                 case MISDN_PROCEEDING:
2405                         if (p->orginator != ORG_AST) 
2406                                 hanguptone_indicate(p);
2407       
2408                         /*p->state=MISDN_CLEANING;*/
2409                         if (bc->need_disconnect)
2410                                 misdn_lib_send_event( bc, EVENT_DISCONNECT);
2411                         break;
2412                 case MISDN_CONNECTED:
2413                 case MISDN_PRECONNECTED:
2414                         /*  Alerting or Disconect */
2415                         if (p->bc->nt) {
2416                                 start_bc_tones(p);
2417                                 hanguptone_indicate(p);
2418                                 p->bc->progress_indicator=8;
2419                         }
2420                         if (bc->need_disconnect)
2421                                 misdn_lib_send_event( bc, EVENT_DISCONNECT);
2422
2423                         /*p->state=MISDN_CLEANING;*/
2424                         break;
2425                 case MISDN_DISCONNECTED:
2426                         misdn_lib_send_event( bc, EVENT_RELEASE);
2427                         p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
2428                         break;
2429
2430                 case MISDN_RELEASED:
2431                 case MISDN_CLEANING:
2432                         p->state=MISDN_CLEANING;
2433                         break;
2434
2435                 case MISDN_BUSY:
2436                         break;
2437       
2438                 case MISDN_HOLD_DISCONNECT:
2439                         /* need to send release here */
2440                         chan_misdn_log(1, bc->port, " --> cause %d\n",bc->cause);
2441                         chan_misdn_log(1, bc->port, " --> out_cause %d\n",bc->out_cause);
2442                         
2443                         bc->out_cause=-1;
2444                         misdn_lib_send_event(bc,EVENT_RELEASE);
2445                         p->state=MISDN_CLEANING;
2446                         break;
2447                 default:
2448                         if (bc->nt) {
2449                                 bc->out_cause=-1;
2450                                 misdn_lib_send_event(bc, EVENT_RELEASE);
2451                                 p->state=MISDN_CLEANING; 
2452                         } else {
2453                                 if (bc->need_disconnect)
2454                                         misdn_lib_send_event(bc, EVENT_DISCONNECT);
2455                         }
2456                 }
2457
2458                 p->state=MISDN_CLEANING;
2459     
2460         }
2461         
2462
2463         chan_misdn_log(1, bc->port, "Channel: %s hanguped new state:%s\n",ast->name,misdn_get_ch_state(p));
2464         
2465         return 0;
2466 }
2467
2468
2469 struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame *frame)
2470 {
2471         struct ast_frame *f,*f2;
2472  
2473         if (tmp->trans) {
2474                 f2 = ast_translate(tmp->trans, frame, 0);
2475                 f = ast_dsp_process(tmp->ast, tmp->dsp, f2);
2476         } else {
2477                 chan_misdn_log(0, tmp->bc->port, "No T-Path found\n");
2478                 return NULL;
2479         }
2480
2481  
2482         if (!f || (f->frametype != AST_FRAME_DTMF))
2483                 return frame;
2484  
2485         ast_log(LOG_DEBUG, "Detected inband DTMF digit: %c", f->subclass);
2486  
2487         if (tmp->faxdetect && (f->subclass == 'f')) {
2488                 /* Fax tone -- Handle and return NULL */
2489                 if (!tmp->faxhandled) {
2490                         struct ast_channel *ast = tmp->ast;
2491                         tmp->faxhandled++;
2492                         chan_misdn_log(0, tmp->bc->port, "Fax detected, preparing %s for fax transfer.\n", ast->name);
2493                         tmp->bc->rxgain = 0;
2494                         isdn_lib_update_rxgain(tmp->bc);
2495                         tmp->bc->txgain = 0;
2496                         isdn_lib_update_txgain(tmp->bc);
2497                         tmp->bc->ec_enable = 0;
2498                         isdn_lib_update_ec(tmp->bc);
2499                         isdn_lib_stop_dtmf(tmp->bc);
2500                         switch (tmp->faxdetect) {
2501                         case 1:
2502                                 if (strcmp(ast->exten, "fax")) {
2503                                         char *context;
2504                                         char context_tmp[BUFFERSIZE];
2505                                         misdn_cfg_get(tmp->bc->port, MISDN_CFG_FAXDETECT_CONTEXT, &context_tmp, sizeof(context_tmp));
2506                                         context = ast_strlen_zero(context_tmp) ? (ast_strlen_zero(ast->macrocontext) ? ast->context : ast->macrocontext) : context_tmp;
2507                                         if (ast_exists_extension(ast, context, "fax", 1, AST_CID_P(ast))) {
2508                                                 if (option_verbose > 2)
2509                                                         ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension (context:%s)\n", ast->name, context);
2510                                                 /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
2511                                                 pbx_builtin_setvar_helper(ast,"FAXEXTEN",ast->exten);
2512                                                 if (ast_async_goto(ast, context, "fax", 1))
2513                                                         ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, context);
2514                                         } else
2515                                                 ast_log(LOG_NOTICE, "Fax detected, but no fax extension ctx:%s exten:%s\n", context, ast->exten);
2516                                 } else 
2517                                         ast_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
2518                                 break;
2519                         case 2:
2520                                 ast_verbose(VERBOSE_PREFIX_3 "Not redirecting %s to fax extension, nojump is set.\n", ast->name);
2521                                 break;
2522                         }
2523                 } else
2524                         ast_log(LOG_DEBUG, "Fax already handled\n");
2525         }
2526         
2527         if (tmp->ast_dsp && (f->subclass != 'f')) {
2528                 chan_misdn_log(2, tmp->bc->port, " --> * SEND: DTMF (AST_DSP) :%c\n", f->subclass);
2529         }
2530
2531         return frame;
2532 }
2533
2534
2535 static struct ast_frame  *misdn_read(struct ast_channel *ast)
2536 {
2537         struct chan_list *tmp;
2538         int len;
2539         
2540         if (!ast) {
2541                 chan_misdn_log(1,0,"misdn_read called without ast\n");
2542                 return NULL;
2543         }
2544         if (!(tmp=MISDN_ASTERISK_TECH_PVT(ast))) {
2545                 chan_misdn_log(1,0,"misdn_read called without ast->pvt\n");
2546                 return NULL;
2547         }
2548         if (!tmp->bc) {
2549                 chan_misdn_log(1,0,"misdn_read called without bc\n");
2550                 return NULL;
2551         }
2552
2553         len=read(tmp->pipe[0],tmp->ast_rd_buf,sizeof(tmp->ast_rd_buf));
2554
2555         if (len<=0) {
2556                 /* we hangup here, since our pipe is closed */
2557                 chan_misdn_log(2,tmp->bc->port,"misdn_read: Pipe closed, hanging up\n");
2558                 return NULL;
2559         }
2560
2561         tmp->frame.frametype  = AST_FRAME_VOICE;
2562         tmp->frame.subclass = AST_FORMAT_ALAW;
2563         tmp->frame.datalen = len;
2564         tmp->frame.samples = len;
2565         tmp->frame.mallocd = 0;
2566         tmp->frame.offset = 0;
2567         tmp->frame.src = NULL;
2568         tmp->frame.data = tmp->ast_rd_buf;
2569
2570         if (tmp->faxdetect && !tmp->faxhandled) {
2571                 if (tmp->faxdetect_timeout) {
2572                         if (ast_tvzero(tmp->faxdetect_tv)) {
2573                                 tmp->faxdetect_tv = ast_tvnow();
2574                                 chan_misdn_log(2,tmp->bc->port,"faxdetect: starting detection with timeout: %ds ...\n", tmp->faxdetect_timeout);
2575                                 return process_ast_dsp(tmp, &tmp->frame);
2576                         } else {
2577                                 struct timeval tv_now = ast_tvnow();
2578                                 int diff = ast_tvdiff_ms(tv_now, tmp->faxdetect_tv);
2579                                 if (diff <= (tmp->faxdetect_timeout * 1000)) {
2580                                         chan_misdn_log(5,tmp->bc->port,"faxdetect: detecting ...\n");
2581                                         return process_ast_dsp(tmp, &tmp->frame);
2582                                 } else {
2583                                         chan_misdn_log(2,tmp->bc->port,"faxdetect: stopping detection (time ran out) ...\n");
2584                                         tmp->faxdetect = 0;
2585                                         return &tmp->frame;
2586                                 }
2587                         }
2588                 } else {
2589                         chan_misdn_log(5,tmp->bc->port,"faxdetect: detecting ... (no timeout)\n");
2590                         return process_ast_dsp(tmp, &tmp->frame);
2591                 }
2592         } else {
2593                 if (tmp->ast_dsp)
2594                         return process_ast_dsp(tmp, &tmp->frame);
2595                 else
2596                         return &tmp->frame;
2597         }
2598 }
2599
2600
2601 static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
2602 {
2603         struct chan_list *ch;
2604         int i  = 0;
2605         
2606         if (!ast || ! (ch=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
2607         
2608         if (!ch->bc ) {
2609                 ast_log(LOG_WARNING, "private but no bc\n");
2610                 return -1;
2611         }
2612         
2613         if (ch->state == MISDN_HOLDED) {
2614                 chan_misdn_log(7, ch->bc->port, "misdn_write: Returning because holded\n");
2615                 return 0;
2616         }
2617         
2618         if (ch->notxtone) {
2619                 chan_misdn_log(7, ch->bc->port, "misdn_write: Returning because notxone\n");
2620                 return 0;
2621         }
2622
2623
2624         if ( !frame->subclass) {
2625                 chan_misdn_log(4, ch->bc->port, "misdn_write: * prods us\n");
2626                 return 0;
2627         }
2628         
2629         if ( !(frame->subclass & prefformat)) {
2630                 
2631                 chan_misdn_log(-1, ch->bc->port, "Got Unsupported Frame with Format:%d\n", frame->subclass);
2632                 return 0;
2633         }
2634         
2635
2636         if ( !frame->samples ) {
2637                 chan_misdn_log(4, ch->bc->port, "misdn_write: zero write\n");
2638                 return 0;
2639         }
2640
2641         if ( ! ch->bc->addr ) {
2642                 chan_misdn_log(8, ch->bc->port, "misdn_write: no addr for bc dropping:%d\n", frame->samples);
2643                 return 0;
2644         }
2645         
2646 #if MISDN_DEBUG
2647         {
2648                 int i, max=5>frame->samples?frame->samples:5;
2649                 
2650                 printf("write2mISDN %p %d bytes: ", p, frame->samples);
2651                 
2652                 for (i=0; i<  max ; i++) printf("%2.2x ",((char*) frame->data)[i]);
2653                 printf ("\n");
2654         }
2655 #endif
2656
2657
2658         switch (ch->bc->bc_state) {
2659                 case BCHAN_ACTIVATED:
2660                 case BCHAN_BRIDGED:
2661                         break;
2662                 default:
2663                 if (!ch->dropped_frame_cnt)
2664                         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);
2665                 
2666                 ch->dropped_frame_cnt++;
2667                 if (ch->dropped_frame_cnt > 100) {
2668                         ch->dropped_frame_cnt=0;
2669                         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);
2670
2671                 }
2672
2673                 return 0;
2674         }
2675
2676         chan_misdn_log(9, ch->bc->port, "Sending :%d bytes 2 MISDN\n",frame->samples);
2677         if ( !ch->bc->nojitter && misdn_cap_is_speech(ch->bc->capability) ) {
2678                 /* Buffered Transmit (triggert by read from isdn side)*/
2679                 if (misdn_jb_fill(ch->jb,frame->data,frame->samples) < 0) {
2680                         if (ch->bc->active)
2681                                 cb_log(0,ch->bc->port,"Misdn Jitterbuffer Overflow.\n");
2682                 }
2683                 
2684         } else {
2685                 /*transmit without jitterbuffer*/
2686                 i=misdn_lib_tx2misdn_frm(ch->bc, frame->data, frame->samples);
2687         }
2688
2689         
2690         
2691         return 0;
2692 }
2693
2694
2695
2696
2697 static enum ast_bridge_result  misdn_bridge (struct ast_channel *c0,
2698                                       struct ast_channel *c1, int flags,
2699                                       struct ast_frame **fo,
2700                                       struct ast_channel **rc,
2701                                       int timeoutms)
2702
2703 {
2704         struct chan_list *ch1,*ch2;
2705         struct ast_channel *carr[2], *who;
2706         int to=-1;
2707         struct ast_frame *f;
2708   
2709         ch1=get_chan_by_ast(c0);
2710         ch2=get_chan_by_ast(c1);
2711
2712         carr[0]=c0;
2713         carr[1]=c1;
2714   
2715   
2716         if (ch1 && ch2 ) ;
2717         else
2718                 return -1;
2719   
2720
2721         int bridging;
2722         misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
2723         if (bridging) {
2724                 int ecwb, ec;
2725                 misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2726                 misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
2727                 if ( !ecwb && ec ) {
2728                         chan_misdn_log(2, ch1->bc->port, "Disabling Echo Cancellor when Bridged\n");
2729                         ch1->bc->ec_enable=0;
2730                         manager_ec_disable(ch1->bc);
2731                 }
2732                 misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
2733                 misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
2734                 if ( !ecwb && ec) {
2735                         chan_misdn_log(2, ch2->bc->port, "Disabling Echo Cancellor when Bridged\n");
2736                         ch2->bc->ec_enable=0;
2737                         manager_ec_disable(ch2->bc); 
2738                 }
2739                 
2740                 /* trying to make a mISDN_dsp conference */
2741                 chan_misdn_log(1, ch1->bc->port, "I SEND: Making conference with Number:%d\n", ch1->bc->pid +1);
2742
2743                 misdn_lib_bridge(ch1->bc,ch2->bc);
2744         }
2745         
2746         if (option_verbose > 2) 
2747                 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
2748
2749         chan_misdn_log(1, ch1->bc->port, "* Making Native Bridge between %s and %s\n", ch1->bc->oad, ch2->bc->oad);
2750  
2751         if (! (flags&AST_BRIDGE_DTMF_CHANNEL_0) )
2752                 ch1->ignore_dtmf=1;
2753
2754         if (! (flags&AST_BRIDGE_DTMF_CHANNEL_1) )
2755                 ch2->ignore_dtmf=1;
2756
2757         while(1) {
2758                 to=-1;
2759                 who = ast_waitfor_n(carr, 2, &to);
2760
2761                 if (!who) {
2762                         ast_log(LOG_NOTICE,"misdn_bridge: empty read, breaking out\n");
2763                         break;
2764                 }
2765                 f = ast_read(who);
2766     
2767                 if (!f || f->frametype == AST_FRAME_CONTROL) {
2768                         /* got hangup .. */
2769
2770                         if (!f) 
2771                                 chan_misdn_log(1,ch1->bc->port,"Read Null Frame\n");
2772                         else
2773                                 chan_misdn_log(1,ch1->bc->port,"Read Frame Controll class:%d\n",f->subclass);
2774                         
2775                         *fo=f;
2776                         *rc=who;
2777       
2778                         break;
2779                 }
2780                 
2781                 if ( f->frametype == AST_FRAME_DTMF ) {
2782                         chan_misdn_log(1,0,"Read DTMF %d from %s\n",f->subclass, who->exten);
2783
2784                         *fo=f;
2785                         *rc=who;
2786                         break;
2787                 }
2788                 
2789                 
2790                 if (who == c0) {
2791                         ast_write(c1,f);
2792                 }
2793                 else {
2794                         ast_write(c0,f);
2795                 }
2796     
2797         }
2798         
2799         chan_misdn_log(1, ch1->bc->port, "I SEND: Splitting conference with Number:%d\n", ch1->bc->pid +1);
2800         
2801         misdn_lib_split_bridge(ch1->bc,ch2->bc);
2802         
2803         
2804         return AST_BRIDGE_COMPLETE;
2805 }
2806
2807 /** AST INDICATIONS END **/
2808
2809 static int dialtone_indicate(struct chan_list *cl)
2810 {
2811         const struct tone_zone_sound *ts= NULL;
2812         struct ast_channel *ast=cl->ast;
2813
2814
2815         int nd=0;
2816         misdn_cfg_get( cl->bc->port, MISDN_CFG_NODIALTONE, &nd, sizeof(nd));
2817
2818         if (nd) {
2819                 chan_misdn_log(1,cl->bc->port,"Not sending Dialtone, because config wants it\n");
2820                 return 0;
2821         }
2822         
2823         chan_misdn_log(3,cl->bc->port," --> Dial\n");
2824         ts=ast_get_indication_tone(ast->zone,"dial");
2825         cl->ts=ts;      
2826         
2827         if (ts) {
2828                 cl->notxtone=0;
2829                 cl->norxtone=0;
2830                 ast_playtones_start(ast,0, ts->data, 0);
2831                 chan_misdn_log(4,cl->bc->port,"Starting Playtones\n");
2832                 misdn_lib_tone_generator_start(cl->bc);
2833         }
2834
2835         return 0;
2836 }
2837
2838 static int hanguptone_indicate(struct chan_list *cl)
2839 {
2840         misdn_lib_send_tone(cl->bc,TONE_HANGUP);
2841         return 0;
2842 }
2843
2844 static int stop_indicate(struct chan_list *cl)
2845 {
2846         struct ast_channel *ast=cl->ast;
2847         chan_misdn_log(3,cl->bc->port," --> None\n");
2848         misdn_lib_tone_generator_stop(cl->bc);
2849         ast_playtones_stop(ast);
2850         /*ast_deactivate_generator(ast);*/
2851         
2852         return 0;
2853 }
2854
2855
2856 static int start_bc_tones(struct chan_list* cl)
2857 {
2858         misdn_lib_tone_generator_stop(cl->bc);
2859         cl->notxtone=0;
2860         cl->norxtone=0;
2861         return 0;
2862 }
2863
2864 static int stop_bc_tones(struct chan_list *cl)
2865 {
2866         if (!cl) return -1;
2867
2868         cl->notxtone=1;
2869         cl->norxtone=1;
2870         
2871         return 0;
2872 }
2873
2874
2875 static struct chan_list *init_chan_list(int orig)
2876 {
2877         struct chan_list *cl=malloc(sizeof(struct chan_list));
2878         
2879         if (!cl) {
2880                 chan_misdn_log(-1, 0, "misdn_request: malloc failed!");
2881                 return NULL;
2882         }
2883         
2884         memset(cl,0,sizeof(struct chan_list));
2885
2886         cl->orginator=orig;
2887         cl->need_queue_hangup=1;
2888         cl->need_hangup=1;
2889         cl->need_busy=1;
2890         cl->overlap_dial_task=-1;
2891         
2892         return cl;
2893         
2894 }
2895
2896 static struct ast_channel *misdn_request(const char *type, int format, void *data, int *cause)
2897
2898 {
2899         struct ast_channel *tmp = NULL;
2900         char group[BUFFERSIZE+1]="";
2901         char buf[128];
2902         char buf2[128], *ext=NULL, *port_str;
2903         char *tokb=NULL, *p=NULL;
2904         int channel=0, port=0;
2905         struct misdn_bchannel *newbc = NULL;
2906         
2907         struct chan_list *cl=init_chan_list(ORG_AST);
2908         
2909         sprintf(buf,"%s/%s",misdn_type,(char*)data);
2910         ast_copy_string(buf2,data, 128);
2911         
2912         port_str=strtok_r(buf2,"/", &tokb);
2913
2914         ext=strtok_r(NULL,"/", &tokb);
2915
2916         if (port_str) {
2917                 if (port_str[0]=='g' && port_str[1]==':' ) {
2918                         /* We make a group call lets checkout which ports are in my group */
2919                         port_str += 2;
2920                         strncpy(group, port_str, BUFFERSIZE);
2921                         group[127] = 0;
2922                         chan_misdn_log(2, 0, " --> Group Call group: %s\n",group);
2923                 } 
2924                 else if ((p = strchr(port_str, ':'))) {
2925                         /* we have a preselected channel */
2926                         *p = 0;
2927                         channel = atoi(++p);
2928                         port = atoi(port_str);
2929                         chan_misdn_log(2, port, " --> Call on preselected Channel (%d).\n", channel);
2930                 }
2931                 else {
2932                         port = atoi(port_str);
2933                 }
2934                 
2935                 
2936         } else {
2937                 ast_log(LOG_WARNING, " --> ! IND : CALL dad:%s WITHOUT PORT/Group, check extension.conf\n",ext);
2938                 return NULL;
2939         }
2940
2941         if (!ast_strlen_zero(group)) {
2942         
2943                 char cfg_group[BUFFERSIZE+1];
2944                 struct robin_list *rr = NULL;
2945
2946                 if (misdn_cfg_is_group_method(group, METHOD_ROUND_ROBIN)) {
2947                         chan_misdn_log(4, port, " --> STARTING ROUND ROBIN...");
2948                         rr = get_robin_position(group);
2949                 }
2950                 
2951                 if (rr) {
2952                         int robin_channel = rr->channel;
2953                         int port_start;
2954                         int next_chan = 1;
2955
2956                         do {
2957                                 port_start = 0;
2958                                 for (port = misdn_cfg_get_next_port_spin(rr->port); port > 0 && port != port_start;
2959                                          port = misdn_cfg_get_next_port_spin(port)) {
2960
2961                                         if (!port_start)
2962                                                 port_start = port;
2963
2964                                         if (port >= port_start)
2965                                                 next_chan = 1;
2966                                         
2967                                         if (port <= port_start && next_chan) {
2968                                                 int maxbchans=misdn_lib_get_maxchans(port);
2969                                                 if (++robin_channel >= maxbchans) {
2970                                                         robin_channel = 1;
2971                                                 }
2972                                                 next_chan = 0;
2973                                         }
2974
2975                                         misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
2976                                         
2977                                         if (!strcasecmp(cfg_group, group)) {
2978                                                 int port_up;
2979                                                 int check;
2980                                                 misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
2981                                                 port_up = misdn_lib_port_up(port, check);
2982
2983                                                 if (check && !port_up) 
2984                                                         chan_misdn_log(1,port,"L1 is not Up on this Port\n");
2985                                                 
2986                                                 if (check && port_up<0) {
2987                                                         ast_log(LOG_WARNING,"This port (%d) is blocked\n", port);
2988                                                 }
2989                                                 
2990                                                 
2991                                                 if ( port_up>0 )        {
2992                                                         newbc = misdn_lib_get_free_bc(port, robin_channel);
2993                                                         if (newbc) {
2994                                                                 chan_misdn_log(4, port, " Success! Found port:%d channel:%d\n", newbc->port, newbc->channel);
2995                                                                 if (port_up)
2996                                                                         chan_misdn_log(4, port, "portup:%d\n",  port_up);
2997                                                                 rr->port = newbc->port;
2998                                                                 rr->channel = newbc->channel;
2999                                                                 break;
3000                                                         }
3001                                                 }
3002                                         }
3003                                 }
3004                         } while (!newbc && robin_channel != rr->channel);
3005                         
3006                         if (!newbc)
3007                                 chan_misdn_log(-1, port, " Failed! No free channel in group %d!", group);
3008                 }
3009                 
3010                 else {          
3011                         for (port=misdn_cfg_get_next_port(0); port > 0;
3012                                  port=misdn_cfg_get_next_port(port)) {
3013                                 
3014                                 misdn_cfg_get( port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
3015
3016                                 chan_misdn_log(3,port, "Group [%s] Port [%d]\n", group, port);
3017                                 if (!strcasecmp(cfg_group, group)) {
3018                                         int port_up;
3019                                         int check;
3020                                         misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
3021                                         port_up = misdn_lib_port_up(port, check);
3022                                         
3023                                         chan_misdn_log(4, port, "portup:%d\n", port_up);
3024                                         
3025                                         if ( port_up>0 ) {
3026                                                 newbc = misdn_lib_get_free_bc(port, 0);
3027                                                 if (newbc)
3028                                                         break;
3029                                         }
3030                                 }
3031                         }
3032                 }
3033                 
3034         } else {
3035                 if (channel)
3036                         chan_misdn_log(1, port," --> preselected_channel: %d\n",channel);
3037                 newbc = misdn_lib_get_free_bc(port, channel);
3038         }
3039         
3040         if (!newbc) {
3041                 chan_misdn_log(-1, 0, "Could not create channel on port:%d with extensions:%s\n",port,ext);
3042                 return NULL;
3043         }
3044
3045         /* create ast_channel and link all the objects together */
3046         cl->bc=newbc;
3047         
3048         tmp = misdn_new(cl, AST_STATE_RESERVED, ext, NULL, format, port, channel);
3049         cl->ast=tmp;
3050         
3051         /* register chan in local list */
3052         cl_queue_chan(&cl_te, cl) ;
3053         
3054         /* fill in the config into the objects */
3055         read_config(cl, ORG_AST);
3056
3057         /* important */
3058         cl->need_hangup=0;
3059         
3060         return tmp;
3061 }
3062
3063
3064 static int misdn_send_text (struct ast_channel *chan, const char *text)
3065 {
3066         struct chan_list *tmp=chan->tech_pvt;
3067         
3068         if (tmp && tmp->bc) {
3069                 ast_copy_string(tmp->bc->display,text,sizeof(tmp->bc->display));
3070                 misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
3071         } else {
3072                 ast_log(LOG_WARNING, "No chan_list but send_text request?\n");
3073                 return -1;
3074         }
3075         
3076         return 0;
3077 }
3078
3079 static struct ast_channel_tech misdn_tech = {
3080         .type="mISDN",
3081         .description="Channel driver for mISDN Support (Bri/Pri)",
3082         .capabilities= AST_FORMAT_ALAW ,
3083         .requester=misdn_request,
3084         .send_digit=misdn_digit,
3085         .call=misdn_call,
3086         .bridge=misdn_bridge, 
3087         .hangup=misdn_hangup,
3088         .answer=misdn_answer,
3089         .read=misdn_read,
3090         .write=misdn_write,
3091         .indicate=misdn_indication,
3092         .fixup=misdn_fixup,
3093         .send_text=misdn_send_text,
3094         .properties=0
3095 };
3096
3097 static struct ast_channel_tech misdn_tech_wo_bridge = {
3098         .type="mISDN",
3099         .description="Channel driver for mISDN Support (Bri/Pri)",
3100         .capabilities=AST_FORMAT_ALAW ,
3101         .requester=misdn_request,
3102         .send_digit=misdn_digit,
3103         .call=misdn_call,
3104         .hangup=misdn_hangup,
3105         .answer=misdn_answer,
3106         .read=misdn_read,
3107         .write=misdn_write,
3108         .indicate=misdn_indication,
3109         .fixup=misdn_fixup,
3110         .send_text=misdn_send_text,
3111         .properties=0
3112 };
3113
3114
3115 static int glob_channel=0;
3116
3117 static void update_name(struct ast_channel *tmp, int port, int c) 
3118 {
3119         int chan_offset=0;
3120         int tmp_port = misdn_cfg_get_next_port(0);
3121         for (; tmp_port > 0; tmp_port=misdn_cfg_get_next_port(tmp_port)) {
3122         if (tmp_port == port) break;
3123                 chan_offset+=misdn_lib_port_is_pri(tmp_port)?30:2;      
3124         }
3125         if (c<0) c=0;
3126
3127         ast_string_field_build(tmp, name, "%s/%d-u%d",
3128                                  misdn_type, chan_offset+c, glob_channel++);
3129
3130         chan_misdn_log(3,port," --> updating channel name to [%s]\n",tmp->name);
3131         
3132 }
3133
3134 static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char *exten, char *callerid, int format, int port, int c)
3135 {
3136         struct ast_channel *tmp;
3137         
3138         tmp = ast_channel_alloc(1);
3139         
3140         if (tmp) {
3141                 chan_misdn_log(2, 0, " --> * NEW CHANNEL dad:%s oad:%s\n",exten,callerid);
3142                 
3143                 update_name(tmp,port,c);
3144         
3145                 tmp->nativeformats = prefformat;
3146