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