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