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