Merged revisions 71214 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                         break;
1513                 case EVENT_CONNECT:
1514
1515                         if ( *bc->crypt_key ) {
1516                                 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);
1517                                 manager_ph_control_block(bc,  BF_ENABLE_KEY, bc->crypt_key, strlen(bc->crypt_key) );
1518                         }
1519                 case EVENT_ALERTING:
1520                 case EVENT_PROGRESS:
1521                 case EVENT_PROCEEDING:
1522                 case EVENT_SETUP_ACKNOWLEDGE:
1523
1524                 setup_bc(bc);
1525
1526                 case EVENT_SETUP:
1527                 {
1528                         if (bc->channel == 0xff) {
1529                                 if (!find_free_chan_in_stack(stack, bc, 0, 0)) {
1530                                         cb_log(0, stack->port, "Any Channel Requested, but we have no more!!\n");
1531                                         bc->out_cause=34;
1532                                         misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
1533                                         return -1;
1534                                 }
1535                         } 
1536
1537                         if (bc->channel >0 && bc->channel<255) {
1538                                 int ret=set_chan_in_stack(stack ,bc->channel);
1539                                 if (event == EVENT_SETUP && ret<0){
1540                                         /* empty bchannel */
1541                                         bc->channel=0;
1542                                         bc->out_cause=44;
1543                                         misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
1544                                         return -1;
1545                                 }
1546                         }
1547                 }
1548                 break;
1549
1550                 case EVENT_RELEASE_COMPLETE:
1551                 case EVENT_RELEASE:
1552                         break;
1553                 default:
1554                         break;
1555                 }
1556         } else {    /** NT MODE **/
1557                 
1558         }
1559         return 0;
1560 }
1561
1562 static int handle_cr ( struct misdn_stack *stack, iframe_t *frm)
1563 {
1564         if (!stack) return -1;
1565   
1566         switch (frm->prim) {
1567         case CC_NEW_CR|INDICATION:
1568                 cb_log(7, stack->port, " --> lib: NEW_CR Ind with l3id:%x on this port.\n",frm->dinfo);
1569
1570                 struct misdn_bchannel* bc=misdn_lib_get_free_bc(stack->port, 0, 1, 0);
1571                 if (!bc) {
1572                         cb_log(0, stack->port, " --> !! lib: No free channel!\n");
1573                         return -1;
1574                 }
1575   
1576                 cb_log(7, stack->port, " --> new_process: New L3Id: %x\n",frm->dinfo);
1577                 bc->l3_id=frm->dinfo;
1578                 return 1;
1579         case CC_NEW_CR|CONFIRM:
1580                 return 1;
1581         case CC_NEW_CR|REQUEST:
1582                 return 1;
1583         case CC_RELEASE_CR|REQUEST:
1584                 return 1;
1585         case CC_RELEASE_CR|CONFIRM:
1586                 break;
1587         case CC_RELEASE_CR|INDICATION:
1588                 cb_log(4, stack->port, " --> lib: RELEASE_CR Ind with l3id:%x\n",frm->dinfo);
1589                 {
1590                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, frm->dinfo);
1591                         struct misdn_bchannel dummybc;
1592       
1593                         if (!bc) {
1594                                 cb_log(4, stack->port, " --> Didn't found BC so temporarly creating dummy BC (l3id:%x) on this port.\n", frm->dinfo);
1595                                 memset (&dummybc,0,sizeof(dummybc));
1596                                 dummybc.port=stack->port;
1597                                 dummybc.l3_id=frm->dinfo;
1598                                 dummybc.nt=stack->nt;
1599                                 bc=&dummybc; 
1600                         }
1601       
1602                         if (bc) {
1603                                 int channel = bc->channel;
1604                                 cb_log(4, stack->port, " --> lib: CLEANING UP l3id: %x\n",frm->dinfo);
1605
1606                                 /*bc->pid = 0;*/
1607                                 bc->need_disconnect=0;
1608                                 bc->need_release=0;
1609                                 bc->need_release_complete=0;
1610
1611                                 cb_event(EVENT_CLEANUP, bc, glob_mgr->user_data);
1612
1613                                 empty_bc(bc);
1614                                 clean_up_bc(bc);
1615
1616                                 if (channel>0)
1617                                         empty_chan_in_stack(stack,channel);
1618                                 bc->in_use=0;
1619
1620                                 dump_chan_list(stack);
1621
1622                                 if (bc->stack_holder) {
1623                                         cb_log(4,stack->port, "REMOVEING Holder\n");
1624                                         stack_holder_remove( stack, bc);
1625                                         free(bc);
1626                                 }
1627                         }
1628                         else {
1629                                 if (stack->nt) 
1630                                         cb_log(4, stack->port, "BC with dinfo: %x  not found.. (prim was %x and addr %x)\n",frm->dinfo, frm->prim, frm->addr);
1631                         }
1632       
1633                         return 1;
1634                 }
1635                 break;
1636         }
1637   
1638         return 0;
1639 }
1640
1641
1642 /*Emptys bc if it's reserved (no SETUP out yet)*/
1643 void misdn_lib_release(struct misdn_bchannel *bc)
1644 {
1645         struct misdn_stack *stack=get_stack_by_bc(bc);
1646
1647         if (!stack) {
1648                 cb_log(1,0,"misdn_release: No Stack found\n");
1649                 return;
1650         }
1651         
1652         if (bc->channel>0) 
1653                 empty_chan_in_stack(stack,bc->channel);
1654         
1655         empty_bc(bc);
1656         clean_up_bc(bc);
1657         bc->in_use=0;
1658 }
1659
1660
1661
1662
1663 int misdn_lib_get_port_up (int port) 
1664 { /* Pull Up L1 */ 
1665         struct misdn_stack *stack;
1666         
1667         for (stack=glob_mgr->stack_list;
1668              stack;
1669              stack=stack->next) {
1670                 
1671                 if (stack->port == port) {
1672
1673                         if (!stack->l1link)
1674                                 misdn_lib_get_l1_up(stack);
1675                         if (!stack->l2link)
1676                                 misdn_lib_get_l2_up(stack);
1677                         
1678                         return 0;
1679                 }
1680         }
1681         return 0;
1682 }
1683
1684
1685 int misdn_lib_get_port_down (int port) 
1686 { /* Pull Down L1 */ 
1687         struct misdn_stack *stack;
1688         for (stack=glob_mgr->stack_list;
1689              stack;
1690              stack=stack->next) {
1691                 if (stack->port == port) {
1692                                 if (stack->l2link)
1693                                         misdn_lib_get_l2_down(stack);
1694                                 misdn_lib_get_l1_down(stack);
1695                         return 0;
1696                 }
1697         }
1698         return 0;
1699 }
1700
1701 int misdn_lib_port_up(int port, int check)
1702 {
1703         struct misdn_stack *stack;
1704
1705
1706         for (stack=glob_mgr->stack_list;
1707              stack;
1708              stack=stack->next) {
1709                 
1710                 if (stack->port == port) {
1711
1712                         if (stack->blocked) {
1713                                 cb_log(0,port, "Port Blocked:%d L2:%d L1:%d\n", stack->blocked, stack->l2link, stack->l1link);
1714                                 return -1;
1715                         }
1716
1717                         if (stack->ptp ) {
1718
1719                                 if (stack->l1link && stack->l2link) {
1720                                         return 1;
1721                                 } else {
1722                                         cb_log(1,port, "Port Down L2:%d L1:%d\n",
1723                                                 stack->l2link, stack->l1link);
1724                                         return 0;
1725                                 }
1726                         } else {
1727                                 if ( !check || stack->l1link )
1728                                         return 1;
1729                                 else {
1730                                         cb_log(1,port, "Port down PMP\n");
1731                                         return 0;
1732                                 }
1733                         }
1734                 }
1735         }
1736   
1737         return -1;
1738 }
1739
1740
1741 int
1742 handle_event_nt(void *dat, void *arg)
1743 {
1744         manager_t *mgr = (manager_t *)dat;
1745         msg_t *msg = (msg_t *)arg;
1746         mISDNuser_head_t *hh;
1747         int reject=0;
1748
1749         struct misdn_stack *stack=find_stack_by_mgr(mgr);
1750         int port;
1751
1752         if (!msg || !mgr)
1753                 return(-EINVAL);
1754
1755         hh=(mISDNuser_head_t*)msg->data;
1756         port=stack->port;
1757         
1758         cb_log(5, stack->port, " --> lib: prim %x dinfo %x\n",hh->prim, hh->dinfo);
1759         {
1760                 switch(hh->prim){
1761                 case CC_RETRIEVE|INDICATION:
1762                 {
1763                         iframe_t frm; /* fake te frm to add callref to global callreflist */
1764                         frm.dinfo = hh->dinfo;
1765
1766                         frm.addr=stack->upper_id | FLG_MSG_DOWN;
1767
1768                         frm.prim = CC_NEW_CR|INDICATION;
1769                         
1770                         if (handle_cr( stack, &frm)< 0) {
1771                                 msg_t *dmsg;
1772                                 cb_log(4, stack->port, "Patch from MEIDANIS:Sending RELEASE_COMPLETE %x (No free Chan for you..)\n", hh->dinfo);
1773                                 dmsg = create_l3msg(CC_RELEASE_COMPLETE | REQUEST,MT_RELEASE_COMPLETE, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1774                                 stack->nst.manager_l3(&stack->nst, dmsg);
1775                                 free_msg(msg);
1776                                 return 0;
1777                         }
1778                         
1779                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1780                         struct misdn_bchannel *hold_bc=stack_holder_find(stack,bc->l3_id);
1781                         cb_log(4, stack->port, "bc_l3id:%x holded_bc_l3id:%x\n",bc->l3_id, hold_bc->l3_id);
1782
1783                         if (hold_bc) {
1784                                 cb_log(4, stack->port, "REMOVEING Holder\n");
1785
1786                                 /*swap the backup to our new channel back*/
1787                                 stack_holder_remove(stack, hold_bc);
1788                                 memcpy(bc,hold_bc,sizeof(struct misdn_bchannel));
1789                                 free(hold_bc);
1790
1791                                 bc->holded=0;
1792                         }
1793                         
1794                 }
1795                         
1796                         break;
1797                         
1798                 case CC_SETUP|CONFIRM:
1799                 {
1800                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1801                         int l3id = *((int *)(((u_char *)msg->data)+ mISDNUSER_HEAD_SIZE));
1802                         cb_log(4, stack->port, " --> lib: Event_ind:SETUP CONFIRM [NT] : new L3ID  is %x\n",l3id );
1803         
1804                         if (!bc) { cb_log(4, stack->port, "Bc Not found (after SETUP CONFIRM)\n"); return 0; }
1805                         cb_log (2,bc->port,"I IND :CC_SETUP|CONFIRM: old l3id:%x new l3id:%x\n", bc->l3_id, l3id);
1806                         bc->l3_id=l3id;
1807                         cb_event(EVENT_NEW_L3ID, bc, glob_mgr->user_data);
1808                 }
1809                 free_msg(msg);
1810                 return 0;
1811       
1812                 case CC_SETUP|INDICATION:
1813                 {
1814                         struct misdn_bchannel* bc=misdn_lib_get_free_bc(stack->port, 0, 1, 0);
1815                         if (!bc) 
1816                         ERR_NO_CHANNEL:
1817                         {
1818                                 msg_t *dmsg;
1819                                 cb_log(4, stack->port, "Patch from MEIDANIS:Sending RELEASE_COMPLETE %x (No free Chan for you..)\n", hh->dinfo);
1820                                 dmsg = create_l3msg(CC_RELEASE_COMPLETE | REQUEST,MT_RELEASE_COMPLETE, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1821                                 stack->nst.manager_l3(&stack->nst, dmsg);
1822                                 free_msg(msg);
1823                                 return 0;
1824                         }
1825   
1826                         cb_log(4, stack->port, " --> new_process: New L3Id: %x\n",hh->dinfo);
1827                         bc->l3_id=hh->dinfo;
1828                 }
1829                 break;
1830
1831                 case CC_CONNECT_ACKNOWLEDGE|INDICATION:
1832 #if 0
1833                 {
1834                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1835                         if (bc) {
1836                                 if ( !misdn_cap_is_speech(bc->capability)) {
1837                                         int ret=setup_bc(bc);
1838                                         if (ret == -EINVAL){
1839                                                 cb_log(0,bc->port,"send_event: setup_bc failed\n");
1840                                                 
1841                                         }
1842                                 }
1843                         }
1844                 }
1845 #endif
1846                 break;
1847                 
1848                 case CC_ALERTING|INDICATION:
1849                 case CC_PROCEEDING|INDICATION:
1850                 case CC_SETUP_ACKNOWLEDGE|INDICATION:
1851                         if(!stack->ptp) break;  
1852                 case CC_CONNECT|INDICATION:
1853                 {
1854 #if 0
1855                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1856                         
1857                         if (!bc) {
1858                                 msg_t *dmsg;
1859                                 cb_log(0, stack->port,"!!!! We didn't found our bc, dinfo:%x on this port.\n",hh->dinfo);
1860                                 
1861                                 cb_log(0, stack->port, "Releaseing call %x (No free Chan for you..)\n", hh->dinfo);
1862                                 dmsg = create_l3msg(CC_RELEASE_COMPLETE | REQUEST,MT_RELEASE_COMPLETE, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1863                                 stack->nst.manager_l3(&stack->nst, dmsg);
1864                                 free_msg(msg);
1865                                 return 0;
1866                                 
1867                         }
1868                         int ret=setup_bc(bc);
1869                         if (ret == -EINVAL){
1870                                 cb_log(0,bc->port,"handle_event_nt: setup_bc failed\n");
1871                                 misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
1872                         }
1873 #endif
1874                 }
1875                 break;
1876                 case CC_DISCONNECT|INDICATION:
1877                 {
1878                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1879                         if (!bc) {
1880                                 bc=find_bc_by_masked_l3id(stack, hh->dinfo, 0xffff0000);
1881                                 if (bc) { 
1882                                         int myprocid=bc->l3_id&0x0000ffff;
1883                                         hh->dinfo=(hh->dinfo&0xffff0000)|myprocid;
1884                                         cb_log(3,stack->port,"Reject dinfo: %x cause:%d\n",hh->dinfo,bc->cause);
1885                                         reject=1;               
1886                                 }
1887                         }
1888                 }
1889                 break;
1890                 
1891                 case CC_FACILITY|INDICATION:
1892                 {
1893                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1894                         if (!bc) {
1895                                 bc=find_bc_by_masked_l3id(stack, hh->dinfo, 0xffff0000);
1896                                 if (bc) { 
1897                                         int myprocid=bc->l3_id&0x0000ffff;
1898                                         hh->dinfo=(hh->dinfo&0xffff0000)|myprocid;
1899                                         cb_log(4,bc->port,"Repaired reject Bug, new dinfo: %x\n",hh->dinfo);
1900                                 }
1901                         }
1902                 }
1903                 break;
1904                 
1905                 case CC_RELEASE_COMPLETE|INDICATION:
1906                         break;
1907
1908                 case CC_SUSPEND|INDICATION:
1909                 {
1910                         msg_t *dmsg;
1911                         cb_log(4, stack->port, " --> Got Suspend, sending Reject for now\n");
1912                         dmsg = create_l3msg(CC_SUSPEND_REJECT | REQUEST,MT_SUSPEND_REJECT, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1913                         stack->nst.manager_l3(&stack->nst, dmsg);
1914                         free_msg(msg);
1915                         return 0;
1916                 }
1917                 break;
1918                 case CC_RESUME|INDICATION:
1919                         break;
1920
1921                 case CC_RELEASE|CONFIRM:
1922                         break;
1923                         
1924                 case CC_RELEASE|INDICATION:
1925                         break;
1926
1927                 case CC_RELEASE_CR|INDICATION:
1928                 {
1929                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1930                         struct misdn_bchannel dummybc;
1931                         iframe_t frm; /* fake te frm to remove callref from global callreflist */
1932                         frm.dinfo = hh->dinfo;
1933
1934                         frm.addr=stack->upper_id | FLG_MSG_DOWN;
1935
1936                         frm.prim = CC_RELEASE_CR|INDICATION;
1937                         cb_log(4, stack->port, " --> Faking Realease_cr for %x\n",frm.addr);
1938                         /** removing procid **/
1939                         if (!bc) {
1940                                 cb_log(4, stack->port, " --> Didn't found BC so temporarly creating dummy BC (l3id:%x) on this port.\n", hh->dinfo);
1941                                 memset (&dummybc,0,sizeof(dummybc));
1942                                 dummybc.port=stack->port;
1943                                 dummybc.l3_id=hh->dinfo;
1944                                 dummybc.nt=stack->nt;
1945                                 bc=&dummybc; 
1946                         }
1947         
1948                         if (bc) {
1949                                 if ( (bc->l3_id & 0xff00) == 0xff00) {
1950                                         cb_log(4, stack->port, " --> Removing Process Id:%x on this port.\n", bc->l3_id&0xff);
1951                                         stack->procids[bc->l3_id&0xff] = 0 ;
1952                                 }
1953                         }
1954                         else cb_log(0, stack->port, "Couldnt find BC so I couldnt remove the Process!!!! this is a bad port.\n");
1955         
1956                         if (handle_cr(stack, &frm)<0) {
1957                         }
1958
1959                         free_msg(msg);
1960                         return 0 ;
1961                 }
1962                 break;
1963       
1964                 case CC_NEW_CR|INDICATION:
1965                         /*  Got New CR for bchan, for now I handle this one in */
1966                         /*  connect_ack, Need to be changed */
1967                 {
1968                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1969                         int l3id = *((int *)(((u_char *)msg->data)+ mISDNUSER_HEAD_SIZE));
1970                         if (!bc) { cb_log(0, stack->port, " --> In NEW_CR: didn't found bc ??\n"); return -1;};
1971                         if (((l3id&0xff00)!=0xff00) && ((bc->l3_id&0xff00)==0xff00)) {
1972                                 cb_log(4, stack->port, " --> Removing Process Id:%x on this port.\n", 0xff&bc->l3_id);
1973                                 stack->procids[bc->l3_id&0xff] = 0 ;
1974                         }
1975                         cb_log(4, stack->port, "lib: Event_ind:CC_NEW_CR : very new L3ID  is %x\n",l3id );
1976         
1977                         bc->l3_id =l3id;
1978                         cb_event(EVENT_NEW_L3ID, bc, glob_mgr->user_data);
1979         
1980                         free_msg(msg);
1981                         return 0;
1982                 }
1983       
1984                 case DL_ESTABLISH | INDICATION:
1985                 case DL_ESTABLISH | CONFIRM:
1986                 {
1987                         cb_log(3, stack->port, "%% GOT L2 Activate Info.\n");
1988                         
1989                         if (stack->ptp && stack->l2link) {
1990                                 cb_log(0, stack->port, "%% GOT L2 Activate Info. but we're activated already.. this l2 is faulty, blocking port\n");
1991                                 cb_event(EVENT_PORT_ALARM, &stack->bc[0], glob_mgr->user_data);
1992                         }
1993                         
1994                         stack->l2link = 1;
1995                         stack->l2upcnt=0;
1996                         
1997                         free_msg(msg);
1998                         return 0;
1999                 }
2000                 break;
2001
2002
2003                 case DL_RELEASE | INDICATION:
2004                 case DL_RELEASE | CONFIRM:
2005                 {
2006                         if (stack->ptp) {
2007                                 cb_log(3 , stack->port, "%% GOT L2 DeActivate Info.\n");
2008
2009                                 if (stack->l2upcnt>3) {
2010                                         cb_log(0 , stack->port, "!!! Could not Get the L2 up after 3 Attemps!!!\n");
2011                                 }  else {
2012 #if 0
2013                                         if (stack->nt) misdn_lib_reinit_nt_stack(stack->port);
2014 #endif
2015                                         if (stack->l1link) {
2016                                                 misdn_lib_get_l2_up(stack);
2017                                                 stack->l2upcnt++;
2018                                         }
2019                                 }
2020                                 
2021                         } else 
2022                                 cb_log(3, stack->port, "%% GOT L2 DeActivate Info.\n");
2023                         
2024                         stack->l2link = 0;
2025                         free_msg(msg);
2026                         return 0;
2027                 }
2028                 break;
2029                 }
2030         }
2031         
2032         {
2033                 /*  Parse Events and fire_up to App. */
2034                 struct misdn_bchannel *bc;
2035                 struct misdn_bchannel dummybc;
2036                 
2037                 enum event_e event = isdn_msg_get_event(msgs_g, msg, 1);
2038     
2039                 bc=find_bc_by_l3id(stack, hh->dinfo);
2040     
2041                 if (!bc) {
2042       
2043                         cb_log(4, stack->port, " --> Didn't found BC so temporarly creating dummy BC (l3id:%x).\n", hh->dinfo);
2044                         memset (&dummybc,0,sizeof(dummybc));
2045                         dummybc.port=stack->port;
2046                         dummybc.l3_id=hh->dinfo;
2047                         dummybc.nt=stack->nt;
2048                         bc=&dummybc; 
2049                 }
2050                 if (bc ) {
2051                         isdn_msg_parse_event(msgs_g,msg,bc, 1);
2052
2053                         switch (event) {
2054                                 case EVENT_SETUP:
2055                                         if (bc->channel<=0 || bc->channel==0xff) {
2056                                                 bc->channel=find_free_chan_in_stack(stack,bc, 0,0);
2057                                                 if (bc->channel<=0)
2058                                                         goto ERR_NO_CHANNEL;
2059                                         } else if (!stack->ptp) 
2060                                                 cb_log(3,stack->port," --> PTMP but channel requested\n"); 
2061
2062                                         int ret=set_chan_in_stack(stack, bc->channel);
2063                                         if (event==EVENT_SETUP && ret<0){
2064                                                 /* empty bchannel */
2065                                                 bc->channel=0;
2066                                                 bc->out_cause=44;
2067
2068                                                 goto ERR_NO_CHANNEL;
2069                                         } 
2070                                         break;
2071                                 case EVENT_RELEASE:
2072                                 case EVENT_RELEASE_COMPLETE:
2073                                         {
2074                                         int channel=bc->channel;
2075                                         int tmpcause=bc->cause; 
2076                                         empty_bc(bc);
2077                                         bc->cause=tmpcause;
2078                                         clean_up_bc(bc);
2079
2080                                         if (channel>0)
2081                                                 empty_chan_in_stack(stack,channel);
2082                                         bc->in_use=0;
2083                                         }
2084                                         break;
2085
2086                                 default:
2087                                 break;
2088                         }
2089                         
2090                         if(!isdn_get_info(msgs_g,event,1)) {
2091                                 cb_log(4, stack->port, "Unknown Event Ind: prim %x dinfo %x\n",hh->prim, hh->dinfo);
2092                         } else {
2093                                 if (reject) {
2094                                         switch(bc->cause){
2095                                                 case 17:
2096                                                         cb_log(1, stack->port, "Siemens Busy reject..\n");
2097
2098                                                         break;
2099                                                 default:
2100                                                         break;
2101                                         }
2102                                 }
2103                                 cb_event(event, bc, glob_mgr->user_data);
2104                         }
2105       
2106                 } else {
2107                         cb_log(4, stack->port, "No BC found with l3id: prim %x dinfo %x\n",hh->prim, hh->dinfo);
2108                 }
2109
2110                 free_msg(msg);
2111         }
2112
2113
2114         return 0;
2115 }
2116
2117
2118 static int handle_timers(msg_t* msg)
2119 {
2120         iframe_t *frm= (iframe_t*)msg->data;
2121         struct misdn_stack *stack; 
2122   
2123         /* Timer Stuff */
2124         switch (frm->prim) {
2125         case MGR_INITTIMER | CONFIRM:
2126         case MGR_ADDTIMER | CONFIRM:
2127         case MGR_DELTIMER | CONFIRM:
2128         case MGR_REMOVETIMER | CONFIRM:
2129                 free_msg(msg);
2130                 return(1);
2131         }
2132   
2133   
2134   
2135         if (frm->prim==(MGR_TIMER | INDICATION) ) {
2136                 for (stack = glob_mgr->stack_list;
2137                      stack;
2138                      stack = stack->next) {
2139                         itimer_t *it;
2140       
2141                         if (!stack->nt) continue;
2142       
2143                         it = stack->nst.tlist;
2144                         /* find timer */
2145                         for(it=stack->nst.tlist;
2146                             it;
2147                             it=it->next) {
2148                                 if (it->id == (int)frm->addr)
2149                                         break;
2150                         }
2151                         if (it) {
2152                                 int ret;
2153                                 ret = mISDN_write_frame(stack->midev, msg->data, frm->addr,
2154                                                         MGR_TIMER | RESPONSE, 0, 0, NULL, TIMEOUT_1SEC);
2155                                 test_and_clear_bit(FLG_TIMER_RUNING, (long unsigned int *)&it->Flags);
2156                                 ret = it->function(it->data);
2157                                 free_msg(msg);
2158                                 return 1;
2159                         }
2160                 }
2161     
2162                 cb_log(0, 0, "Timer Msg without Timer ??\n");
2163                 free_msg(msg);
2164                 return 1;
2165         }
2166   
2167         return 0;
2168 }
2169
2170
2171
2172 void misdn_lib_tone_generator_start(struct misdn_bchannel *bc)
2173 {
2174         bc->generate_tone=1;
2175 }
2176
2177 void misdn_lib_tone_generator_stop(struct misdn_bchannel *bc)
2178 {
2179         bc->generate_tone=0;
2180 }
2181
2182
2183 static int do_tone(struct misdn_bchannel *bc, int len)
2184 {
2185         bc->tone_cnt=len;
2186         
2187         if (bc->generate_tone) {
2188                 cb_event(EVENT_TONE_GENERATE, bc, glob_mgr->user_data);
2189                 
2190                 if ( !bc->nojitter ) {
2191                         misdn_tx_jitter(bc,len);
2192                 }
2193                 
2194                 return 1;
2195         }
2196         
2197         return 0;
2198 }
2199
2200
2201 #ifdef MISDN_SAVE_DATA
2202 static void misdn_save_data(int id, char *p1, int l1, char *p2, int l2) 
2203 {
2204         char n1[32],n2[32];
2205
2206         sprintf(n1,"/tmp/misdn-rx-%d.raw",id);
2207         sprintf(n2,"/tmp/misdn-tx-%d.raw",id);
2208
2209         FILE *rx=fopen(n1,"a+"); 
2210         FILE *tx=fopen(n2,"a+");
2211
2212         if (!rx || !tx) {
2213                 cb_log(0,0,"Couldn't open files: %s\n",strerror(errno));
2214                 return ;
2215         }
2216         
2217         fwrite(p1,1,l1,rx);
2218         fwrite(p2,1,l2,tx);
2219         
2220         fclose(rx);
2221         fclose(tx);
2222
2223 }
2224 #endif
2225
2226 void misdn_tx_jitter(struct misdn_bchannel *bc, int len)
2227 {
2228         char buf[4096 + mISDN_HEADER_LEN];
2229         char *data=&buf[mISDN_HEADER_LEN];
2230         iframe_t *txfrm= (iframe_t*)buf;
2231         int jlen, r;
2232         
2233         jlen=cb_jb_empty(bc,data,len);
2234         
2235         if (jlen) {
2236 #ifdef MISDN_SAVE_DATA
2237                 misdn_save_data((bc->port*100+bc->channel), data, jlen, bc->bframe, bc->bframe_len);
2238 #endif
2239                 flip_buf_bits( data, jlen);
2240                 
2241                 if (jlen < len) {
2242                         cb_log(7,bc->port,"Jitterbuffer Underrun.\n");
2243                 }
2244                 
2245                 txfrm->prim = DL_DATA|REQUEST;
2246                 
2247                 txfrm->dinfo = 0;
2248                 
2249                 txfrm->addr = bc->addr|FLG_MSG_DOWN; /*  | IF_DOWN; */
2250                 
2251                 txfrm->len =jlen;
2252                 cb_log(9, bc->port, "Transmitting %d samples 2 misdn\n", txfrm->len);
2253
2254                 r=mISDN_write( glob_mgr->midev, buf, txfrm->len + mISDN_HEADER_LEN, 8000 );
2255         } else {
2256 #define MISDN_GEN_SILENCE
2257 #ifdef MISDN_GEN_SILENCE
2258                 int cnt=len/TONE_SILENCE_SIZE;
2259                 int rest=len%TONE_SILENCE_SIZE;
2260                 int i;
2261
2262                 for (i=0; i<cnt; i++) {
2263                         memcpy(data, tone_silence_flip, TONE_SILENCE_SIZE );
2264                         data +=TONE_SILENCE_SIZE;
2265                 }
2266
2267                 if (rest) {
2268                         memcpy(data, tone_silence_flip, rest);
2269                 }
2270
2271                 txfrm->prim = DL_DATA|REQUEST;
2272
2273                 txfrm->dinfo = 0;
2274
2275                 txfrm->addr = bc->addr|FLG_MSG_DOWN; /*  | IF_DOWN; */
2276
2277                 txfrm->len =len;
2278                 cb_log(9, bc->port, "Transmitting %d samples 2 misdn\n", txfrm->len);
2279
2280                 r=mISDN_write( glob_mgr->midev, buf, txfrm->len + mISDN_HEADER_LEN, 8000 );
2281 #endif
2282
2283         }
2284 }
2285
2286 static int handle_bchan(msg_t *msg)
2287 {
2288         iframe_t *frm= (iframe_t*)msg->data;
2289
2290
2291         struct misdn_bchannel *bc=find_bc_by_addr(frm->addr);
2292         
2293         if (!bc) {
2294                 cb_log(1,0,"handle_bchan: BC not found for prim:%x with addr:%x dinfo:%x\n", frm->prim, frm->addr, frm->dinfo);
2295                 return 0 ;
2296         }
2297         
2298         struct misdn_stack *stack=get_stack_by_bc(bc);
2299         
2300         if (!stack) {
2301                 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);
2302                 return 0;
2303         }
2304         
2305         switch (frm->prim) {
2306
2307         case MGR_SETSTACK| CONFIRM:
2308                 cb_log(3, stack->port, "BCHAN: MGR_SETSTACK|CONFIRM pid:%d\n",bc->pid);
2309                 break;
2310                 
2311         case MGR_SETSTACK| INDICATION:
2312                 cb_log(3, stack->port, "BCHAN: MGR_SETSTACK|IND pid:%d\n",bc->pid);
2313         break;
2314 #if 0
2315         AGAIN:
2316                 bc->addr = mISDN_get_layerid(stack->midev, bc->b_stid, bc->layer);
2317                 if (!bc->addr) {
2318
2319                         if (errno == EAGAIN) {
2320                                 usleep(1000);
2321                                 goto AGAIN;
2322                         }
2323                         
2324                         cb_log(0,stack->port,"$$$ Get Layer (%d) Id Error: %s\n",bc->layer,strerror(errno));
2325                         
2326                         /* we kill the channel later, when we received some
2327                            data. */
2328                         bc->addr= frm->addr;
2329                 } else if ( bc->addr < 0) {
2330                         cb_log(0, stack->port,"$$$ bc->addr <0 Error:%s\n",strerror(errno));
2331                         bc->addr=0;
2332                 }
2333                 
2334                 cb_log(4, stack->port," --> Got Adr %x\n", bc->addr);
2335
2336                 free_msg(msg);
2337         
2338                 
2339                 switch(bc->bc_state) {
2340                 case BCHAN_SETUP:
2341                         bc_state_change(bc,BCHAN_SETUPED);
2342                 break;
2343
2344                 case BCHAN_CLEAN_REQUEST:
2345                 default:
2346                         cb_log(0, stack->port," --> STATE WASN'T SETUP (but %s) in SETSTACK|IND pid:%d\n",bc_state2str(bc->bc_state), bc->pid);
2347                         clean_up_bc(bc);
2348                 }
2349                 return 1;
2350 #endif
2351
2352         case MGR_DELLAYER| INDICATION:
2353                 cb_log(3, stack->port, "BCHAN: MGR_DELLAYER|IND pid:%d\n",bc->pid);
2354                 break;
2355                 
2356         case MGR_DELLAYER| CONFIRM:
2357                 cb_log(3, stack->port, "BCHAN: MGR_DELLAYER|CNF pid:%d\n",bc->pid);
2358                 
2359                 bc->pid=0;
2360                 bc->addr=0;
2361                 
2362                 free_msg(msg);
2363                 return 1;
2364                 
2365         case PH_ACTIVATE | INDICATION:
2366         case DL_ESTABLISH | INDICATION:
2367                 cb_log(3, stack->port, "BCHAN: ACT Ind pid:%d\n", bc->pid);
2368
2369                 free_msg(msg);
2370                 return 1;    
2371
2372         case PH_ACTIVATE | CONFIRM:
2373         case DL_ESTABLISH | CONFIRM:
2374                 
2375                 cb_log(3, stack->port, "BCHAN: bchan ACT Confirm pid:%d\n",bc->pid);
2376                 free_msg(msg);
2377                 
2378                 return 1;    
2379
2380         case DL_ESTABLISH | REQUEST:
2381                 {
2382                         char buf[128];
2383                         mISDN_write_frame(stack->midev, buf, bc->addr | FLG_MSG_TARGET | FLG_MSG_DOWN,  DL_ESTABLISH | CONFIRM, 0,0, NULL, TIMEOUT_1SEC);
2384                 }
2385                 free_msg(msg);
2386                 return 1;
2387
2388         case DL_RELEASE|REQUEST:
2389                 {
2390                         char buf[128];
2391                         mISDN_write_frame(stack->midev, buf, bc->addr | FLG_MSG_TARGET | FLG_MSG_DOWN,  DL_RELEASE| CONFIRM, 0,0, NULL, TIMEOUT_1SEC);
2392                 }
2393                 free_msg(msg);
2394                 return 1;
2395                 
2396         case PH_DEACTIVATE | INDICATION:
2397         case DL_RELEASE | INDICATION:
2398                 cb_log (3, stack->port, "BCHAN: DeACT Ind pid:%d\n",bc->pid);
2399                 
2400                 free_msg(msg);
2401                 return 1;
2402     
2403         case PH_DEACTIVATE | CONFIRM:
2404         case DL_RELEASE | CONFIRM:
2405                 cb_log(3, stack->port, "BCHAN: DeACT Conf pid:%d\n",bc->pid);
2406                 
2407                 free_msg(msg);
2408                 return 1;
2409     
2410         case PH_CONTROL|INDICATION:
2411         {
2412                 unsigned int cont = *((unsigned int *)&frm->data.p);
2413                 
2414                 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);
2415
2416                 if ((cont&~DTMF_TONE_MASK) == DTMF_TONE_VAL) {
2417                         int dtmf = cont & DTMF_TONE_MASK;
2418                         cb_log(4, stack->port, " --> DTMF TONE: %c\n",dtmf);
2419                         bc->dtmf=dtmf;
2420                         cb_event(EVENT_DTMF_TONE, bc, glob_mgr->user_data);
2421         
2422                         free_msg(msg);
2423                         return 1;
2424                 }
2425                 if (cont == BF_REJECT) {
2426                         cb_log(4, stack->port, " --> BF REJECT\n");
2427                         free_msg(msg);
2428                         return 1;
2429                 }
2430                 if (cont == BF_ACCEPT) {
2431                         cb_log(4, stack->port, " --> BF ACCEPT\n");
2432                         free_msg(msg);
2433                         return 1;
2434                 }
2435         }
2436         break;
2437
2438         case PH_DATA|REQUEST:
2439         case DL_DATA|REQUEST:
2440                 cb_log(0, stack->port, "DL_DATA REQUEST \n");
2441                 do_tone(bc, 64);
2442                 
2443                 free_msg(msg);
2444                 return 1;
2445         
2446         
2447         case PH_DATA|INDICATION:
2448         case DL_DATA|INDICATION:
2449         {
2450                 bc->bframe = (void*)&frm->data.i;
2451                 bc->bframe_len = frm->len;
2452
2453                 /** Anyway flip the bufbits **/
2454                 if ( misdn_cap_is_speech(bc->capability) ) 
2455                         flip_buf_bits(bc->bframe, bc->bframe_len);
2456         
2457
2458                 if (!bc->bframe_len) {
2459                         cb_log(2, stack->port, "DL_DATA INDICATION bc->addr:%x frm->addr:%x\n", bc->addr, frm->addr);
2460                         free_msg(msg);
2461                         return 1;
2462                 }
2463
2464                 if ( (bc->addr&STACK_ID_MASK) != (frm->addr&STACK_ID_MASK) ) {
2465                         cb_log(2, stack->port, "DL_DATA INDICATION bc->addr:%x frm->addr:%x\n", bc->addr, frm->addr);
2466                         free_msg(msg);
2467                         return 1;
2468                 }
2469                 
2470 #if MISDN_DEBUG
2471                 cb_log(0, stack->port, "DL_DATA INDICATION Len %d\n", frm->len);
2472
2473 #endif
2474                 
2475                 if ( (bc->bc_state == BCHAN_ACTIVATED) && frm->len > 0) {
2476                         int t;
2477
2478 #ifdef MISDN_B_DEBUG
2479                         cb_log(0,bc->port,"do_tone START\n");
2480 #endif
2481                         t=do_tone(bc,frm->len);
2482
2483 #ifdef MISDN_B_DEBUG
2484                         cb_log(0,bc->port,"do_tone STOP (%d)\n",t);
2485 #endif
2486                         if (  !t ) {
2487                                 
2488                                 if ( misdn_cap_is_speech(bc->capability)) {
2489                                         if ( !bc->nojitter ) {
2490 #ifdef MISDN_B_DEBUG
2491                                                 cb_log(0,bc->port,"tx_jitter START\n");
2492 #endif
2493                                                 misdn_tx_jitter(bc,frm->len);
2494 #ifdef MISDN_B_DEBUG
2495                                                 cb_log(0,bc->port,"tx_jitter STOP\n");
2496 #endif
2497                                         }
2498                                 }
2499
2500 #ifdef MISDN_B_DEBUG    
2501                                 cb_log(0,bc->port,"EVENT_B_DATA START\n");
2502 #endif
2503                                 
2504                                 int i=cb_event( EVENT_BCHAN_DATA, bc, glob_mgr->user_data);
2505 #ifdef MISDN_B_DEBUG    
2506                                 cb_log(0,bc->port,"EVENT_B_DATA STOP\n");
2507 #endif
2508                                 
2509                                 if (i<0) {
2510                                         cb_log(10,stack->port,"cb_event returned <0\n");
2511                                         /*clean_up_bc(bc);*/
2512                                 }
2513                         }
2514                 }
2515                 free_msg(msg);
2516                 return 1;
2517         }
2518
2519
2520         case PH_CONTROL | CONFIRM:
2521                 cb_log(4, stack->port, "PH_CONTROL|CNF bc->addr:%x\n", frm->addr);
2522                 free_msg(msg);
2523                 return 1;
2524
2525         case PH_DATA | CONFIRM:
2526         case DL_DATA|CONFIRM:
2527 #if MISDN_DEBUG
2528
2529                 cb_log(0, stack->port, "Data confirmed\n");
2530
2531 #endif
2532                 free_msg(msg);
2533                 return 1;
2534         case DL_DATA|RESPONSE:
2535 #if MISDN_DEBUG
2536                 cb_log(0, stack->port, "Data response\n");
2537
2538 #endif
2539                 break;
2540         }
2541   
2542         return 0;
2543 }
2544
2545
2546
2547 static int handle_frm_nt(msg_t *msg)
2548 {
2549         iframe_t *frm= (iframe_t*)msg->data;
2550         struct misdn_stack *stack;
2551         int err=0;
2552
2553         stack=find_stack_by_addr( frm->addr );
2554
2555         
2556   
2557         if (!stack || !stack->nt) {
2558                 return 0;
2559         }
2560
2561         
2562         if ((err=stack->nst.l1_l2(&stack->nst,msg))) {
2563     
2564                 if (nt_err_cnt > 0 ) {
2565                         if (nt_err_cnt < 100) {
2566                                 nt_err_cnt++; 
2567                                 cb_log(0, stack->port, "NT Stack sends us error: %d \n", err);
2568                         } else if (nt_err_cnt < 105){
2569                                 cb_log(0, stack->port, "NT Stack sends us error: %d over 100 times, so I'll stop this message\n", err);
2570                                 nt_err_cnt = - 1; 
2571                         }
2572                 }
2573                 free_msg(msg);
2574                 return 1;
2575                 
2576         }
2577         
2578         return 1;
2579 }
2580
2581
2582 static int handle_frm(msg_t *msg)
2583 {
2584         iframe_t *frm = (iframe_t*) msg->data;
2585         
2586         struct misdn_stack *stack=find_stack_by_addr(frm->addr);
2587
2588         if (!stack || stack->nt) {
2589                 return 0;
2590         }
2591         
2592         cb_log(4,stack?stack->port:0,"handle_frm: frm->addr:%x frm->prim:%x\n",frm->addr,frm->prim);
2593
2594         {
2595                 struct misdn_bchannel *bc;
2596                 int ret=handle_cr(stack, frm);
2597
2598                 if (ret<0) {
2599                         cb_log(3,stack?stack->port:0,"handle_frm: handle_cr <0 prim:%x addr:%x\n", frm->prim, frm->addr);
2600
2601
2602                 }
2603
2604                 if(ret) {
2605                         free_msg(msg);
2606                         return 1;
2607                 }
2608     
2609                 bc=find_bc_by_l3id(stack, frm->dinfo);
2610     
2611 handle_frm_bc:
2612                 if (bc ) {
2613                         enum event_e event = isdn_msg_get_event(msgs_g, msg, 0);
2614                         enum event_response_e response=RESPONSE_OK;
2615       
2616                         isdn_msg_parse_event(msgs_g,msg,bc, 0);
2617                         
2618                         /** Preprocess some Events **/
2619                         int ret=handle_event(bc, event, frm);
2620                         if (ret<0) {
2621                                 cb_log(0,stack->port,"couldn't handle event\n");
2622                                 free_msg(msg);
2623                                 return 1;
2624                         }
2625                         /*  shoot up event to App: */
2626                         cb_log(5, stack->port, "lib Got Prim: Addr %x prim %x dinfo %x\n",frm->addr, frm->prim, frm->dinfo);
2627       
2628                         if(!isdn_get_info(msgs_g,event,0)) 
2629                                 cb_log(0, stack->port, "Unknown Event Ind: Addr:%x prim %x dinfo %x\n",frm->addr, frm->prim, frm->dinfo);
2630                         else
2631                                 response=cb_event(event, bc, glob_mgr->user_data);
2632 #if 1
2633                         if (event == EVENT_SETUP) {
2634                                 switch (response) {
2635                                 case RESPONSE_IGNORE_SETUP_WITHOUT_CLOSE:
2636
2637                                         cb_log(0, stack->port, "TOTALY IGNORING SETUP \n");                                     
2638                                         
2639                                         break;
2640                                 case RESPONSE_IGNORE_SETUP:
2641                                         /* I think we should send CC_RELEASE_CR, but am not sure*/
2642                                         bc->out_cause=16;
2643                                 
2644                                 case RESPONSE_RELEASE_SETUP:
2645                                         misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
2646                                         if (bc->channel>0)
2647                                                 empty_chan_in_stack(stack, bc->channel);
2648                                         empty_bc(bc);
2649                                         bc_state_change(bc,BCHAN_CLEANED);
2650                                         bc->in_use=0;
2651
2652                                         cb_log(0, stack->port, "GOT IGNORE SETUP\n");
2653                                         break;
2654                                 case RESPONSE_OK:
2655                                         cb_log(4, stack->port, "GOT SETUP OK\n");
2656
2657                                         
2658                                         break;
2659                                 default:
2660                                         break;
2661                                 }
2662                         }
2663
2664                         if (event == EVENT_RELEASE_COMPLETE) {
2665                                 /* release bchannel only after we've anounced the RELEASE_COMPLETE */
2666                                 int channel=bc->channel;
2667                                 int tmpcause=bc->cause; 
2668                                 int tmp_out_cause=bc->out_cause;        
2669                                 empty_bc(bc);
2670                                 bc->cause=tmpcause;
2671                                 bc->out_cause=tmp_out_cause;
2672                                 clean_up_bc(bc);
2673                                 
2674                                 if (tmpcause == 44) {
2675                                         cb_log(0,stack->port,"**** Received CAUSE:44, so not cleaning up channel %d\n", channel);
2676                                         cb_log(0,stack->port,"**** This channel is now no longer available,\nplease try to restart it with 'misdn send restart <port> <channel>'\n");
2677                                                 set_chan_in_stack(stack,bc->channel);
2678                                 } else {
2679                                         if (channel>0)
2680                                                 empty_chan_in_stack(stack,channel);
2681                                 }
2682                                 bc->in_use=0;
2683                         }
2684
2685                         cb_log(5, stack->port, "Freeing Msg on prim:%x \n",frm->prim);
2686
2687                         
2688                         free_msg(msg);
2689                         return 1;
2690 #endif
2691       
2692                 } else {
2693                         cb_log(0, stack->port, " --> Didn't find BC so temporarly creating dummy BC (l3id:%x) on this port.\n", frm->dinfo);
2694                         struct misdn_bchannel dummybc;
2695                         memset (&dummybc,0,sizeof(dummybc));
2696                         dummybc.port=stack->port;
2697                         dummybc.l3_id=frm->dinfo;
2698                         bc=&dummybc; 
2699                         goto handle_frm_bc;
2700                 }
2701         }
2702
2703         cb_log(4, stack->port, "TE_FRM_HANDLER: Returning 0 on prim:%x \n",frm->prim);
2704         return 0;
2705 }
2706
2707
2708 static int handle_l1(msg_t *msg)
2709 {
2710         iframe_t *frm = (iframe_t*) msg->data;
2711         struct misdn_stack *stack = find_stack_by_addr(frm->addr);
2712         int i ;
2713         
2714         if (!stack) return 0 ;
2715
2716         switch (frm->prim) {
2717         case PH_ACTIVATE | CONFIRM:
2718         case PH_ACTIVATE | INDICATION:
2719                 cb_log (3, stack->port, "L1: PH L1Link Up!\n");
2720                 stack->l1link=1;
2721                 
2722                 if (stack->nt) {
2723                         
2724                         if (stack->nst.l1_l2(&stack->nst, msg))
2725                                 free_msg(msg);
2726
2727                         if (stack->ptp)
2728                                 misdn_lib_get_l2_up(stack);
2729                 } else {
2730                         free_msg(msg);
2731                 }
2732                 
2733                 for (i=0;i<=stack->b_num; i++) {
2734                         if (stack->bc[i].evq != EVENT_NOTHING) {
2735                                 cb_log(4, stack->port, "Fireing Queued Event %s because L1 got up\n", isdn_get_info(msgs_g, stack->bc[i].evq, 0));
2736                                 misdn_lib_send_event(&stack->bc[i],stack->bc[i].evq);
2737                                 stack->bc[i].evq=EVENT_NOTHING;
2738                         }
2739                         
2740                 }
2741                 return 1;
2742
2743         case PH_ACTIVATE | REQUEST:
2744                 free_msg(msg);
2745                 cb_log(3,stack->port,"L1: PH_ACTIVATE|REQUEST \n");
2746                 return 1;
2747                 
2748         case PH_DEACTIVATE | REQUEST:
2749                 free_msg(msg);
2750                 cb_log(3,stack->port,"L1: PH_DEACTIVATE|REQUEST \n");
2751                 return 1;
2752                 
2753         case PH_DEACTIVATE | CONFIRM:
2754         case PH_DEACTIVATE | INDICATION:
2755                 cb_log (3, stack->port, "L1: PH L1Link Down! \n");
2756                 
2757                 for (i=0; i<=stack->b_num; i++) {
2758                         if (global_state == MISDN_INITIALIZED)  {
2759                                 cb_event(EVENT_CLEANUP, &stack->bc[i], glob_mgr->user_data);
2760                         }
2761                 }
2762                 
2763                 if (stack->nt) {
2764                         if (stack->nst.l1_l2(&stack->nst, msg))
2765                                 free_msg(msg);
2766                 } else {
2767                         free_msg(msg);
2768                 }
2769                 
2770                 stack->l1link=0;
2771                 stack->l2link=0;
2772                 return 1;
2773         }
2774   
2775         return 0;
2776 }
2777
2778 static int handle_l2(msg_t *msg)
2779 {
2780         iframe_t *frm = (iframe_t*) msg->data;
2781
2782         struct misdn_stack *stack = find_stack_by_addr(frm->addr);
2783         
2784         if (!stack) {
2785                 return 0 ;
2786         }
2787         
2788         switch(frm->prim) {
2789
2790         case DL_ESTABLISH | REQUEST:
2791                 cb_log(1,stack->port,"DL_ESTABLISH|REQUEST \n");
2792                 return 1;
2793         case DL_RELEASE | REQUEST:
2794                 cb_log(1,stack->port,"DL_RELEASE|REQUEST \n");
2795                 return 1;
2796                 
2797         case DL_ESTABLISH | INDICATION:
2798         case DL_ESTABLISH | CONFIRM:
2799         {
2800                 cb_log (3, stack->port, "L2: L2Link Up! \n");
2801                 if (stack->ptp && stack->l2link) {
2802                         cb_log (-1, stack->port, "L2: L2Link Up! but it's already UP.. must be faulty, blocking port\n"); 
2803                         cb_event(EVENT_PORT_ALARM, &stack->bc[0], glob_mgr->user_data);
2804                 }
2805                 stack->l2link=1;
2806                 free_msg(msg);
2807                 return 1;
2808         }
2809         break;
2810     
2811         case DL_RELEASE | INDICATION:
2812         case DL_RELEASE | CONFIRM:
2813         {
2814                 cb_log (3, stack->port, "L2: L2Link Down! \n");
2815                 stack->l2link=0;
2816                 
2817                 free_msg(msg);
2818                 return 1;
2819         }
2820         break;
2821         }
2822         return 0;
2823 }
2824
2825 static int handle_mgmt(msg_t *msg)
2826 {
2827         iframe_t *frm = (iframe_t*) msg->data;
2828
2829         if ( (frm->addr == 0) && (frm->prim == (MGR_DELLAYER|CONFIRM)) ) {
2830                 cb_log(2, 0, "MGMT: DELLAYER|CONFIRM Addr: 0 !\n") ;
2831                 free_msg(msg);
2832                 return 1;
2833         }
2834         
2835         struct misdn_stack * stack=find_stack_by_addr(frm->addr);
2836         
2837         if (!stack) {
2838                 if (frm->prim == (MGR_DELLAYER|CONFIRM)) {
2839                         cb_log(2, 0, "MGMT: DELLAYER|CONFIRM Addr: %x !\n",
2840                                         frm->addr) ;
2841                         free_msg(msg);
2842                         return 1;
2843                 }
2844                 
2845                 return 0;
2846         }
2847         
2848         switch(frm->prim) {
2849         case MGR_SHORTSTATUS | INDICATION:
2850         case MGR_SHORTSTATUS | CONFIRM:
2851                 cb_log(5, 0, "MGMT: Short status dinfo %x\n",frm->dinfo);
2852                 
2853                 switch (frm->dinfo) {
2854                 case SSTATUS_L1_ACTIVATED:
2855                         cb_log(3, 0, "MGMT: SSTATUS: L1_ACTIVATED \n");
2856                         stack->l1link=1;
2857                 
2858                         break;
2859                 case SSTATUS_L1_DEACTIVATED:
2860                         cb_log(3, 0, "MGMT: SSTATUS: L1_DEACTIVATED \n");
2861                         stack->l1link=0;
2862
2863                         clear_l3(stack);
2864                         break;
2865
2866                 case SSTATUS_L2_ESTABLISHED:
2867                         cb_log(3, stack->port, "MGMT: SSTATUS: L2_ESTABLISH \n");
2868                         stack->l2link=1;
2869                         break;
2870                         
2871                 case SSTATUS_L2_RELEASED:
2872                         cb_log(3, stack->port, "MGMT: SSTATUS: L2_RELEASED \n");
2873                         stack->l2link=0;
2874                         break;
2875                 }
2876                 
2877                 free_msg(msg);
2878                 return 1;
2879                 
2880         case MGR_SETSTACK | INDICATION:
2881                 cb_log(4, stack->port, "MGMT: SETSTACK|IND dinfo %x\n",frm->dinfo);
2882                 free_msg(msg);
2883                 return 1;
2884         case MGR_DELLAYER | CONFIRM:
2885                 cb_log(4, stack->port, "MGMT: DELLAYER|CNF dinfo %x\n",frm->dinfo) ;
2886                 free_msg(msg);
2887                 return 1;
2888                 
2889         }
2890         
2891         /*
2892         if ( (frm->prim & 0x0f0000) ==  0x0f0000) {
2893         cb_log(5, 0, "$$$ MGMT FRAME: prim %x addr %x dinfo %x\n",frm->prim, frm->addr, frm->dinfo) ;
2894         free_msg(msg);
2895         return 1;
2896         } */
2897     
2898         return 0;
2899 }
2900
2901
2902 static msg_t *fetch_msg(int midev) 
2903 {
2904         msg_t *msg=alloc_msg(MAX_MSG_SIZE);
2905         int r;
2906
2907         if (!msg) {
2908                 cb_log(0, 0, "fetch_msg: alloc msg failed !!");
2909                 return NULL;
2910         }
2911
2912         AGAIN:
2913                 r=mISDN_read(midev,msg->data,MAX_MSG_SIZE, TIMEOUT_10SEC);
2914                 msg->len=r;
2915     
2916                 if (r==0) {
2917                         free_msg(msg); /* danger, cauz usualy freeing in main_loop */
2918                         cb_log(6,0,"Got empty Msg..\n");
2919                         return NULL;
2920                 }
2921
2922                 if (r<0) {
2923                         if (errno == EAGAIN) {
2924                                 /*we wait for mISDN here*/
2925                                 cb_log(4,0,"mISDN_read wants us to wait\n");
2926                                 usleep(5000);
2927                                 goto AGAIN;
2928                         }
2929                         
2930                         cb_log(0,0,"mISDN_read returned :%d error:%s (%d)\n",r,strerror(errno),errno); 
2931                 }
2932
2933 #if 0
2934                if  (!(frm->prim == (DL_DATA|INDICATION) )|| (frm->prim == (PH_DATA|INDICATION)))
2935                        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 );
2936 #endif
2937                 return msg;
2938 }
2939
2940 void misdn_lib_isdn_l1watcher(int port)
2941 {
2942         struct misdn_stack *stack;
2943
2944         for (stack = glob_mgr->stack_list; stack && (stack->port != port); stack = stack->next)
2945                 ;
2946
2947         if (stack) {
2948                 cb_log(4, port, "Checking L1 State\n"); 
2949                 if (!stack->l1link) {
2950                         cb_log(4, port, "L1 State Down, trying to get it up again\n");  
2951                         misdn_lib_get_short_status(stack);
2952                         misdn_lib_get_l1_up(stack); 
2953                         misdn_lib_get_l2_up(stack); 
2954                 }
2955         }
2956 }
2957
2958 static void misdn_lib_isdn_event_catcher(void *arg)
2959 {
2960         struct misdn_lib *mgr = arg;
2961         int zero_frm=0 , fff_frm=0 ;
2962         int midev= mgr->midev;
2963         int port=0;
2964         
2965         while (1) {
2966                 msg_t *msg = fetch_msg(midev); 
2967                 iframe_t *frm;
2968                 
2969                 
2970                 if (!msg) continue;
2971                 
2972                 frm = (iframe_t*) msg->data;
2973                 
2974                 /** When we make a call from NT2Ast we get this frames **/
2975                 if (frm->len == 0 && frm->addr == 0 && frm->dinfo == 0 && frm->prim == 0 ) {
2976                         zero_frm++; 
2977                         free_msg(msg);
2978                         continue;
2979                 } else {
2980                         if (zero_frm) {
2981                                 cb_log(0, port, "*** Alert: %d zero_frms caught\n", zero_frm);
2982                                 zero_frm = 0 ;
2983                         }
2984                 }
2985                 
2986                 /** I get this sometimes after setup_bc **/
2987                 if (frm->len == 0 &&  frm->dinfo == 0 && frm->prim == 0xffffffff ) {
2988                         fff_frm++; 
2989                         free_msg(msg);
2990                         continue;
2991                 } else {
2992                         if (fff_frm) {
2993                                 cb_log(0, port, "*** Alert: %d fff_frms caught\n", fff_frm);
2994                                 fff_frm = 0 ;
2995                         }
2996                 }
2997                 
2998                 manager_isdn_handler(frm, msg);
2999         }
3000
3001 }
3002
3003
3004 /** App Interface **/
3005
3006 int te_lib_init() {
3007         char buff[1025];
3008         iframe_t *frm=(iframe_t*)buff;
3009         int midev=mISDN_open();
3010         int ret;
3011
3012         memset(buff,0,1025);
3013   
3014         if  (midev<=0) return midev;
3015   
3016 /* create entity for layer 3 TE-mode */
3017         mISDN_write_frame(midev, buff, 0, MGR_NEWENTITY | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
3018         ret = mISDN_read_frame(midev, frm, sizeof(iframe_t), 0, MGR_NEWENTITY | CONFIRM, TIMEOUT_1SEC);
3019   
3020         if (ret < mISDN_HEADER_LEN) {
3021         noentity:
3022                 fprintf(stderr, "cannot request MGR_NEWENTITY from mISDN: %s\n",strerror(errno));
3023                 exit(-1);
3024         }
3025   
3026         entity = frm->dinfo & 0xffff ;
3027   
3028         if (!entity)
3029                 goto noentity;
3030
3031         return midev;
3032   
3033 }
3034
3035 void te_lib_destroy(int midev)
3036 {
3037         char buf[1024];
3038         mISDN_write_frame(midev, buf, 0, MGR_DELENTITY | REQUEST, entity, 0, NULL, TIMEOUT_1SEC);
3039
3040         cb_log(4, 0, "Entetity deleted\n");
3041         mISDN_close(midev);
3042         cb_log(4, 0, "midev closed\n");
3043 }
3044
3045
3046
3047 void misdn_lib_transfer(struct misdn_bchannel* holded_bc)
3048 {
3049         holded_bc->holded=0;
3050 }
3051
3052 struct misdn_bchannel *manager_find_bc_by_pid(int pid)
3053 {
3054         struct misdn_stack *stack;
3055         int i;
3056   
3057         for (stack=glob_mgr->stack_list;
3058              stack;
3059              stack=stack->next) {
3060                 for (i=0; i<=stack->b_num; i++)
3061                         if (stack->bc[i].pid == pid) return &stack->bc[i];
3062         }
3063   
3064         return NULL;
3065 }
3066
3067 struct misdn_bchannel *manager_find_bc_holded(struct misdn_bchannel* bc)
3068 {
3069         struct misdn_stack *stack=get_stack_by_bc(bc);
3070         return find_bc_holded(stack);
3071 }
3072
3073
3074
3075 static void prepare_bc(struct misdn_bchannel*bc, int channel)
3076 {
3077         bc->channel = channel;
3078         bc->channel_preselected = channel?1:0;
3079         bc->in_use = 1;
3080         bc->need_disconnect=1;
3081         bc->need_release=1;
3082         bc->need_release_complete=1;
3083         bc->cause=16;
3084
3085         if (++mypid>5000) mypid=1;
3086         bc->pid=mypid;
3087
3088 #if 0
3089         bc->addr=0;
3090         bc->b_stid=0;
3091         bc->layer_id=0;
3092 #endif
3093 }
3094
3095 struct misdn_bchannel* misdn_lib_get_free_bc(int port, int channel, int inout, int dec)
3096 {
3097         struct misdn_stack *stack;
3098         int i;
3099         
3100         if (channel < 0 || channel > MAX_BCHANS) {
3101                 cb_log(0,port,"Requested channel out of bounds (%d)\n",channel);
3102                 return NULL;
3103         }
3104
3105         for (stack=glob_mgr->stack_list; stack; stack=stack->next) {
3106     
3107                 if (stack->port == port) {
3108                         if (stack->blocked) {
3109                                 cb_log(0,port,"Port is blocked\n");
3110                                 return NULL;
3111                         }
3112                 
3113                         if (channel > 0) {
3114                                 if (channel <= stack->b_num) {
3115                                         for (i = 0; i < stack->b_num; i++) {
3116                                                 if (stack->bc[i].in_use && stack->bc[i].channel == channel) {
3117                     &nb