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