f7295bdb3a89a25618e894c604f39b90bf8e6951
[asterisk/asterisk.git] / channels / misdn / isdn_lib.c
1 /*
2  * Chan_Misdn -- Channel Driver for Asterisk
3  *
4  * Interface to mISDN
5  *
6  * Copyright (C) 2004, Christian Richter
7  *
8  * Christian Richter <crich@beronet.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 /*! \file 
15  * \brief Interface to mISDN
16  * \author Christian Richter <crich@beronet.com>
17  */
18
19
20
21 #include <syslog.h>
22 #include <sys/time.h>
23 #include <mISDNuser/isdn_debug.h>
24
25 #include "isdn_lib_intern.h"
26 #include "isdn_lib.h"
27
28 enum event_response_e (*cb_event) (enum event_e event, struct misdn_bchannel *bc, void *user_data);
29
30 void (*cb_log) (int level, int port, char *tmpl, ...)
31         __attribute__ ((format (printf, 3, 4)));
32
33 int (*cb_jb_empty)(struct misdn_bchannel *bc, char *buffer, int len);
34
35
36 /* 
37  * Define ARRAY_LEN() because I cannot
38  * #include "asterisk/utils.h"
39  */
40 #define ARRAY_LEN(a) (sizeof(a) / sizeof(a[0]))
41
42 #include "asterisk/causes.h"
43
44 void misdn_join_conf(struct misdn_bchannel *bc, int conf_id);
45 void misdn_split_conf(struct misdn_bchannel *bc, int conf_id);
46
47 int queue_cleanup_bc(struct misdn_bchannel *bc) ;
48
49 int misdn_lib_get_l2_up(struct misdn_stack *stack);
50
51 struct misdn_stack* get_misdn_stack( void );
52
53 static int set_chan_in_stack(struct misdn_stack *stack, int channel);
54
55 int release_cr(struct misdn_stack *stack, mISDNuser_head_t *hh);
56
57 int misdn_lib_port_is_pri(int port)
58 {
59         struct misdn_stack *stack=get_misdn_stack();
60         for ( ; stack; stack=stack->next) {
61                 if (stack->port == port) {
62                         return stack->pri;
63                 }
64         }
65         
66         return -1;
67 }
68
69 int misdn_lib_port_is_nt(int port)
70 {
71         struct misdn_stack *stack=get_misdn_stack();
72         for ( ; stack; stack=stack->next) {
73                 if (stack->port == port) {
74                         return stack->nt;
75                 }
76         }
77         
78         return -1;
79 }
80
81 void misdn_make_dummy(struct misdn_bchannel *dummybc, int port, int l3id, int nt, int channel) 
82 {
83         memset (dummybc,0,sizeof(struct misdn_bchannel));
84         dummybc->port=port;
85         if (l3id==0) 
86                 dummybc->l3_id = MISDN_ID_DUMMY;
87         else
88                 dummybc->l3_id=l3id;
89
90         dummybc->nt=nt;
91         dummybc->dummy=1;
92         dummybc->channel=channel;
93 }
94
95 int misdn_lib_port_block(int port)
96 {
97         struct misdn_stack *stack=get_misdn_stack();
98         for ( ; stack; stack=stack->next) {
99                 if (stack->port == port) {
100                         stack->blocked=1;
101                         return 0;
102                 }
103         }
104         return -1;
105
106 }
107
108 int misdn_lib_port_unblock(int port)
109 {
110         struct misdn_stack *stack=get_misdn_stack();
111         for ( ; stack; stack=stack->next) {
112                 if (stack->port == port) {
113                         stack->blocked=0;
114                         return 0;
115                 }
116         }
117         return -1;
118
119 }
120
121 int misdn_lib_is_port_blocked(int port)
122 {       
123         struct misdn_stack *stack=get_misdn_stack();
124         for ( ; stack; stack=stack->next) {
125                 if (stack->port == port) {
126                         return stack->blocked;
127                 }
128         }
129         return -1;
130 }
131
132 int misdn_lib_is_ptp(int port)
133 {
134         struct misdn_stack *stack=get_misdn_stack();
135         for ( ; stack; stack=stack->next) {
136                 if (stack->port == port) return stack->ptp;
137         }
138         return -1;
139 }
140
141 int misdn_lib_get_maxchans(int port) 
142 {
143         struct misdn_stack *stack=get_misdn_stack();
144         for ( ; stack; stack=stack->next) {
145                 if (stack->port == port) {
146                         if (stack->pri) 
147                                 return 30;
148                         else
149                                 return 2;
150                 }
151         }
152         return -1;
153 }
154
155
156 struct misdn_stack *get_stack_by_bc(struct misdn_bchannel *bc)
157 {
158         struct misdn_stack *stack = get_misdn_stack();
159
160         if (!bc)
161                 return NULL;
162         
163         for ( ; stack; stack = stack->next) {
164                 if (bc->port == stack->port)
165                         return stack;
166         }
167
168         return NULL;
169 }
170
171
172 void get_show_stack_details(int port, char *buf)
173 {
174         struct misdn_stack *stack=get_misdn_stack();
175         
176         for ( ; stack; stack=stack->next) {
177                 if (stack->port == port) break;
178         }
179         
180         if (stack) {
181                 sprintf(buf, "* Port %d Type %s Prot. %s L2Link %s L1Link:%s Blocked:%d",
182                         stack->port, stack->nt ? "NT" : "TE", stack->ptp ? "PTP" : "PMP",
183                         stack->l2link ? "UP" : "DOWN", stack->l1link ? "UP" : "DOWN",
184                         stack->blocked);
185         } else {
186                 buf[0]=0;
187         }
188 }
189
190
191 static int nt_err_cnt =0 ;
192
193 enum global_states {
194         MISDN_INITIALIZING,
195         MISDN_INITIALIZED
196 } ;
197
198 static enum global_states  global_state=MISDN_INITIALIZING;
199
200
201 #include <mISDNuser/net_l2.h>
202 #include <mISDNuser/tone.h>
203 #include <unistd.h>
204 #include <semaphore.h>
205 #include <pthread.h>
206 #include <signal.h>
207
208 #include "isdn_lib.h"
209
210
211 struct misdn_lib {
212         /*! \brief mISDN device handle returned by mISDN_open() */
213         int midev;
214         int midev_nt;   /* Not used */
215
216         pthread_t event_thread;
217         pthread_t event_handler_thread;
218
219         void *user_data;
220
221         msg_queue_t upqueue;
222         msg_queue_t activatequeue; 
223   
224         sem_t new_msg;
225   
226         struct misdn_stack *stack_list;
227 } ;
228
229 #ifndef ECHOCAN_ON
230 #define ECHOCAN_ON 123
231 #define ECHOCAN_OFF 124
232 #endif
233
234 #define MISDN_DEBUG 0
235
236 void misdn_tx_jitter(struct misdn_bchannel *bc, int len);
237
238 struct misdn_bchannel *find_bc_by_l3id(struct misdn_stack *stack, unsigned long l3id);
239
240 struct misdn_bchannel *find_bc_by_confid(unsigned long confid);
241
242 struct misdn_bchannel *stack_holder_find_bychan(struct misdn_stack *stack, int chan);
243
244 int setup_bc(struct misdn_bchannel *bc);
245
246 int manager_isdn_handler(iframe_t *frm ,msg_t *msg);
247
248 int misdn_lib_port_restart(int port);
249 int misdn_lib_pid_restart(int pid);
250
251 extern struct isdn_msg msgs_g[]; 
252
253 #define ISDN_PID_L3_B_USER 0x430000ff
254 #define ISDN_PID_L4_B_USER 0x440000ff
255
256 /* #define MISDN_IBUF_SIZE 1024 */
257 #define MISDN_IBUF_SIZE 512
258
259 /*  Fine Tuning of Inband  Signalling time */
260 #define TONE_ALERT_CNT 41 /*  1 Sec  */
261 #define TONE_ALERT_SILENCE_CNT 200 /*  4 Sec */
262
263 #define TONE_BUSY_CNT 20 /*  ? */
264 #define TONE_BUSY_SILENCE_CNT 48 /*  ? */
265
266 static int  entity;
267
268 static struct misdn_lib *glob_mgr;
269
270 static char tone_425_flip[TONE_425_SIZE];
271 static char tone_silence_flip[TONE_SILENCE_SIZE];
272
273 static void misdn_lib_isdn_event_catcher(void *arg);
274 static int handle_event_nt(void *dat, void *arg);
275
276
277 void stack_holder_add(struct misdn_stack *stack, struct misdn_bchannel *holder);
278 void stack_holder_remove(struct misdn_stack *stack, struct misdn_bchannel *holder);
279 struct misdn_bchannel *stack_holder_find(struct misdn_stack *stack, unsigned long l3id);
280
281 /* from isdn_lib.h */
282         /* user iface */
283 int te_lib_init( void ) ; /* returns midev */
284 void te_lib_destroy(int midev) ;
285 struct misdn_bchannel *manager_find_bc_by_pid(int pid);
286 struct misdn_bchannel *manager_find_bc_holded(struct misdn_bchannel* bc);
287 void manager_ph_control_block(struct misdn_bchannel *bc, int c1, void *c2, int c2_len);
288 void manager_clean_bc(struct misdn_bchannel *bc );
289 void manager_bchannel_setup (struct misdn_bchannel *bc);
290 void manager_bchannel_cleanup (struct misdn_bchannel *bc);
291
292 void ec_chunk( struct misdn_bchannel *bc, unsigned char *rxchunk, unsigned char *txchunk, int chunk_size);
293         /* end */
294 int bchdev_echocancel_activate(struct misdn_bchannel* dev);
295 void bchdev_echocancel_deactivate(struct misdn_bchannel* dev);
296 /* end */
297
298
299 static char *bearer2str(int cap) {
300         static char *bearers[]={
301                 "Speech",
302                 "Audio 3.1k",
303                 "Unres Digital",
304                 "Res Digital",
305                 "Unknown Bearer"
306         };
307         
308         switch (cap) {
309         case INFO_CAPABILITY_SPEECH:
310                 return bearers[0];
311                 break;
312         case INFO_CAPABILITY_AUDIO_3_1K:
313                 return bearers[1];
314                 break;
315         case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
316                 return bearers[2];
317                 break;
318         case INFO_CAPABILITY_DIGITAL_RESTRICTED:
319                 return bearers[3];
320                 break;
321         default:
322                 return bearers[4];
323                 break;
324         }
325 }
326
327
328 static char flip_table[256];
329
330 static void init_flip_bits(void)
331 {
332         int i,k;
333         
334         for (i = 0 ; i < 256 ; i++) {
335                 unsigned char sample = 0 ;
336                 for (k = 0; k<8; k++) {
337                         if ( i & 1 << k ) sample |= 0x80 >>  k;
338                 }
339                 flip_table[i] = sample;
340         }
341 }
342
343 static char * flip_buf_bits ( char * buf , int len)
344 {
345         int i;
346         char * start = buf;
347         
348         for (i = 0 ; i < len; i++) {
349                 buf[i] = flip_table[(unsigned char)buf[i]];
350         }
351         
352         return start;
353 }
354
355
356
357
358 static msg_t *create_l2msg(int prim, int dinfo, int size) /* NT only */
359 {
360         int i = 0;
361         msg_t *dmsg;
362   
363         while(i < 10)
364         {
365                 dmsg = prep_l3data_msg(prim, dinfo, size, 256, NULL);
366                 if (dmsg)
367                         return(dmsg);
368       
369                 if (!i)
370                         printf("cannot allocate memory, trying again...\n");
371                 i++;
372                 usleep(300000);
373         }
374         printf("cannot allocate memory, system overloaded.\n");
375         exit(-1);
376 }
377
378
379
380 msg_t *create_l3msg(int prim, int mt, int dinfo, int size, int ntmode)
381 {
382         int i = 0;
383         msg_t *dmsg;
384         Q931_info_t *qi;
385         iframe_t *frm;
386   
387         if (!ntmode)
388                 size = sizeof(Q931_info_t)+2;
389   
390         while(i < 10) {
391                 if (ntmode) {
392                         dmsg = prep_l3data_msg(prim, dinfo, size, 256, NULL);
393                         if (dmsg) {
394                                 return(dmsg);
395                         }
396                 } else {
397                         dmsg = alloc_msg(size+256+mISDN_HEADER_LEN+DEFAULT_HEADROOM);
398                         if (dmsg)
399                         {
400                                 memset(msg_put(dmsg,size+mISDN_HEADER_LEN), 0, size+mISDN_HEADER_LEN);
401                                 frm = (iframe_t *)dmsg->data;
402                                 frm->prim = prim;
403                                 frm->dinfo = dinfo;
404                                 qi = (Q931_info_t *)(dmsg->data + mISDN_HEADER_LEN);
405                                 qi->type = mt;
406                                 return(dmsg);
407                         }
408                 }
409     
410                 if (!i) printf("cannot allocate memory, trying again...\n");
411                 i++;
412                 usleep(300000);
413         }
414         printf("cannot allocate memory, system overloaded.\n");
415         exit(-1);
416 }
417
418
419 static int send_msg (int midev, struct misdn_bchannel *bc, msg_t *dmsg)
420 {
421         iframe_t *frm = (iframe_t *)dmsg->data;
422         struct misdn_stack *stack=get_stack_by_bc(bc);
423
424         if (!stack) {
425                 cb_log(0,bc->port,"send_msg: IEK!! no stack\n ");
426                 return -1;
427         }
428         
429         frm->addr = (stack->upper_id | FLG_MSG_DOWN);
430         frm->dinfo = bc->l3_id;
431         frm->len = (dmsg->len) - mISDN_HEADER_LEN;
432                                 
433         cb_log(4,stack->port,"Sending msg, prim:%x addr:%x dinfo:%x\n",frm->prim,frm->addr,frm->dinfo);
434
435         mISDN_write(midev, dmsg->data, dmsg->len, TIMEOUT_1SEC);
436         free_msg(dmsg);
437
438         return 0;
439 }
440
441
442 static int mypid=1;
443
444
445 int misdn_cap_is_speech(int cap)
446 /** Poor mans version **/
447 {
448         if ( (cap != INFO_CAPABILITY_DIGITAL_UNRESTRICTED) &&
449              (cap != INFO_CAPABILITY_DIGITAL_RESTRICTED) ) return 1;
450         return 0;
451 }
452
453 int misdn_inband_avail(struct misdn_bchannel *bc)
454 {
455
456         if (!bc->early_bconnect) {
457                 /* We have opted to never receive any available inband recorded messages */
458                 return 0;
459         }
460         
461         switch (bc->progress_indicator) {
462         case INFO_PI_INBAND_AVAILABLE:
463         case INFO_PI_CALL_NOT_E2E_ISDN:
464         case INFO_PI_CALLED_NOT_ISDN:
465                 return 1;
466         default:
467                 return 0;
468         }
469         return 0;
470 }
471
472
473 static void dump_chan_list(struct misdn_stack *stack)
474 {
475         int i;
476
477         for (i=0; i <= stack->b_num; i++) {
478                 cb_log(6, stack->port, "Idx:%d stack->cchan:%d in_use:%d Chan:%d\n",i,stack->channels[i], stack->bc[i].in_use, i+1);
479         }
480 }
481
482
483 void misdn_dump_chanlist(void)
484 {
485         struct misdn_stack *stack=get_misdn_stack();
486         for ( ; stack; stack=stack->next) {
487                 dump_chan_list(stack);
488         }
489
490 }
491
492 static int set_chan_in_stack(struct misdn_stack *stack, int channel)
493 {
494
495         cb_log(4,stack->port,"set_chan_in_stack: %d\n",channel);
496         dump_chan_list(stack);
497         if (channel >=1 && channel <= MAX_BCHANS) {
498                 if (!stack->channels[channel-1])
499                         stack->channels[channel-1] = 1;
500                 else {
501                         cb_log(4,stack->port,"channel already in use:%d\n", channel );
502                         return -1;
503                 }
504         } else {
505                 cb_log(0,stack->port,"couldn't set channel %d in\n", channel );
506                 return -1;
507         }
508   
509         return 0;
510 }
511
512
513
514 static int find_free_chan_in_stack(struct misdn_stack *stack, struct misdn_bchannel *bc, int channel, int dec)
515 {
516         int i;
517         int chan=0;
518         int bnums = stack->pri ? stack->b_num : stack->b_num - 1;
519
520         if (bc->channel_found)  
521                 return 0;
522         
523         bc->channel_found=1;
524
525         cb_log(5,stack->port,"find_free_chan: req_chan:%d\n",channel);
526
527         if (channel < 0 || channel > MAX_BCHANS) {
528                 cb_log(0, stack->port, " !! out of bound call to find_free_chan_in_stack! (ch:%d)\n", channel);
529                 return 0;
530         }
531         
532         channel--;
533
534         if (dec) {
535                 for (i = bnums; i >=0; i--) {
536                         if (i != 15 && (channel < 0 || i == channel)) { /* skip E1 D channel ;) and work with chan preselection */
537                                 if (!stack->channels[i]) {
538                                         cb_log (3, stack->port, " --> found chan%s: %d\n", channel>=0?" (preselected)":"", i+1);
539                                         chan=i+1;
540                                         break;
541                                 }
542                         }
543                 }
544         } else {
545                 for (i = 0; i <= bnums; i++) {
546                         if (i != 15 && (channel < 0 || i == channel)) { /* skip E1 D channel ;) and work with chan preselection */
547                                 if (!stack->channels[i]) {
548                                         cb_log (3, stack->port, " --> found chan%s: %d\n", channel>=0?" (preselected)":"", i+1);
549                                         chan=i+1;
550                                         break;
551                                 }
552                         }
553                 }
554         }
555
556         if (!chan) {
557                 cb_log (1, stack->port, " !! NO FREE CHAN IN STACK\n");
558                 dump_chan_list(stack);
559                 bc->out_cause = AST_CAUSE_NORMAL_CIRCUIT_CONGESTION;
560                 return -1;
561         }       
562
563         if (set_chan_in_stack(stack, chan)<0) {
564                 cb_log (0, stack->port, "Channel Already in use:%d\n", chan);
565                 bc->out_cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL;
566                 return -1;
567         }
568
569         bc->channel=chan;
570         return 0;
571 }
572
573 static int empty_chan_in_stack(struct misdn_stack *stack, int channel)
574 {
575         if (channel<=0 || channel>MAX_BCHANS) {
576                 cb_log(0,stack?stack->port:0, "empty_chan_in_stack: cannot empty channel %d\n",channel);
577                 return -1;
578         }
579         
580         cb_log (4, stack?stack->port:0, "empty_chan_in_stack: %d\n",channel); 
581         stack->channels[channel-1] = 0;
582         dump_chan_list(stack);
583         return 0;
584 }
585
586 char *bc_state2str(enum bchannel_state state) {
587         int i;
588         
589         struct bchan_state_s {
590                 char *n;
591                 enum bchannel_state s;
592         } states[] = {
593                 {"BCHAN_CLEANED", BCHAN_CLEANED },
594                 {"BCHAN_EMPTY", BCHAN_EMPTY},
595                 {"BCHAN_SETUP", BCHAN_SETUP},
596                 {"BCHAN_SETUPED", BCHAN_SETUPED},
597                 {"BCHAN_ACTIVE", BCHAN_ACTIVE},
598                 {"BCHAN_ACTIVATED", BCHAN_ACTIVATED},
599                 {"BCHAN_BRIDGE",  BCHAN_BRIDGE},
600                 {"BCHAN_BRIDGED", BCHAN_BRIDGED},
601                 {"BCHAN_RELEASE", BCHAN_RELEASE},
602                 {"BCHAN_RELEASED", BCHAN_RELEASED},
603                 {"BCHAN_CLEAN", BCHAN_CLEAN},
604                 {"BCHAN_CLEAN_REQUEST", BCHAN_CLEAN_REQUEST},
605                 {"BCHAN_ERROR", BCHAN_ERROR}
606         };
607         
608         for (i=0; i< sizeof(states)/sizeof(struct bchan_state_s); i++)
609                 if ( states[i].s == state)
610                         return states[i].n;
611
612         return "UNKNOWN";
613 }
614
615 void bc_state_change(struct misdn_bchannel *bc, enum bchannel_state state)
616 {
617         cb_log(5,bc->port,"BC_STATE_CHANGE: l3id:%x from:%s to:%s\n",
618                 bc->l3_id,
619                bc_state2str(bc->bc_state),
620                bc_state2str(state) );
621         
622         switch (state) {
623                 case BCHAN_ACTIVATED:
624                         if (bc->next_bc_state ==  BCHAN_BRIDGED) {
625                                 misdn_join_conf(bc, bc->conf_id);
626                                 bc->next_bc_state = BCHAN_EMPTY;
627                                 return;
628                         }
629                 default:
630                         bc->bc_state=state;
631                         break;
632         }
633 }
634
635 static void bc_next_state_change(struct misdn_bchannel *bc, enum bchannel_state state)
636 {
637         cb_log(5,bc->port,"BC_NEXT_STATE_CHANGE: from:%s to:%s\n",
638                bc_state2str(bc->next_bc_state),
639                bc_state2str(state) );
640
641         bc->next_bc_state=state;
642 }
643
644
645 static void empty_bc(struct misdn_bchannel *bc)
646 {
647         bc->dummy=0;
648
649         bc->bframe_len=0;
650
651         bc->cw= 0;
652
653         bc->dec=0;
654         bc->channel = 0;
655
656         bc->sending_complete = 0;
657
658         bc->restart_channel=0;
659         
660         bc->conf_id = 0;
661
662         bc->need_more_infos = 0;
663         
664         bc->send_dtmf=0;
665         bc->nodsp=0;
666         bc->nojitter=0;
667
668         bc->time_usec=0;
669         
670         bc->rxgain=0;
671         bc->txgain=0;
672
673         bc->crypt=0;
674         bc->curptx=0; bc->curprx=0;
675         
676         bc->crypt_key[0] = 0;
677         
678         bc->generate_tone=0;
679         bc->tone_cnt=0;
680   
681         bc->dnumplan=NUMPLAN_UNKNOWN;
682         bc->onumplan=NUMPLAN_UNKNOWN;
683         bc->rnumplan=NUMPLAN_UNKNOWN;
684         bc->cpnnumplan=NUMPLAN_UNKNOWN;
685         
686
687         bc->active = 0;
688
689         bc->early_bconnect = 1;
690         
691 #ifdef MISDN_1_2
692         *bc->pipeline = 0;
693 #else
694         bc->ec_enable = 0;
695         bc->ec_deftaps = 128;
696 #endif
697
698         bc->AOCD_need_export = 0;
699
700         bc->orig=0;
701   
702         bc->cause = AST_CAUSE_NORMAL_CLEARING;
703         bc->out_cause = AST_CAUSE_NORMAL_CLEARING;
704         bc->pres = 0;   /* allowed */
705         
706         bc->evq=EVENT_NOTHING;
707
708         bc->progress_coding=0;
709         bc->progress_location=0;
710         bc->progress_indicator=0;
711         
712 /** Set Default Bearer Caps **/
713         bc->capability=INFO_CAPABILITY_SPEECH;
714         bc->law=INFO_CODEC_ALAW;
715         bc->mode=0;
716         bc->rate=0x10;
717         bc->user1=0;
718         bc->urate=0;
719         
720         bc->hdlc=0;
721         
722         
723         bc->info_dad[0] = 0;
724         bc->display[0] = 0;
725         bc->infos_pending[0] = 0;
726         bc->cad[0] = 0;
727         bc->oad[0] = 0;
728         bc->dad[0] = 0;
729         bc->rad[0] = 0;
730         bc->orig_dad[0] = 0;
731         bc->uu[0]=0;
732         bc->uulen=0;
733         
734         bc->fac_in.Function = Fac_None;
735         bc->fac_out.Function = Fac_None;
736         
737         bc->te_choose_channel = 0;
738         bc->channel_found= 0;
739
740         gettimeofday(&bc->last_used, NULL);
741 }
742
743
744 static int clean_up_bc(struct misdn_bchannel *bc)
745 {
746         int ret=0;
747         unsigned char buff[32];
748         struct misdn_stack * stack;
749
750         cb_log(3, bc?bc->port:0, "$$$ CLEANUP CALLED pid:%d\n", bc?bc->pid:-1);
751         
752         if (!bc  ) return -1;
753         stack=get_stack_by_bc(bc);
754         
755         if (!stack) return -1;
756         
757         switch (bc->bc_state ) {
758         case BCHAN_CLEANED:
759                 cb_log(5, stack->port, "$$$ Already cleaned up bc with stid :%x\n", bc->b_stid);
760                 return -1;
761                 
762         default:
763                 break;
764         }
765         
766         cb_log(2, stack->port, "$$$ Cleaning up bc with stid :%x pid:%d\n", bc->b_stid, bc->pid);
767         
768         manager_ec_disable(bc);
769
770         manager_bchannel_deactivate(bc);
771
772         mISDN_write_frame(stack->midev, buff, bc->layer_id|FLG_MSG_TARGET|FLG_MSG_DOWN, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
773         
774         bc->b_stid = 0;
775         bc_state_change(bc, BCHAN_CLEANED);
776         
777         return ret;
778 }
779
780
781
782 static void clear_l3(struct misdn_stack *stack)
783 {
784         int i;
785
786         for (i=0; i<=stack->b_num; i++) {
787                 if (global_state == MISDN_INITIALIZED)  {
788                         cb_event(EVENT_CLEANUP, &stack->bc[i], NULL); 
789                         empty_chan_in_stack(stack,i+1);
790                         empty_bc(&stack->bc[i]);
791                         clean_up_bc(&stack->bc[i]);
792                         stack->bc[i].in_use = 0;
793                 }
794                 
795         } 
796 }
797
798 static int newteid=0;
799
800 #define MAXPROCS 0x100
801
802 static int misdn_lib_get_l1_down(struct misdn_stack *stack)
803 {
804         /* Pull Up L1 */ 
805         iframe_t act;
806         act.prim = PH_DEACTIVATE | REQUEST; 
807         act.addr = stack->lower_id|FLG_MSG_DOWN;
808         act.dinfo = 0;
809         act.len = 0;
810
811         cb_log(1, stack->port, "SENDING PH_DEACTIVATE | REQ\n");
812         return mISDN_write(stack->midev, &act, mISDN_HEADER_LEN+act.len, TIMEOUT_1SEC);
813 }
814
815
816 static int misdn_lib_get_l2_down(struct misdn_stack *stack)
817 {
818         
819         if (stack->ptp && (stack->nt) ) {
820                 msg_t *dmsg;
821                 /* L2 */
822                 dmsg = create_l2msg(DL_RELEASE| REQUEST, 0, 0);
823                 
824                 if (stack->nst.manager_l3(&stack->nst, dmsg))
825                         free_msg(dmsg);
826                 
827         } else {
828                 iframe_t act;
829                 
830                 act.prim = DL_RELEASE| REQUEST;
831                 act.addr = (stack->upper_id |FLG_MSG_DOWN)  ;
832                 
833                 act.dinfo = 0;
834                 act.len = 0;
835                 return mISDN_write(stack->midev, &act, mISDN_HEADER_LEN+act.len, TIMEOUT_1SEC);
836         }
837         
838         return 0;
839 }
840
841
842 static int misdn_lib_get_l1_up(struct misdn_stack *stack)
843 {
844         /* Pull Up L1 */ 
845         iframe_t act;
846         act.prim = PH_ACTIVATE | REQUEST; 
847         act.addr = (stack->upper_id | FLG_MSG_DOWN)  ;
848
849         
850         act.dinfo = 0;
851         act.len = 0;
852
853         return mISDN_write(stack->midev, &act, mISDN_HEADER_LEN+act.len, TIMEOUT_1SEC);
854
855 }
856
857 int misdn_lib_get_l2_up(struct misdn_stack *stack)
858 {
859         
860         if (stack->ptp && (stack->nt) ) {
861                 msg_t *dmsg;
862                 /* L2 */
863                 dmsg = create_l2msg(DL_ESTABLISH | REQUEST, 0, 0);
864                 
865                 if (stack->nst.manager_l3(&stack->nst, dmsg))
866                         free_msg(dmsg);
867                 
868         } else {
869                 iframe_t act;
870                 
871                 act.prim = DL_ESTABLISH | REQUEST;
872                 act.addr = (stack->upper_id |FLG_MSG_DOWN)  ;
873                 
874                 act.dinfo = 0;
875                 act.len = 0;
876                 return mISDN_write(stack->midev, &act, mISDN_HEADER_LEN+act.len, TIMEOUT_1SEC);
877         }
878         
879         return 0;
880 }
881
882 #if 0
883 static int misdn_lib_get_l2_te_ptp_up(struct misdn_stack *stack)
884 {
885         iframe_t act;
886                 
887         act.prim = DL_ESTABLISH | REQUEST;
888         act.addr = (stack->upper_id  & ~LAYER_ID_MASK) | 3 | FLG_MSG_DOWN;
889                 
890         act.dinfo = 0;
891         act.len = 0;
892         return mISDN_write(stack->midev, &act, mISDN_HEADER_LEN+act.len, TIMEOUT_1SEC);
893         return 0;
894 }
895 #endif
896
897 static int misdn_lib_get_short_status(struct misdn_stack *stack)
898 {
899         iframe_t act;
900         
901         
902         act.prim = MGR_SHORTSTATUS | REQUEST; 
903         
904         act.addr = (stack->upper_id | MSG_BROADCAST)  ;
905
906         act.dinfo = SSTATUS_BROADCAST_BIT | SSTATUS_ALL;
907         
908         act.len = 0;
909         return mISDN_write(stack->midev, &act, mISDN_HEADER_LEN+act.len, TIMEOUT_1SEC);
910 }
911
912
913
914 static int create_process (int midev, struct misdn_bchannel *bc) {
915         iframe_t ncr;
916         int l3_id;
917         int i;
918         struct misdn_stack *stack=get_stack_by_bc(bc);
919   
920         if (stack->nt) {
921                 if (find_free_chan_in_stack(stack, bc, bc->channel_preselected?bc->channel:0, 0)<0) return -1;
922                 cb_log(4,stack->port, " -->  found channel: %d\n",bc->channel);
923     
924                 for (i=0; i <= MAXPROCS; i++)
925                         if (stack->procids[i]==0) break;
926     
927                 if (i== MAXPROCS) {
928                         cb_log(0, stack->port, "Couldn't Create New ProcId.\n");
929                         return -1;
930                 }
931                 stack->procids[i]=1;
932
933                 l3_id = 0xff00 | i;
934     
935                 ncr.prim = CC_NEW_CR | REQUEST; 
936
937                 ncr.addr = (stack->upper_id | FLG_MSG_DOWN)  ;
938
939                 ncr.dinfo = l3_id;
940                 ncr.len = 0;
941
942                 bc->l3_id = l3_id;
943                 cb_log(3, stack->port, " --> new_l3id %x\n",l3_id);
944     
945         } else { 
946                 if (stack->ptp || bc->te_choose_channel) {
947                         /* we know exactly which channels are in use */
948                         if (find_free_chan_in_stack(stack, bc, bc->channel_preselected?bc->channel:0, bc->dec)<0) return -1;
949                         cb_log(2,stack->port, " -->  found channel: %d\n",bc->channel);
950                 } else {
951                         /* other phones could have made a call also on this port (ptmp) */
952                         bc->channel=0xff;
953                 }
954     
955     
956                 /* if we are in te-mode, we need to create a process first */
957                 if (newteid++ > 0xffff)
958                         newteid = 0x0001;
959     
960                 l3_id = (entity<<16) | newteid;
961                 /* preparing message */
962                 ncr.prim = CC_NEW_CR | REQUEST; 
963
964                 ncr.addr = (stack->upper_id | FLG_MSG_DOWN)  ;
965
966                 ncr.dinfo =l3_id;
967                 ncr.len = 0;
968                 /* send message */
969
970                 bc->l3_id = l3_id;
971                 cb_log(3, stack->port, "--> new_l3id %x\n",l3_id);
972     
973                 mISDN_write(midev, &ncr, mISDN_HEADER_LEN+ncr.len, TIMEOUT_1SEC);
974         }
975   
976         return l3_id;
977 }
978
979
980 void misdn_lib_setup_bc(struct misdn_bchannel *bc)
981 {
982         clean_up_bc(bc);
983         setup_bc(bc);
984 }
985
986
987 int setup_bc(struct misdn_bchannel *bc)
988 {
989         unsigned char buff[1025];
990         int midev;
991         int channel;
992         int b_stid;
993         int i;
994         mISDN_pid_t pid;
995         int ret;
996
997         struct misdn_stack *stack=get_stack_by_bc(bc);
998
999         if (!stack) {
1000                 cb_log(0, bc->port, "setup_bc: NO STACK FOUND!!\n");
1001                 return -1;
1002         }
1003         
1004         midev = stack->midev;
1005         channel = bc->channel - 1 - (bc->channel > 16);
1006         b_stid = stack->b_stids[channel >= 0 ? channel : 0];
1007
1008         switch (bc->bc_state) {
1009                 case BCHAN_CLEANED:
1010                         break;
1011                 default:
1012                         cb_log(4, stack->port, "$$$ bc already setup stid :%x (state:%s)\n", b_stid, bc_state2str(bc->bc_state) );
1013                         return -1;
1014         }
1015         
1016         cb_log(5, stack->port, "$$$ Setting up bc with stid :%x\n", b_stid);
1017         
1018         /*check if the b_stid is already initialized*/
1019         for (i=0; i <= stack->b_num; i++) {
1020                 if (stack->bc[i].b_stid == b_stid) {
1021                         cb_log(0, bc->port, "setup_bc: b_stid:%x already in use !!!\n", b_stid);
1022                         return -1;
1023                 }
1024         }
1025         
1026         if (b_stid <= 0) {
1027                 cb_log(0, stack->port," -- Stid <=0 at the moment in channel:%d\n",channel);
1028                 
1029                 bc_state_change(bc,BCHAN_ERROR);
1030                 return 1;
1031         }
1032
1033         bc->b_stid = b_stid;
1034
1035         {
1036                 layer_info_t li;
1037                 memset(&li, 0, sizeof(li));
1038     
1039                 li.object_id = -1;
1040                 li.extentions = 0;
1041                 
1042                 li.st = bc->b_stid; /*  given idx */
1043
1044
1045 #define MISDN_DSP
1046 #ifndef MISDN_DSP
1047                 bc->nodsp=1;
1048 #endif
1049                 if ( bc->hdlc || bc->nodsp) {
1050                         cb_log(4, stack->port,"setup_bc: without dsp\n");
1051                         { 
1052                                 int l = sizeof(li.name);
1053                                 strncpy(li.name, "B L3", l);
1054                                 li.name[l-1] = 0;
1055                         }
1056                         li.pid.layermask = ISDN_LAYER((3));
1057                         li.pid.protocol[3] = ISDN_PID_L3_B_USER;
1058                         
1059                         bc->layer=3;
1060                 } else {
1061                         cb_log(4, stack->port,"setup_bc: with dsp\n");
1062                         { 
1063                                 int l = sizeof(li.name);
1064                                 strncpy(li.name, "B L4", l);
1065                                 li.name[l-1] = 0;
1066                         }
1067                         li.pid.layermask = ISDN_LAYER((4));
1068                         li.pid.protocol[4] = ISDN_PID_L4_B_USER;
1069
1070                         bc->layer=4;
1071                 }  
1072                 
1073                 ret = mISDN_new_layer(midev, &li);
1074                 if (ret ) {
1075                         cb_log(0, stack->port,"New Layer Err: %d %s\n",ret,strerror(errno));
1076
1077                         bc_state_change(bc,BCHAN_ERROR);
1078                         return(-EINVAL);
1079                 }
1080                 
1081                 bc->layer_id = li.id;
1082         }
1083         
1084         memset(&pid, 0, sizeof(pid));
1085         
1086         
1087         
1088         cb_log(4, stack->port," --> Channel is %d\n", bc->channel);
1089         
1090         if (bc->nodsp) {
1091                 cb_log(2, stack->port," --> TRANSPARENT Mode (no DSP, no HDLC)\n");
1092                 pid.protocol[1] = ISDN_PID_L1_B_64TRANS;
1093                 pid.protocol[2] = ISDN_PID_L2_B_TRANS;
1094                 pid.protocol[3] = ISDN_PID_L3_B_USER;
1095                 pid.layermask = ISDN_LAYER((1)) | ISDN_LAYER((2)) | ISDN_LAYER((3));
1096                 
1097         } else if ( bc->hdlc ) {
1098                 cb_log(2, stack->port," --> HDLC Mode\n");
1099                 pid.protocol[1] = ISDN_PID_L1_B_64HDLC ;
1100                 pid.protocol[2] = ISDN_PID_L2_B_TRANS  ;
1101                 pid.protocol[3] = ISDN_PID_L3_B_USER;
1102                 pid.layermask = ISDN_LAYER((1)) | ISDN_LAYER((2)) | ISDN_LAYER((3)) ;
1103         } else {
1104                 cb_log(2, stack->port," --> TRANSPARENT Mode\n");
1105                 pid.protocol[1] = ISDN_PID_L1_B_64TRANS;
1106                 pid.protocol[2] = ISDN_PID_L2_B_TRANS;
1107                 pid.protocol[3] = ISDN_PID_L3_B_DSP;
1108                 pid.protocol[4] = ISDN_PID_L4_B_USER;
1109                 pid.layermask = ISDN_LAYER((1)) | ISDN_LAYER((2)) | ISDN_LAYER((3)) | ISDN_LAYER((4));
1110                 
1111         } 
1112
1113         ret = mISDN_set_stack(midev, bc->b_stid, &pid);
1114
1115         if (ret){
1116                 cb_log(0, stack->port,"$$$ Set Stack Err: %d %s\n",ret,strerror(errno));
1117                 
1118                 mISDN_write_frame(midev, buff, bc->layer_id, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
1119                 
1120                 bc_state_change(bc,BCHAN_ERROR);
1121                 cb_event(EVENT_BCHAN_ERROR, bc, glob_mgr->user_data);
1122                 return(-EINVAL);
1123         }
1124
1125         ret = mISDN_get_setstack_ind(midev, bc->layer_id);
1126
1127         if (ret) {
1128                 cb_log(0, stack->port,"$$$ Set StackIND Err: %d %s\n",ret,strerror(errno));
1129                 mISDN_write_frame(midev, buff, bc->layer_id, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
1130                 
1131                 bc_state_change(bc,BCHAN_ERROR);
1132                 cb_event(EVENT_BCHAN_ERROR, bc, glob_mgr->user_data);
1133                 return(-EINVAL);
1134         }
1135
1136         ret = mISDN_get_layerid(midev, bc->b_stid, bc->layer) ;
1137
1138         bc->addr = ret>0? ret : 0;
1139
1140         if (!bc->addr) {
1141                 cb_log(0, stack->port,"$$$ Get Layerid Err: %d %s\n",ret,strerror(errno));
1142                 mISDN_write_frame(midev, buff, bc->layer_id, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
1143                 
1144                 bc_state_change(bc,BCHAN_ERROR);
1145                 cb_event(EVENT_BCHAN_ERROR, bc, glob_mgr->user_data);
1146                 return (-EINVAL);
1147         }
1148
1149         manager_bchannel_activate(bc);
1150         
1151         bc_state_change(bc,BCHAN_ACTIVATED);
1152
1153         return 0;
1154 }
1155
1156
1157
1158 /** IFACE **/
1159 static int init_bc(struct misdn_stack *stack, struct misdn_bchannel *bc, int midev, int port, int bidx, char *msn, int firsttime)
1160 {
1161         unsigned char buff[1025] = "";
1162         iframe_t *frm = (iframe_t *)buff;
1163         int ret;
1164   
1165         if (!bc) return -1;
1166   
1167         cb_log(8, port, "Init.BC %d.\n",bidx);
1168         
1169         memset(bc, 0,sizeof(struct misdn_bchannel));
1170
1171         bc->send_lock=malloc(sizeof(struct send_lock));
1172         if (!bc->send_lock) {
1173                 return -1;
1174         }
1175         pthread_mutex_init(&bc->send_lock->lock, NULL);
1176         
1177         if (msn) {
1178                 int l = sizeof(bc->msn);
1179                 strncpy(bc->msn,msn, l);
1180                 bc->msn[l-1] = 0;
1181         }
1182         
1183         
1184         empty_bc(bc);
1185         bc_state_change(bc, BCHAN_CLEANED);
1186         
1187         bc->port=stack->port;
1188         bc->nt=stack->nt?1:0;
1189         bc->pri=stack->pri;
1190         
1191         {
1192                 ibuffer_t* ibuf= init_ibuffer(MISDN_IBUF_SIZE);
1193
1194                 if (!ibuf) return -1;
1195                 
1196                 clear_ibuffer( ibuf);
1197                 
1198                 ibuf->rsem=malloc(sizeof(sem_t));
1199                 if (!ibuf->rsem) {
1200                         return -1;
1201                 }
1202                 
1203                 bc->astbuf=ibuf;
1204
1205                 if (sem_init(ibuf->rsem,1,0)<0)
1206                         sem_init(ibuf->rsem,0,0);
1207                 
1208         }
1209         
1210         {
1211                 stack_info_t *stinf;
1212                 ret = mISDN_get_stack_info(midev, stack->port, buff, sizeof(buff));
1213                 if (ret < 0) {
1214                         cb_log(0, port, "%s: Cannot get stack info for this port. (ret=%d)\n", __FUNCTION__, ret);
1215                         return -1;
1216                 }
1217     
1218                 stinf = (stack_info_t *)&frm->data.p;
1219     
1220                 cb_log(8, port, " --> Child %x\n",stinf->child[bidx]);
1221         }
1222   
1223         return 0;
1224 }
1225
1226
1227
1228 static struct misdn_stack *stack_init(int midev, int port, int ptp)
1229 {
1230         int ret;
1231         unsigned char buff[1025];
1232         iframe_t *frm = (iframe_t *)buff;
1233         stack_info_t *stinf;
1234         int i; 
1235         layer_info_t li;
1236
1237         struct misdn_stack *stack = malloc(sizeof(struct misdn_stack));
1238         if (!stack ) return NULL;
1239
1240
1241         cb_log(8, port, "Init. Stack.\n");
1242   
1243         memset(stack,0,sizeof(struct misdn_stack));
1244   
1245         for (i=0; i<MAX_BCHANS + 1; i++ ) stack->channels[i]=0;
1246         
1247         stack->port=port;
1248         stack->midev=midev;
1249         stack->ptp=ptp;
1250   
1251         stack->holding=NULL;
1252         stack->pri=0;
1253   
1254         msg_queue_init(&stack->downqueue);
1255         msg_queue_init(&stack->upqueue);
1256   
1257         /* query port's requirements */
1258         ret = mISDN_get_stack_info(midev, port, buff, sizeof(buff));
1259         if (ret < 0) {
1260                 cb_log(0, port, "%s: Cannot get stack info for this port. (ret=%d)\n", __FUNCTION__, ret);
1261                 return(NULL);
1262         }
1263   
1264         stinf = (stack_info_t *)&frm->data.p;
1265
1266         stack->d_stid = stinf->id;
1267         stack->b_num = stinf->childcnt;
1268
1269         for (i=0; i<=stinf->childcnt; i++)
1270                 stack->b_stids[i] = stinf->child[i];
1271   
1272         switch(stinf->pid.protocol[0] & ~ISDN_PID_FEATURE_MASK) {
1273         case ISDN_PID_L0_TE_S0:
1274                 stack->nt=0;
1275                 break;
1276         case ISDN_PID_L0_NT_S0:
1277                 cb_log(8, port, "NT Stack\n");
1278
1279                 stack->nt=1;
1280                 break;
1281         case ISDN_PID_L0_TE_E1:
1282                 cb_log(8, port, "TE S2M Stack\n");
1283                 stack->nt=0;
1284                 stack->pri=1;
1285                 break;
1286         case ISDN_PID_L0_NT_E1:
1287                 cb_log(8, port, "TE S2M Stack\n");
1288                 stack->nt=1;
1289                 stack->pri=1;
1290                 
1291                 break;
1292         default:
1293                 cb_log(0, port, "this is a unknown port type 0x%08x\n", stinf->pid.protocol[0]);
1294
1295         }
1296
1297         if (!stack->nt) {
1298                 if (stinf->pid.protocol[2] & ISDN_PID_L2_DF_PTP ) { 
1299                         stack->ptp = 1;
1300                 } else {
1301                         stack->ptp = 0;
1302                 }
1303         }
1304         
1305         {
1306                 int ret;
1307                 int nt=stack->nt;
1308
1309                 cb_log(8, port, "Init. Stack.\n");
1310                 
1311                 memset(&li, 0, sizeof(li));
1312                 {
1313                         int l = sizeof(li.name);
1314                         strncpy(li.name,nt?"net l2":"user l4", l);
1315                         li.name[l-1] = 0;
1316                 }
1317                 li.object_id = -1;
1318                 li.extentions = 0;
1319                 li.pid.protocol[nt?2:4] = nt?ISDN_PID_L2_LAPD_NET:ISDN_PID_L4_CAPI20;
1320                 li.pid.layermask = ISDN_LAYER((nt?2:4));
1321                 li.st = stack->d_stid;
1322                 
1323                 
1324                 ret = mISDN_new_layer(midev, &li);
1325                 if (ret) {
1326                         cb_log(0, port, "%s: Cannot add layer %d to this port.\n", __FUNCTION__, nt?2:4);
1327                         return(NULL);
1328                 }
1329                 
1330                 
1331                 stack->upper_id = li.id;
1332                 ret = mISDN_register_layer(midev, stack->d_stid, stack->upper_id);
1333                 if (ret)
1334                 {
1335                         cb_log(0,port,"Cannot register layer %d of this port.\n", nt?2:4);
1336                         return(NULL);
1337                 }
1338                 
1339                 stack->lower_id = mISDN_get_layerid(midev, stack->d_stid, nt?1:3); 
1340                 if (stack->lower_id < 0) {
1341                         cb_log(0, port, "%s: Cannot get layer(%d) id of this port.\n", __FUNCTION__, nt?1:3);
1342                         return(NULL);
1343                 }
1344                 
1345                 stack->upper_id = mISDN_get_layerid(midev, stack->d_stid, nt?2:4);
1346                 if (stack->upper_id < 0) {
1347                         cb_log(0, port, "%s: Cannot get layer(%d) id of this port.\n", __FUNCTION__, 2);
1348                         return(NULL);
1349                 }
1350                 
1351                 cb_log(8, port, "NT Stacks upper_id %x\n",stack->upper_id);
1352                 
1353                 
1354                 /* create nst (nt-mode only) */
1355                 if (nt) {
1356                         
1357                         memset(&stack->nst, 0, sizeof(net_stack_t));
1358                         memset(&stack->mgr, 0, sizeof(manager_t));
1359     
1360                         stack->mgr.nst = &stack->nst;
1361                         stack->nst.manager = &stack->mgr;
1362     
1363                         stack->nst.l3_manager = handle_event_nt;
1364                         stack->nst.device = midev;
1365                         stack->nst.cardnr = port;
1366                         stack->nst.d_stid = stack->d_stid;
1367     
1368                         stack->nst.feature = FEATURE_NET_HOLD;
1369                         if (stack->ptp)
1370                                 stack->nst.feature |= FEATURE_NET_PTP;
1371                         if (stack->pri)
1372                                 stack->nst.feature |= FEATURE_NET_CRLEN2 | FEATURE_NET_EXTCID;
1373                         
1374                         stack->nst.l1_id = stack->lower_id;
1375                         stack->nst.l2_id = stack->upper_id;
1376                         
1377                         msg_queue_init(&stack->nst.down_queue);
1378                         
1379                         Isdnl2Init(&stack->nst);
1380                         Isdnl3Init(&stack->nst);
1381                         
1382                 } 
1383                 
1384                 if (!stack->nt) {
1385                         /*assume L1 is up, we'll get DEACTIVATES soon, for non
1386                          * up L1s*/
1387                         stack->l1link=0;
1388                 }
1389                 stack->l1link=0;
1390                 stack->l2link=0;
1391 #if 0   
1392                 if (!stack->nt) {
1393                         misdn_lib_get_short_status(stack);
1394                 } else {
1395                         misdn_lib_get_l1_up(stack);
1396                         if (!stack->ptp) misdn_lib_get_l1_up(stack);
1397                         misdn_lib_get_l2_up(stack);
1398                 }
1399 #endif
1400
1401                 misdn_lib_get_short_status(stack);
1402                 misdn_lib_get_l1_up(stack);
1403                 misdn_lib_get_l2_up(stack); 
1404                 
1405         }
1406
1407         cb_log(8,0,"stack_init: port:%d lowerId:%x  upperId:%x\n",stack->port,stack->lower_id, stack->upper_id);
1408         
1409         return stack;
1410 }
1411
1412
1413 static void stack_destroy(struct misdn_stack *stack)
1414 {
1415         char buf[1024];
1416         if (!stack) return;
1417
1418         if (stack->nt) {
1419                 cleanup_Isdnl2(&stack->nst);
1420                 cleanup_Isdnl3(&stack->nst);
1421         }
1422   
1423         if (stack->lower_id) 
1424                 mISDN_write_frame(stack->midev, buf, stack->lower_id, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
1425
1426         if (stack->upper_id) 
1427                 mISDN_write_frame(stack->midev, buf, stack->upper_id, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
1428 }
1429
1430
1431 static struct misdn_stack * find_stack_by_addr(int  addr)
1432 {
1433         struct misdn_stack *stack;
1434         
1435         for (stack=glob_mgr->stack_list;
1436              stack;
1437              stack=stack->next) {
1438                 if ( (stack->upper_id&STACK_ID_MASK) == (addr&STACK_ID_MASK)) return stack;
1439
1440         }
1441   
1442         return NULL;
1443 }
1444
1445
1446 static struct misdn_stack * find_stack_by_port(int port)
1447 {
1448         struct misdn_stack *stack;
1449   
1450         for (stack=glob_mgr->stack_list;
1451              stack;
1452              stack=stack->next) 
1453                 if (stack->port == port) return stack;
1454   
1455         return NULL;
1456 }
1457
1458 static struct misdn_stack * find_stack_by_mgr(manager_t* mgr_nt)
1459 {
1460         struct misdn_stack *stack;
1461   
1462         for (stack=glob_mgr->stack_list;
1463              stack;
1464              stack=stack->next) 
1465                 if ( &stack->mgr == mgr_nt) return stack;
1466   
1467         return NULL;
1468 }
1469
1470 static struct misdn_bchannel *find_bc_by_masked_l3id(struct misdn_stack *stack, unsigned long l3id, unsigned long mask)
1471 {
1472         int i;
1473         for (i=0; i<=stack->b_num; i++) {
1474                 if ( (stack->bc[i].l3_id & mask)  ==  (l3id & mask)) return &stack->bc[i] ;
1475         }
1476         return stack_holder_find(stack,l3id);
1477 }
1478
1479
1480 struct misdn_bchannel *find_bc_by_l3id(struct misdn_stack *stack, unsigned long l3id)
1481 {
1482         int i;
1483         for (i=0; i<=stack->b_num; i++) {
1484                 if (stack->bc[i].l3_id == l3id) return &stack->bc[i] ;
1485         }
1486         return stack_holder_find(stack,l3id);
1487 }
1488
1489 static struct misdn_bchannel *find_bc_holded(struct misdn_stack *stack)
1490 {
1491         int i;
1492         for (i=0; i<=stack->b_num; i++) {
1493                 if (stack->bc[i].holded ) return &stack->bc[i] ;
1494         }
1495         return NULL;
1496 }
1497
1498
1499 static struct misdn_bchannel *find_bc_by_addr(unsigned long addr)
1500 {
1501         struct misdn_stack* stack;
1502         int i;
1503
1504         for (stack=glob_mgr->stack_list;
1505              stack;
1506              stack=stack->next) {
1507                 for (i=0; i<=stack->b_num; i++) {
1508                         if ( (stack->bc[i].addr&STACK_ID_MASK)==(addr&STACK_ID_MASK) ||  stack->bc[i].layer_id== addr ) {
1509                                 return &stack->bc[i];
1510                         }
1511                 }
1512         }
1513         
1514         return NULL;
1515 }
1516
1517 struct misdn_bchannel *find_bc_by_confid(unsigned long confid)
1518 {
1519         struct misdn_stack* stack;
1520         int i;
1521         
1522         for (stack=glob_mgr->stack_list;
1523              stack;
1524              stack=stack->next) {
1525                 for (i=0; i<=stack->b_num; i++) {
1526                         if ( stack->bc[i].conf_id==confid ) {
1527                                 return &stack->bc[i];
1528                         }
1529                 }
1530         }
1531         return NULL;
1532 }
1533
1534
1535 static struct misdn_bchannel *find_bc_by_channel(int port, int channel)
1536 {
1537         struct misdn_stack* stack=find_stack_by_port(port);
1538         int i;
1539
1540         if (!stack) return NULL;        
1541         
1542         for (i=0; i<=stack->b_num; i++) {
1543                 if ( stack->bc[i].channel== channel ) {
1544                         return &stack->bc[i];
1545                 }
1546         }
1547                 
1548         return NULL;
1549 }
1550
1551
1552
1553
1554
1555 static int handle_event ( struct misdn_bchannel *bc, enum event_e event, iframe_t *frm)
1556 {
1557         struct misdn_stack *stack=get_stack_by_bc(bc);
1558         
1559         if (!stack->nt) {
1560                 
1561                 switch (event) {
1562
1563                 case EVENT_CONNECT_ACKNOWLEDGE:
1564                         setup_bc(bc);
1565
1566                         if ( *bc->crypt_key ) {
1567                                 cb_log(4, stack->port, "ENABLING BLOWFISH channel:%d oad%d:%s dad%d:%s\n", bc->channel, bc->onumplan,bc->oad, bc->dnumplan,bc->dad);
1568                                 manager_ph_control_block(bc,  BF_ENABLE_KEY, bc->crypt_key, strlen(bc->crypt_key) );
1569                         }
1570
1571                         if (misdn_cap_is_speech(bc->capability)) {
1572                                 if (  !bc->nodsp) manager_ph_control(bc,  DTMF_TONE_START, 0);
1573                                 manager_ec_enable(bc);
1574
1575                                 if ( bc->txgain != 0 ) {
1576                                         cb_log(4, stack->port, "--> Changing txgain to %d\n", bc->txgain);
1577                                         manager_ph_control(bc, VOL_CHANGE_TX, bc->txgain);
1578                                 }
1579                                 if ( bc->rxgain != 0 ) {
1580                                         cb_log(4, stack->port, "--> Changing rxgain to %d\n", bc->rxgain);
1581                                         manager_ph_control(bc, VOL_CHANGE_RX, bc->rxgain);
1582                                 }
1583                         }
1584
1585                         break;
1586                 case EVENT_CONNECT:
1587
1588                         if ( *bc->crypt_key ) {
1589                                 cb_log(4, stack->port, "ENABLING BLOWFISH channel:%d oad%d:%s dad%d:%s\n", bc->channel, bc->onumplan,bc->oad, bc->dnumplan,bc->dad);
1590                                 manager_ph_control_block(bc,  BF_ENABLE_KEY, bc->crypt_key, strlen(bc->crypt_key) );
1591                         }
1592                 case EVENT_ALERTING:
1593                 case EVENT_PROGRESS:
1594                 case EVENT_PROCEEDING:
1595                 case EVENT_SETUP_ACKNOWLEDGE:
1596                 case EVENT_SETUP:
1597                 {
1598                         if (bc->channel == 0xff || bc->channel<=0)
1599                                 bc->channel=0;
1600
1601                         if (find_free_chan_in_stack(stack, bc, bc->channel, 0)<0){
1602                                 if (!stack->pri && !stack->ptp)  {
1603                                         bc->cw=1;
1604                                         break;
1605                                 }
1606
1607                                 if (!bc->channel)
1608                                         cb_log(0, stack->port, "Any Channel Requested, but we have no more!!\n");
1609                                 else 
1610                                         cb_log(0, stack->port, "Requested Channel Already in Use releasing this call with cause 34!!!!\n");
1611
1612                                 /* when the channel is already in use, we can't
1613                                  * simply clear it, we need to make sure that 
1614                                  * it will still be marked as in_use in the 
1615                                  * available channels list.*/
1616                                 bc->channel=0;
1617
1618                                 misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
1619                                 return -1;
1620                         }
1621                 }
1622
1623                 setup_bc(bc);
1624                 break;
1625
1626                 case EVENT_RELEASE_COMPLETE:
1627                 case EVENT_RELEASE:
1628                         break;
1629                 default:
1630                         break;
1631                 }
1632         } else {    /** NT MODE **/
1633                 
1634         }
1635         return 0;
1636 }
1637
1638 static int handle_cr ( struct misdn_stack *stack, iframe_t *frm)
1639 {
1640         struct misdn_bchannel *bc;
1641
1642         if (!stack) return -1;
1643   
1644         switch (frm->prim) {
1645         case CC_NEW_CR|INDICATION:
1646                 cb_log(7, stack->port, " --> lib: NEW_CR Ind with l3id:%x on this port.\n",frm->dinfo);
1647
1648                 bc = misdn_lib_get_free_bc(stack->port, 0, 1, 0);
1649                 if (!bc) {
1650                         cb_log(0, stack->port, " --> !! lib: No free channel!\n");
1651                         return -1;
1652                 }
1653   
1654                 cb_log(7, stack->port, " --> new_process: New L3Id: %x\n",frm->dinfo);
1655                 bc->l3_id=frm->dinfo;
1656                 return 1;
1657         case CC_NEW_CR|CONFIRM:
1658                 return 1;
1659         case CC_NEW_CR|REQUEST:
1660                 return 1;
1661         case CC_RELEASE_CR|REQUEST:
1662                 return 1;
1663         case CC_RELEASE_CR|CONFIRM:
1664                 break;
1665         case CC_RELEASE_CR|INDICATION:
1666                 cb_log(4, stack->port, " --> lib: RELEASE_CR Ind with l3id:%x\n",frm->dinfo);
1667                 {
1668                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, frm->dinfo);
1669                         struct misdn_bchannel dummybc;
1670       
1671                         if (!bc) {
1672                                 cb_log(4, stack->port, " --> Didn't find BC so temporarily creating dummy BC (l3id:%x) on this port.\n", frm->dinfo);
1673                                 misdn_make_dummy(&dummybc, stack->port, frm->dinfo, stack->nt, 0);
1674                                 
1675                                 bc=&dummybc; 
1676                         }
1677       
1678                         if (bc) {
1679                                 int channel = bc->channel;
1680                                 cb_log(4, stack->port, " --> lib: CLEANING UP l3id: %x\n",frm->dinfo);
1681
1682                                 /*bc->pid = 0;*/
1683                                 bc->need_disconnect=0;
1684                                 bc->need_release=0;
1685                                 bc->need_release_complete=0;
1686
1687                                 cb_event(EVENT_CLEANUP, bc, glob_mgr->user_data);
1688
1689                                 empty_bc(bc);
1690                                 clean_up_bc(bc);
1691
1692                                 if (channel>0)
1693                                         empty_chan_in_stack(stack,channel);
1694                                 bc->in_use=0;
1695
1696                                 dump_chan_list(stack);
1697
1698                                 if (bc->stack_holder) {
1699                                         cb_log(4,stack->port, "REMOVING Holder\n");
1700                                         stack_holder_remove( stack, bc);
1701                                         free(bc);
1702                                 }
1703                         }
1704                         else {
1705                                 if (stack->nt) 
1706                                         cb_log(4, stack->port, "BC with dinfo: %x  not found.. (prim was %x and addr %x)\n",frm->dinfo, frm->prim, frm->addr);
1707                         }
1708       
1709                         return 1;
1710                 }
1711                 break;
1712         }
1713   
1714         return 0;
1715 }
1716
1717
1718 /* Empties bc if it's reserved (no SETUP out yet) */
1719 void misdn_lib_release(struct misdn_bchannel *bc)
1720 {
1721         struct misdn_stack *stack=get_stack_by_bc(bc);
1722
1723         if (!stack) {
1724                 cb_log(1,0,"misdn_release: No Stack found\n");
1725                 return;
1726         }
1727         
1728         if (bc->channel>0) 
1729                 empty_chan_in_stack(stack,bc->channel);
1730         
1731         empty_bc(bc);
1732         clean_up_bc(bc);
1733         bc->in_use=0;
1734 }
1735
1736
1737
1738
1739 int misdn_lib_get_port_up (int port) 
1740 { /* Pull Up L1 */ 
1741         struct misdn_stack *stack;
1742         
1743         for (stack=glob_mgr->stack_list;
1744              stack;
1745              stack=stack->next) {
1746                 
1747                 if (stack->port == port) {
1748
1749                         if (!stack->l1link)
1750                                 misdn_lib_get_l1_up(stack);
1751                         if (!stack->l2link)
1752                                 misdn_lib_get_l2_up(stack);
1753                         
1754                         return 0;
1755                 }
1756         }
1757         return 0;
1758 }
1759
1760
1761 int misdn_lib_get_port_down (int port) 
1762 { /* Pull Down L1 */ 
1763         struct misdn_stack *stack;
1764         for (stack=glob_mgr->stack_list;
1765              stack;
1766              stack=stack->next) {
1767                 if (stack->port == port) {
1768                                 if (stack->l2link)
1769                                         misdn_lib_get_l2_down(stack);
1770                                 misdn_lib_get_l1_down(stack);
1771                         return 0;
1772                 }
1773         }
1774         return 0;
1775 }
1776
1777 int misdn_lib_port_up(int port, int check)
1778 {
1779         struct misdn_stack *stack;
1780
1781
1782         for (stack=glob_mgr->stack_list;
1783              stack;
1784              stack=stack->next) {
1785                 
1786                 if (stack->port == port) {
1787
1788                         if (stack->blocked) {
1789                                 cb_log(0,port, "Port Blocked:%d L2:%d L1:%d\n", stack->blocked, stack->l2link, stack->l1link);
1790                                 return -1;
1791                         }
1792
1793                         if (stack->ptp ) {
1794
1795                                 if (stack->l1link && stack->l2link) {
1796                                         return 1;
1797                                 } else {
1798                                         cb_log(1,port, "Port Down L2:%d L1:%d\n",
1799                                                 stack->l2link, stack->l1link);
1800                                         return 0;
1801                                 }
1802                         } else {
1803                                 if ( !check || stack->l1link )
1804                                         return 1;
1805                                 else {
1806                                         cb_log(1,port, "Port down PMP\n");
1807                                         return 0;
1808                                 }
1809                         }
1810                 }
1811         }
1812   
1813         return -1;
1814 }
1815
1816
1817 int release_cr(struct misdn_stack *stack, mISDNuser_head_t *hh)
1818 {
1819         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1820         struct misdn_bchannel dummybc;
1821         iframe_t frm; /* fake te frm to remove callref from global callreflist */
1822         frm.dinfo = hh->dinfo;
1823
1824         frm.addr=stack->upper_id | FLG_MSG_DOWN;
1825
1826         frm.prim = CC_RELEASE_CR|INDICATION;
1827         cb_log(4, stack->port, " --> CC_RELEASE_CR: Faking Release_cr for %x l3id:%x\n",frm.addr, frm.dinfo);
1828         /** removing procid **/
1829         if (!bc) {
1830                 cb_log(4, stack->port, " --> Didn't find BC so temporarily creating dummy BC (l3id:%x) on this port.\n", hh->dinfo);
1831                 misdn_make_dummy(&dummybc, stack->port, hh->dinfo, stack->nt, 0);
1832                 bc=&dummybc; 
1833         }
1834
1835         if (bc) {
1836                 if ( (bc->l3_id & 0xff00) == 0xff00) {
1837                         cb_log(4, stack->port, " --> Removing Process Id:%x on this port.\n", bc->l3_id&0xff);
1838                         stack->procids[bc->l3_id&0xff] = 0 ;
1839                 }
1840         }
1841         else cb_log(0, stack->port, "Couldn't find BC so I couldn't remove the Process!!!! this is a bad port.\n");
1842
1843         if (handle_cr(stack, &frm)<0) {
1844         }
1845
1846         return 0 ;
1847 }
1848
1849 static int
1850 handle_event_nt(void *dat, void *arg)
1851 {
1852         manager_t *mgr = (manager_t *)dat;
1853         msg_t *msg = (msg_t *)arg;
1854         mISDNuser_head_t *hh;
1855         int reject=0;
1856
1857         struct misdn_stack *stack=find_stack_by_mgr(mgr);
1858         int port;
1859
1860         if (!msg || !mgr)
1861                 return(-EINVAL);
1862
1863         hh=(mISDNuser_head_t*)msg->data;
1864         port=stack->port;
1865         
1866         cb_log(5, stack->port, " --> lib: prim %x dinfo %x\n",hh->prim, hh->dinfo);
1867         {
1868                 switch(hh->prim){
1869                 case CC_RETRIEVE|INDICATION:
1870                 {
1871                         struct misdn_bchannel *bc;
1872                         struct misdn_bchannel *hold_bc;
1873
1874                         iframe_t frm; /* fake te frm to add callref to global callreflist */
1875                         frm.dinfo = hh->dinfo;
1876
1877                         frm.addr=stack->upper_id | FLG_MSG_DOWN;
1878
1879                         frm.prim = CC_NEW_CR|INDICATION;
1880                         
1881                         if (handle_cr( stack, &frm)< 0) {
1882                                 msg_t *dmsg;
1883                                 cb_log(4, stack->port, "Patch from MEIDANIS:Sending RELEASE_COMPLETE %x (No free Chan for you..)\n", hh->dinfo);
1884                                 dmsg = create_l3msg(CC_RELEASE_COMPLETE | REQUEST,MT_RELEASE_COMPLETE, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1885                                 stack->nst.manager_l3(&stack->nst, dmsg);
1886                                 free_msg(msg);
1887                                 return 0;
1888                         }
1889                         
1890                         bc = find_bc_by_l3id(stack, hh->dinfo);
1891                         hold_bc = stack_holder_find(stack, bc->l3_id);
1892                         cb_log(4, stack->port, "bc_l3id:%x holded_bc_l3id:%x\n",bc->l3_id, hold_bc->l3_id);
1893
1894                         if (hold_bc) {
1895                                 cb_log(4, stack->port, "REMOVING Holder\n");
1896
1897                                 /*swap the backup to our new channel back*/
1898                                 stack_holder_remove(stack, hold_bc);
1899                                 memcpy(bc, hold_bc, sizeof(*bc));
1900                                 free(hold_bc);
1901
1902                                 bc->holded=0;
1903                                 bc->b_stid=0;
1904                         }
1905                         
1906                 }
1907                         
1908                         break;
1909                         
1910                 case CC_SETUP|CONFIRM:
1911                 {
1912                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1913                         int l3id = *((int *)(((u_char *)msg->data)+ mISDNUSER_HEAD_SIZE));
1914                         cb_log(4, stack->port, " --> lib: Event_ind:SETUP CONFIRM [NT] : new L3ID  is %x\n",l3id );
1915         
1916                         if (!bc) { cb_log(4, stack->port, "Bc Not found (after SETUP CONFIRM)\n"); return 0; }
1917                         cb_log (2,bc->port,"I IND :CC_SETUP|CONFIRM: old l3id:%x new l3id:%x\n", bc->l3_id, l3id);
1918                         bc->l3_id=l3id;
1919                         cb_event(EVENT_NEW_L3ID, bc, glob_mgr->user_data);
1920                 }
1921                 free_msg(msg);
1922                 return 0;
1923       
1924                 case CC_SETUP|INDICATION:
1925                 {
1926                         struct misdn_bchannel* bc=misdn_lib_get_free_bc(stack->port, 0, 1, 0);
1927                         if (!bc) 
1928                         ERR_NO_CHANNEL:
1929                         {
1930                                 msg_t *dmsg;
1931                                 cb_log(4, stack->port, "Patch from MEIDANIS:Sending RELEASE_COMPLETE %x (No free Chan for you..)\n", hh->dinfo);
1932                                 dmsg = create_l3msg(CC_RELEASE_COMPLETE | REQUEST,MT_RELEASE_COMPLETE, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1933                                 stack->nst.manager_l3(&stack->nst, dmsg);
1934                                 free_msg(msg);
1935                                 return 0;
1936                         }
1937   
1938                         cb_log(4, stack->port, " --> new_process: New L3Id: %x\n",hh->dinfo);
1939                         bc->l3_id=hh->dinfo;
1940                 }
1941                 break;
1942
1943                 case CC_CONNECT_ACKNOWLEDGE|INDICATION:
1944                 break;
1945                 
1946                 case CC_ALERTING|INDICATION:
1947                 case CC_PROCEEDING|INDICATION:
1948                 case CC_SETUP_ACKNOWLEDGE|INDICATION:
1949                         if(!stack->ptp) break;  
1950                 case CC_CONNECT|INDICATION:
1951                 break;
1952                 case CC_DISCONNECT|INDICATION:
1953                 {
1954                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1955                         if (!bc) {
1956                                 bc=find_bc_by_masked_l3id(stack, hh->dinfo, 0xffff0000);
1957                                 if (bc) { 
1958                                         int myprocid=bc->l3_id&0x0000ffff;
1959                                         hh->dinfo=(hh->dinfo&0xffff0000)|myprocid;
1960                                         cb_log(3,stack->port,"Reject dinfo: %x cause:%d\n",hh->dinfo,bc->cause);
1961                                         reject=1;               
1962                                 }
1963                         }
1964                 }
1965                 break;
1966                 
1967                 case CC_FACILITY|INDICATION:
1968                 {
1969                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1970                         if (!bc) {
1971                                 bc=find_bc_by_masked_l3id(stack, hh->dinfo, 0xffff0000);
1972                                 if (bc) { 
1973                                         int myprocid=bc->l3_id&0x0000ffff;
1974                                         hh->dinfo=(hh->dinfo&0xffff0000)|myprocid;
1975                                         cb_log(4,bc->port,"Repaired reject Bug, new dinfo: %x\n",hh->dinfo);
1976                                 }
1977                         }
1978                 }
1979                 break;
1980                 
1981                 case CC_RELEASE_COMPLETE|INDICATION:
1982                         break;
1983
1984                 case CC_SUSPEND|INDICATION:
1985                 {
1986                         msg_t *dmsg;
1987                         cb_log(4, stack->port, " --> Got Suspend, sending Reject for now\n");
1988                         dmsg = create_l3msg(CC_SUSPEND_REJECT | REQUEST,MT_SUSPEND_REJECT, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1989                         stack->nst.manager_l3(&stack->nst, dmsg);
1990                         free_msg(msg);
1991                         return 0;
1992                 }
1993                 break;
1994                 case CC_RESUME|INDICATION:
1995                         break;
1996
1997                 case CC_RELEASE|CONFIRM:
1998                         {
1999                                 struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
2000
2001                                 if (bc) { 
2002                                         cb_log(1, stack->port, "CC_RELEASE|CONFIRM (l3id:%x), sending RELEASE_COMPLETE\n", hh->dinfo);
2003                                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE);
2004                                 }
2005                         }
2006                         break;
2007                         
2008                 case CC_RELEASE|INDICATION:
2009                         break;
2010
2011                 case CC_RELEASE_CR|INDICATION:
2012                         release_cr(stack, hh);
2013                         free_msg(msg);
2014                         return 0 ;
2015                 break;
2016       
2017                 case CC_NEW_CR|INDICATION:
2018                         /*  Got New CR for bchan, for now I handle this one in */
2019                         /*  connect_ack, Need to be changed */
2020                 {
2021                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
2022                         int l3id = *((int *)(((u_char *)msg->data)+ mISDNUSER_HEAD_SIZE));
2023                         if (!bc) { cb_log(0, stack->port, " --> In NEW_CR: didn't found bc ??\n"); return -1;};
2024                         if (((l3id&0xff00)!=0xff00) && ((bc->l3_id&0xff00)==0xff00)) {
2025                                 cb_log(4, stack->port, " --> Removing Process Id:%x on this port.\n", 0xff&bc->l3_id);
2026                                 stack->procids[bc->l3_id&0xff] = 0 ;
2027                         }
2028                         cb_log(4, stack->port, "lib: Event_ind:CC_NEW_CR : very new L3ID  is %x\n",l3id );
2029         
2030                         bc->l3_id =l3id;
2031                         cb_event(EVENT_NEW_L3ID, bc, glob_mgr->user_data);
2032         
2033                         free_msg(msg);
2034                         return 0;
2035                 }
2036       
2037                 case DL_ESTABLISH | INDICATION:
2038                 case DL_ESTABLISH | CONFIRM:
2039                 {
2040                         cb_log(3, stack->port, "%% GOT L2 Activate Info.\n");
2041                         
2042                         if (stack->ptp && stack->l2link) {
2043                                 cb_log(0, stack->port, "%% GOT L2 Activate Info. but we're activated already.. this l2 is faulty, blocking port\n");
2044                                 cb_event(EVENT_PORT_ALARM, &stack->bc[0], glob_mgr->user_data);
2045                         }
2046
2047                         if (stack->ptp && !stack->restart_sent) {
2048                                 /* make sure we restart the interface of the 
2049                                  * other side */
2050                                 stack->restart_sent=1;
2051                                 misdn_lib_send_restart(stack->port, -1);
2052
2053                         }
2054                 
2055                         /* when we get the L2 UP, the L1 is UP definitely too*/
2056                         stack->l2link = 1;
2057                         stack->l2upcnt=0;
2058                         
2059                         free_msg(msg);
2060                         return 0;
2061                 }
2062                 break;
2063
2064
2065                 case DL_RELEASE | INDICATION:
2066                 case DL_RELEASE | CONFIRM:
2067                 {
2068                         if (stack->ptp) {
2069                                 cb_log(3 , stack->port, "%% GOT L2 DeActivate Info.\n");
2070
2071                                 if (stack->l2upcnt>3) {
2072                                         cb_log(0 , stack->port, "!!! Could not Get the L2 up after 3 Attempts!!!\n");
2073                                 }  else {
2074 #if 0
2075                                         if (stack->nt) misdn_lib_reinit_nt_stack(stack->port);
2076 #endif
2077                                         if (stack->l1link) {
2078                                                 misdn_lib_get_l2_up(stack);
2079                                                 stack->l2upcnt++;
2080                                         }
2081                                 }
2082                                 
2083                         } else 
2084                                 cb_log(3, stack->port, "%% GOT L2 DeActivate Info.\n");
2085                         
2086                         stack->l2link = 0;
2087                         free_msg(msg);
2088                         return 0;
2089                 }
2090                 break;
2091                 }
2092         }
2093         
2094         {
2095                 /*  Parse Events and fire_up to App. */
2096                 struct misdn_bchannel *bc;
2097                 struct misdn_bchannel dummybc;
2098                 
2099                 enum event_e event = isdn_msg_get_event(msgs_g, msg, 1);
2100     
2101                 bc=find_bc_by_l3id(stack, hh->dinfo);
2102     
2103                 if (!bc) {
2104                         cb_log(4, stack->port, " --> Didn't find BC so temporarily creating dummy BC (l3id:%x).\n", hh->dinfo);
2105                         misdn_make_dummy(&dummybc, stack->port,  hh->dinfo, stack->nt, 0);
2106                         bc=&dummybc; 
2107                 }
2108                 if (bc ) {
2109                         isdn_msg_parse_event(msgs_g,msg,bc, 1);
2110
2111                         switch (event) {
2112                                 case EVENT_SETUP:
2113                                         if (bc->channel<=0 || bc->channel==0xff) 
2114                                                 bc->channel=0;
2115                                 
2116                                         if (find_free_chan_in_stack(stack,bc, bc->channel,0)<0) 
2117                                                 goto ERR_NO_CHANNEL;
2118                                         break;
2119                                 case EVENT_RELEASE:
2120                                 case EVENT_RELEASE_COMPLETE:
2121                                         {
2122                                         int channel=bc->channel;
2123                                         int tmpcause=bc->cause; 
2124                                         empty_bc(bc);
2125                                         bc->cause=tmpcause;
2126                                         clean_up_bc(bc);
2127
2128                                         if (channel>0)
2129                                                 empty_chan_in_stack(stack,channel);
2130                                         bc->in_use=0;
2131                                         }
2132                                         break;
2133
2134                                 default:
2135                                 break;
2136                         }
2137                         
2138                         if(!isdn_get_info(msgs_g,event,1)) {
2139                                 cb_log(4, stack->port, "Unknown Event Ind: prim %x dinfo %x\n",hh->prim, hh->dinfo);
2140                         } else {
2141                                 if (reject) {
2142                                         switch(bc->cause){
2143                                                 case AST_CAUSE_USER_BUSY:
2144                                                         cb_log(1, stack->port, "Siemens Busy reject..\n");
2145
2146                                                         break;
2147                                                 default:
2148                                                         break;
2149                                         }
2150                                 }
2151                                 cb_event(event, bc, glob_mgr->user_data);
2152                         }
2153                 } else {
2154                         cb_log(4, stack->port, "No BC found with l3id: prim %x dinfo %x\n",hh->prim, hh->dinfo);
2155                 }
2156
2157                 free_msg(msg);
2158         }
2159
2160
2161         return 0;
2162 }
2163
2164
2165 static int handle_timers(msg_t* msg)
2166 {
2167         iframe_t *frm= (iframe_t*)msg->data;
2168         struct misdn_stack *stack; 
2169   
2170         /* Timer Stuff */
2171         switch (frm->prim) {
2172         case MGR_INITTIMER | CONFIRM:
2173         case MGR_ADDTIMER | CONFIRM:
2174         case MGR_DELTIMER | CONFIRM:
2175         case MGR_REMOVETIMER | CONFIRM:
2176                 free_msg(msg);
2177                 return(1);
2178         }
2179   
2180   
2181   
2182         if (frm->prim==(MGR_TIMER | INDICATION) ) {
2183                 for (stack = glob_mgr->stack_list;
2184                      stack;
2185                      stack = stack->next) {
2186                         itimer_t *it;
2187       
2188                         if (!stack->nt) continue;
2189       
2190                         it = stack->nst.tlist;
2191                         /* find timer */
2192                         for(it=stack->nst.tlist;
2193                             it;
2194                             it=it->next) {
2195                                 if (it->id == (int)frm->addr)
2196                                         break;
2197                         }
2198                         if (it) {
2199                                 int ret;
2200                                 ret = mISDN_write_frame(stack->midev, msg->data, frm->addr,
2201                                                         MGR_TIMER | RESPONSE, 0, 0, NULL, TIMEOUT_1SEC);
2202                                 test_and_clear_bit(FLG_TIMER_RUNING, (long unsigned int *)&it->Flags);
2203                                 ret = it->function(it->data);
2204                                 free_msg(msg);
2205                                 return 1;
2206                         }
2207                 }
2208     
2209                 cb_log(0, 0, "Timer Msg without Timer ??\n");
2210                 free_msg(msg);
2211                 return 1;
2212         }
2213   
2214         return 0;
2215 }
2216
2217
2218
2219 void misdn_lib_tone_generator_start(struct misdn_bchannel *bc)
2220 {
2221         bc->generate_tone=1;
2222 }
2223
2224 void misdn_lib_tone_generator_stop(struct misdn_bchannel *bc)
2225 {
2226         bc->generate_tone=0;
2227 }
2228
2229
2230 static int do_tone(struct misdn_bchannel *bc, int len)
2231 {
2232         bc->tone_cnt=len;
2233         
2234         if (bc->generate_tone) {
2235                 cb_event(EVENT_TONE_GENERATE, bc, glob_mgr->user_data);
2236                 
2237                 if ( !bc->nojitter ) {
2238                         misdn_tx_jitter(bc,len);
2239                 }
2240                 
2241                 return 1;
2242         }
2243         
2244         return 0;
2245 }
2246
2247
2248 #ifdef MISDN_SAVE_DATA
2249 static void misdn_save_data(int id, char *p1, int l1, char *p2, int l2) 
2250 {
2251         char n1[32],n2[32];
2252         FILE *rx, *tx;
2253
2254         sprintf(n1,"/tmp/misdn-rx-%d.raw",id);
2255         sprintf(n2,"/tmp/misdn-tx-%d.raw",id);
2256
2257         rx = fopen(n1,"a+"); 
2258         tx = fopen(n2,"a+");
2259
2260         if (!rx || !tx) {
2261                 cb_log(0,0,"Couldn't open files: %s\n",strerror(errno));
2262                 return ;
2263         }
2264         
2265         fwrite(p1,1,l1,rx);
2266         fwrite(p2,1,l2,tx);
2267         
2268         fclose(rx);
2269         fclose(tx);
2270
2271 }
2272 #endif
2273
2274 void misdn_tx_jitter(struct misdn_bchannel *bc, int len)
2275 {
2276         char buf[4096 + mISDN_HEADER_LEN];
2277         char *data=&buf[mISDN_HEADER_LEN];
2278         iframe_t *txfrm= (iframe_t*)buf;
2279         int jlen, r;
2280         
2281         jlen=cb_jb_empty(bc,data,len);
2282         
2283         if (jlen) {
2284 #ifdef MISDN_SAVE_DATA
2285                 misdn_save_data((bc->port*100+bc->channel), data, jlen, bc->bframe, bc->bframe_len);
2286 #endif
2287                 flip_buf_bits( data, jlen);
2288                 
2289                 if (jlen < len) {
2290                         cb_log(7,bc->port,"Jitterbuffer Underrun.\n");
2291                 }
2292                 
2293                 txfrm->prim = DL_DATA|REQUEST;
2294                 
2295                 txfrm->dinfo = 0;
2296                 
2297                 txfrm->addr = bc->addr|FLG_MSG_DOWN; /*  | IF_DOWN; */
2298                 
2299                 txfrm->len =jlen;
2300                 cb_log(9, bc->port, "Transmitting %d samples 2 misdn\n", txfrm->len);
2301
2302                 r=mISDN_write( glob_mgr->midev, buf, txfrm->len + mISDN_HEADER_LEN, 8000 );
2303         } else {
2304 #define MISDN_GEN_SILENCE
2305 #ifdef MISDN_GEN_SILENCE
2306                 int cnt=len/TONE_SILENCE_SIZE;
2307                 int rest=len%TONE_SILENCE_SIZE;
2308                 int i;
2309
2310                 for (i=0; i<cnt; i++) {
2311                         memcpy(data, tone_silence_flip, TONE_SILENCE_SIZE );
2312                         data +=TONE_SILENCE_SIZE;
2313                 }
2314
2315                 if (rest) {
2316                         memcpy(data, tone_silence_flip, rest);
2317                 }
2318
2319                 txfrm->prim = DL_DATA|REQUEST;
2320
2321                 txfrm->dinfo = 0;
2322
2323                 txfrm->addr = bc->addr|FLG_MSG_DOWN; /*  | IF_DOWN; */
2324
2325                 txfrm->len =len;
2326                 cb_log(9, bc->port, "Transmitting %d samples 2 misdn\n", txfrm->len);
2327
2328                 r=mISDN_write( glob_mgr->midev, buf, txfrm->len + mISDN_HEADER_LEN, 8000 );
2329 #endif
2330
2331         }
2332 }
2333
2334 static int handle_bchan(msg_t *msg)
2335 {
2336         iframe_t *frm= (iframe_t*)msg->data;
2337         struct misdn_bchannel *bc=find_bc_by_addr(frm->addr);
2338         struct misdn_stack *stack;
2339         
2340         if (!bc) {
2341                 cb_log(1,0,"handle_bchan: BC not found for prim:%x with addr:%x dinfo:%x\n", frm->prim, frm->addr, frm->dinfo);
2342                 return 0 ;
2343         }
2344         
2345         stack = get_stack_by_bc(bc);
2346         
2347         if (!stack) {
2348                 cb_log(0, bc->port,"handle_bchan: STACK not found for prim:%x with addr:%x dinfo:%x\n", frm->prim, frm->addr, frm->dinfo);
2349                 return 0;
2350         }
2351         
2352         switch (frm->prim) {
2353
2354         case MGR_SETSTACK| CONFIRM:
2355                 cb_log(3, stack->port, "BCHAN: MGR_SETSTACK|CONFIRM pid:%d\n",bc->pid);
2356                 break;
2357                 
2358         case MGR_SETSTACK| INDICATION:
2359                 cb_log(3, stack->port, "BCHAN: MGR_SETSTACK|IND pid:%d\n",bc->pid);
2360         break;
2361 #if 0
2362         AGAIN:
2363                 bc->addr = mISDN_get_layerid(stack->midev, bc->b_stid, bc->layer);
2364                 if (!bc->addr) {
2365
2366                         if (errno == EAGAIN) {
2367                                 usleep(1000);
2368                                 goto AGAIN;
2369                         }
2370                         
2371                         cb_log(0,stack->port,"$$$ Get Layer (%d) Id Error: %s\n",bc->layer,strerror(errno));
2372                         
2373                         /* we kill the channel later, when we received some
2374                            data. */
2375                         bc->addr= frm->addr;
2376                 } else if ( bc->addr < 0) {
2377                         cb_log(0, stack->port,"$$$ bc->addr <0 Error:%s\n",strerror(errno));
2378                         bc->addr=0;
2379                 }
2380                 
2381                 cb_log(4, stack->port," --> Got Adr %x\n", bc->addr);
2382
2383                 free_msg(msg);
2384         
2385                 
2386                 switch(bc->bc_state) {
2387                 case BCHAN_SETUP:
2388                         bc_state_change(bc,BCHAN_SETUPED);
2389                 break;
2390
2391                 case BCHAN_CLEAN_REQUEST:
2392                 default:
2393                         cb_log(0, stack->port," --> STATE WASN'T SETUP (but %s) in SETSTACK|IND pid:%d\n",bc_state2str(bc->bc_state), bc->pid);
2394                         clean_up_bc(bc);
2395                 }
2396                 return 1;
2397 #endif
2398
2399         case MGR_DELLAYER| INDICATION:
2400                 cb_log(3, stack->port, "BCHAN: MGR_DELLAYER|IND pid:%d\n",bc->pid);
2401                 break;
2402                 
2403         case MGR_DELLAYER| CONFIRM:
2404                 cb_log(3, stack->port, "BCHAN: MGR_DELLAYER|CNF pid:%d\n",bc->pid);
2405                 
2406                 bc->pid=0;
2407                 bc->addr=0;
2408                 
2409                 free_msg(msg);
2410                 return 1;
2411                 
2412         case PH_ACTIVATE | INDICATION:
2413         case DL_ESTABLISH | INDICATION:
2414                 cb_log(3, stack->port, "BCHAN: ACT Ind pid:%d\n", bc->pid);
2415
2416                 free_msg(msg);
2417                 return 1;    
2418
2419         case PH_ACTIVATE | CONFIRM:
2420         case DL_ESTABLISH | CONFIRM:
2421                 
2422                 cb_log(3, stack->port, "BCHAN: bchan ACT Confirm pid:%d\n",bc->pid);
2423                 free_msg(msg);
2424                 
2425                 return 1;    
2426
2427         case DL_ESTABLISH | REQUEST:
2428                 {
2429                         char buf[128];
2430                         mISDN_write_frame(stack->midev, buf, bc->addr | FLG_MSG_TARGET | FLG_MSG_DOWN,  DL_ESTABLISH | CONFIRM, 0,0, NULL, TIMEOUT_1SEC);
2431                 }
2432                 free_msg(msg);
2433                 return 1;
2434
2435         case DL_RELEASE|REQUEST:
2436                 {
2437                         char buf[128];
2438                         mISDN_write_frame(stack->midev, buf, bc->addr | FLG_MSG_TARGET | FLG_MSG_DOWN,  DL_RELEASE| CONFIRM, 0,0, NULL, TIMEOUT_1SEC);
2439                 }
2440                 free_msg(msg);
2441                 return 1;
2442                 
2443         case PH_DEACTIVATE | INDICATION:
2444         case DL_RELEASE | INDICATION:
2445                 cb_log (3, stack->port, "BCHAN: DeACT Ind pid:%d\n",bc->pid);
2446                 
2447                 free_msg(msg);
2448                 return 1;
2449     
2450         case PH_DEACTIVATE | CONFIRM:
2451         case DL_RELEASE | CONFIRM:
2452                 cb_log(3, stack->port, "BCHAN: DeACT Conf pid:%d\n",bc->pid);
2453                 
2454                 free_msg(msg);
2455                 return 1;
2456     
2457         case PH_CONTROL|INDICATION:
2458         {
2459                 unsigned int *cont = (unsigned int *) &frm->data.p;
2460                 
2461                 cb_log(4, stack->port, "PH_CONTROL: channel:%d oad%d:%s dad%d:%s \n", bc->channel, bc->onumplan,bc->oad, bc->dnumplan,bc->dad);
2462
2463                 if ((*cont & ~DTMF_TONE_MASK) == DTMF_TONE_VAL) {
2464                         int dtmf = *cont & DTMF_TONE_MASK;
2465                         cb_log(4, stack->port, " --> DTMF TONE: %c\n",dtmf);
2466                         bc->dtmf=dtmf;
2467                         cb_event(EVENT_DTMF_TONE, bc, glob_mgr->user_data);
2468         
2469                         free_msg(msg);
2470                         return 1;
2471                 }
2472                 if (*cont == BF_REJECT) {
2473                         cb_log(4, stack->port, " --> BF REJECT\n");
2474                         free_msg(msg);
2475                         return 1;
2476                 }
2477                 if (*cont == BF_ACCEPT) {
2478                         cb_log(4, stack->port, " --> BF ACCEPT\n");
2479                         free_msg(msg);
2480                         return 1;
2481                 }
2482         }
2483         break;
2484
2485         case PH_DATA|REQUEST:
2486         case DL_DATA|REQUEST:
2487                 cb_log(0, stack->port, "DL_DATA REQUEST \n");
2488                 do_tone(bc, 64);
2489                 
2490                 free_msg(msg);
2491                 return 1;
2492         
2493         
2494         case PH_DATA|INDICATION:
2495         case DL_DATA|INDICATION:
2496         {
2497                 bc->bframe = (void*)&frm->data.i;
2498                 bc->bframe_len = frm->len;
2499
2500                 /** Anyway flip the bufbits **/
2501                 if ( misdn_cap_is_speech(bc->capability) ) 
2502                         flip_buf_bits(bc->bframe, bc->bframe_len);
2503         
2504
2505                 if (!bc->bframe_len) {
2506                         cb_log(2, stack->port, "DL_DATA INDICATION bc->addr:%x frm->addr:%x\n", bc->addr, frm->addr);
2507                         free_msg(msg);
2508                         return 1;
2509                 }
2510
2511                 if ( (bc->addr&STACK_ID_MASK) != (frm->addr&STACK_ID_MASK) ) {
2512                         cb_log(2, stack->port, "DL_DATA INDICATION bc->addr:%x frm->addr:%x\n", bc->addr, frm->addr);
2513                         free_msg(msg);
2514                         return 1;
2515                 }
2516                 
2517 #if MISDN_DEBUG
2518                 cb_log(0, stack->port, "DL_DATA INDICATION Len %d\n", frm->len);
2519
2520 #endif
2521                 
2522                 if ( (bc->bc_state == BCHAN_ACTIVATED) && frm->len > 0) {
2523                         int t;
2524
2525 #ifdef MISDN_B_DEBUG
2526                         cb_log(0,bc->port,"do_tone START\n");
2527 #endif
2528                         t=do_tone(bc,frm->len);
2529
2530 #ifdef MISDN_B_DEBUG
2531                         cb_log(0,bc->port,"do_tone STOP (%d)\n",t);
2532 #endif
2533                         if (  !t ) {
2534                                 int i;
2535                                 
2536                                 if ( misdn_cap_is_speech(bc->capability)) {
2537                                         if ( !bc->nojitter ) {
2538 #ifdef MISDN_B_DEBUG
2539                                                 cb_log(0,bc->port,"tx_jitter START\n");
2540 #endif
2541                                                 misdn_tx_jitter(bc,frm->len);
2542 #ifdef MISDN_B_DEBUG
2543                                                 cb_log(0,bc->port,"tx_jitter STOP\n");
2544 #endif
2545                                         }
2546                                 }
2547
2548 #ifdef MISDN_B_DEBUG    
2549                                 cb_log(0,bc->port,"EVENT_B_DATA START\n");
2550 #endif
2551                                 
2552                                 i = cb_event(EVENT_BCHAN_DATA, bc, glob_mgr->user_data);
2553 #ifdef MISDN_B_DEBUG    
2554                                 cb_log(0,bc->port,"EVENT_B_DATA STOP\n");
2555 #endif
2556                                 
2557                                 if (i<0) {
2558                                         cb_log(10,stack->port,"cb_event returned <0\n");
2559                                         /*clean_up_bc(bc);*/
2560                                 }
2561                         }
2562                 }
2563                 free_msg(msg);
2564                 return 1;
2565         }
2566
2567
2568         case PH_CONTROL | CONFIRM:
2569                 cb_log(4, stack->port, "PH_CONTROL|CNF bc->addr:%x\n", frm->addr);
2570                 free_msg(msg);
2571                 return 1;
2572
2573         case PH_DATA | CONFIRM:
2574         case DL_DATA|CONFIRM:
2575 #if MISDN_DEBUG
2576
2577                 cb_log(0, stack->port, "Data confirmed\n");
2578
2579 #endif
2580                 free_msg(msg);
2581                 return 1;
2582         case DL_DATA|RESPONSE:
2583 #if MISDN_DEBUG
2584                 cb_log(0, stack->port, "Data response\n");
2585
2586 #endif
2587                 break;
2588         }
2589   
2590         return 0;
2591 }
2592
2593
2594
2595 static int handle_frm_nt(msg_t *msg)
2596 {
2597         iframe_t *frm= (iframe_t*)msg->data;
2598         struct misdn_stack *stack;
2599         int err=0;
2600
2601         stack=find_stack_by_addr( frm->addr );
2602
2603         
2604   
2605         if (!stack || !stack->nt) {
2606                 return 0;
2607         }
2608
2609         
2610         if ((err=stack->nst.l1_l2(&stack->nst,msg))) {
2611     
2612                 if (nt_err_cnt > 0 ) {
2613                         if (nt_err_cnt < 100) {
2614                                 nt_err_cnt++; 
2615                                 cb_log(0, stack->port, "NT Stack sends us error: %d \n", err);
2616                         } else if (nt_err_cnt < 105){
2617                                 cb_log(0, stack->port, "NT Stack sends us error: %d over 100 times, so I'll stop this message\n", err);
2618                                 nt_err_cnt = - 1; 
2619                         }
2620                 }
2621                 free_msg(msg);
2622                 return 1;
2623                 
2624         }
2625         
2626         return 1;
2627 }
2628
2629
2630 static int handle_frm(msg_t *msg)
2631 {
2632         iframe_t *frm = (iframe_t*) msg->data;
2633         
2634         struct misdn_stack *stack=find_stack_by_addr(frm->addr);
2635
2636         if (!stack || stack->nt) {
2637                 return 0;
2638         }
2639         
2640         cb_log(4,stack?stack->port:0,"handle_frm: frm->addr:%x frm->prim:%x\n",frm->addr,frm->prim);
2641
2642         {
2643                 struct misdn_bchannel dummybc;
2644                 struct misdn_bchannel *bc;
2645                 int ret=handle_cr(stack, frm);
2646
2647                 if (ret<0) {
2648                         cb_log(3,stack?stack->port:0,"handle_frm: handle_cr <0 prim:%x addr:%x\n", frm->prim, frm->addr);
2649
2650
2651                 }
2652
2653                 if(ret) {
2654                         free_msg(msg);
2655                         return 1;
2656                 }
2657     
2658                 bc=find_bc_by_l3id(stack, frm->dinfo);
2659
2660                 if (!bc && (frm->prim==(CC_RESTART|CONFIRM)) ) {
2661                         misdn_make_dummy(&dummybc, stack->port, MISDN_ID_GLOBAL, stack->nt, 0);
2662                         bc=&dummybc;
2663                 }
2664
2665                 if (!bc && (frm->prim==(CC_SETUP|INDICATION)) ) {
2666                         misdn_make_dummy(&dummybc, stack->port, MISDN_ID_GLOBAL, stack->nt, 0);
2667                         dummybc.port=stack->port;
2668                         dummybc.l3_id=frm->dinfo;
2669                         bc=&dummybc;
2670
2671                         misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
2672
2673                         free_msg(msg);
2674                         return 1;
2675                 }
2676
2677     
2678 handle_frm_bc:
2679                 if (bc ) {
2680                         enum event_e event = isdn_msg_get_event(msgs_g, msg, 0);
2681                         enum event_response_e response=RESPONSE_OK;
2682                         int ret;
2683       
2684                         isdn_msg_parse_event(msgs_g,msg,bc, 0);
2685                         
2686                         /** Preprocess some Events **/
2687                         ret = handle_event(bc, event, frm);
2688                         if (ret<0) {
2689                                 cb_log(0,stack->port,"couldn't handle event\n");
2690                                 free_msg(msg);
2691                                 return 1;
2692                         }
2693                         /*  shoot up event to App: */
2694                         cb_log(5, stack->port, "lib Got Prim: Addr %x prim %x dinfo %x\n",frm->addr, frm->prim, frm->dinfo);
2695       
2696                         if(!isdn_get_info(msgs_g,event,0)) 
2697                                 cb_log(0, stack->port, "Unknown Event Ind: Addr:%x prim %x dinfo %x\n",frm->addr, frm->prim, frm->dinfo);
2698                         else
2699                                 response=cb_event(event, bc, glob_mgr->user_data);
2700 #if 1
2701                         if (event == EVENT_SETUP) {
2702                                 switch (response) {
2703                                 case RESPONSE_IGNORE_SETUP_WITHOUT_CLOSE:
2704
2705                                         cb_log(0, stack->port, "TOTALLY IGNORING SETUP\n");                                     
2706                                         
2707                                         break;
2708                                 case RESPONSE_IGNORE_SETUP:
2709                                         /* I think we should send CC_RELEASE_CR, but am not sure*/
2710                                         bc->out_cause = AST_CAUSE_NORMAL_CLEARING;
2711                                 
2712                                 case RESPONSE_RELEASE_SETUP:
2713                                         misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
2714                                         if (bc->channel>0)
2715                                                 empty_chan_in_stack(stack, bc->channel);
2716                                         empty_bc(bc);
2717                                         bc_state_change(bc,BCHAN_CLEANED);
2718                                         bc->in_use=0;
2719
2720                                         cb_log(0, stack->port, "GOT IGNORE SETUP\n");
2721                                         break;
2722                                 case RESPONSE_OK:
2723                                         cb_log(4, stack->port, "GOT SETUP OK\n");
2724
2725                                         
2726                                         break;
2727                                 default:
2728                                         break;
2729                                 }
2730                         }
2731
2732                         if (event == EVENT_RELEASE_COMPLETE) {
2733                                 /* release bchannel only after we've announced the RELEASE_COMPLETE */
2734                                 int channel=bc->channel;
2735                                 int tmpcause=bc->cause; 
2736                                 int tmp_out_cause=bc->out_cause;        
2737                                 empty_bc(bc);
2738                                 bc->cause=tmpcause;
2739                                 bc->out_cause=tmp_out_cause;
2740                                 clean_up_bc(bc);
2741                                 
2742                                 if (tmpcause == AST_CAUSE_REQUESTED_CHAN_UNAVAIL) {
2743                                         cb_log(0,stack->port,"**** Received CAUSE:%d, so not cleaning up channel %d\n", AST_CAUSE_REQUESTED_CHAN_UNAVAIL, channel);
2744                                         cb_log(0,stack->port,"**** This channel is now no longer available,\nplease try to restart it with 'misdn send restart <port> <channel>'\n");
2745                                         set_chan_in_stack(stack, channel);
2746                                         bc->channel=channel;
2747                                         misdn_lib_send_restart(stack->port, channel);
2748                                 } else {
2749                                         if (channel>0)
2750                                                 empty_chan_in_stack(stack, channel);
2751                                 }
2752                                 bc->in_use=0;
2753                         }
2754
2755                         if (event == EVENT_RESTART) {
2756                                 cb_log(0, stack->port, "**** Received RESTART_ACK channel:%d\n", bc->restart_channel);
2757                                 empty_chan_in_stack(stack, bc->restart_channel);
2758                         }
2759
2760                         cb_log(5, stack->port, "Freeing Msg on prim:%x \n",frm->prim);
2761
2762                         
2763                         free_msg(msg);
2764                         return 1;
2765 #endif
2766       
2767                 } else {
2768                         struct misdn_bchannel dummybc;
2769                         if (frm->prim!=(CC_FACILITY|INDICATION))
2770                                 cb_log(0, stack->port, " --> Didn't find BC so temporarily creating dummy BC (l3id:%x) on this port.\n", frm->dinfo);
2771                         else
2772                                 cb_log(5, stack->port, " --> Using Dummy BC for FACILITY\n");
2773
2774                         memset (&dummybc,0,sizeof(dummybc));
2775                         dummybc.port=stack->port;
2776                         dummybc.l3_id=frm->dinfo;
2777                         bc=&dummybc; 
2778                         goto handle_frm_bc;
2779                 }
2780         }
2781
2782         cb_log(4, stack->port, "TE_FRM_HANDLER: Returning 0 on prim:%x \n",frm->prim);
2783         return 0;
2784 }
2785
2786
2787 static int handle_l1(msg_t *msg)
2788 {
2789         iframe_t *frm = (iframe_t*) msg->data;
2790         struct misdn_stack *stack = find_stack_by_addr(frm->addr);
2791         int i ;
2792         
2793         if (!stack) return 0 ;
2794
2795         switch (frm->prim) {
2796         case PH_ACTIVATE | CONFIRM:
2797         case PH_ACTIVATE | INDICATION:
2798                 cb_log (3, stack->port, "L1: PH L1Link Up!\n");
2799                 stack->l1link=1;
2800                 
2801                 if (stack->nt) {
2802                         
2803                         if (stack->nst.l1_l2(&stack->nst, msg))
2804                                 free_msg(msg);
2805
2806                         if (stack->ptp)
2807                                 misdn_lib_get_l2_up(stack);
2808                 } else {
2809                         free_msg(msg);
2810                 }
2811                 
2812                 for (i=0;i<=stack->b_num; i++) {
2813                         if (stack->bc[i].evq != EVENT_NOTHING) {
2814                                 cb_log(4, stack->port, "Firing Queued Event %s because L1 got up\n", isdn_get_info(msgs_g, stack->bc[i].evq, 0));
2815                                 misdn_lib_send_event(&stack->bc[i],stack->bc[i].evq);
2816                                 stack->bc[i].evq=EVENT_NOTHING;
2817                         }
2818                         
2819                 }
2820                 return 1;
2821
2822         case PH_ACTIVATE | REQUEST:
2823                 free_msg(msg);
2824                 cb_log(3,stack->port,"L1: PH_ACTIVATE|REQUEST \n");
2825                 return 1;
2826                 
2827         case PH_DEACTIVATE | REQUEST:
2828                 free_msg(msg);
2829                 cb_log(3,stack->port,"L1: PH_DEACTIVATE|REQUEST \n");
2830                 return 1;
2831                 
2832         case PH_DEACTIVATE | CONFIRM:
2833         case PH_DEACTIVATE | INDICATION:
2834                 cb_log (3, stack->port, "L1: PH L1Link Down! \n");
2835         
2836 #if 0
2837                 for (i=0; i<=stack->b_num; i++) {
2838                         if (global_state == MISDN_INITIALIZED)  {
2839                                 cb_event(EVENT_CLEANUP, &stack->bc[i], glob_mgr->user_data);
2840                         }
2841                 }
2842 #endif
2843                 
2844                 if (stack->nt) {
2845                         if (stack->nst.l1_l2(&stack->nst, msg))
2846                                 free_msg(msg);
2847                 } else {
2848                         free_msg(msg);
2849                 }
2850                 
2851                 stack->l1link=0;
2852                 stack->l2link=0;
2853                 return 1;
2854         }
2855   
2856         return 0;
2857 }
2858
2859 static int handle_l2(msg_t *msg)
2860 {
2861         iframe_t *frm = (iframe_t*) msg->data;
2862
2863         struct misdn_stack *stack = find_stack_by_addr(frm->addr);
2864         
2865         if (!stack) {
2866                 return 0 ;
2867         }
2868         
2869         switch(frm->prim) {
2870
2871         case DL_ESTABLISH | REQUEST:
2872                 cb_log(1,stack->port,"DL_ESTABLISH|REQUEST \n");
2873                 return 1;
2874         case DL_RELEASE | REQUEST:
2875                 cb_log(1,stack->port,"DL_RELEASE|REQUEST \n");
2876                 return 1;
2877                 
2878         case DL_ESTABLISH | INDICATION:
2879         case DL_ESTABLISH | CONFIRM:
2880         {
2881                 cb_log (3, stack->port, "L2: L2Link Up! \n");
2882                 if (stack->ptp && stack->l2link) {
2883                         cb_log (-1, stack->port, "L2: L2Link Up! but it's already UP.. must be faulty, blocking port\n"); 
2884                         cb_event(EVENT_PORT_ALARM, &stack->bc[0], glob_mgr->user_data);
2885                 }
2886                 stack->l2link=1;
2887                 free_msg(msg);
2888                 return 1;
2889         }
2890         break;
2891     
2892         case DL_RELEASE | INDICATION:
2893         case DL_RELEASE | CONFIRM:
2894         {
2895                 cb_log (3, stack->port, "L2: L2Link Down! \n");
2896                 stack->l2link=0;
2897                 
2898                 free_msg(msg);
2899                 return 1;
2900         }
2901         break;
2902         }
2903         return 0;
2904 }
2905
2906 static int handle_mgmt(msg_t *msg)
2907 {
2908         iframe_t *frm = (iframe_t*) msg->data;
2909         struct misdn_stack *stack;
2910
2911         if ( (frm->addr == 0) && (frm->prim == (MGR_DELLAYER|CONFIRM)) ) {
2912                 cb_log(2, 0, "MGMT: DELLAYER|CONFIRM Addr: 0 !\n") ;
2913                 free_msg(msg);
2914                 return 1;
2915         }
2916         
2917         stack = find_stack_by_addr(frm->addr);
2918         
2919         if (!stack) {
2920                 if (frm->prim == (MGR_DELLAYER|CONFIRM)) {
2921                         cb_log(2, 0, "MGMT: DELLAYER|CONFIRM Addr: %x !\n",
2922                                         frm->addr) ;
2923                         free_msg(msg);
2924                         return 1;
2925                 }
2926                 
2927                 return 0;
2928         }
2929         
2930         switch(frm->prim) {
2931         case MGR_SHORTSTATUS | INDICATION:
2932         case MGR_SHORTSTATUS | CONFIRM:
2933                 cb_log(5, 0, "MGMT: Short status dinfo %x\n",frm->dinfo);
2934                 
2935                 switch (frm->dinfo) {
2936                 case SSTATUS_L1_ACTIVATED:
2937                         cb_log(3, 0, "MGMT: SSTATUS: L1_ACTIVATED \n");
2938                         stack->l1link=1;
2939                 
2940                         break;
2941                 case SSTATUS_L1_DEACTIVATED:
2942                         cb_log(3, 0, "MGMT: SSTATUS: L1_DEACTIVATED \n");
2943                         stack->l1link=0;
2944 #if 0
2945                         clear_l3(stack);
2946 #endif
2947                         break;
2948
2949                 case SSTATUS_L2_ESTABLISHED:
2950                         cb_log(3, stack->port, "MGMT: SSTATUS: L2_ESTABLISH \n");
2951                         stack->l2link=1;
2952                         break;
2953                         
2954                 case SSTATUS_L2_RELEASED:
2955                         cb_log(3, stack->port, "MGMT: SSTATUS: L2_RELEASED \n");
2956                         stack->l2link=0;
2957                         break;
2958                 }
2959                 
2960                 free_msg(msg);
2961                 return 1;
2962                 
2963         case MGR_SETSTACK | INDICATION:
2964                 cb_log(4, stack->port, "MGMT: SETSTACK|IND dinfo %x\n",frm->dinfo);
2965                 free_msg(msg);
2966                 return 1;
2967         case MGR_DELLAYER | CONFIRM:
2968                 cb_log(4, stack->port, "MGMT: DELLAYER|CNF dinfo %x\n",frm->dinfo) ;
2969                 free_msg(msg);
2970                 return 1;
2971                 
2972         }
2973         
2974         /*
2975         if ( (frm->prim & 0x0f0000) ==  0x0f0000) {
2976         cb_log(5, 0, "$$$ MGMT FRAME: prim %x addr %x dinfo %x\n",frm->prim, frm->addr, frm->dinfo) ;
2977         free_msg(msg);
2978         return 1;
2979         } */
2980     
2981         return 0;
2982 }
2983
2984
2985 static msg_t *fetch_msg(int midev) 
2986 {
2987         msg_t *msg=alloc_msg(MAX_MSG_SIZE);
2988         int r;
2989
2990         if (!msg) {
2991                 cb_log(0, 0, "fetch_msg: alloc msg failed !!");
2992                 return NULL;
2993         }
2994
2995         AGAIN:
2996                 r=mISDN_read(midev,msg->data,MAX_MSG_SIZE, TIMEOUT_10SEC);
2997                 msg->len=r;
2998     
2999                 if (r==0) {
3000                         free_msg(msg); /* danger, cause usually freeing in main_loop */
3001                         cb_log(6,0,"Got empty Msg..\n");
3002                         return NULL;
3003                 }
3004
3005                 if (r<0) {
3006                         if (errno == EAGAIN) {
3007                                 /*we wait for mISDN here*/
3008                                 cb_log(4,0,"mISDN_read wants us to wait\n");
3009                                 usleep(5000);
3010                                 goto AGAIN;
3011                         }
3012                         
3013                         cb_log(0,0,"mISDN_read returned :%d error:%s (%d)\n",r,strerror(errno),errno); 
3014                 }
3015
3016 #if 0
3017                if  (!(frm->prim == (DL_DATA|INDICATION) )|| (frm->prim == (PH_DATA|INDICATION)))
3018                        cb_log(0,0,"prim: %x dinfo:%x addr:%x msglen:%d frm->len:%d\n",frm->prim, frm->dinfo, frm->addr, msg->len,frm->len );
3019 #endif
3020                 return msg;
3021 }
3022
3023 void misdn_lib_isdn_l1watcher(int port)
3024 {
3025         struct misdn_stack *stack;
3026
3027         for (stack = glob_mgr->stack_list; stack && (stack->port != port); stack = stack->next)
3028                 ;
3029
3030         if (stack) {
3031                 cb_log(4, port, "Checking L1 State\n"); 
3032                 if (!stack->l1link) {
3033                         cb_log(4, port, "L1 State Down, trying to get it up again\n");  
3034                         misdn_lib_get_short_status(stack);
3035                         misdn_lib_get_l1_up(stack); 
3036                         misdn_lib_get_l2_up(stack); 
3037                 }
3038         }
3039 }
3040
3041 /* This is a thread */
3042 static void misdn_lib_isdn_event_catcher(void *arg)
3043 {
3044         struct misdn_lib *mgr = arg;
3045         int zero_frm=0 , fff_frm=0 ;
3046         int midev= mgr->midev;
3047         int port=0;
3048         
3049         while (1) {
3050                 msg_t *msg = fetch_msg(midev); 
3051                 iframe_t *frm;
3052                 
3053                 
3054                 if (!msg) continue;
3055                 
3056                 frm = (iframe_t*) msg->data;
3057                 
3058                 /** When we make a call from NT2Ast we get these frames **/
3059                 if (frm->len == 0 && frm->addr == 0 && frm->dinfo == 0 && frm->prim == 0 ) {
3060                         zero_frm++; 
3061                         free_msg(msg);
3062                         continue;
3063                 } else {
3064                         if (zero_frm) {
3065                                 cb_log(0, port, "*** Alert: %d zero_frms caught\n", zero_frm);
3066                                 zero_frm = 0 ;
3067                         }
3068                 }
3069                 
3070                 /** I get this sometimes after setup_bc **/
3071                 if (frm->len == 0 &&  frm->dinfo == 0 && frm->prim == 0xffffffff ) {
3072                         fff_frm++; 
3073                         free_msg(msg);
3074                         continue;
3075                 } else {
3076                         if (fff_frm) {
3077                                 cb_log(0, port, "*** Alert: %d fff_frms caught\n", fff_frm);
3078                                 fff_frm = 0 ;
3079                         }
3080                 }
3081                 
3082                 manager_isdn_handler(frm, msg);
3083         }
3084
3085 }
3086
3087
3088 /** App Interface **/
3089
3090 int te_lib_init(void) {
3091         char buff[1025] = "";
3092         iframe_t *frm=(iframe_t*)buff;
3093         int midev=mISDN_open();
3094         int ret;
3095
3096         if  (midev<=0) return midev;
3097   
3098 /* create entity for layer 3 TE-mode */
3099         mISDN_write_frame(midev, buff, 0, MGR_NEWENTITY | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
3100         ret = mISDN_read_frame(midev, frm, sizeof(iframe_t), 0, MGR_NEWENTITY | CONFIRM, TIMEOUT_1SEC);
3101   
3102         if (ret < mISDN_HEADER_LEN) {
3103         noentity:
3104                 fprintf(stderr, "cannot request MGR_NEWENTITY from mISDN: %s\n",strerror(errno));
3105                 exit(-1);
3106         }
3107   
3108         entity = frm->dinfo & 0xffff ;
3109   
3110         if (!entity)
3111                 goto noentity;
3112
3113         return midev;
3114   
3115 }
3116
3117 void te_lib_destroy(int midev)
3118 {
3119         char buf[1024];
3120         mISDN_write_frame(midev, buf, 0, MGR_DELENTITY | REQUEST, entity, 0, NULL, TIMEOUT_1SEC);
3121
3122         cb_log(4, 0, "Entity deleted\n");
3123         mISDN_close(midev);
3124         cb_log(4, 0, "midev closed\n");
3125 }
3126
3127
3128
3129 void misdn_lib_transfer(struct misdn_bchannel* holded_bc)
3130 {
3131         holded_bc->holded=0;
3132 }
3133
3134 struct misdn_bchannel *manager_find_bc_by_pid(int pid)
3135 {
3136         struct misdn_stack *stack;
3137         int i;
3138   
3139         for (stack=glob_mgr->stack_list;
3140              stack;
3141              stack=stack->next) {
3142                 for (i=0; i<=stack->b_num; i++)
3143                         if (stack->bc[i].pid == pid) return &stack->bc[i];
3144         }
3145   
3146         return NULL;
3147 }
3148
3149 struct misdn_bchannel *manager_find_bc_holded(struct misdn_bchannel* bc)
3150 {
3151         struct misdn_stack *stack=get_stack_by_bc(bc);
3152         return find_bc_holded(stack);
3153 }
3154
3155
3156
3157 static int test_inuse(struct misdn_bchannel *bc)
3158 {
3159         struct timeval now;
3160         gettimeofday(&now, NULL);
3161         if (!bc->in_use) {
3162                 if (misdn_lib_port_is_pri(bc->port) && bc->last_used.tv_sec == now.tv_sec ) {
3163                         cb_log(2,bc->port, "channel with stid:%x for one second still in use! (n:%d lu:%d)\n", bc->b_stid, (int) now.tv_sec, (int) bc->last_used.tv_sec);
3164                         return 1;
3165                 }
3166                 
3167
3168                 cb_log(3,bc->port, "channel with stid:%x not in use!\n", bc->b_stid);
3169                 return 0;
3170         }
3171         
3172         cb_log(2,bc->port, "channel with stid:%x in use!\n", bc->b_stid);
3173         return 1;
3174 }
3175
3176
3177 static void prepare_bc(struct misdn_bchannel*bc, int channel)
3178 {
3179         bc->channel = channel;
3180         bc->channel_preselected = channel?1:0;
3181         bc->in_use = 1;
3182         bc->need_disconnect=1;
3183         bc->need_release=1;
3184         bc->need_release_complete=1;
3185         bc->cause = AST_CAUSE_NORMAL_CLEARING;
3186
3187         if (++mypid>5000) mypid=1;
3188         bc->pid=mypid;
3189
3190 #if 0
3191         bc->addr=0;
3192         bc->b_stid=0;
3193         bc->layer_id=0;
3194 #endif
3195 }
3196
3197 struct misdn_bchannel* misdn_lib_get_free_bc(int port, int channel, int inout, int dec)
3198 {
3199         struct misdn_stack *stack;
3200         int i;
3201         
3202         if (channel < 0 || channel > MAX_BCHANS) {
3203                 cb_log(0,port,"Requested channel out of bounds (%d)\n",channel);
3204                 return NULL;
3205         }
3206
3207         usleep(1000);
3208
3209         for (stack=glob_mgr->stack_list; stack; stack=stack->next) {
3210     
3211                 if (stack->port == port) {
3212                         int maxnum;
3213
3214                         if (stack->blocked) {
3215                                 cb_log(0,port,"Port is blocked\n");
3216                                 return NULL;
3217                         }
3218                 
3219                         if (channel > 0) {
3220                                 if (channel <= stack->b_num) {
3221                                         for (i = 0; i < stack->b_num; i++) {
3222                                                 if ( stack->bc[i].channel == channel) {
3223                                                         if (test_inuse(&stack->bc[i])) { 
3224                                                                 cb_log(0,port,"Requested channel:%d on port:%d is already in use\n",channel, port);
3225                                                                 return NULL;
3226
3227                                                         } else {
3228                                                                 prepare_bc(&stack->bc[i], channel);
3229                                                                 return &stack->bc[i];
3230                                                         }
3231                                                 }
3232                                         }
3233                                 } else {
3234                                         cb_log(0,port,"Requested channel:%d is out of bounds on port:%d\n",channel, port);
3235                                         return NULL;
3236                                 }
3237                         }
3238
3239                         maxnum = inout && !stack->pri && !stack->ptp ? stack->b_num + 1 : stack->b_num;
3240
3241                         if (dec) {
3242                                 for (i = maxnum-1; i>=0; i--) {
3243                                         if (!test_inuse(&stack->bc[i])) {
3244                                                 /* 3. channel on bri means CW*/
3245                                                 if (!stack->pri && i==stack->b_num)
3246                                                         stack->bc[i].cw=1;
3247                                                         
3248                                                 prepare_bc(&stack->bc[i], channel);
3249                                                 stack->bc[i].dec=1;
3250                                                 return &stack->bc[i];
3251                                         }
3252                                 }
3253                         } else {
3254                                 for (i = 0; i <maxnum; i++) {
3255                                         if (!test_inuse(&stack->bc[i])) {
3256                                                 /* 3. channel on bri means CW*/
3257                                                 if (!stack->pri && i==stack->b_num)
3258                                                         stack->bc[i].cw=1;
3259
3260                                                 prepare_bc(&stack->bc[i], channel);
3261                                                 return &stack->bc[i];
3262                                         }
3263                                 }
3264                         }
3265
3266                         cb_log(1,port,"There is no free channel on port (%d)\n",port);
3267                         return NULL;
3268                 }
3269         }
3270
3271         cb_log(0,port,"Port is not configured (%d)\n",port);
3272         return NULL;
3273 }
3274
3275
3276
3277
3278 /* ******************************************************************* */
3279 /*!
3280  * \internal
3281  * \brief Convert the facility function enum value into a string.
3282  *
3283  * \return String version of the enum value
3284  */
3285 static const char *fac2str(enum FacFunction facility)
3286 {
3287         static const struct { 
3288                 enum FacFunction facility; 
3289                 char *name;
3290         } arr[] = {
3291 /* *INDENT-OFF* */
3292                 { Fac_None, "Fac_None" },
3293                 { Fac_GetSupportedServices, "Fac_GetSupportedServices" },
3294                 { Fac_Listen, "Fac_Listen" },
3295                 { Fac_Suspend, "Fac_Suspend" },
3296                 { Fac_Resume, "Fac_Resume" },
3297                 { Fac_CFActivate, "Fac_CFActivate" },
3298                 { Fac_CFDeactivate, "Fac_CFDeactivate" },
3299                 { Fac_CFInterrogateParameters, "Fac_CFInterrogateParameters" },
3300                 { Fac_CFInterrogateNumbers, "Fac_CFInterrogateNumbers" },
3301                 { Fac_CD, "Fac_CD" },
3302                 { Fac_AOCDCurrency, "Fac_AOCDCurrency" },
3303                 { Fac_AOCDChargingUnit, "Fac_AOCDChargingUnit" },
3304 /* *INDENT-ON* */
3305         };
3306         
3307         unsigned index;
3308         
3309         for (index = 0; index < ARRAY_LEN(arr); ++index) {
3310                 if (arr[index].facility == facility) {
3311                         return arr[index].name;
3312                 }
3313         }       /* end for */
3314
3315         return "unknown";
3316 }       /* end fac2str() */
3317
3318 void misdn_lib_log_ies(struct misdn_bchannel *bc)
3319 {
3320         struct misdn_stack *stack;
3321
3322         if (!bc) return;
3323
3324         stack = get_stack_by_bc(bc);
3325
3326         if (!stack) return;
3327
3328         cb_log(2, stack->port, " --> channel:%d mode:%s cause:%d ocause:%d rad:%s cad:%s\n", bc->channel, stack->nt?"NT":"TE", bc->cause, bc->out_cause, bc->rad, bc->cad);
3329         
3330         cb_log(2, stack->port,
3331                " --> info_dad:%s onumplan:%c dnumplan:%c rnumplan:%c cpnnumplan:%c\n",
3332                bc->info_dad,
3333                bc->onumplan>=0?'0'+bc->onumplan:' ',
3334                bc->dnumplan>=0?'0'+bc->dnumplan:' ',
3335                bc->rnumplan>=0?'0'+bc->rnumplan:' ',
3336                bc->cpnnumplan>=0?'0'+bc->cpnnumplan:' '
3337                 );
3338         
3339         cb_log(3, stack->port, " --> caps:%s pi:%x keypad:%s sending_complete:%d\n", bearer2str(bc->capability),bc->progress_indicator, bc->keypad, bc->sending_complete);
3340         cb_log(4, stack->port, " --> screen:%d --> pres:%d\n",
3341                         bc->screen, bc->pres);
3342         
3343         cb_log(4, stack->port, " --> addr:%x l3id:%x b_stid:%x layer_id:%x\n", bc->addr, bc->l3_id, bc->b_stid, bc->layer_id);
3344         
3345         cb_log(4, stack->port, " --> facility:%s out_facility:%s\n",fac2str(bc->fac_in.Function),fac2str(bc->fac_out.Function));
3346
3347         cb_log(5, stack->port, " --> urate:%d rate:%d mode:%d user1:%d\n", bc->urate, bc->rate, bc->mode,bc->user1);
3348         
3349         cb_log(5, stack->port, " --> bc:%p h:%d sh:%d\n", bc, bc->holded, bc->stack_holder);
3350 }
3351
3352
3353 #define RETURN(a,b) {retval=a; goto b;}
3354
3355 static void misdn_send_lock(struct misdn_bchannel *bc)
3356 {
3357         //cb_log(0,bc->port,"Locking bc->pid:%d\n", bc->pid);
3358         if (bc->send_lock)
3359                 pthread_mutex_lock(&bc->send_lock->lock);
3360 }
3361
3362 static void misdn_send_unlock(struct misdn_bchannel *bc)
3363 {
3364         //cb_log(0,bc->port,"UnLocking bc->pid:%d\n", bc->pid);
3365         if (bc->send_lock)
3366                 pthread_mutex_unlock(&bc->send_lock->lock);
3367 }
3368
3369 int misdn_lib_send_event(struct misdn_bchannel *bc, enum event_e event )
3370 {
3371         msg_t *msg; 
3372         int retval=0;
3373         struct misdn_stack *stack;
3374   
3375         if (!bc) RETURN(-1,OUT_POST_UNLOCK);
3376         
3377         stack = get_stack_by_bc(bc);
3378         
3379         if (!stack) {
3380                 cb_log(0,bc->port,"SENDEVENT: no Stack for event:%s oad:%s dad:%s \n", isdn_get_info(msgs_g, event, 0), bc->oad, bc->dad);
3381                 RETURN(-1,OUT);
3382         }
3383         
3384         misdn_send_lock(bc);
3385
3386
3387         cb_log(6,stack->port,"SENDEVENT: stack->nt:%d stack->upperid:%x\n",stack->nt, stack->upper_id);
3388
3389         if ( stack->nt && !stack->l1link) {
3390                 /** Queue Event **/
3391                 bc->evq=event;
3392                 cb_log(1, stack->port, "Queueing Event %s because L1 is down (btw. Activating L1)\n", isdn_get_info(msgs_g, event, 0));
3393                 misdn_lib_get_l1_up(stack);
3394                 RETURN(0,OUT);
3395         }
3396         
3397         cb_log(1, stack->port, "I SEND:%s oad:%s dad:%s pid:%d\n", isdn_get_info(msgs_g, event, 0), bc->oad, bc->dad, bc->pid);
3398         cb_log(4, stack->port, " --> bc_state:%s\n",bc_state2str(bc->bc_state));
3399         misdn_lib_log_ies(bc);
3400         
3401         switch (event) {
3402         case EVENT_SETUP:
3403                 if (create_process(glob_mgr->midev, bc)<0) {
3404                         cb_log(0,  stack->port, " No free channel at the moment @ send_event\n");
3405
3406                         RETURN(-ENOCHAN,OUT);
3407                 }
3408                 break;
3409
3410         case EVENT_PROGRESS:
3411         case EVENT_ALERTING:
3412         case EVENT_PROCEEDING:
3413         case EVENT_SETUP_ACKNOWLEDGE:
3414         case EVENT_CONNECT:
3415                 if (!stack->nt) break;
3416
3417         case EVENT_RETRIEVE_ACKNOWLEDGE:
3418
3419                 if (stack->nt) {
3420                         if (bc->channel <=0 ) { /*  else we have the channel already */
3421                                 if (find_free_chan_in_stack(stack, bc, 0, 0)<0) {
3422                                         cb_log(0, stack->port, " No free channel at the moment\n");
3423                                         /*FIXME: add disconnect*/
3424                                         RETURN(-ENOCHAN,OUT);
3425                                 }
3426                         }
3427                         /* Its that i generate channels */
3428                 }
3429
3430                 retval=setup_bc(bc);
3431                 if (retval == -EINVAL) {
3432                         cb_log(0,bc->port,"send_event: setup_bc failed\n");
3433                 }
3434
3435                 if (misdn_cap_is_speech(bc->capability)) {
3436                         if ((event==EVENT_CONNECT)||(event==EVENT_RETRIEVE_ACKNOWLEDGE)) {
3437                                 if ( *bc->crypt_key ) {
3438                                         cb_log(4, stack->port,  " --> ENABLING BLOWFISH channel:%d oad%d:%s dad%d:%s \n", bc->channel, bc->onumplan,bc->oad, bc->dnumplan,bc->dad);
3439                                         
3440                                         manager_ph_control_block(bc,  BF_ENABLE_KEY, bc->crypt_key, strlen(bc->crypt_key) );
3441                                 }
3442                                 
3443                                 if (!bc->nodsp) manager_ph_control(bc,  DTMF_TONE_START, 0);
3444                                 manager_ec_enable(bc);
3445                                 
3446                                 if (bc->txgain != 0) {
3447                                         cb_log(4, stack->port,  "--> Changing txgain to %d\n", bc->txgain);
3448                                         manager_ph_control(bc, VOL_CHANGE_TX, bc->txgain);
3449                                 }
3450                                 
3451                                 if ( bc->rxgain != 0 ) {
3452                                         cb_log(4, stack->port,  "--> Changing rxgain to %d\n", bc->rxgain);
3453                                         manager_ph_control(bc, VOL_CHANGE_RX, bc->rxgain);
3454                                 }
3455                         }
3456                 }
3457                 break;
3458
3459         case EVENT_HOLD_ACKNOWLEDGE:
3460         {
3461                 struct misdn_bchannel *holded_bc=malloc(sizeof(struct misdn_bchannel));
3462                 if (!holded_bc) {
3463                         cb_log(0,bc->port, "Could not allocate holded_bc!!!\n");
3464                         RETURN(-1,OUT);
3465                 }
3466
3467                 /*backup the bc*/
3468                 memcpy(holded_bc,bc,sizeof(struct misdn_bchannel));
3469                 holded_bc->holded=1;
3470                 bc_state_change(holded_bc,BCHAN_CLEANED);
3471
3472                 stack_holder_add(stack,holded_bc);
3473         
3474                 /*kill the bridge and clean the bchannel*/
3475                 if (stack->nt) {
3476                         int channel;
3477                         if (bc->bc_state == BCHAN_BRIDGED) {
3478                                 struct misdn_bchannel *bc2;
3479
3480                                 misdn_split_conf(bc,bc->conf_id);
3481                                 bc2 = find_bc_by_confid(bc->conf_id);
3482                                 if (!bc2) {
3483                                         cb_log(0,bc->port,"We have no second bc in bridge???\n");
3484                                 } else {
3485                                         misdn_split_conf(bc2,bc->conf_id);
3486                                 }
3487                         }
3488                         
3489                         channel = bc->channel;
3490
3491                         empty_bc(bc);
3492                         clean_up_bc(bc);
3493
3494                         if (channel>0)
3495                                 empty_chan_in_stack(stack,channel);
3496
3497                         bc->in_use=0;   
3498                 }
3499                 
3500         }
3501         break;
3502
3503         /* finishing the channel eh ? */
3504         case EVENT_DISCONNECT:
3505                 if (!bc->need_disconnect) {
3506                         cb_log(0,bc->port," --> we have already send Disconnect\n");
3507                         RETURN(-1,OUT);
3508                 }
3509                 
3510                 bc->need_disconnect=0;
3511                 break;
3512         case EVENT_RELEASE:
3513                 if (!bc->need_release) {
3514                         cb_log(0,bc->port," --> we have already send Release\n");
3515                         RETURN(-1,OUT);
3516                 }
3517                 bc->need_disconnect=0;
3518                 bc->need_release=0;
3519                 break;
3520         case EVENT_RELEASE_COMPLETE:
3521                 if (!bc->need_release_complete) {
3522                         cb_log(0,bc->port," --> we have already send Release_complete\n");
3523                         RETURN(-1,OUT);
3524                 }
3525                 bc->need_disconnect=0;
3526                 bc->need_release=0;
3527                 bc->need_release_complete=0;
3528
3529                 if (!stack->nt) {
3530                         /*create cleanup in TE*/
3531                         int channel=bc->channel;
3532
3533                         int tmpcause=bc->cause; 
3534                         int tmp_out_cause=bc->out_cause;        
3535                         empty_bc(bc);
3536                         bc->cause=tmpcause;
3537                         bc->out_cause=tmp_out_cause;
3538                         clean_up_bc(bc);
3539                         
3540                         if (channel>0)
3541                                 empty_chan_in_stack(stack,channel);
3542                         
3543                         bc->in_use=0;
3544                 }
3545                 break;
3546     
3547         case EVENT_CONNECT_ACKNOWLEDGE:
3548
3549                 if ( bc->nt || misdn_cap_is_speech(bc->capability)) {
3550                         int retval=setup_bc(bc);
3551                         if (retval == -EINVAL){
3552                                 cb_log(0,bc->port,"send_event: setup_bc failed\n");
3553                                 
3554                         }
3555                 }
3556                 
3557                 if (misdn_cap_is_speech(bc->capability)) {
3558                         if (  !bc->nodsp) manager_ph_control(bc,  DTMF_TONE_START, 0);
3559                         manager_ec_enable(bc);
3560
3561                         if ( bc->txgain != 0 ) {
3562                                 cb_log(4, stack->port, "--> Changing txgain to %d\n", bc->txgain);
3563                                 manager_ph_control(bc, VOL_CHANGE_TX, bc->txgain);
3564                         }
3565                         if ( bc->rxgain !=