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