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