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