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