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