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