46cdba77fa464af54b76ae981ae36ac2320f2fe5
[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                 for (i=0; i <= MAXPROCS; i++)
807                         if (stack->procids[i]==0) break;
808     
809                 if (i== MAXPROCS) {
810                         cb_log(-1, stack->port, "Couldnt Create New ProcId.\n");
811                         return -1;
812                 }
813                 stack->procids[i]=1;
814
815                 l3_id = 0xff00 | i;
816     
817                 ncr.prim = CC_NEW_CR | REQUEST; 
818
819                 ncr.addr = (stack->upper_id | FLG_MSG_DOWN)  ;
820
821                 ncr.dinfo = l3_id;
822                 ncr.len = 0;
823
824                 bc->l3_id = l3_id;
825                 if (mypid>5000) mypid=0;
826                 bc->pid=mypid++;
827       
828                 cb_log(3, stack->port, " --> new_l3id %x\n",l3_id);
829     
830         } else { 
831                 if (stack->ptp || bc->te_choose_channel) {
832                         /* we know exactly which channels are in use */
833                         free_chan = find_free_chan_in_stack(stack, bc->channel_preselected?bc->channel:0);
834                         if (!free_chan) return -1;
835                         bc->channel=free_chan;
836                 } else {
837                         /* other phones could have made a call also on this port (ptmp) */
838                         bc->channel=0xff;
839                 }
840     
841     
842                 /* if we are in te-mode, we need to create a process first */
843                 if (newteid++ > 0xffff)
844                         newteid = 0x0001;
845     
846                 l3_id = (entity<<16) | newteid;
847                 /* preparing message */
848                 ncr.prim = CC_NEW_CR | REQUEST; 
849
850                 ncr.addr = (stack->upper_id | FLG_MSG_DOWN)  ;
851
852                 ncr.dinfo =l3_id;
853                 ncr.len = 0;
854                 /* send message */
855
856                 bc->l3_id = l3_id;
857                 if (mypid>5000) mypid=0;
858                 bc->pid=mypid++;
859     
860                 cb_log(3, stack->port, "--> new_l3id %x\n",l3_id);
861     
862                 mISDN_write(midev, &ncr, mISDN_HEADER_LEN+ncr.len, TIMEOUT_1SEC);
863         }
864   
865         return l3_id;
866 }
867
868
869 void misdn_lib_setup_bc(struct misdn_bchannel *bc)
870 {
871         setup_bc(bc);
872 }
873
874
875 int setup_bc(struct misdn_bchannel *bc)
876 {
877         unsigned char buff[1025];
878   
879         mISDN_pid_t pid;
880         int ret;
881         
882
883         struct misdn_stack *stack=get_stack_by_bc(bc);
884
885         if (!stack) {
886                 cb_log(-1, bc->port, "setup_bc: NO STACK FOUND!!\n");
887                 return -1;
888         }
889         
890         int midev=stack->midev;
891         int channel=bc->channel-1-(bc->channel>16);
892         int b_stid=stack->b_stids[channel>=0?channel:0];
893
894
895         if ( bc->bc_state != BCHAN_CLEANED) {
896                 cb_log(4, stack->port, "$$$ bc already upsetted stid :%x (state:%s)\n", b_stid, bc_state2str(bc->bc_state) );
897                 return -1;
898         }
899         
900         cb_log(5, stack->port, "$$$ Setting up bc with stid :%x\n", b_stid);
901         
902         if (b_stid <= 0) {
903                 cb_log(-1, stack->port," -- Stid <=0 at the moment in channel:%d\n",channel);
904                 
905                 bc_state_change(bc,BCHAN_ERROR);
906                 return 1;
907         }
908         
909         
910         bc->b_stid = b_stid;
911         
912         {
913                 layer_info_t li;
914                 memset(&li, 0, sizeof(li));
915     
916                 li.object_id = -1;
917                 li.extentions = 0;
918                 
919                 li.st = bc->b_stid; /*  given idx */
920
921
922 #define MISDN_DSP
923 #ifndef MISDN_DSP
924                 bc->nodsp=1;
925 #endif
926                 if ( bc->hdlc || bc->nodsp) {
927                         cb_log(4, stack->port,"setup_bc: without dsp\n");
928                         { 
929                                 int l = sizeof(li.name);
930                                 strncpy(li.name, "B L3", l);
931                                 li.name[l-1] = 0;
932                         }
933                         li.pid.layermask = ISDN_LAYER((3));
934                         li.pid.protocol[3] = ISDN_PID_L3_B_USER;
935                         
936                         bc->layer=3;
937                 } else {
938                         cb_log(4, stack->port,"setup_bc: with dsp\n");
939                         { 
940                                 int l = sizeof(li.name);
941                                 strncpy(li.name, "B L4", l);
942                                 li.name[l-1] = 0;
943                         }
944                         li.pid.layermask = ISDN_LAYER((4));
945                         li.pid.protocol[4] = ISDN_PID_L4_B_USER
946 ;
947                         bc->layer=4;
948                         
949                 }  
950                 
951                 ret = mISDN_new_layer(midev, &li);
952                 if (ret ) {
953                         cb_log(-1, stack->port,"New Layer Err: %d %s\n",ret,strerror(errno));
954
955                         bc_state_change(bc,BCHAN_ERROR);
956                         return(-EINVAL);
957                 }
958                 
959                 bc->layer_id = li.id;
960         }
961         
962         memset(&pid, 0, sizeof(pid));
963         
964         
965         
966         cb_log(4, stack->port," --> Channel is %d\n", bc->channel);
967         
968         if (bc->nodsp) {
969                 cb_log(2, stack->port," --> TRANSPARENT Mode (no DSP, no HDLC)\n");
970                 pid.protocol[1] = ISDN_PID_L1_B_64TRANS;
971                 pid.protocol[2] = ISDN_PID_L2_B_TRANS;
972                 pid.protocol[3] = ISDN_PID_L3_B_USER;
973                 pid.layermask = ISDN_LAYER((1)) | ISDN_LAYER((2)) | ISDN_LAYER((3));
974                 
975         } else if ( bc->hdlc ) {
976                 cb_log(2, stack->port," --> HDLC Mode\n");
977 #ifdef ACK_HDLC
978                 bc->ack_hdlc=(sem_t*)malloc(sizeof(sem_t));
979                 if ( sem_init((sem_t*)bc->ack_hdlc, 1, 0)<0 )
980                         sem_init((sem_t*)bc->ack_hdlc, 0, 0);
981 #endif
982                 
983                 pid.protocol[1] = ISDN_PID_L1_B_64HDLC ;
984                 pid.protocol[2] = ISDN_PID_L2_B_TRANS  ;
985                 pid.protocol[3] = ISDN_PID_L3_B_USER;
986                 pid.layermask = ISDN_LAYER((1)) | ISDN_LAYER((2)) | ISDN_LAYER((3)) ;
987         } else {
988                 cb_log(2, stack->port," --> TRANSPARENT Mode\n");
989                 pid.protocol[1] = ISDN_PID_L1_B_64TRANS;
990                 pid.protocol[2] = ISDN_PID_L2_B_TRANS;
991                 pid.protocol[3] = ISDN_PID_L3_B_DSP;
992                 pid.protocol[4] = ISDN_PID_L4_B_USER;
993                 pid.layermask = ISDN_LAYER((1)) | ISDN_LAYER((2)) | ISDN_LAYER((3)) | ISDN_LAYER((4));
994                 
995         } 
996         
997         ret = mISDN_set_stack(midev, bc->b_stid, &pid);
998         
999         if (ret){
1000                 cb_log(5, stack->port,"$$$ Set Stack Err: %d %s\n",ret,strerror(errno));
1001                 
1002                 mISDN_write_frame(midev, buff, bc->layer_id, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
1003
1004                 bc_state_change(bc,BCHAN_ERROR);
1005                 return(-EINVAL);
1006         }
1007
1008
1009         bc_state_change(bc,BCHAN_SETUP);
1010
1011         
1012         /*manager_bchannel_deactivate(bc);*/
1013         
1014         
1015         return 0;
1016 }
1017
1018
1019
1020 /** IFACE **/
1021 int init_bc(struct misdn_stack *stack,  struct misdn_bchannel *bc, int midev, int port, int bidx,  char *msn, int firsttime)
1022 {
1023         unsigned char buff[1025];
1024         iframe_t *frm = (iframe_t *)buff;
1025         int ret;
1026   
1027         if (!bc) return -1;
1028   
1029         cb_log(4, port, "Init.BC %d.\n",bidx);
1030         
1031         memset(bc, 0,sizeof(struct misdn_bchannel));
1032         
1033         if (msn) {
1034                 int l = sizeof(bc->msn);
1035                 strncpy(bc->msn,msn, l);
1036                 bc->msn[l-1] = 0;
1037         }
1038         
1039         
1040         empty_bc(bc);
1041         bc_state_change(bc, BCHAN_CLEANED);
1042         
1043         bc->port=stack->port;
1044         bc->nt=stack->nt?1:0;
1045         
1046         {
1047                 ibuffer_t* ibuf= init_ibuffer(MISDN_IBUF_SIZE);
1048
1049                 if (!ibuf) return -1;
1050                 
1051                 clear_ibuffer( ibuf);
1052                 
1053                 ibuf->rsem=malloc(sizeof(sem_t));
1054                 
1055                 bc->astbuf=ibuf;
1056
1057                 if (sem_init(ibuf->rsem,1,0)<0)
1058                         sem_init(ibuf->rsem,0,0);
1059                 
1060         }
1061         
1062         
1063         
1064         
1065         {
1066                 stack_info_t *stinf;
1067                 ret = mISDN_get_stack_info(midev, stack->port, buff, sizeof(buff));
1068                 if (ret < 0) {
1069                         cb_log(-1, port, "%s: Cannot get stack info for this port. (ret=%d)\n", __FUNCTION__, ret);
1070                         return -1;
1071                 }
1072     
1073                 stinf = (stack_info_t *)&frm->data.p;
1074     
1075                 cb_log(4, port, " --> Child %x\n",stinf->child[bidx]);
1076         }
1077   
1078         return 0;
1079 }
1080
1081
1082
1083 struct misdn_stack* stack_init( int midev, int port, int ptp )
1084 {
1085         int ret;
1086         unsigned char buff[1025];
1087         iframe_t *frm = (iframe_t *)buff;
1088         stack_info_t *stinf;
1089         int i; 
1090         layer_info_t li;
1091
1092         struct misdn_stack *stack = malloc(sizeof(struct misdn_stack));
1093         if (!stack ) return NULL;
1094
1095
1096         cb_log(4, port, "Init. Stack.\n");
1097   
1098         memset(stack,0,sizeof(struct misdn_stack));
1099   
1100         for (i=0; i<MAX_BCHANS + 1; i++ ) stack->channels[i]=0;
1101         
1102         stack->port=port;
1103         stack->midev=midev;
1104         stack->ptp=ptp;
1105   
1106         stack->holding=NULL;
1107         stack->pri=0;
1108   
1109         msg_queue_init(&stack->downqueue);
1110   
1111         /* query port's requirements */
1112         ret = mISDN_get_stack_info(midev, port, buff, sizeof(buff));
1113         if (ret < 0) {
1114                 cb_log(-1, port, "%s: Cannot get stack info for this port. (ret=%d)\n", __FUNCTION__, ret);
1115                 return(NULL);
1116         }
1117   
1118         stinf = (stack_info_t *)&frm->data.p;
1119
1120         stack->d_stid = stinf->id;
1121         stack->b_num = stinf->childcnt;
1122
1123         for (i=0; i<stinf->childcnt; i++)
1124                 stack->b_stids[i] = stinf->child[i];
1125   
1126         switch(stinf->pid.protocol[0] & ~ISDN_PID_FEATURE_MASK) {
1127         case ISDN_PID_L0_TE_S0:
1128                 stack->nt=0;
1129                 break;
1130         case ISDN_PID_L0_NT_S0:
1131                 cb_log(4, port, "NT Stack\n");
1132
1133                 stack->nt=1;
1134                 break;
1135
1136         case ISDN_PID_L0_TE_U:
1137                 break;
1138         case ISDN_PID_L0_NT_U:
1139                 break;
1140         case ISDN_PID_L0_TE_UP2:
1141                 break;
1142         case ISDN_PID_L0_NT_UP2:
1143                 break;
1144         case ISDN_PID_L0_TE_E1:
1145                 cb_log(4, port, "TE S2M Stack\n");
1146                 stack->nt=0;
1147                 stack->pri=1;
1148                 break;
1149         case ISDN_PID_L0_NT_E1:
1150                 cb_log(4, port, "TE S2M Stack\n");
1151                 stack->nt=1;
1152                 stack->pri=1;
1153                 
1154                 break;
1155         default:
1156                 cb_log(-1, port, "this is a unknown port type 0x%08x\n", stinf->pid.protocol[0]);
1157
1158         }
1159
1160         if (!stack->nt) {
1161                 if (stinf->pid.protocol[2] & ISDN_PID_L2_DF_PTP ) { 
1162                         stack->ptp = 1;
1163                 } else {
1164                         stack->ptp = 0;
1165                 }
1166         }
1167         
1168         {
1169                 int ret;
1170                 int nt=stack->nt;
1171
1172                 cb_log(4, port, "Init. Stack.\n");
1173                 
1174                 memset(&li, 0, sizeof(li));
1175                 {
1176                         int l = sizeof(li.name);
1177                         strncpy(li.name,nt?"net l2":"user l4", l);
1178                         li.name[l-1] = 0;
1179                 }
1180                 li.object_id = -1;
1181                 li.extentions = 0;
1182                 li.pid.protocol[nt?2:4] = nt?ISDN_PID_L2_LAPD_NET:ISDN_PID_L4_CAPI20;
1183                 li.pid.layermask = ISDN_LAYER((nt?2:4));
1184                 li.st = stack->d_stid;
1185                 
1186                 
1187                 ret = mISDN_new_layer(midev, &li);
1188                 if (ret) {
1189                         cb_log(-1, port, "%s: Cannot add layer %d to this port.\n", __FUNCTION__, nt?2:4);
1190                         return(NULL);
1191                 }
1192                 
1193                 
1194                 stack->upper_id = li.id;
1195                 ret = mISDN_register_layer(midev, stack->d_stid, stack->upper_id);
1196                 if (ret)
1197                 {
1198                         cb_log(-1,port,"Cannot register layer %d of this port.\n", nt?2:4);
1199                         return(NULL);
1200                 }
1201                 
1202                 stack->lower_id = mISDN_get_layerid(midev, stack->d_stid, nt?1:3); 
1203                 if (stack->lower_id < 0) {
1204                         cb_log(-1, port, "%s: Cannot get layer(%d) id of this port.\n", __FUNCTION__, nt?1:3);
1205                         return(NULL);
1206                 }
1207                 
1208                 stack->upper_id = mISDN_get_layerid(midev, stack->d_stid, nt?2:4);
1209                 if (stack->upper_id < 0) {
1210                         cb_log(-1, port, "%s: Cannot get layer(%d) id of this port.\n", __FUNCTION__, 2);
1211                         return(NULL);
1212                 }
1213                 
1214                 cb_log(4, port, "NT Stacks upper_id %x\n",stack->upper_id);
1215                 
1216                 
1217                 /* create nst (nt-mode only) */
1218                 if (nt) {
1219                         
1220                         memset(&stack->nst, 0, sizeof(net_stack_t));
1221                         memset(&stack->mgr, 0, sizeof(manager_t));
1222     
1223                         stack->mgr.nst = &stack->nst;
1224                         stack->nst.manager = &stack->mgr;
1225     
1226                         stack->nst.l3_manager = handle_event_nt;
1227                         stack->nst.device = midev;
1228                         stack->nst.cardnr = port;
1229                         stack->nst.d_stid = stack->d_stid;
1230     
1231                         stack->nst.feature = FEATURE_NET_HOLD;
1232                         if (stack->ptp)
1233                                 stack->nst.feature |= FEATURE_NET_PTP;
1234                         if (stack->pri)
1235                                 stack->nst.feature |= FEATURE_NET_CRLEN2 | FEATURE_NET_EXTCID;
1236                         
1237                         stack->nst.l1_id = stack->lower_id;
1238                         stack->nst.l2_id = stack->upper_id;
1239                         
1240                         msg_queue_init(&stack->nst.down_queue);
1241                         
1242                         Isdnl2Init(&stack->nst);
1243                         Isdnl3Init(&stack->nst);
1244                         
1245                 } 
1246                 
1247                 if (!stack->nt) {
1248                         /*assume L1 is up, we'll get DEACTIVATES soon, for non
1249                          * up L1s*/
1250                         stack->l1link=0;
1251                 }
1252
1253                 misdn_lib_get_short_status(stack);
1254                 misdn_lib_get_l1_up(stack);
1255                 misdn_lib_get_l2_up(stack);
1256                 
1257         }
1258
1259         cb_log(1,0,"stack_init: port:%d lowerId:%x  upperId:%x\n",stack->port,stack->lower_id, stack->upper_id);
1260         
1261         return stack;
1262 }
1263
1264
1265 void stack_te_destroy(struct misdn_stack* stack)
1266 {
1267         char buf[1024];
1268         if (!stack) return;
1269   
1270         if (stack->lower_id) 
1271                 mISDN_write_frame(stack->midev, buf, stack->lower_id, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
1272
1273         if (stack->upper_id) 
1274                 mISDN_write_frame(stack->midev, buf, stack->upper_id, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
1275 }
1276
1277
1278 struct misdn_stack * find_stack_by_addr(int  addr)
1279 {
1280         struct misdn_stack *stack;
1281         
1282         for (stack=glob_mgr->stack_list;
1283              stack;
1284              stack=stack->next) {
1285                 if ( (stack->upper_id&STACK_ID_MASK) == (addr&STACK_ID_MASK)) return stack;
1286
1287         }
1288   
1289         return NULL;
1290 }
1291
1292
1293 struct misdn_stack * find_stack_by_port(int port)
1294 {
1295         struct misdn_stack *stack;
1296   
1297         for (stack=glob_mgr->stack_list;
1298              stack;
1299              stack=stack->next) 
1300                 if (stack->port == port) return stack;
1301   
1302         return NULL;
1303 }
1304
1305 struct misdn_stack * find_stack_by_mgr(manager_t* mgr_nt)
1306 {
1307         struct misdn_stack *stack;
1308   
1309         for (stack=glob_mgr->stack_list;
1310              stack;
1311              stack=stack->next) 
1312                 if ( &stack->mgr == mgr_nt) return stack;
1313   
1314         return NULL;
1315 }
1316
1317 struct misdn_bchannel *find_bc_by_masked_l3id(struct misdn_stack *stack, unsigned long l3id, unsigned long mask)
1318 {
1319         int i;
1320         for (i=0; i<stack->b_num; i++) {
1321                 if ( (stack->bc[i].l3_id & mask)  ==  (l3id & mask)) return &stack->bc[i] ;
1322         }
1323         return stack_holder_find(stack,l3id);
1324 }
1325
1326
1327 struct misdn_bchannel *find_bc_by_l3id(struct misdn_stack *stack, unsigned long l3id)
1328 {
1329         int i;
1330         for (i=0; i<stack->b_num; i++) {
1331                 if (stack->bc[i].l3_id == l3id) return &stack->bc[i] ;
1332         }
1333         return stack_holder_find(stack,l3id);
1334 }
1335
1336 struct misdn_bchannel *find_bc_holded(struct misdn_stack *stack)
1337 {
1338         int i;
1339         for (i=0; i<stack->b_num; i++) {
1340                 if (stack->bc[i].holded ) return &stack->bc[i] ;
1341         }
1342         return NULL;
1343 }
1344
1345
1346 struct misdn_bchannel *find_bc_by_addr(unsigned long addr)
1347 {
1348         struct misdn_stack* stack;
1349         int i;
1350
1351         
1352         for (stack=glob_mgr->stack_list;
1353              stack;
1354              stack=stack->next) {
1355                 
1356                 for (i=0; i< stack->b_num; i++) {
1357
1358                         if ( (stack->bc[i].addr&STACK_ID_MASK)==(addr&STACK_ID_MASK) ||  stack->bc[i].layer_id== addr ) {
1359                                 return &stack->bc[i];
1360                         }
1361                 }
1362                 
1363         }
1364
1365         
1366         return NULL;
1367 }
1368
1369
1370 struct misdn_bchannel *find_bc_by_channel(int port, int channel)
1371 {
1372         struct misdn_stack* stack=find_stack_by_port(port);
1373         int i;
1374
1375         if (!stack) return NULL;        
1376         
1377         for (i=0; i< stack->b_num; i++) {
1378                 if ( stack->bc[i].channel== channel ) {
1379                         return &stack->bc[i];
1380                 }
1381         }
1382                 
1383         return NULL;
1384 }
1385
1386
1387
1388
1389
1390 int handle_event ( struct misdn_bchannel *bc, enum event_e event, iframe_t *frm)
1391 {
1392         struct misdn_stack *stack=get_stack_by_bc(bc);
1393         
1394         if (!stack->nt) {
1395                 
1396                 switch (event) {
1397
1398                 case EVENT_CONNECT_ACKNOWLEDGE:
1399                         
1400                         if ( !misdn_cap_is_speech(bc->capability)) {
1401                                 int ret=setup_bc(bc);
1402                                 if (ret == -EINVAL){
1403                                         cb_log(-1,bc->port,"send_event: setup_bc failed\n");
1404                                 }
1405                         }
1406                         
1407                         manager_bchannel_activate(bc);
1408                         break;
1409                 case EVENT_CONNECT:
1410
1411                         if ( *bc->crypt_key ) {
1412                                 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);
1413                                 manager_ph_control_block(bc,  BF_ENABLE_KEY, bc->crypt_key, strlen(bc->crypt_key) );
1414                         }
1415                 case EVENT_SETUP:
1416                         if (bc->channel>0 && bc->channel<255)
1417                                 set_chan_in_stack(stack, bc->channel);
1418                         break;
1419                 case EVENT_ALERTING:
1420                 case EVENT_PROGRESS:
1421                 case EVENT_PROCEEDING:
1422                 case EVENT_SETUP_ACKNOWLEDGE:
1423                         
1424                 {
1425                         if (bc->channel == 0xff) {
1426                                 bc->channel=find_free_chan_in_stack(stack, 0);
1427                                 if (!bc->channel) {
1428                                         cb_log(-1, stack->port, "Any Channel Requested, but we have no more!!\n");
1429                                         break;
1430                                 }
1431                         } 
1432                         
1433                         if (!stack->nt) {
1434                                 int ret=setup_bc(bc);
1435                                 if (ret == -EINVAL){
1436                                         cb_log(-1,bc->port,"handle_event: setup_bc failed\n");
1437                                         misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
1438                                 }
1439                         }
1440                 }
1441                 
1442                 default:
1443                         break;
1444                 }
1445         } else {    /** NT MODE **/
1446                 
1447         }
1448         return 0;
1449 }
1450
1451 int handle_new_process(struct misdn_stack *stack, iframe_t *frm)
1452 {
1453   
1454         struct misdn_bchannel* bc=misdn_lib_get_free_bc(stack->port, 0);
1455         
1456         
1457         if (!bc) {
1458                 cb_log(-1, stack->port, " --> !! lib: No free channel!\n");
1459                 return -1;
1460         }
1461   
1462         cb_log(7, stack->port, " --> new_process: New L3Id: %x\n",frm->dinfo);
1463         bc->l3_id=frm->dinfo;
1464         
1465         if (mypid>5000) mypid=0;
1466         bc->pid=mypid++;
1467         return 0;
1468 }
1469
1470 int handle_cr ( struct misdn_stack *stack, iframe_t *frm)
1471 {
1472         if (!stack) return -1;
1473   
1474         switch (frm->prim) {
1475         case CC_NEW_CR|INDICATION:
1476                 cb_log(7, stack->port, " --> lib: NEW_CR Ind with l3id:%x on this port.\n",frm->dinfo);
1477                 if (handle_new_process(stack, frm) <0) 
1478                         return -1;
1479                 return 1;
1480         case CC_NEW_CR|CONFIRM:
1481                 return 1;
1482         case CC_NEW_CR|REQUEST:
1483                 return 1;
1484         case CC_RELEASE_CR|REQUEST:
1485                 return 1;
1486         case CC_RELEASE_CR|CONFIRM:
1487                 break;
1488         case CC_RELEASE_CR|INDICATION:
1489                 cb_log(4, stack->port, " --> lib: RELEASE_CR Ind with l3id:%x\n",frm->dinfo);
1490                 {
1491                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, frm->dinfo);
1492                         struct misdn_bchannel dummybc;
1493       
1494                         if (!bc) {
1495                                 cb_log(4, stack->port, " --> Didn't found BC so temporarly creating dummy BC (l3id:%x) on this port.\n", frm->dinfo);
1496                                 memset (&dummybc,0,sizeof(dummybc));
1497                                 dummybc.port=stack->port;
1498                                 dummybc.l3_id=frm->dinfo;
1499                                 bc=&dummybc; 
1500                         }
1501       
1502                         if (bc) {
1503                                 cb_log(4, stack->port, " --> lib: CLEANING UP l3id: %x\n",frm->dinfo);
1504                                 empty_chan_in_stack(stack,bc->channel);
1505                                 empty_bc(bc);
1506                                 clean_up_bc(bc);
1507                                 dump_chan_list(stack);
1508                                 bc->pid = 0;
1509                                 cb_event(EVENT_CLEANUP, bc, glob_mgr->user_data);
1510                                 if (bc->stack_holder) {
1511                                         cb_log(4,stack->port, "REMOVEING Holder\n");
1512                                         stack_holder_remove( stack, bc);
1513                                         free(bc);
1514                                 }
1515                         }
1516                         else {
1517                                 if (stack->nt) 
1518                                         cb_log(4, stack->port, "BC with dinfo: %x  not found.. (prim was %x and addr %x)\n",frm->dinfo, frm->prim, frm->addr);
1519                         }
1520       
1521                         return 1;
1522                 }
1523                 break;
1524         }
1525   
1526         return 0;
1527 }
1528
1529
1530 /*Emptys bc if it's reserved (no SETUP out yet)*/
1531 void misdn_lib_release(struct misdn_bchannel *bc)
1532 {
1533         struct misdn_stack *stack=get_stack_by_bc(bc);
1534
1535         if (!stack) {
1536                 cb_log(1,0,"misdn_release: No Stack found\n");
1537                 return;
1538         }
1539         
1540         if (bc->channel>=0) {
1541                 empty_chan_in_stack(stack,bc->channel);
1542                 empty_bc(bc);
1543         }
1544         clean_up_bc(bc);
1545 }
1546
1547
1548
1549
1550 int misdn_lib_get_port_up (int port) 
1551 { /* Pull Up L1 */ 
1552         struct misdn_stack *stack;
1553         
1554         for (stack=glob_mgr->stack_list;
1555              stack;
1556              stack=stack->next) {
1557                 
1558                 if (stack->port == port) {
1559
1560                         if (!stack->l1link)
1561                                 misdn_lib_get_l1_up(stack);
1562                         if (!stack->l2link)
1563                                 misdn_lib_get_l2_up(stack);
1564                         
1565                         return 0;
1566                 }
1567         }
1568         return 0;
1569 }
1570
1571
1572 int misdn_lib_get_port_down (int port) 
1573 { /* Pull Down L1 */ 
1574         struct misdn_stack *stack;
1575         for (stack=glob_mgr->stack_list;
1576              stack;
1577              stack=stack->next) {
1578                 if (stack->port == port) {
1579                                 if (stack->l2link)
1580                                         misdn_lib_get_l2_down(stack);
1581                                 misdn_lib_get_l1_down(stack);
1582                         return 0;
1583                 }
1584         }
1585         return 0;
1586 }
1587
1588 int misdn_lib_send_facility(struct misdn_bchannel *bc, enum facility_type fac, void *data)
1589 {
1590         switch (fac) {
1591         case FACILITY_CALLDEFLECT:
1592                 strcpy(bc->out_fac.calldeflect_nr,(char*)data);
1593                 break;
1594         default:
1595                 cb_log(1,bc?bc->port:0,"We don't handle this facility yet: %d\n",fac);
1596                 return 0;
1597         }
1598         
1599         bc->out_fac_type=fac;
1600         
1601         misdn_lib_send_event(bc,EVENT_FACILITY);
1602         return 0;
1603 }
1604
1605
1606 int misdn_lib_port_up(int port, int check)
1607 {
1608         struct misdn_stack *stack;
1609
1610
1611         for (stack=glob_mgr->stack_list;
1612              stack;
1613              stack=stack->next) {
1614                 
1615                 if ( !stack->ptp && !check) return 1;
1616                 
1617                 if (stack->port == port) {
1618                         if (stack->l1link)
1619                                 return 1;
1620                         else {
1621                                 cb_log(-1,port, "Port down [%s]\n",
1622                                        stack->ptp?"PP":"PMP");
1623                                 return 0;
1624                         }
1625                 }
1626         }
1627   
1628         return -1;
1629 }
1630
1631
1632 int
1633 handle_event_nt(void *dat, void *arg)
1634 {
1635         manager_t *mgr = (manager_t *)dat;
1636         msg_t *msg = (msg_t *)arg;
1637         mISDNuser_head_t *hh;
1638         int reject=0;
1639
1640         struct misdn_stack *stack=find_stack_by_mgr(mgr);
1641         int port;
1642
1643         if (!msg || !mgr)
1644                 return(-EINVAL);
1645
1646         hh=(mISDNuser_head_t*)msg->data;
1647         port=stack->port;
1648         
1649         cb_log(4, stack->port, " --> lib: prim %x dinfo %x\n",hh->prim, hh->dinfo);
1650         {
1651                 switch(hh->prim){
1652                 case CC_RETRIEVE|INDICATION:
1653                 {
1654                         iframe_t frm; /* fake te frm to add callref to global callreflist */
1655                         frm.dinfo = hh->dinfo;
1656
1657                         frm.addr=stack->upper_id | FLG_MSG_DOWN;
1658
1659                         frm.prim = CC_NEW_CR|INDICATION;
1660                         
1661                         if (handle_cr( stack, &frm)< 0) {
1662                                 msg_t *dmsg;
1663                                 cb_log(4, stack->port, "Patch from MEIDANIS:Sending RELEASE_COMPLETE %x (No free Chan for you..)\n", hh->dinfo);
1664                                 dmsg = create_l3msg(CC_RELEASE_COMPLETE | REQUEST,MT_RELEASE_COMPLETE, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1665                                 stack->nst.manager_l3(&stack->nst, dmsg);
1666                                 free_msg(msg);
1667                                 return 0;
1668                         }
1669                         
1670                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1671                         cb_event(EVENT_NEW_BC, bc, glob_mgr->user_data);
1672                         struct misdn_bchannel *hold_bc=stack_holder_find(stack,bc->l3_id);
1673                         if (hold_bc) {
1674                                 cb_log(4, stack->port, "REMOVEING Holder\n");
1675                                 stack_holder_remove(stack, hold_bc);
1676                                 free(hold_bc);
1677                         }
1678                         
1679                 }
1680                         
1681                         break;
1682                         
1683                 case CC_SETUP|CONFIRM:
1684                 {
1685                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1686                         int l3id = *((int *)(((u_char *)msg->data)+ mISDNUSER_HEAD_SIZE));
1687                         cb_log(4, stack->port, " --> lib: Event_ind:SETUP CONFIRM [NT] : new L3ID  is %x\n",l3id );
1688         
1689                         if (!bc) { cb_log(4, stack->port, "Bc Not found (after SETUP CONFIRM)\n"); return 0; }
1690                         cb_log (2,bc->port,"I IND :CC_SETUP|CONFIRM: old l3id:%x new l3id:%x\n", bc->l3_id, l3id);
1691                         bc->l3_id=l3id;
1692                         cb_event(EVENT_NEW_L3ID, bc, glob_mgr->user_data);
1693                 }
1694                 free_msg(msg);
1695                 return 0;
1696       
1697                 case CC_SETUP|INDICATION:
1698                 {
1699                         iframe_t frm; /* fake te frm to add callref to global callreflist */
1700                         frm.dinfo = hh->dinfo;
1701                         frm.addr=stack->upper_id;
1702                         frm.prim = CC_NEW_CR|INDICATION;
1703                         
1704                         if (handle_cr(stack, &frm)< 0) {
1705                                 msg_t *dmsg;
1706                                 cb_log(4, stack->port, "Patch from MEIDANIS:Sending RELEASE_COMPLETE %x (No free Chan for you..)\n", hh->dinfo);
1707                                 dmsg = create_l3msg(CC_RELEASE_COMPLETE | REQUEST,MT_RELEASE_COMPLETE, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1708                                 stack->nst.manager_l3(&stack->nst, dmsg);
1709                                 free_msg(msg);
1710                                 return 0;
1711                         }
1712                 }
1713                 break;
1714
1715                 case CC_CONNECT_ACKNOWLEDGE|INDICATION:
1716 #if 0
1717                 {
1718                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1719                         if (bc) {
1720                                 if ( !misdn_cap_is_speech(bc->capability)) {
1721                                         int ret=setup_bc(bc);
1722                                         if (ret == -EINVAL){
1723                                                 cb_log(-1,bc->port,"send_event: setup_bc failed\n");
1724                                                 
1725                                         }
1726                                 }
1727                                 
1728                                 manager_bchannel_activate(bc);
1729                         }
1730                 }
1731 #endif
1732                 break;
1733                 
1734                 case CC_CONNECT|INDICATION:
1735                 case CC_ALERTING|INDICATION:
1736                 case CC_PROCEEDING|INDICATION:
1737                 case CC_SETUP_ACKNOWLEDGE|INDICATION:
1738
1739                 {
1740                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1741                         
1742                         if (!bc) {
1743                                 msg_t *dmsg;
1744                                 cb_log(-1, stack->port,"!!!! We didn't found our bc, dinfo:%x on this port.\n",hh->dinfo);
1745                                 
1746                                 cb_log(-1, stack->port, "Releaseing call %x (No free Chan for you..)\n", hh->dinfo);
1747                                 dmsg = create_l3msg(CC_RELEASE_COMPLETE | REQUEST,MT_RELEASE_COMPLETE, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1748                                 stack->nst.manager_l3(&stack->nst, dmsg);
1749                                 free_msg(msg);
1750                                 return 0;
1751                                 
1752                         }
1753                         int ret=setup_bc(bc);
1754                         if (ret == -EINVAL){
1755                                 cb_log(-1,bc->port,"handle_event_nt: setup_bc failed\n");
1756                                 misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
1757                         }
1758                 }
1759                 break;
1760                 case CC_DISCONNECT|INDICATION:
1761                 {
1762                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1763                         if (!bc) {
1764                                 bc=find_bc_by_masked_l3id(stack, hh->dinfo, 0xffff0000);
1765                                 if (bc) { 
1766                                         int myprocid=bc->l3_id&0x0000ffff;
1767                                         hh->dinfo=(hh->dinfo&0xffff0000)|myprocid;
1768                                         cb_log(3,stack->port,"Reject dinfo: %x cause:%d\n",hh->dinfo,bc->cause);
1769                                         reject=1;               
1770                                 }
1771                         }
1772                 }
1773                 break;
1774                 
1775                 case CC_FACILITY|INDICATION:
1776                 {
1777                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1778                         if (!bc) {
1779                                 bc=find_bc_by_masked_l3id(stack, hh->dinfo, 0xffff0000);
1780                                 if (bc) { 
1781                                         int myprocid=bc->l3_id&0x0000ffff;
1782                                         hh->dinfo=(hh->dinfo&0xffff0000)|myprocid;
1783                                         cb_log(4,bc->port,"Repaired reject Bug, new dinfo: %x\n",hh->dinfo);
1784                                 }
1785                         }
1786                 }
1787                 break;
1788                 
1789                 case CC_RELEASE_COMPLETE|INDICATION:
1790                         break;
1791
1792                 case CC_SUSPEND|INDICATION:
1793                 {
1794                         msg_t *dmsg;
1795                         cb_log(4, stack->port, " --> Got Suspend, sending Reject for now\n");
1796                         dmsg = create_l3msg(CC_SUSPEND_REJECT | REQUEST,MT_SUSPEND_REJECT, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1797                         stack->nst.manager_l3(&stack->nst, dmsg);
1798                         free_msg(msg);
1799                         return 0;
1800                 }
1801                 break;
1802                 case CC_RESUME|INDICATION:
1803                         break;
1804
1805                 case CC_RELEASE|CONFIRM:
1806                         break;
1807                         
1808                 case CC_RELEASE|INDICATION:
1809                         break;
1810
1811                 case CC_RELEASE_CR|INDICATION:
1812                 {
1813                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1814                         struct misdn_bchannel dummybc;
1815                         iframe_t frm; /* fake te frm to remove callref from global callreflist */
1816                         frm.dinfo = hh->dinfo;
1817
1818                         frm.addr=stack->upper_id | FLG_MSG_DOWN;
1819
1820                         frm.prim = CC_RELEASE_CR|INDICATION;
1821                         cb_log(4, stack->port, " --> Faking Realease_cr for %x\n",frm.addr);
1822                         /** removing procid **/
1823                         if (!bc) {
1824                                 cb_log(4, stack->port, " --> Didn't found BC so temporarly creating dummy BC (l3id:%x) on this port.\n", hh->dinfo);
1825                                 memset (&dummybc,0,sizeof(dummybc));
1826                                 dummybc.port=stack->port;
1827                                 dummybc.l3_id=hh->dinfo;
1828                                 bc=&dummybc; 
1829                         }
1830         
1831                         if (bc) {
1832                                 if ( (bc->l3_id & 0xff00) == 0xff00) {
1833                                         cb_log(4, stack->port, " --> Removing Process Id:%x on this port.\n", bc->l3_id&0xff);
1834                                         stack->procids[bc->l3_id&0xff] = 0 ;
1835                                 }
1836                         }
1837                         else cb_log(-1, stack->port, "Couldnt find BC so I couldnt remove the Process!!!! this is a bad port.\n");
1838         
1839                         handle_cr(stack, &frm);
1840                         free_msg(msg);
1841                         return 0 ;
1842                 }
1843                 break;
1844       
1845                 case CC_NEW_CR|INDICATION:
1846                         /*  Got New CR for bchan, for now I handle this one in */
1847                         /*  connect_ack, Need to be changed */
1848                 {
1849                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1850                         int l3id = *((int *)(((u_char *)msg->data)+ mISDNUSER_HEAD_SIZE));
1851                         if (!bc) { cb_log(-1, stack->port, " --> In NEW_CR: didn't found bc ??\n"); return -1;};
1852                         if (((l3id&0xff00)!=0xff00) && ((bc->l3_id&0xff00)==0xff00)) {
1853                                 cb_log(4, stack->port, " --> Removing Process Id:%x on this port.\n", 0xff&bc->l3_id);
1854                                 stack->procids[bc->l3_id&0xff] = 0 ;
1855                         }
1856                         cb_log(4, stack->port, "lib: Event_ind:CC_NEW_CR : very new L3ID  is %x\n",l3id );
1857         
1858                         bc->l3_id =l3id;
1859                         cb_event(EVENT_NEW_L3ID, bc, glob_mgr->user_data);
1860         
1861                         free_msg(msg);
1862                         return 0;
1863                 }
1864       
1865                 case DL_ESTABLISH | INDICATION:
1866                 case DL_ESTABLISH | CONFIRM:
1867                 {
1868                         cb_log(4, stack->port, "%% GOT L2 Activate Info.\n");
1869                         stack->l2link = 1;
1870                         
1871                         free_msg(msg);
1872                         return 0;
1873                 }
1874                 break;
1875
1876                 case DL_RELEASE | INDICATION:
1877                 case DL_RELEASE | CONFIRM:
1878                 {
1879                         cb_log(4, stack->port, "%% GOT L2 DeActivate Info.\n");
1880                         stack->l2link = 0;
1881                         
1882                         free_msg(msg);
1883                         return 0;
1884                 }
1885                 break;
1886                 }
1887         }
1888         
1889         {
1890                 /*  Parse Events and fire_up to App. */
1891                 struct misdn_bchannel *bc;
1892                 struct misdn_bchannel dummybc;
1893                 
1894                 enum event_e event = isdn_msg_get_event(msgs_g, msg, 1);
1895     
1896                 bc=find_bc_by_l3id(stack, hh->dinfo);
1897     
1898                 if (!bc) {
1899       
1900                         cb_log(4, stack->port, " --> Didn't found BC so temporarly creating dummy BC (l3id:%x).\n", hh->dinfo);
1901                         memset (&dummybc,0,sizeof(dummybc));
1902                         dummybc.port=stack->port;
1903                         dummybc.l3_id=hh->dinfo;
1904                         bc=&dummybc; 
1905                 }
1906                 if (bc ) {
1907                         isdn_msg_parse_event(msgs_g,msg,bc, 1);
1908                         
1909                         if(!isdn_get_info(msgs_g,event,1)) {
1910                                 cb_log(4, stack->port, "Unknown Event Ind: prim %x dinfo %x\n",hh->prim, hh->dinfo);
1911                         } else {
1912                                 if (reject) {
1913                                         switch(bc->cause){
1914                                                 case 17:
1915                                                         cb_log(1, stack->port, "Siemens Busy reject..\n");
1916
1917                                                         break;
1918                                                 default:
1919                                                         return 0;
1920                                         }
1921                                 }
1922                                 cb_event(event, bc, glob_mgr->user_data);
1923                         }
1924       
1925                 } else {
1926                         cb_log(4, stack->port, "No BC found with l3id: prim %x dinfo %x\n",hh->prim, hh->dinfo);
1927                 }
1928
1929                 free_msg(msg);
1930         }
1931
1932
1933         return 0;
1934 }
1935
1936
1937 int handle_timers(msg_t* msg)
1938 {
1939         iframe_t *frm= (iframe_t*)msg->data;
1940         struct misdn_stack *stack; 
1941   
1942         /* Timer Stuff */
1943         switch (frm->prim) {
1944         case MGR_INITTIMER | CONFIRM:
1945         case MGR_ADDTIMER | CONFIRM:
1946         case MGR_DELTIMER | CONFIRM:
1947         case MGR_REMOVETIMER | CONFIRM:
1948                 free_msg(msg);
1949                 return(1);
1950         }
1951   
1952   
1953   
1954         if (frm->prim==(MGR_TIMER | INDICATION) ) {
1955                 for (stack = glob_mgr->stack_list;
1956                      stack;
1957                      stack = stack->next) {
1958                         itimer_t *it;
1959       
1960                         if (!stack->nt) continue;
1961       
1962                         it = stack->nst.tlist;
1963                         /* find timer */
1964                         for(it=stack->nst.tlist;
1965                             it;
1966                             it=it->next) {
1967                                 if (it->id == (int)frm->addr)
1968                                         break;
1969                         }
1970                         if (it) {
1971                                 int ret;
1972                                 ret = mISDN_write_frame(stack->midev, msg->data, frm->addr,
1973                                                         MGR_TIMER | RESPONSE, 0, 0, NULL, TIMEOUT_1SEC);
1974                                 test_and_clear_bit(FLG_TIMER_RUNING, (long unsigned int *)&it->Flags);
1975                                 ret = it->function(it->data);
1976                                 free_msg(msg);
1977                                 return 1;
1978                         }
1979                 }
1980     
1981                 cb_log(-1, 0, "Timer Msg without Timer ??\n");
1982                 free_msg(msg);
1983                 return 1;
1984         }
1985   
1986         return 0;
1987 }
1988
1989
1990
1991 void misdn_lib_tone_generator_start(struct misdn_bchannel *bc)
1992 {
1993         bc->generate_tone=1;
1994 }
1995
1996 void misdn_lib_tone_generator_stop(struct misdn_bchannel *bc)
1997 {
1998         bc->generate_tone=0;
1999 }
2000
2001
2002 static int do_tone(struct misdn_bchannel *bc, int len)
2003 {
2004         bc->tone_cnt=len;
2005         
2006         if (bc->generate_tone) {
2007                 cb_event(EVENT_TONE_GENERATE, bc, glob_mgr->user_data);
2008
2009                 if ( !bc->nojitter ) {
2010                         misdn_tx_jitter(bc,len);
2011                 }
2012                 
2013                 return 1;
2014         }
2015         
2016         return 0;
2017 }
2018
2019
2020
2021 void misdn_tx_jitter(struct misdn_bchannel *bc, int len)
2022 {
2023         char buf[4096 + mISDN_HEADER_LEN];
2024         iframe_t *txfrm= (iframe_t*)buf;
2025         int jlen, r;
2026         
2027         jlen=cb_jb_empty(bc,&buf[mISDN_HEADER_LEN],len);
2028         
2029         if (jlen) {
2030                 
2031                 if (jlen < len) {
2032                         cb_log(5,bc->port,"Jitterbuffer Underrun.\n");
2033                 }
2034                 
2035                 txfrm->prim = DL_DATA|REQUEST;
2036                 
2037                 txfrm->dinfo = 0;
2038                 
2039                 txfrm->addr = bc->addr|FLG_MSG_DOWN; /*  | IF_DOWN; */
2040                 
2041                 txfrm->len =jlen;
2042                 cb_log(9, bc->port, "Transmitting %d samples 2 misdn\n", txfrm->len);
2043                 
2044                 r=mISDN_write( glob_mgr->midev, buf, txfrm->len + mISDN_HEADER_LEN, 8000 );
2045         }
2046 }
2047
2048 int handle_bchan(msg_t *msg)
2049 {
2050         iframe_t *frm= (iframe_t*)msg->data;
2051         struct misdn_bchannel *bc;
2052
2053         bc=find_bc_by_addr(frm->addr);
2054         
2055         if (!bc) {
2056                 cb_log(0,0,"handle_bchan: BC not found for prim:%x with addr:%x dinfo:%x\n", frm->prim, frm->addr, frm->dinfo);
2057                 return 0 ;
2058         }
2059         
2060         struct misdn_stack *stack=get_stack_by_bc(bc);
2061         
2062         if (!stack) {
2063                 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);
2064                 return 0;
2065         }
2066         
2067         switch (frm->prim) {
2068
2069         case MGR_SETSTACK| CONFIRM:
2070                 cb_log(2, stack->port, "BCHAN: MGR_SETSTACK|CONFIRM \n");
2071                 break;
2072                 
2073         case MGR_SETSTACK| INDICATION:
2074                 cb_log(2, stack->port, "BCHAN: MGR_SETSTACK|IND \n");
2075                 
2076                 bc->addr = mISDN_get_layerid(stack->midev, bc->b_stid, bc->layer);
2077                 if (!bc->addr) {
2078                         cb_log(0,stack->port,"$$$ Get Layer (%d) Id Error: %s\n",bc->layer,strerror(errno));
2079
2080                         /* we kill the channel later, when we received some
2081                            data. */
2082                         bc->addr= frm->addr;
2083                 }
2084                 
2085                 cb_log(4, stack->port," --> Got Adr %x\n", bc->addr);
2086
2087                 free_msg(msg);
2088                 
2089                 if (bc->bc_state !=  BCHAN_SETUP) {
2090                         cb_log(4, stack->port," --> STATE WASN'T SETUP in SETSTACK|IND\n");
2091                 }
2092                 
2093                 bc_state_change(bc,BCHAN_SETUPED);
2094                 
2095                 
2096                 manager_bchannel_activate(bc);
2097                                 
2098                 return 1;
2099
2100         case MGR_DELLAYER| INDICATION:
2101                 cb_log(2, stack->port, "BCHAN: MGR_DELLAYER|IND\n");
2102                 break;
2103                 
2104         case MGR_DELLAYER| CONFIRM:
2105                 cb_log(2, stack->port, "BCHAN: MGR_DELLAYER|CNF \n");
2106                 
2107                 bc_state_change(bc,BCHAN_CLEANED);
2108                 
2109                 free_msg(msg);
2110                 return 1;
2111                 
2112         case PH_ACTIVATE | INDICATION:
2113         case DL_ESTABLISH | INDICATION:
2114                 cb_log(4, stack->port, "BCHAN: ACT Ind\n");
2115
2116                 bc_state_change(bc,BCHAN_ACTIVATED);
2117                 
2118                 free_msg(msg);
2119                 return 1;    
2120
2121         case PH_ACTIVATE | CONFIRM:
2122         case DL_ESTABLISH | CONFIRM:
2123                 
2124                 bc_state_change(bc,BCHAN_ACTIVATED);
2125                 
2126                 cb_log(4, stack->port, "BCHAN: bchan ACT Confirm\n");
2127                 free_msg(msg);
2128                 
2129                 return 1;    
2130                 
2131         case PH_DEACTIVATE | INDICATION:
2132         case DL_RELEASE | INDICATION:
2133                 cb_log (4, stack->port, "BCHAN: DeACT Ind\n");
2134                 
2135                 bc_state_change(bc,BCHAN_RELEASED);
2136                 free_msg(msg);
2137                 return 1;
2138     
2139         case PH_DEACTIVATE | CONFIRM:
2140         case DL_RELEASE | CONFIRM:
2141                 cb_log(4, stack->port, "BCHAN: DeACT Conf\n");
2142                 
2143                 bc_state_change(bc,BCHAN_RELEASED);
2144                 free_msg(msg);
2145                 return 1;
2146     
2147         case PH_CONTROL|INDICATION:
2148         {
2149                 unsigned int cont = *((unsigned int *)&frm->data.p);
2150                 
2151                 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);
2152
2153                 if ((cont&~DTMF_TONE_MASK) == DTMF_TONE_VAL) {
2154                         int dtmf = cont & DTMF_TONE_MASK;
2155                         cb_log(4, stack->port, " --> DTMF TONE: %c\n",dtmf);
2156                         bc->dtmf=dtmf;
2157                         cb_event(EVENT_DTMF_TONE, bc, glob_mgr->user_data);
2158         
2159                         free_msg(msg);
2160                         return 1;
2161                 }
2162                 if (cont == BF_REJECT) {
2163                         cb_log(4, stack->port, " --> BF REJECT\n");
2164                         free_msg(msg);
2165                         return 1;
2166                 }
2167                 if (cont == BF_ACCEPT) {
2168                         cb_log(4, stack->port, " --> BF ACCEPT\n");
2169                         free_msg(msg);
2170                         return 1;
2171                 }
2172         }
2173         break;
2174
2175         case PH_DATA|REQUEST:
2176         case DL_DATA|REQUEST:
2177                 cb_log(0, stack->port, "DL_DATA REQUEST \n");
2178                 do_tone(bc, 64);
2179                 
2180                 free_msg(msg);
2181                 return 1;
2182                 
2183         case PH_DATA|INDICATION:
2184         case DL_DATA|INDICATION:
2185         {
2186                 bc->bframe = (void*)&frm->data.i;
2187                 bc->bframe_len = frm->len;
2188
2189                 /** Anyway flip the bufbits **/
2190                 if ( misdn_cap_is_speech(bc->capability) ) 
2191                         flip_buf_bits(bc->bframe, bc->bframe_len);
2192         
2193
2194                 if (!bc->bframe_len) {
2195                         cb_log(2, stack->port, "DL_DATA INDICATION bc->addr:%x frm->addr:%x\n", bc->addr, frm->addr);
2196                         free_msg(msg);
2197                         return 1;
2198                 }
2199
2200                 if ( (bc->addr&STACK_ID_MASK) != (frm->addr&STACK_ID_MASK) ) {
2201                         cb_log(2, stack->port, "DL_DATA INDICATION bc->addr:%x frm->addr:%x\n", bc->addr, frm->addr);
2202                         free_msg(msg);
2203                         return 1;
2204                 }
2205                 
2206 #if MISDN_DEBUG
2207                 cb_log(-1, stack->port, "DL_DATA INDICATION Len %d\n", frm->len);
2208
2209 #endif
2210                 
2211                 if ( (bc->bc_state == BCHAN_ACTIVATED) && frm->len > 0) {
2212                         if (  !do_tone(bc, frm->len)   ) {
2213                                 
2214                                 if ( misdn_cap_is_speech(bc->capability)) {
2215                                         if ( !bc->nojitter ) {
2216                                                 misdn_tx_jitter(bc,frm->len);
2217                                         }
2218                                 }
2219                                 
2220                                 int i=cb_event( EVENT_BCHAN_DATA, bc, glob_mgr->user_data);
2221                                 if (i<0) {
2222                                         cb_log(10,stack->port,"cb_event returned <0\n");
2223                                         /*clean_up_bc(bc);*/
2224                                 }
2225                         }
2226                 }
2227                 free_msg(msg);
2228                 return 1;
2229         }
2230
2231
2232         case PH_CONTROL | CONFIRM:
2233                 cb_log(2, stack->port, "PH_CONTROL|CNF bc->addr:%x\n", frm->addr);
2234                 free_msg(msg);
2235                 return 1;
2236
2237         case PH_DATA | CONFIRM:
2238         case DL_DATA|CONFIRM:
2239 #if MISDN_DEBUG
2240
2241                 cb_log(-1, stack->port, "Data confirmed\n");
2242
2243 #endif
2244                 free_msg(msg);
2245                 
2246                 return 1;
2247         case DL_DATA|RESPONSE:
2248 #if MISDN_DEBUG
2249                 cb_log(-1, stack->port, "Data response\n");
2250
2251 #endif
2252                 break;
2253         }
2254   
2255         return 0;
2256 }
2257
2258
2259
2260 int handle_frm_nt(msg_t *msg)
2261 {
2262         iframe_t *frm= (iframe_t*)msg->data;
2263         struct misdn_stack *stack;
2264         int err=0;
2265
2266         stack=find_stack_by_addr( frm->addr );
2267
2268         
2269   
2270         if (!stack || !stack->nt) {
2271                 return 0;
2272         }
2273   
2274         if ((err=stack->nst.l1_l2(&stack->nst,msg))) {
2275     
2276                 if (nt_err_cnt > 0 ) {
2277                         if (nt_err_cnt < 100) {
2278                                 nt_err_cnt++; 
2279                                 cb_log(-1, stack->port, "NT Stack sends us error: %d \n", err);
2280                         } else if (nt_err_cnt < 105){
2281                                 cb_log(-1, stack->port, "NT Stack sends us error: %d over 100 times, so I'll stop this message\n", err);
2282                                 nt_err_cnt = - 1; 
2283                         }
2284                 }
2285                 free_msg(msg);
2286                 return 1;
2287                 
2288         }
2289         
2290         return 1;
2291 }
2292
2293
2294 int handle_frm(msg_t *msg)
2295 {
2296         iframe_t *frm = (iframe_t*) msg->data;
2297         
2298         struct misdn_stack *stack=find_stack_by_addr(frm->addr);
2299
2300         
2301         cb_log(4,stack?stack->port:0,"handle_frm: frm->addr:%x frm->prim:%x\n",frm->addr,frm->prim);
2302         
2303   
2304         if (!stack || stack->nt) {
2305                 return 0;
2306         }
2307
2308         {
2309                 struct misdn_bchannel *bc;
2310                 int ret=handle_cr(stack, frm);
2311
2312                 if (ret<0) {
2313                         cb_log(3,stack?stack->port:0,"handle_frm: handle_cr <0 prim:%x addr:%x\n", frm->prim, frm->addr);
2314                 }
2315
2316                 if(ret) {
2317                         free_msg(msg);
2318                         return 1;
2319                 }
2320     
2321                 bc=find_bc_by_l3id(stack, frm->dinfo);
2322     
2323                 if (bc ) {
2324                         enum event_e event = isdn_msg_get_event(msgs_g, msg, 0);
2325                         enum event_response_e response=RESPONSE_OK;
2326       
2327                         isdn_msg_parse_event(msgs_g,msg,bc, 0);
2328                         
2329                         /** Preprocess some Events **/
2330                         handle_event(bc, event, frm);
2331                         /*  shoot up event to App: */
2332                         cb_log(5, stack->port, "lib Got Prim: Addr %x prim %x dinfo %x\n",frm->addr, frm->prim, frm->dinfo);
2333       
2334                         if(!isdn_get_info(msgs_g,event,0)) 
2335                                 cb_log(-1, stack->port, "Unknown Event Ind: Addr:%x prim %x dinfo %x\n",frm->addr, frm->prim, frm->dinfo);
2336                         else 
2337                                 response=cb_event(event, bc, glob_mgr->user_data);
2338 #if 1
2339                         if (event == EVENT_SETUP) {
2340                                 switch (response) {
2341                                 case RESPONSE_IGNORE_SETUP_WITHOUT_CLOSE:
2342
2343                                         cb_log(-1, stack->port, "TOTALY IGNORING SETUP \n");                                    
2344                                         
2345                                         break;
2346                                 case RESPONSE_IGNORE_SETUP:
2347                                         /* I think we should send CC_RELEASE_CR, but am not sure*/
2348                                         empty_chan_in_stack(stack, bc->channel);
2349                                         empty_bc(bc);
2350                                         cb_log(-1, stack->port, "GOT IGNORE SETUP\n");
2351
2352                                         
2353                                         break;
2354                                 case RESPONSE_OK:
2355                                         cb_log(4, stack->port, "GOT SETUP OK\n");
2356
2357                                         
2358                                         break;
2359                                 default:
2360                                         break;
2361                                 }
2362                         }
2363
2364                         cb_log(5, stack->port, "Freeing Msg on prim:%x \n",frm->prim);
2365
2366                         
2367                         free_msg(msg);
2368                         return 1;
2369 #endif
2370       
2371                 } else {
2372                         cb_log(-1, stack->port, "NO BC FOR STACK\n");           
2373                 }
2374         }
2375
2376         cb_log(4, stack->port, "TE_FRM_HANDLER: Returning 0 on prim:%x \n",frm->prim);
2377         return 0;
2378 }
2379
2380
2381 int handle_l1(msg_t *msg)
2382 {
2383         iframe_t *frm = (iframe_t*) msg->data;
2384         struct misdn_stack *stack = find_stack_by_addr(frm->addr);
2385         int i ;
2386         
2387         if (!stack) return 0 ;
2388   
2389         switch (frm->prim) {
2390         case PH_ACTIVATE | CONFIRM:
2391         case PH_ACTIVATE | INDICATION:
2392                 cb_log (1, stack->port, "L1: PH L1Link Up!\n");
2393                 stack->l1link=1;
2394                 
2395                 if (stack->nt) {
2396                         
2397                         if (stack->nst.l1_l2(&stack->nst, msg))
2398                                 free_msg(msg);
2399                 } else {
2400                         free_msg(msg);
2401                 }
2402                 
2403                 for (i=0;i<stack->b_num; i++) {
2404                         if (stack->bc[i].evq != EVENT_NOTHING) {
2405                                 cb_log(4, stack->port, "Fireing Queued Event %s because L1 got up\n", isdn_get_info(msgs_g, stack->bc[i].evq, 0));
2406                                 misdn_lib_send_event(&stack->bc[i],stack->bc[i].evq);
2407                                 stack->bc[i].evq=EVENT_NOTHING;
2408                         }
2409                         
2410                 }
2411                 return 1;
2412
2413         case PH_ACTIVATE | REQUEST:
2414                 free_msg(msg);
2415                 cb_log(1,stack->port,"L1: PH_ACTIVATE|REQUEST \n");
2416                 return 1;
2417                 
2418         case PH_DEACTIVATE | REQUEST:
2419                 free_msg(msg);
2420                 cb_log(1,stack->port,"L1: PH_DEACTIVATE|REQUEST \n");
2421                 return 1;
2422                 
2423         case PH_DEACTIVATE | CONFIRM:
2424         case PH_DEACTIVATE | INDICATION:
2425                 cb_log (1, stack->port, "L1: PH L1Link Down! \n");
2426                 
2427                 for (i=0; i<stack->b_num; i++) {
2428                         if (global_state == MISDN_INITIALIZED)  {
2429                                 cb_event(EVENT_CLEANUP, &stack->bc[i], glob_mgr->user_data);
2430                         }
2431                 }
2432                 
2433                 if (stack->nt) {
2434                         if (stack->nst.l1_l2(&stack->nst, msg))
2435                                 free_msg(msg);
2436                 } else {
2437                         free_msg(msg);
2438                 }
2439                 
2440                 stack->l1link=0;
2441                 stack->l2link=0;
2442                 
2443                 return 1;
2444         }
2445   
2446         return 0;
2447 }
2448
2449 int handle_l2(msg_t *msg)
2450 {
2451         iframe_t *frm = (iframe_t*) msg->data;
2452
2453         struct misdn_stack *stack = find_stack_by_addr(frm->addr);
2454         
2455         if (!stack) {
2456                 return 0 ;
2457         }
2458         
2459         switch(frm->prim) {
2460
2461         case DL_ESTABLISH | REQUEST:
2462                 cb_log(1,stack->port,"DL_ESTABLISH|REQUEST \n");
2463                 return 1;
2464         case DL_RELEASE | REQUEST:
2465                 cb_log(1,stack->port,"DL_RELEASE|REQUEST \n");
2466                 return 1;
2467                 
2468         case DL_ESTABLISH | INDICATION:
2469         case DL_ESTABLISH | CONFIRM:
2470         {
2471                 cb_log (3, stack->port, "L2: L2Link Up! \n");
2472                 stack->l2link=1;
2473                 free_msg(msg);
2474                 return 1;
2475         }
2476         break;
2477     
2478         case DL_RELEASE | INDICATION:
2479         case DL_RELEASE | CONFIRM:
2480         {
2481                 cb_log (3, stack->port, "L2: L2Link Down! \n");
2482                 stack->l2link=0;
2483                 
2484                 free_msg(msg);
2485                 return 1;
2486         }
2487         break;
2488         }
2489         return 0;
2490 }
2491
2492 int handle_mgmt(msg_t *msg)
2493 {
2494         iframe_t *frm = (iframe_t*) msg->data;
2495
2496         if ( (frm->addr == 0) && (frm->prim == (MGR_DELLAYER|CONFIRM)) ) {
2497                 cb_log(2, 0, "MGMT: DELLAYER|CONFIRM Addr: 0 !\n") ;
2498                 free(msg);
2499                 return 1;
2500         }
2501         
2502         struct misdn_stack * stack=find_stack_by_addr(frm->addr);
2503         
2504         if (!stack) {
2505                 if (frm->prim == (MGR_DELLAYER|CONFIRM)) {
2506                         cb_log(2, 0, "MGMT: DELLAYER|CONFIRM Addr: %x !\n",
2507                                         frm->addr) ;
2508                         free(msg);
2509                         return 1;
2510                 }
2511                 
2512                 return 0;
2513         }
2514         
2515         switch(frm->prim) {
2516         case MGR_SHORTSTATUS | INDICATION:
2517         case MGR_SHORTSTATUS | CONFIRM:
2518                 cb_log(2, 0, "MGMT: Short status dinfo %x\n",frm->dinfo);
2519                 
2520                 switch (frm->dinfo) {
2521                 case SSTATUS_L1_ACTIVATED:
2522                         cb_log(1, 0, "MGMT: SSTATUS: L1_ACTIVATED \n");
2523                         stack->l1link=1;
2524                 
2525                         break;
2526                 case SSTATUS_L1_DEACTIVATED:
2527                         cb_log(1, 0, "MGMT: SSTATUS: L1_DEACTIVATED \n");
2528
2529                         /*reopen L1 if down*/
2530                         if (stack->l1link==2)
2531                                 stack->l1link--;
2532                         else                    
2533                                 stack->l1link=0;
2534                         
2535                         break;
2536
2537                 case SSTATUS_L2_ESTABLISHED:
2538                         cb_log(1, stack->port, "MGMT: SSTATUS: L2_ESTABLISH \n");
2539                         stack->l2link=1;
2540                         if ( !stack->ptp && !stack->nt )
2541                                 stack->l1link=2;
2542                         break;
2543                         
2544                 case SSTATUS_L2_RELEASED:
2545                         cb_log(1, stack->port, "MGMT: SSTATUS: L2_RELEASED \n");
2546                         stack->l2link=0;
2547                         break;
2548                 }
2549                 
2550                 free_msg(msg);
2551                 return 1;
2552                 
2553         case MGR_SETSTACK | INDICATION:
2554                 cb_log(2, stack->port, "MGMT: SETSTACK|IND dinfo %x\n",frm->dinfo);
2555                 free_msg(msg);
2556                 return 1;
2557         case MGR_DELLAYER | CONFIRM:
2558                 cb_log(2, stack->port, "MGMT: DELLAYER|CNF dinfo %x\n",frm->dinfo) ;
2559                 free_msg(msg);
2560                 return 1;
2561                 
2562         }
2563         
2564         /*
2565         if ( (frm->prim & 0x0f0000) ==  0x0f0000) {
2566         cb_log(5, 0, "$$$ MGMT FRAME: prim %x addr %x dinfo %x\n",frm->prim, frm->addr, frm->dinfo) ;
2567         free_msg(msg);
2568         return 1;
2569         } */
2570     
2571         return 0;
2572 }
2573
2574
2575 msg_t *fetch_msg(int midev) 
2576 {
2577         msg_t *msg=alloc_msg(MAX_MSG_SIZE);
2578         int r;
2579         fd_set rdfs;
2580
2581         if (!msg) {
2582                 cb_log(-1, 0, "fetch_msg: alloc msg failed !!");
2583                 return NULL;
2584         }
2585         
2586         FD_ZERO(&rdfs);
2587         FD_SET(midev,&rdfs);
2588   
2589         mISDN_select(FD_SETSIZE, &rdfs, NULL, NULL, NULL);
2590   
2591         if (FD_ISSET(midev, &rdfs)) {
2592     
2593                 r=mISDN_read(midev,msg->data,MAX_MSG_SIZE,0);
2594                 msg->len=r;
2595     
2596                 if (r==0) {
2597                         free_msg(msg); /* danger, cauz usualy freeing in main_loop */
2598                         printf ("Got empty Msg?\n");
2599                         return NULL;
2600                 }
2601
2602                 return msg;
2603         } else {
2604                 printf ("Select timeout\n");
2605         }
2606   
2607         return NULL;
2608 }
2609
2610
2611 static void misdn_lib_isdn_event_catcher(void *arg)
2612 {
2613         struct misdn_lib *mgr = arg;
2614         int zero_frm=0 , fff_frm=0 ;
2615         int midev= mgr->midev;
2616         int port=0;
2617         
2618         while (1) {
2619                 msg_t *msg = fetch_msg(midev); 
2620                 iframe_t *frm;
2621                 
2622                 
2623                 if (!msg) continue;
2624                 
2625                 frm = (iframe_t*) msg->data;
2626                 
2627                 /** When we make a call from NT2Ast we get this frames **/
2628                 if (frm->len == 0 && frm->addr == 0 && frm->dinfo == 0 && frm->prim == 0 ) {
2629                         zero_frm++; 
2630                         free_msg(msg);
2631                         continue;
2632                 } else {
2633                         if (zero_frm) {
2634                                 cb_log(-1, port, "*** Alert: %d zero_frms caught\n", zero_frm);
2635                                 zero_frm = 0 ;
2636                         }
2637                 }
2638                 
2639                 /** I get this sometimes after setup_bc **/
2640                 if (frm->len == 0 &&  frm->dinfo == 0 && frm->prim == 0xffffffff ) {
2641                         fff_frm++; 
2642                         free_msg(msg);
2643                         continue;
2644                 } else {
2645                         if (fff_frm) {
2646                                 cb_log(-1, port, "*** Alert: %d fff_frms caught\n", fff_frm);
2647                                 fff_frm = 0 ;
2648                         }
2649                 }
2650                 
2651                 manager_isdn_handler(frm, msg);
2652         }
2653
2654 }
2655
2656
2657 /** App Interface **/
2658
2659 int te_lib_init() {
2660         char buff[1025];
2661         iframe_t *frm=(iframe_t*)buff;
2662         int midev=mISDN_open();
2663         int ret;
2664
2665         memset(buff,0,1025);
2666   
2667         if  (midev<=0) return midev;
2668   
2669 /* create entity for layer 3 TE-mode */
2670         mISDN_write_frame(midev, buff, 0, MGR_NEWENTITY | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
2671         ret = mISDN_read_frame(midev, frm, sizeof(iframe_t), 0, MGR_NEWENTITY | CONFIRM, TIMEOUT_1SEC);
2672   
2673         if (ret < mISDN_HEADER_LEN) {
2674         noentity:
2675                 fprintf(stderr, "cannot request MGR_NEWENTITY from mISDN: %s\n",strerror(errno));
2676                 exit(-1);
2677         }
2678   
2679         entity = frm->dinfo & 0xffff ;
2680   
2681         if (!entity)
2682                 goto noentity;
2683
2684         return midev;
2685   
2686 }
2687
2688 void te_lib_destroy(int midev)
2689 {
2690         char buf[1024];
2691         mISDN_write_frame(midev, buf, 0, MGR_DELENTITY | REQUEST, entity, 0, NULL, TIMEOUT_1SEC);
2692
2693         cb_log(4, 0, "Entetity deleted\n");
2694         mISDN_close(midev);
2695         cb_log(4, 0, "midev closed\n");
2696 }
2697
2698
2699
2700 void misdn_lib_transfer(struct misdn_bchannel* holded_bc)
2701 {
2702         holded_bc->holded=0;
2703 }
2704
2705 struct misdn_bchannel *manager_find_bc_by_pid(int pid)
2706 {
2707         struct misdn_stack *stack;
2708         int i;
2709   
2710         for (stack=glob_mgr->stack_list;
2711              stack;
2712              stack=stack->next) {
2713                 for (i=0; i<stack->b_num; i++)
2714                         if (stack->bc[i].pid == pid) return &stack->bc[i];
2715         }
2716   
2717         return NULL;
2718 }
2719
2720 struct misdn_bchannel *manager_find_bc_holded(struct misdn_bchannel* bc)
2721 {
2722         struct misdn_stack *stack=get_stack_by_bc(bc);
2723         return find_bc_holded(stack);
2724 }
2725
2726
2727
2728 struct misdn_bchannel* misdn_lib_get_free_bc(int port, int channel)
2729 {
2730         struct misdn_stack *stack;
2731         int i;
2732         
2733         if (channel < 0 || channel > MAX_BCHANS)
2734                 return NULL;
2735
2736         for (stack=glob_mgr->stack_list; stack; stack=stack->next) {
2737     
2738                 if (stack->port == port) {
2739                         if (channel > 0) {
2740                                 if (channel <= stack->b_num) {
2741                                         for (i = 0; i < stack->b_num; i++) {
2742                                                 if (stack->bc[i].in_use && stack->bc[i].channel == channel) {
2743                                                         return NULL;
2744                                                 }
2745                                         }
2746                                 } else
2747                                         return NULL;
2748                         }
2749                         for (i = 0; i < stack->b_num; i++) {
2750                                 if (!stack->bc[i].in_use) {
2751                                         stack->bc[i].channel = channel;
2752                                         stack->bc[i].channel_preselected = channel?1:0;
2753                                         stack->bc[i].in_use = 1;
2754                                         return &stack->bc[i];
2755                                 }
2756                         }
2757                         return NULL;
2758                 }
2759         }
2760         return NULL;
2761 }
2762
2763
2764 char *fac2str (enum facility_type type) {
2765         struct arr_el { 
2766                 enum facility_type p; 
2767                 char *s ; 
2768         } arr[] = {
2769                 { FACILITY_NONE, "FAC_NONE" },
2770                 { FACILITY_CALLDEFLECT, "FAC_CALLDEFLECT"},
2771                 { FACILITY_CENTREX, "FAC_CENTREX"}
2772         };
2773         
2774         int i;
2775         
2776         for (i=0; i < sizeof(arr)/sizeof( struct arr_el) ; i ++)
2777                 if ( arr[i].p==type) return arr[i].s;
2778         
2779         return "FAC_UNKNOWN";
2780 }
2781
2782 void misdn_lib_log_ies(struct misdn_bchannel *bc)
2783 {
2784         if (!bc) return;
2785
2786         struct misdn_stack *stack=get_stack_by_bc(bc);
2787
2788         if (!stack) return;
2789
2790         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);
2791         
2792         cb_log(3, stack->port, " --> facility:%s out_facility:%s\n",fac2str(bc->fac_type),fac2str(bc->out_fac_type));
2793         
2794         cb_log(2, stack->port,
2795                " --> info_dad:%s onumplan:%c dnumplan:%c rnumplan:%c cpnnumplan:%c\n",
2796                bc->info_dad,
2797                bc->onumplan>=0?'0'+bc->onumplan:' ',
2798                bc->dnumplan>=0?'0'+bc->dnumplan:' ',
2799                bc->rnumplan>=0?'0'+bc->rnumplan:' ',
2800                bc->cpnnumplan>=0?'0'+bc->cpnnumplan:' '
2801                 );
2802         cb_log(3, stack->port, " --> screen:%d --> pres:%d\n",
2803                         bc->screen, bc->pres);
2804         
2805         cb_log(2, stack->port, " --> channel:%d caps:%s pi:%x keypad:%s\n", bc->channel, bearer2str(bc->capability),bc->progress_indicator, bc->keypad);
2806
2807         cb_log(3, stack->port, " --> urate:%d rate:%d mode:%d user1:%d\n", bc->urate, bc->rate, bc->mode,bc->user1);
2808         
2809         cb_log(3, stack->port, " --> pid:%d addr:%x l3id:%x\n", bc->pid, bc->addr, bc->l3_id);
2810         cb_log(3, stack->port, " --> b_stid:%x layer_id:%x\n", bc->b_stid, bc->layer_id);
2811         
2812         cb_log(4, stack->port, " --> bc:%x h:%d sh:%d\n", bc, bc->holded, bc->stack_holder);
2813 }
2814
2815 int misdn_lib_send_event(struct misdn_bchannel *bc, enum event_e event )
2816 {
2817         msg_t *msg; 
2818         int err = -1 ;
2819   
2820         if (!bc) goto ERR; 
2821         
2822         struct misdn_stack *stack=get_stack_by_bc(bc);
2823         
2824         if (!stack) {
2825                 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);
2826                 return -1;
2827         }
2828         
2829         cb_log(6,stack->port,"SENDEVENT: stack->nt:%d stack->uperid:%x\n",stack->nt, stack->upper_id);
2830
2831         if ( stack->nt && !stack->l1link) {
2832                 /** Queue Event **/
2833                 bc->evq=event;
2834                 cb_log(1, stack->port, "Queueing Event %s because L1 is down (btw. Activating L1)\n", isdn_get_info(msgs_g, event, 0));
2835                 misdn_lib_get_l1_up(stack);
2836                 return 0;
2837         }
2838         
2839         cb_log(1, stack->port, "I SEND:%s oad:%s dad:%s \n", isdn_get_info(msgs_g, event, 0), bc->oad, bc->dad);
2840         cb_log(1, stack->port, " --> bc_state:%s\n",bc_state2str(bc->bc_state));
2841         misdn_lib_log_ies(bc);
2842         
2843         switch (event) {
2844         case EVENT_SETUP:
2845                 if (create_process(glob_mgr->midev, bc)<0) {
2846                         cb_log(-1,  stack->port, " No free channel at the moment @ send_event\n");
2847
2848                         err=-ENOCHAN;
2849                         goto ERR;
2850                 }
2851                 break;
2852
2853         case EVENT_CONNECT:
2854         case EVENT_PROGRESS:
2855         case EVENT_ALERTING:
2856         case EVENT_PROCEEDING:
2857         case EVENT_SETUP_ACKNOWLEDGE:
2858         case EVENT_RETRIEVE_ACKNOWLEDGE:
2859                 if (stack->nt) {
2860                         if (bc->channel <=0 ) { /*  else we have the channel already */
2861                                 bc->channel = find_free_chan_in_stack(stack, 0);
2862                                 if (!bc->channel) {
2863                                         cb_log(-1, stack->port, " No free channel at the moment\n");
2864                                         
2865                                         err=-ENOCHAN;
2866                                         goto ERR;
2867                                 }
2868                         }
2869                         /* Its that i generate channels */
2870                 }
2871                 
2872                 if ( bc->nt || misdn_cap_is_speech(bc->capability)) {
2873                         int ret=setup_bc(bc);
2874                         if (ret == -EINVAL){
2875                                 cb_log(-1,bc->port,"send_event: setup_bc failed\n");
2876                                 
2877                         }
2878                 } 
2879                 
2880                 if ( (event == EVENT_CONNECT ) && misdn_cap_is_speech(bc->capability) ) {
2881                         if ( *bc->crypt_key ) {
2882                                 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);
2883                                 
2884                                 manager_ph_control_block(bc,  BF_ENABLE_KEY, bc->crypt_key, strlen(bc->crypt_key) );
2885                         }
2886                         
2887                         if (!bc->nodsp) manager_ph_control(bc,  DTMF_TONE_START, 0);
2888                         
2889                         if (bc->ec_enable) manager_ec_enable(bc);
2890                         
2891                         if (bc->txgain != 0) {
2892                                 cb_log(4, stack->port,  "--> Changing txgain to %d\n", bc->txgain);
2893                                 manager_ph_control(bc, VOL_CHANGE_TX, bc->txgain);
2894                         }
2895                         
2896                         if ( bc->rxgain != 0 ) {
2897                                 cb_log(4, stack->port,  "--> Changing rxgain to %d\n", bc->rxgain);
2898                                 manager_ph_control(bc, VOL_CHANGE_RX, bc->rxgain);
2899                         }
2900                         
2901                 }
2902                 
2903                 if (event == EVENT_RETRIEVE_ACKNOWLEDGE) {
2904                         manager_bchannel_activate(bc);
2905                 }
2906                 break;
2907
2908         case EVENT_HOLD_ACKNOWLEDGE:
2909         {
2910                 struct misdn_bchannel *holded_bc=malloc(sizeof(struct misdn_bchannel));
2911                 memcpy(holded_bc,bc,sizeof(struct misdn_bchannel));
2912                 holded_bc->holded=1;
2913                 stack_holder_add(stack,holded_bc);
2914                 
2915                 if (stack->nt) {
2916                         if (bc->bc_state == BCHAN_BRIDGED) {
2917                                 misdn_split_conf(bc,bc->conf_id);
2918                                 misdn_split_conf(bc->holded_bc,bc->holded_bc->conf_id);
2919                                 /*bc_state_change(bc,BCHAN_SETUPED);
2920                                 manager_bchannel_activate(bc);*/
2921                         }
2922
2923                         empty_chan_in_stack(stack,bc->channel);
2924                         empty_bc(bc);
2925                         clean_up_bc(bc);
2926                 }
2927                 
2928                 /** we set it up later at RETRIEVE_ACK again.**/
2929                 /*holded_bc->upset=0;
2930                   holded_bc->active=0;*/
2931                 bc_state_change(holded_bc,BCHAN_CLEANED);
2932                 
2933                 cb_event( EVENT_NEW_BC, holded_bc, glob_mgr->user_data);
2934         }
2935         break;
2936         
2937         case EVENT_RELEASE:
2938                 break;
2939                 
2940         case EVENT_RELEASE_COMPLETE:
2941                 /*we do the cleanup in EVENT_CLEANUP*/
2942                 break;
2943     
2944         case EVENT_CONNECT_ACKNOWLEDGE:
2945                 
2946                 if (misdn_cap_is_speech(bc->capability)) {
2947                         if (  !bc->nodsp) manager_ph_control(bc,  DTMF_TONE_START, 0);
2948                         if (bc->ec_enable) manager_ec_enable(bc);
2949                         if ( bc->txgain != 0 ) {
2950                                 cb_log(4, stack->port, "--> Changing txgain to %d\n", bc->txgain);
2951                                 manager_ph_control(bc, VOL_CHANGE_TX, bc->txgain);
2952                         }
2953                         if ( bc->rxgain != 0 ) {
2954                                 cb_log(4, stack->port, "--> Changing rxgain to %d\n", bc->rxgain);
2955                                 manager_ph_control(bc, VOL_CHANGE_RX, bc->rxgain);
2956                         }
2957                 }
2958                 break;
2959     
2960         default:
2961                 break;
2962         }
2963   
2964         /* Later we should think about sending bchannel data directly to misdn. */
2965         msg = isdn_msg_build_event(msgs_g, bc, event, stack->nt);
2966         msg_queue_tail(&stack->downqueue, msg);
2967         sem_post(&glob_mgr->new_msg);
2968   
2969         return 0;
2970   
2971  ERR:
2972         return -1; 
2973 }
2974
2975
2976 int handle_err(msg_t *msg)
2977 {
2978         iframe_t *frm = (iframe_t*) msg->data;
2979         
2980         switch (frm->prim) {
2981                 case DL_DATA|INDICATION:
2982                 {
2983                         int port=(frm->addr&MASTER_ID_MASK) >> 8;
2984                         int channel=(frm->addr&CHILD_ID_MASK) >> 16;
2985
2986                         cb_log(3,0,"BCHAN DATA without BC: addr:%x port:%d channel:%d\n",frm->addr, port,channel);
2987                         
2988                         struct misdn_bchannel *bc=find_bc_by_channel( port , channel);
2989
2990                         if (!bc) {
2991                                 struct misdn_stack *stack=find_stack_by_port( port );
2992
2993                                 if (!stack) {
2994                                         cb_log(-1,0," --> stack not found\n");
2995                                         free_msg(msg);
2996                                         return 1;
2997                                 }
2998                                 
2999                                 cb_log(-1,0," --> bc not found by channel\n");
3000                                 if (stack->l2link)
3001                                         misdn_lib_get_l2_down(stack);
3002
3003                                 if (stack->l1link)
3004                                         misdn_lib_get_l1_down(stack);
3005
3006                                 free_msg(msg);
3007                                 return 1;
3008                         }
3009                         
3010                         cb_log(3,port," --> BC in state:%s\n", bc_state2str(bc->bc_state));
3011                 }
3012         }
3013
3014         return 0;
3015 }
3016
3017
3018 int manager_isdn_handler(iframe_t *frm ,msg_t *msg)
3019 {  
3020
3021         if (frm->dinfo==(signed long)0xffffffff && frm->prim==(PH_DATA|CONFIRM)) {
3022                 printf("SERIOUS BUG, dinfo == 0xffffffff, prim == PH_DATA | CONFIRM !!!!\n");
3023         }
3024
3025         if ( ((frm->addr | ISDN_PID_BCHANNEL_BIT )>> 28 ) == 0x5) {
3026                 if (handle_bchan(msg)) 
3027                         return 0 ;
3028         }       
3029
3030         if (handle_timers(msg)) 
3031                 return 0 ;
3032         
3033         if (handle_mgmt(msg)) 
3034                 return 0 ; 
3035         
3036         if (handle_l2(msg)) 
3037                 return 0 ;
3038
3039         /* Its important to handle l1 AFTER l2  */
3040         if (handle_l1(msg)) 
3041                 return 0 ;
3042         
3043         
3044         /** Handle L2/3 Signalling after bchans **/ 
3045         if (handle_frm_nt(msg)) 
3046                 return 0 ;
3047         
3048         if (handle_frm(msg)) 
3049                 return 0 ;
3050
3051         if (handle_err(msg)) 
3052                 return 0 ;
3053         
3054         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);           
3055    
3056         free_msg(msg);
3057
3058         return 0;
3059 }
3060
3061
3062
3063
3064 int misdn_lib_get_port_info(int port)
3065 {
3066         msg_t *msg=alloc_msg(MAX_MSG_SIZE);
3067         iframe_t *frm;
3068         struct misdn_stack *stack=find_stack_by_port(port);
3069         if (!msg) {
3070                 cb_log(-1, port, "misgn_lib_get_port: alloc_msg failed!\n");
3071                 return -1;
3072         }
3073         frm=(iframe_t*)msg->data;
3074         if (!stack ) {
3075                 cb_log(-1, port, "There is no Stack for this port.\n");
3076                 return -1;
3077         }
3078         /* activate bchannel */
3079         frm->prim = CC_STATUS_ENQUIRY | REQUEST;
3080
3081         frm->addr = stack->upper_id| FLG_MSG_DOWN;
3082
3083         frm->dinfo = 0;
3084         frm->len = 0;
3085   
3086         msg_queue_tail(&glob_mgr->activatequeue, msg);
3087         sem_post(&glob_mgr->new_msg);
3088
3089   
3090         return 0; 
3091 }
3092
3093 int misdn_lib_port_restart(int port)
3094 {
3095         struct misdn_stack *stack=find_stack_by_port(port);
3096  
3097         cb_log(0, port, "Restarting this port.\n");
3098         if (stack) {
3099                 cb_log(0, port, "Stack:%p\n",stack);
3100                 
3101                 clear_l3(stack);
3102                 {
3103                         msg_t *msg=alloc_msg(MAX_MSG_SIZE);
3104                         iframe_t *frm;
3105
3106                         if (!msg) {
3107                                 cb_log(-1, port, "port_restart: alloc_msg failed\n");
3108                                 return -1;
3109                         }
3110                         
3111                         frm=(iframe_t*)msg->data;
3112                         /* we must activate if we are deactivated */
3113                         /* activate bchannel */
3114                         frm->prim = DL_RELEASE | REQUEST;
3115                         frm->addr = stack->upper_id | FLG_MSG_DOWN;
3116
3117                         frm->dinfo = 0;
3118                         frm->len = 0;
3119                         msg_queue_tail(&glob_mgr->activatequeue, msg);
3120                         sem_post(&glob_mgr->new_msg);
3121                 }
3122                 return 0;
3123     
3124                 stack_te_destroy(stack);
3125       
3126                 {
3127                         struct misdn_stack *tmpstack;
3128                         struct misdn_stack *newstack=stack_init(stack->midev ,port, stack->ptp);
3129       
3130       
3131                         if (stack == glob_mgr->stack_list) {
3132                                 struct misdn_stack *n=glob_mgr->stack_list->next;
3133                                 glob_mgr->stack_list = newstack ;
3134                                 glob_mgr->stack_list->next = n;
3135                         } else {
3136                                 for (tmpstack=glob_mgr->stack_list;
3137                                      tmpstack->next;
3138                                      tmpstack=tmpstack->next) 
3139                                         if (tmpstack->next == stack) break;
3140
3141                                 if (!tmpstack->next) {
3142                                         cb_log(-1, port, "Stack to restart not found\n");
3143                                         return 0;
3144                                 }  else {
3145                                         struct misdn_stack *n=tmpstack->next->next;
3146                                         tmpstack->next=newstack;
3147                                         newstack->next=n;
3148                                 }
3149                         }
3150       
3151                         {
3152                                 int i;
3153                                 for(i=0;i<newstack->b_num; i++) {
3154                                         int r;
3155                                         if ((r=init_bc(newstack, &newstack->bc[i], newstack->midev,port,i, "", 1))<0) {
3156                                                 cb_log(-1, port, "Got Err @ init_bc :%d\n",r);
3157                                                 return 0;
3158                                         }
3159                                 }
3160                         }
3161       
3162                         free(stack);
3163                 }
3164         }
3165
3166         return 0;
3167 }
3168
3169
3170
3171 sem_t handler_started; 
3172
3173 void manager_event_handler(void *arg)
3174 {
3175         sem_post(&handler_started); 
3176         while (1) {
3177                 struct misdn_stack *stack;
3178                 msg_t *msg;
3179     
3180                 /** wait for events **/
3181                 sem_wait(&glob_mgr->new_msg);
3182     
3183                 for (msg=msg_dequeue(&glob_mgr->activatequeue);
3184                      msg;
3185                      msg=msg_dequeue(&glob_mgr->activatequeue)
3186                         )
3187                 {
3188         
3189                         iframe_t *frm =  (iframe_t*) msg->data ;
3190
3191                         switch ( frm->prim) {
3192                         case MGR_SETSTACK | REQUEST :
3193                                 break;
3194                         default:
3195                                 mISDN_write(glob_mgr->midev, frm, mISDN_HEADER_LEN+frm->len, TIMEOUT_1SEC);
3196                                 free_msg(msg);
3197                         }
3198                 }
3199
3200                 for (stack=glob_mgr->stack_list;
3201                      stack;
3202                      stack=stack->next ) { 
3203                         while ( (msg=msg_dequeue(&stack->downqueue)) ) {
3204                                 if (stack->nt ) {
3205                                         if (stack->nst.manager_l3(&stack->nst, msg))
3206                                                 cb_log(-1, stack->port, "Error@ Sending Message in NT-Stack.\n");
3207           
3208                                 } else {
3209                                         iframe_t *frm = (iframe_t *)msg->data;
3210                                         struct misdn_bchannel *bc = find_bc_by_l3id(stack, frm->dinfo);
3211                                         if (bc) send_msg(glob_mgr->midev, bc, msg);
3212                                 }
3213                         }
3214                 }
3215         }
3216 }
3217
3218
3219 int misdn_lib_maxports_get() { /** BE AWARE WE HAVE NO CB_LOG HERE! **/
3220         
3221         int i = mISDN_open();
3222         int max=0;
3223         
3224         if (i<0)
3225                 return -1;
3226
3227         max = mISDN_get_stack_count(i);
3228         
3229         mISDN_close(i);
3230         
3231         return max;
3232 }
3233
3234 int misdn_lib_init(char *portlist, struct misdn_lib_iface *iface, void *user_data)
3235 {
3236         struct misdn_lib *mgr=calloc(1, sizeof(struct misdn_lib));
3237         char *tok, *tokb;
3238         char plist[1024];
3239         int midev;
3240         int port_count=0;
3241  
3242         cb_log = iface->cb_log;
3243         cb_event = iface->cb_event;
3244         cb_jb_empty = iface->cb_jb_empty;
3245         
3246         glob_mgr = mgr;
3247   
3248         msg_init();
3249 #if 0
3250         int flags=0xff;
3251         flags &= ~DBGM_MSG;
3252         debug_init( flags , NULL, NULL, NULL);
3253 #else
3254         debug_init(0 , NULL, NULL, NULL);
3255 #endif  
3256         if (!portlist || (*portlist == 0) ) return 1;
3257         
3258         init_flip_bits();
3259         
3260         {
3261                 strncpy(plist,portlist, 1024);
3262                 plist[1023] = 0;
3263         }
3264   
3265         memcpy(tone_425_flip,tone_425,TONE_425_SIZE);
3266         flip_buf_bits(tone_425_flip,TONE_425_SIZE);
3267
3268         memcpy(tone_silence_flip,tone_SILENCE,TONE_SILENCE_SIZE);
3269         flip_buf_bits(tone_silence_flip,TONE_SILENCE_SIZE);
3270   
3271         midev=te_lib_init();
3272         mgr->midev=midev;
3273
3274         port_count=mISDN_get_stack_count(midev);
3275   
3276         msg_queue_init(&mgr->activatequeue);
3277   
3278         if (sem_init(&mgr->new_msg, 1, 0)<0)
3279                 sem_init(&mgr->new_msg, 0, 0);
3280   
3281         for (tok=strtok_r(plist," ,",&tokb );
3282              tok; 
3283              tok=strtok_r(NULL," ,",&tokb)) {
3284                 int port = atoi(tok);
3285                 struct misdn_stack *stack;
3286                 static int first=1;
3287                 int ptp=0;
3288     
3289                 if (strstr(tok, "ptp"))
3290                         ptp=1;
3291
3292                 if (port > port_count) {
3293                         cb_log(-1, port, "Couldn't Initialize this port since we have only %d ports\n", port_count);
3294                         exit(1);
3295                 }
3296                 stack=stack_init(midev, port, ptp);
3297     
3298                 if (!stack) {
3299                         perror("init_stack");
3300                         exit(1);
3301                 }
3302     
3303                 if (stack && first) {
3304                         mgr->stack_list=stack;
3305                         first=0;
3306                         {
3307                                 int i;
3308                                 for(i=0;i<stack->b_num; i++) {
3309                                         int r;
3310                                         if ((r=init_bc(stack, &stack->bc[i], stack->midev,port,i, "", 1))<0) {
3311                                                 cb_log(-1, port, "Got Err @ init_bc :%d\n",r);
3312                                                 exit(1);
3313                                         }
3314                                 }
3315                         }
3316       
3317                         continue;
3318                 }
3319     
3320                 if (stack) {
3321                         struct misdn_stack * help;
3322                         for ( help=mgr->stack_list; help; help=help->next ) 
3323                                 if (help->next == NULL) break;
3324       
3325       
3326                         help->next=stack;
3327
3328                         {
3329                                 int i;
3330                                 for(i=0;i<stack->b_num; i++) {
3331                                         int r;
3332                                         if ((r=init_bc(stack, &stack->bc[i], stack->midev,port,i, "",1 ))<0) {
3333                                                 cb_log(-1, port, "Got Err @ init_bc :%d\n",r);
3334                                                 exit(1);
3335                                         } 
3336                                 }
3337                         }
3338                 }
3339     
3340         }
3341   
3342         if (sem_init(&handler_started, 1, 0)<0)
3343                 sem_init(&handler_started, 0, 0);
3344   
3345         cb_log(4, 0, "Starting Event Handler\n");
3346         pthread_create( &mgr->event_handler_thread, NULL,(void*)manager_event_handler, mgr);
3347   
3348         sem_wait(&handler_started) ;
3349         cb_log(4, 0, "Starting Event Catcher\n");
3350         pthread_create( &mgr->event_thread, NULL, (void*)misdn_lib_isdn_event_catcher, mgr);
3351   
3352         cb_log(4, 0, "Event Catcher started\n");
3353   
3354         global_state= MISDN_INITIALIZED; 
3355   
3356         return (mgr == NULL);
3357 }
3358
3359 void misdn_lib_destroy()
3360 {
3361         struct misdn_stack *help;
3362         int i;
3363   
3364         for ( help=glob_mgr->stack_list; help; help=help->next ) {
3365                 for(i=0;i<help->b_num; i++) {
3366                         char buf[1024];
3367                         mISDN_write_frame(help->midev, buf, help->bc[i].addr, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
3368                         help->bc[i].addr = 0;
3369                 }
3370                 cb_log (1, help->port, "Destroying this port.\n");
3371                 stack_te_destroy(help);
3372         }
3373         
3374         if (global_state == MISDN_INITIALIZED) {
3375                 cb_log(4, 0, "Killing Handler Thread\n");
3376                 if ( pthread_cancel(glob_mgr->event_handler_thread) == 0 ) {
3377                         cb_log(4, 0, "Joining Handler Thread\n");
3378                         pthread_join(glob_mgr->event_handler_thread, NULL);
3379                 }
3380           
3381                 cb_log(4, 0, "Killing Main Thread\n");
3382                 if ( pthread_cancel(glob_mgr->event_thread) == 0 ) {
3383                         cb_log(4, 0, "Joining Main Thread\n");
3384                         pthread_join(glob_mgr->event_thread, NULL);
3385                 }
3386         }
3387   
3388         cb_log(1, 0, "Closing mISDN device\n");
3389         te_lib_destroy(glob_mgr->midev);
3390 }
3391
3392 char *manager_isdn_get_info(enum event_e event)
3393 {
3394         return isdn_get_info(msgs_g , event, 0);
3395 }
3396
3397 void manager_bchannel_activate(struct misdn_bchannel *bc)
3398 {
3399         msg_t *msg=alloc_msg(MAX_MSG_SIZE);
3400         iframe_t *frm;
3401         
3402         struct misdn_stack *stack=get_stack_by_bc(bc);
3403
3404         if (!stack) {
3405                 cb_log(-1, bc->port, "bchannel_activate: Stack not found !");
3406                 return ;
3407         }
3408         
3409         if (!msg) {
3410                 cb_log(-1, stack->port, "bchannel_activate: alloc_msg failed !");
3411
3412                 return ;
3413         }
3414
3415
3416         switch (bc->bc_state) {
3417
3418         case BCHAN_SETUPED:
3419                 break;
3420                 
3421         default:
3422                 cb_log(1, stack->port, "bchannel_activate: BC Not properly upsetted (state:%s) addr:%x\n", bc_state2str(bc->bc_state), bc->addr);
3423
3424                 
3425                 return;
3426         }
3427         
3428
3429         
3430         frm=(iframe_t*)msg->data;
3431         /* we must activate if we are deactivated */
3432         clear_ibuffer(bc->astbuf);
3433         
3434         cb_log(5, stack->port, "$$$ Bchan Activated addr %x\n", bc->addr);
3435         
3436         /* activate bchannel */
3437         frm->prim = DL_ESTABLISH | REQUEST;
3438         frm->addr = bc->addr | FLG_MSG_DOWN ;
3439         frm->dinfo = 0;
3440         frm->len = 0;
3441         
3442         msg_queue_tail(&glob_mgr->activatequeue, msg);
3443         sem_post(&glob_mgr->new_msg);
3444         
3445         bc_state_change(bc, BCHAN_ACTIVE);
3446         
3447         return ;
3448   
3449 }
3450
3451
3452 void manager_bchannel_deactivate(struct misdn_bchannel * bc)
3453 {
3454
3455         struct misdn_stack *stack=get_stack_by_bc(bc);
3456
3457
3458         switch (bc->bc_state) {
3459                 case BCHAN_ACTIVATED:
3460                         break;
3461                 case BCHAN_BRIDGED:
3462                         misdn_split_conf(bc,bc->conf_id);
3463                         break;
3464                 default:
3465                         cb_log( 4, bc->port,"bchan_deactivate: called but not activated\n");
3466                         return ;
3467
3468         }
3469         
3470         cb_log(5, stack->port, "$$$ Bchan deActivated addr %x\n", bc->addr);
3471         
3472         bc->generate_tone=0;
3473         
3474         iframe_t dact;
3475         dact.prim = DL_RELEASE | REQUEST;
3476         dact.addr = bc->addr | FLG_MSG_DOWN;
3477         dact.dinfo = 0;
3478         dact.len = 0;
3479         
3480         mISDN_write(stack->midev, &dact, mISDN_HEADER_LEN+dact.len, TIMEOUT_1SEC);
3481         clear_ibuffer(bc->astbuf);
3482         
3483         bc_state_change(bc,BCHAN_RELEASE);
3484   
3485         return;
3486 }
3487
3488
3489 int misdn_lib_tx2misdn_frm(struct misdn_bchannel *bc, void *data, int len)
3490 {
3491         struct misdn_stack *stack=get_stack_by_bc(bc);
3492
3493         switch (bc->bc_state) {
3494                 case BCHAN_ACTIVATED:
3495                 case BCHAN_BRIDGED:
3496                         break;
3497                 default:
3498                         cb_log(3, bc->port, "BC not yet activated (state:%s)\n",bc_state2str(bc->bc_state));
3499                         return -1;
3500         }
3501         
3502         char buf[4096 + mISDN_HEADER_LEN];
3503         iframe_t *frm= (iframe_t*)buf;
3504         int  r;
3505         
3506         frm->prim = DL_DATA|REQUEST;
3507         frm->dinfo = 0;
3508         frm->addr = bc->addr | FLG_MSG_DOWN ;
3509         
3510         frm->len = len;
3511         memcpy(&buf[mISDN_HEADER_LEN], data,len);
3512         
3513         if ( ! misdn_cap_is_speech(bc->capability))
3514                 cb_log(6, stack->port, "Writing %d data bytes\n",len);
3515         
3516         cb_log(9, stack->port, "Writing %d bytes 2 mISDN\n",len);
3517         r=mISDN_write(stack->midev, buf, frm->len + mISDN_HEADER_LEN, TIMEOUT_INFINIT);
3518 #ifdef ACK_HDLC
3519         if (bc->hdlc && bc->ack_hdlc) {
3520                 cb_log(4,stack->port,"Awaiting Acknowledge [%d]\n",len);
3521                 sem_wait((sem_t*)bc->ack_hdlc);
3522                 cb_log(4,stack->port,"Acknowledged\n");
3523         }
3524 #endif  
3525         return 0;
3526 }
3527
3528
3529
3530 /*
3531  * send control information to the channel (dsp-module)
3532  */
3533 void manager_ph_control(struct misdn_bchannel *bc, long c1, long c2)
3534 {
3535         unsigned char buffer[mISDN_HEADER_LEN+2*sizeof(long)];
3536         iframe_t *ctrl = (iframe_t *)buffer; /* preload data */
3537         unsigned long *d = (unsigned long *)&ctrl->data.p;
3538         struct misdn_stack *stack=get_stack_by_bc(bc);
3539         
3540         ctrl->prim = PH_CONTROL | REQUEST;
3541         ctrl->addr = bc->addr | FLG_MSG_DOWN;
3542         ctrl->dinfo = 0;
3543         ctrl->len = sizeof(unsigned long)*2;
3544         *d++ = c1;
3545         *d++ = c2;
3546         mISDN_write(stack->midev, ctrl, mISDN_HEADER_LEN+ctrl->len, TIMEOUT_1SEC);
3547 }
3548
3549 /*
3550  * send control information to the channel (dsp-module)
3551  */
3552 void manager_ph_control_block(struct misdn_bchannel *bc, long c1, void *c2, int c2_len)
3553 {
3554         unsigned char buffer[mISDN_HEADER_LEN+sizeof(long)+c2_len];
3555         iframe_t *ctrl = (iframe_t *)buffer;
3556         unsigned long *d = (unsigned long *)&ctrl->data.p;
3557         struct misdn_stack *stack=get_stack_by_bc(bc);
3558         
3559         ctrl->prim = PH_CONTROL | REQUEST;
3560         ctrl->addr = bc->addr | FLG_MSG_DOWN;
3561         ctrl->dinfo = 0;
3562         ctrl->len = sizeof(unsigned long) + c2_len;
3563         *d++ = c1;
3564         memcpy(d, c2, c2_len);
3565         mISDN_write(stack->midev, ctrl, mISDN_HEADER_LEN+ctrl->len, TIMEOUT_1SEC);
3566 }
3567
3568
3569
3570
3571 void manager_clean_bc(struct misdn_bchannel *bc )
3572 {
3573         struct misdn_stack *stack=get_stack_by_bc(bc);
3574         
3575         empty_chan_in_stack(stack, bc->channel);
3576         empty_bc(bc);
3577   
3578         misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
3579 }
3580
3581
3582 void stack_holder_add(struct misdn_stack *stack, struct misdn_bchannel *holder)
3583 {
3584         struct misdn_bchannel *help;
3585         cb_log(4,stack->port, "*HOLDER: add %x\n",holder->l3_id);
3586         
3587         holder->stack_holder=1;
3588
3589         if (!stack ) return ;
3590         
3591         holder->next=NULL;
3592         
3593         if (!stack->holding) {
3594                 stack->holding = holder;
3595                 return;
3596         }
3597   
3598         for (help=stack->holding;
3599              help;
3600              help=help->next) {
3601                 if (!help->next) {
3602                         help->next=holder;
3603                         break;
3604                 }
3605         }
3606   
3607 }
3608
3609 void stack_holder_remove(struct misdn_stack *stack, struct misdn_bchannel *holder)
3610 {
3611         struct misdn_bchannel *h1;
3612
3613         if (!holder->stack_holder) return;
3614         
3615         cb_log(4,stack->port, "*HOLDER: remove %x\n",holder->l3_id);
3616         if (!stack || ! stack->holding) return;
3617   
3618         if (holder == stack->holding) {
3619                 stack->holding = stack->holding->next;
3620                 return;
3621         }
3622         
3623         for (h1=stack->holding;
3624              h1;
3625              h1=h1->next) {
3626                 if (h1->next == holder) {
3627                         h1->next=h1->next->next;
3628                         return ;
3629                 }
3630         }
3631 }
3632
3633
3634 struct misdn_bchannel *stack_holder_find(struct misdn_stack *stack, unsigned long l3id)
3635 {