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