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