* Miscellaneous formatting changes to make v1.4 and trunk
[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;
983         int channel;
984         int b_stid;
985         int i;
986         mISDN_pid_t pid;
987         int ret;
988
989         struct misdn_stack *stack=get_stack_by_bc(bc);
990
991         if (!stack) {
992                 cb_log(0, bc->port, "setup_bc: NO STACK FOUND!!\n");
993                 return -1;
994         }
995         
996         midev = stack->midev;
997         channel = bc->channel - 1 - (bc->channel > 16);
998         b_stid = stack->b_stids[channel >= 0 ? channel : 0];
999
1000         switch (bc->bc_state) {
1001                 case BCHAN_CLEANED:
1002                         break;
1003                 default:
1004                         cb_log(4, stack->port, "$$$ bc already setup stid :%x (state:%s)\n", b_stid, bc_state2str(bc->bc_state) );
1005                         return -1;
1006         }
1007         
1008         cb_log(5, stack->port, "$$$ Setting up bc with stid :%x\n", b_stid);
1009         
1010         /*check if the b_stid is already initialized*/
1011         for (i=0; i <= stack->b_num; i++) {
1012                 if (stack->bc[i].b_stid == b_stid) {
1013                         cb_log(0, bc->port, "setup_bc: b_stid:%x already in use !!!\n", b_stid);
1014                         return -1;
1015                 }
1016         }
1017         
1018         if (b_stid <= 0) {
1019                 cb_log(0, stack->port," -- Stid <=0 at the moment in channel:%d\n",channel);
1020                 
1021                 bc_state_change(bc,BCHAN_ERROR);
1022                 return 1;
1023         }
1024
1025         bc->b_stid = b_stid;
1026
1027         {
1028                 layer_info_t li;
1029                 memset(&li, 0, sizeof(li));
1030     
1031                 li.object_id = -1;
1032                 li.extentions = 0;
1033                 
1034                 li.st = bc->b_stid; /*  given idx */
1035
1036
1037 #define MISDN_DSP
1038 #ifndef MISDN_DSP
1039                 bc->nodsp=1;
1040 #endif
1041                 if ( bc->hdlc || bc->nodsp) {
1042                         cb_log(4, stack->port,"setup_bc: without dsp\n");
1043                         { 
1044                                 int l = sizeof(li.name);
1045                                 strncpy(li.name, "B L3", l);
1046                                 li.name[l-1] = 0;
1047                         }
1048                         li.pid.layermask = ISDN_LAYER((3));
1049                         li.pid.protocol[3] = ISDN_PID_L3_B_USER;
1050                         
1051                         bc->layer=3;
1052                 } else {
1053                         cb_log(4, stack->port,"setup_bc: with dsp\n");
1054                         { 
1055                                 int l = sizeof(li.name);
1056                                 strncpy(li.name, "B L4", l);
1057                                 li.name[l-1] = 0;
1058                         }
1059                         li.pid.layermask = ISDN_LAYER((4));
1060                         li.pid.protocol[4] = ISDN_PID_L4_B_USER;
1061
1062                         bc->layer=4;
1063                 }  
1064                 
1065                 ret = mISDN_new_layer(midev, &li);
1066                 if (ret ) {
1067                         cb_log(0, stack->port,"New Layer Err: %d %s\n",ret,strerror(errno));
1068
1069                         bc_state_change(bc,BCHAN_ERROR);
1070                         return(-EINVAL);
1071                 }
1072                 
1073                 bc->layer_id = li.id;
1074         }
1075         
1076         memset(&pid, 0, sizeof(pid));
1077         
1078         
1079         
1080         cb_log(4, stack->port," --> Channel is %d\n", bc->channel);
1081         
1082         if (bc->nodsp) {
1083                 cb_log(2, stack->port," --> TRANSPARENT Mode (no DSP, no HDLC)\n");
1084                 pid.protocol[1] = ISDN_PID_L1_B_64TRANS;
1085                 pid.protocol[2] = ISDN_PID_L2_B_TRANS;
1086                 pid.protocol[3] = ISDN_PID_L3_B_USER;
1087                 pid.layermask = ISDN_LAYER((1)) | ISDN_LAYER((2)) | ISDN_LAYER((3));
1088                 
1089         } else if ( bc->hdlc ) {
1090                 cb_log(2, stack->port," --> HDLC Mode\n");
1091                 pid.protocol[1] = ISDN_PID_L1_B_64HDLC ;
1092                 pid.protocol[2] = ISDN_PID_L2_B_TRANS  ;
1093                 pid.protocol[3] = ISDN_PID_L3_B_USER;
1094                 pid.layermask = ISDN_LAYER((1)) | ISDN_LAYER((2)) | ISDN_LAYER((3)) ;
1095         } else {
1096                 cb_log(2, stack->port," --> TRANSPARENT Mode\n");
1097                 pid.protocol[1] = ISDN_PID_L1_B_64TRANS;
1098                 pid.protocol[2] = ISDN_PID_L2_B_TRANS;
1099                 pid.protocol[3] = ISDN_PID_L3_B_DSP;
1100                 pid.protocol[4] = ISDN_PID_L4_B_USER;
1101                 pid.layermask = ISDN_LAYER((1)) | ISDN_LAYER((2)) | ISDN_LAYER((3)) | ISDN_LAYER((4));
1102                 
1103         } 
1104
1105         ret = mISDN_set_stack(midev, bc->b_stid, &pid);
1106
1107         if (ret){
1108                 cb_log(0, stack->port,"$$$ Set Stack Err: %d %s\n",ret,strerror(errno));
1109                 
1110                 mISDN_write_frame(midev, buff, bc->layer_id, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
1111                 
1112                 bc_state_change(bc,BCHAN_ERROR);
1113                 cb_event(EVENT_BCHAN_ERROR, bc, glob_mgr->user_data);
1114                 return(-EINVAL);
1115         }
1116
1117         ret = mISDN_get_setstack_ind(midev, bc->layer_id);
1118
1119         if (ret) {
1120                 cb_log(0, stack->port,"$$$ Set StackIND Err: %d %s\n",ret,strerror(errno));
1121                 mISDN_write_frame(midev, buff, bc->layer_id, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
1122                 
1123                 bc_state_change(bc,BCHAN_ERROR);
1124                 cb_event(EVENT_BCHAN_ERROR, bc, glob_mgr->user_data);
1125                 return(-EINVAL);
1126         }
1127
1128         ret = mISDN_get_layerid(midev, bc->b_stid, bc->layer) ;
1129
1130         bc->addr = ret>0? ret : 0;
1131
1132         if (!bc->addr) {
1133                 cb_log(0, stack->port,"$$$ Get Layerid Err: %d %s\n",ret,strerror(errno));
1134                 mISDN_write_frame(midev, buff, bc->layer_id, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
1135                 
1136                 bc_state_change(bc,BCHAN_ERROR);
1137                 cb_event(EVENT_BCHAN_ERROR, bc, glob_mgr->user_data);
1138                 return (-EINVAL);
1139         }
1140
1141         manager_bchannel_activate(bc);
1142         
1143         bc_state_change(bc,BCHAN_ACTIVATED);
1144
1145         return 0;
1146 }
1147
1148
1149
1150 /** IFACE **/
1151 static int init_bc(struct misdn_stack *stack, struct misdn_bchannel *bc, int midev, int port, int bidx, char *msn, int firsttime)
1152 {
1153         unsigned char buff[1025] = "";
1154         iframe_t *frm = (iframe_t *)buff;
1155         int ret;
1156   
1157         if (!bc) return -1;
1158   
1159         cb_log(8, port, "Init.BC %d.\n",bidx);
1160         
1161         memset(bc, 0,sizeof(struct misdn_bchannel));
1162
1163         bc->send_lock=malloc(sizeof(struct send_lock));
1164         if (!bc->send_lock) {
1165                 return -1;
1166         }
1167         pthread_mutex_init(&bc->send_lock->lock, NULL);
1168         
1169         if (msn) {
1170                 int l = sizeof(bc->msn);
1171                 strncpy(bc->msn,msn, l);
1172                 bc->msn[l-1] = 0;
1173         }
1174         
1175         
1176         empty_bc(bc);
1177         bc_state_change(bc, BCHAN_CLEANED);
1178         
1179         bc->port=stack->port;
1180         bc->nt=stack->nt?1:0;
1181         bc->pri=stack->pri;
1182         
1183         {
1184                 ibuffer_t* ibuf= init_ibuffer(MISDN_IBUF_SIZE);
1185
1186                 if (!ibuf) return -1;
1187                 
1188                 clear_ibuffer( ibuf);
1189                 
1190                 ibuf->rsem=malloc(sizeof(sem_t));
1191                 if (!ibuf->rsem) {
1192                         return -1;
1193                 }
1194                 
1195                 bc->astbuf=ibuf;
1196
1197                 if (sem_init(ibuf->rsem,1,0)<0)
1198                         sem_init(ibuf->rsem,0,0);
1199                 
1200         }
1201         
1202         {
1203                 stack_info_t *stinf;
1204                 ret = mISDN_get_stack_info(midev, stack->port, buff, sizeof(buff));
1205                 if (ret < 0) {
1206                         cb_log(0, port, "%s: Cannot get stack info for this port. (ret=%d)\n", __FUNCTION__, ret);
1207                         return -1;
1208                 }
1209     
1210                 stinf = (stack_info_t *)&frm->data.p;
1211     
1212                 cb_log(8, port, " --> Child %x\n",stinf->child[bidx]);
1213         }
1214   
1215         return 0;
1216 }
1217
1218
1219
1220 static struct misdn_stack *stack_init(int midev, int port, int ptp)
1221 {
1222         int ret;
1223         unsigned char buff[1025];
1224         iframe_t *frm = (iframe_t *)buff;
1225         stack_info_t *stinf;
1226         int i; 
1227         layer_info_t li;
1228
1229         struct misdn_stack *stack = malloc(sizeof(struct misdn_stack));
1230         if (!stack ) return NULL;
1231
1232
1233         cb_log(8, port, "Init. Stack.\n");
1234   
1235         memset(stack,0,sizeof(struct misdn_stack));
1236   
1237         for (i=0; i<MAX_BCHANS + 1; i++ ) stack->channels[i]=0;
1238         
1239         stack->port=port;
1240         stack->midev=midev;
1241         stack->ptp=ptp;
1242   
1243         stack->holding=NULL;
1244         stack->pri=0;
1245   
1246         msg_queue_init(&stack->downqueue);
1247         msg_queue_init(&stack->upqueue);
1248   
1249         /* query port's requirements */
1250         ret = mISDN_get_stack_info(midev, port, buff, sizeof(buff));
1251         if (ret < 0) {
1252                 cb_log(0, port, "%s: Cannot get stack info for this port. (ret=%d)\n", __FUNCTION__, ret);
1253                 return(NULL);
1254         }
1255   
1256         stinf = (stack_info_t *)&frm->data.p;
1257
1258         stack->d_stid = stinf->id;
1259         stack->b_num = stinf->childcnt;
1260
1261         for (i=0; i<=stinf->childcnt; i++)
1262                 stack->b_stids[i] = stinf->child[i];
1263   
1264         switch(stinf->pid.protocol[0] & ~ISDN_PID_FEATURE_MASK) {
1265         case ISDN_PID_L0_TE_S0:
1266                 stack->nt=0;
1267                 break;
1268         case ISDN_PID_L0_NT_S0:
1269                 cb_log(8, port, "NT Stack\n");
1270
1271                 stack->nt=1;
1272                 break;
1273         case ISDN_PID_L0_TE_E1:
1274                 cb_log(8, port, "TE S2M Stack\n");
1275                 stack->nt=0;
1276                 stack->pri=1;
1277                 break;
1278         case ISDN_PID_L0_NT_E1:
1279                 cb_log(8, port, "TE S2M Stack\n");
1280                 stack->nt=1;
1281                 stack->pri=1;
1282                 
1283                 break;
1284         default:
1285                 cb_log(0, port, "this is a unknown port type 0x%08x\n", stinf->pid.protocol[0]);
1286
1287         }
1288
1289         if (!stack->nt) {
1290                 if (stinf->pid.protocol[2] & ISDN_PID_L2_DF_PTP ) { 
1291                         stack->ptp = 1;
1292                 } else {
1293                         stack->ptp = 0;
1294                 }
1295         }
1296         
1297         {
1298                 int ret;
1299                 int nt=stack->nt;
1300
1301                 cb_log(8, port, "Init. Stack.\n");
1302                 
1303                 memset(&li, 0, sizeof(li));
1304                 {
1305                         int l = sizeof(li.name);
1306                         strncpy(li.name,nt?"net l2":"user l4", l);
1307                         li.name[l-1] = 0;
1308                 }
1309                 li.object_id = -1;
1310                 li.extentions = 0;
1311                 li.pid.protocol[nt?2:4] = nt?ISDN_PID_L2_LAPD_NET:ISDN_PID_L4_CAPI20;
1312                 li.pid.layermask = ISDN_LAYER((nt?2:4));
1313                 li.st = stack->d_stid;
1314                 
1315                 
1316                 ret = mISDN_new_layer(midev, &li);
1317                 if (ret) {
1318                         cb_log(0, port, "%s: Cannot add layer %d to this port.\n", __FUNCTION__, nt?2:4);
1319                         return(NULL);
1320                 }
1321                 
1322                 
1323                 stack->upper_id = li.id;
1324                 ret = mISDN_register_layer(midev, stack->d_stid, stack->upper_id);
1325                 if (ret)
1326                 {
1327                         cb_log(0,port,"Cannot register layer %d of this port.\n", nt?2:4);
1328                         return(NULL);
1329                 }
1330                 
1331                 stack->lower_id = mISDN_get_layerid(midev, stack->d_stid, nt?1:3); 
1332                 if (stack->lower_id < 0) {
1333                         cb_log(0, port, "%s: Cannot get layer(%d) id of this port.\n", __FUNCTION__, nt?1:3);
1334                         return(NULL);
1335                 }
1336                 
1337                 stack->upper_id = mISDN_get_layerid(midev, stack->d_stid, nt?2:4);
1338                 if (stack->upper_id < 0) {
1339                         cb_log(0, port, "%s: Cannot get layer(%d) id of this port.\n", __FUNCTION__, 2);
1340                         return(NULL);
1341                 }
1342                 
1343                 cb_log(8, port, "NT Stacks upper_id %x\n",stack->upper_id);
1344                 
1345                 
1346                 /* create nst (nt-mode only) */
1347                 if (nt) {
1348                         
1349                         memset(&stack->nst, 0, sizeof(net_stack_t));
1350                         memset(&stack->mgr, 0, sizeof(manager_t));
1351     
1352                         stack->mgr.nst = &stack->nst;
1353                         stack->nst.manager = &stack->mgr;
1354     
1355                         stack->nst.l3_manager = handle_event_nt;
1356                         stack->nst.device = midev;
1357                         stack->nst.cardnr = port;
1358                         stack->nst.d_stid = stack->d_stid;
1359     
1360                         stack->nst.feature = FEATURE_NET_HOLD;
1361                         if (stack->ptp)
1362                                 stack->nst.feature |= FEATURE_NET_PTP;
1363                         if (stack->pri)
1364                                 stack->nst.feature |= FEATURE_NET_CRLEN2 | FEATURE_NET_EXTCID;
1365                         
1366                         stack->nst.l1_id = stack->lower_id;
1367                         stack->nst.l2_id = stack->upper_id;
1368                         
1369                         msg_queue_init(&stack->nst.down_queue);
1370                         
1371                         Isdnl2Init(&stack->nst);
1372                         Isdnl3Init(&stack->nst);
1373                         
1374                 } 
1375                 
1376                 if (!stack->nt) {
1377                         /*assume L1 is up, we'll get DEACTIVATES soon, for non
1378                          * up L1s*/
1379                         stack->l1link=0;
1380                 }
1381                 stack->l1link=0;
1382                 stack->l2link=0;
1383 #if 0   
1384                 if (!stack->nt) {
1385                         misdn_lib_get_short_status(stack);
1386                 } else {
1387                         misdn_lib_get_l1_up(stack);
1388                         if (!stack->ptp) misdn_lib_get_l1_up(stack);
1389                         misdn_lib_get_l2_up(stack);
1390                 }
1391 #endif
1392
1393                 misdn_lib_get_short_status(stack);
1394                 misdn_lib_get_l1_up(stack);
1395                 misdn_lib_get_l2_up(stack); 
1396                 
1397         }
1398
1399         cb_log(8,0,"stack_init: port:%d lowerId:%x  upperId:%x\n",stack->port,stack->lower_id, stack->upper_id);
1400         
1401         return stack;
1402 }
1403
1404
1405 static void stack_destroy(struct misdn_stack *stack)
1406 {
1407         char buf[1024];
1408         if (!stack) return;
1409
1410         if (stack->nt) {
1411                 cleanup_Isdnl2(&stack->nst);
1412                 cleanup_Isdnl3(&stack->nst);
1413         }
1414   
1415         if (stack->lower_id) 
1416                 mISDN_write_frame(stack->midev, buf, stack->lower_id, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
1417
1418         if (stack->upper_id) 
1419                 mISDN_write_frame(stack->midev, buf, stack->upper_id, MGR_DELLAYER | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
1420 }
1421
1422
1423 static struct misdn_stack * find_stack_by_addr(int  addr)
1424 {
1425         struct misdn_stack *stack;
1426         
1427         for (stack=glob_mgr->stack_list;
1428              stack;
1429              stack=stack->next) {
1430                 if ( (stack->upper_id&STACK_ID_MASK) == (addr&STACK_ID_MASK)) return stack;
1431
1432         }
1433   
1434         return NULL;
1435 }
1436
1437
1438 static struct misdn_stack * find_stack_by_port(int port)
1439 {
1440         struct misdn_stack *stack;
1441   
1442         for (stack=glob_mgr->stack_list;
1443              stack;
1444              stack=stack->next) 
1445                 if (stack->port == port) return stack;
1446   
1447         return NULL;
1448 }
1449
1450 static struct misdn_stack * find_stack_by_mgr(manager_t* mgr_nt)
1451 {
1452         struct misdn_stack *stack;
1453   
1454         for (stack=glob_mgr->stack_list;
1455              stack;
1456              stack=stack->next) 
1457                 if ( &stack->mgr == mgr_nt) return stack;
1458   
1459         return NULL;
1460 }
1461
1462 static struct misdn_bchannel *find_bc_by_masked_l3id(struct misdn_stack *stack, unsigned long l3id, unsigned long mask)
1463 {
1464         int i;
1465         for (i=0; i<=stack->b_num; i++) {
1466                 if ( (stack->bc[i].l3_id & mask)  ==  (l3id & mask)) return &stack->bc[i] ;
1467         }
1468         return stack_holder_find(stack,l3id);
1469 }
1470
1471
1472 struct misdn_bchannel *find_bc_by_l3id(struct misdn_stack *stack, unsigned long l3id)
1473 {
1474         int i;
1475         for (i=0; i<=stack->b_num; i++) {
1476                 if (stack->bc[i].l3_id == l3id) return &stack->bc[i] ;
1477         }
1478         return stack_holder_find(stack,l3id);
1479 }
1480
1481 static struct misdn_bchannel *find_bc_holded(struct misdn_stack *stack)
1482 {
1483         int i;
1484         for (i=0; i<=stack->b_num; i++) {
1485                 if (stack->bc[i].holded ) return &stack->bc[i] ;
1486         }
1487         return NULL;
1488 }
1489
1490
1491 static struct misdn_bchannel *find_bc_by_addr(unsigned long addr)
1492 {
1493         struct misdn_stack* stack;
1494         int i;
1495
1496         for (stack=glob_mgr->stack_list;
1497              stack;
1498              stack=stack->next) {
1499                 for (i=0; i<=stack->b_num; i++) {
1500                         if ( (stack->bc[i].addr&STACK_ID_MASK)==(addr&STACK_ID_MASK) ||  stack->bc[i].layer_id== addr ) {
1501                                 return &stack->bc[i];
1502                         }
1503                 }
1504         }
1505         
1506         return NULL;
1507 }
1508
1509 struct misdn_bchannel *find_bc_by_confid(unsigned long confid)
1510 {
1511         struct misdn_stack* stack;
1512         int i;
1513         
1514         for (stack=glob_mgr->stack_list;
1515              stack;
1516              stack=stack->next) {
1517                 for (i=0; i<=stack->b_num; i++) {
1518                         if ( stack->bc[i].conf_id==confid ) {
1519                                 return &stack->bc[i];
1520                         }
1521                 }
1522         }
1523         return NULL;
1524 }
1525
1526
1527 static struct misdn_bchannel *find_bc_by_channel(int port, int channel)
1528 {
1529         struct misdn_stack* stack=find_stack_by_port(port);
1530         int i;
1531
1532         if (!stack) return NULL;        
1533         
1534         for (i=0; i<=stack->b_num; i++) {
1535                 if ( stack->bc[i].channel== channel ) {
1536                         return &stack->bc[i];
1537                 }
1538         }
1539                 
1540         return NULL;
1541 }
1542
1543
1544
1545
1546
1547 static int handle_event ( struct misdn_bchannel *bc, enum event_e event, iframe_t *frm)
1548 {
1549         struct misdn_stack *stack=get_stack_by_bc(bc);
1550         
1551         if (!stack->nt) {
1552                 
1553                 switch (event) {
1554
1555                 case EVENT_CONNECT_ACKNOWLEDGE:
1556                         setup_bc(bc);
1557
1558                         if ( *bc->crypt_key ) {
1559                                 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);
1560                                 manager_ph_control_block(bc,  BF_ENABLE_KEY, bc->crypt_key, strlen(bc->crypt_key) );
1561                         }
1562
1563                         if (misdn_cap_is_speech(bc->capability)) {
1564                                 if (  !bc->nodsp) manager_ph_control(bc,  DTMF_TONE_START, 0);
1565                                 manager_ec_enable(bc);
1566
1567                                 if ( bc->txgain != 0 ) {
1568                                         cb_log(4, stack->port, "--> Changing txgain to %d\n", bc->txgain);
1569                                         manager_ph_control(bc, VOL_CHANGE_TX, bc->txgain);
1570                                 }
1571                                 if ( bc->rxgain != 0 ) {
1572                                         cb_log(4, stack->port, "--> Changing rxgain to %d\n", bc->rxgain);
1573                                         manager_ph_control(bc, VOL_CHANGE_RX, bc->rxgain);
1574                                 }
1575                         }
1576
1577                         break;
1578                 case EVENT_CONNECT:
1579
1580                         if ( *bc->crypt_key ) {
1581                                 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);
1582                                 manager_ph_control_block(bc,  BF_ENABLE_KEY, bc->crypt_key, strlen(bc->crypt_key) );
1583                         }
1584                 case EVENT_ALERTING:
1585                 case EVENT_PROGRESS:
1586                 case EVENT_PROCEEDING:
1587                 case EVENT_SETUP_ACKNOWLEDGE:
1588                 case EVENT_SETUP:
1589                 {
1590                         if (bc->channel == 0xff || bc->channel<=0)
1591                                 bc->channel=0;
1592
1593                         if (find_free_chan_in_stack(stack, bc, bc->channel, 0)<0){
1594                                 if (!stack->pri && !stack->ptp)  {
1595                                         bc->cw=1;
1596                                         break;
1597                                 }
1598
1599                                 if (!bc->channel)
1600                                         cb_log(0, stack->port, "Any Channel Requested, but we have no more!!\n");
1601                                 else 
1602                                         cb_log(0, stack->port, "Requested Channel Already in Use releasing this call with cause 34!!!!\n");
1603
1604                                 /* when the channel is already in use, we can't
1605                                  * simply clear it, we need to make sure that 
1606                                  * it will still be marked as in_use in the 
1607                                  * available channels list.*/
1608                                 bc->channel=0;
1609
1610                                 misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
1611                                 return -1;
1612                         }
1613                 }
1614
1615                 setup_bc(bc);
1616                 break;
1617
1618                 case EVENT_RELEASE_COMPLETE:
1619                 case EVENT_RELEASE:
1620                         break;
1621                 default:
1622                         break;
1623                 }
1624         } else {    /** NT MODE **/
1625                 
1626         }
1627         return 0;
1628 }
1629
1630 static int handle_cr ( struct misdn_stack *stack, iframe_t *frm)
1631 {
1632         struct misdn_bchannel *bc;
1633
1634         if (!stack) return -1;
1635   
1636         switch (frm->prim) {
1637         case CC_NEW_CR|INDICATION:
1638                 cb_log(7, stack->port, " --> lib: NEW_CR Ind with l3id:%x on this port.\n",frm->dinfo);
1639
1640                 bc = misdn_lib_get_free_bc(stack->port, 0, 1, 0);
1641                 if (!bc) {
1642                         cb_log(0, stack->port, " --> !! lib: No free channel!\n");
1643                         return -1;
1644                 }
1645   
1646                 cb_log(7, stack->port, " --> new_process: New L3Id: %x\n",frm->dinfo);
1647                 bc->l3_id=frm->dinfo;
1648                 return 1;
1649         case CC_NEW_CR|CONFIRM:
1650                 return 1;
1651         case CC_NEW_CR|REQUEST:
1652                 return 1;
1653         case CC_RELEASE_CR|REQUEST:
1654                 return 1;
1655         case CC_RELEASE_CR|CONFIRM:
1656                 break;
1657         case CC_RELEASE_CR|INDICATION:
1658                 cb_log(4, stack->port, " --> lib: RELEASE_CR Ind with l3id:%x\n",frm->dinfo);
1659                 {
1660                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, frm->dinfo);
1661                         struct misdn_bchannel dummybc;
1662       
1663                         if (!bc) {
1664                                 cb_log(4, stack->port, " --> Didn't find BC so temporarily creating dummy BC (l3id:%x) on this port.\n", frm->dinfo);
1665                                 misdn_make_dummy(&dummybc, stack->port, frm->dinfo, stack->nt, 0);
1666                                 
1667                                 bc=&dummybc; 
1668                         }
1669       
1670                         if (bc) {
1671                                 int channel = bc->channel;
1672                                 cb_log(4, stack->port, " --> lib: CLEANING UP l3id: %x\n",frm->dinfo);
1673
1674                                 /*bc->pid = 0;*/
1675                                 bc->need_disconnect=0;
1676                                 bc->need_release=0;
1677                                 bc->need_release_complete=0;
1678
1679                                 cb_event(EVENT_CLEANUP, bc, glob_mgr->user_data);
1680
1681                                 empty_bc(bc);
1682                                 clean_up_bc(bc);
1683
1684                                 if (channel>0)
1685                                         empty_chan_in_stack(stack,channel);
1686                                 bc->in_use=0;
1687
1688                                 dump_chan_list(stack);
1689
1690                                 if (bc->stack_holder) {
1691                                         cb_log(4,stack->port, "REMOVING Holder\n");
1692                                         stack_holder_remove( stack, bc);
1693                                         free(bc);
1694                                 }
1695                         }
1696                         else {
1697                                 if (stack->nt) 
1698                                         cb_log(4, stack->port, "BC with dinfo: %x  not found.. (prim was %x and addr %x)\n",frm->dinfo, frm->prim, frm->addr);
1699                         }
1700       
1701                         return 1;
1702                 }
1703                 break;
1704         }
1705   
1706         return 0;
1707 }
1708
1709
1710 /* Empties bc if it's reserved (no SETUP out yet) */
1711 void misdn_lib_release(struct misdn_bchannel *bc)
1712 {
1713         struct misdn_stack *stack=get_stack_by_bc(bc);
1714
1715         if (!stack) {
1716                 cb_log(1,0,"misdn_release: No Stack found\n");
1717                 return;
1718         }
1719         
1720         if (bc->channel>0) 
1721                 empty_chan_in_stack(stack,bc->channel);
1722         
1723         empty_bc(bc);
1724         clean_up_bc(bc);
1725         bc->in_use=0;
1726 }
1727
1728
1729
1730
1731 int misdn_lib_get_port_up (int port) 
1732 { /* Pull Up L1 */ 
1733         struct misdn_stack *stack;
1734         
1735         for (stack=glob_mgr->stack_list;
1736              stack;
1737              stack=stack->next) {
1738                 
1739                 if (stack->port == port) {
1740
1741                         if (!stack->l1link)
1742                                 misdn_lib_get_l1_up(stack);
1743                         if (!stack->l2link)
1744                                 misdn_lib_get_l2_up(stack);
1745                         
1746                         return 0;
1747                 }
1748         }
1749         return 0;
1750 }
1751
1752
1753 int misdn_lib_get_port_down (int port) 
1754 { /* Pull Down L1 */ 
1755         struct misdn_stack *stack;
1756         for (stack=glob_mgr->stack_list;
1757              stack;
1758              stack=stack->next) {
1759                 if (stack->port == port) {
1760                                 if (stack->l2link)
1761                                         misdn_lib_get_l2_down(stack);
1762                                 misdn_lib_get_l1_down(stack);
1763                         return 0;
1764                 }
1765         }
1766         return 0;
1767 }
1768
1769 int misdn_lib_port_up(int port, int check)
1770 {
1771         struct misdn_stack *stack;
1772
1773
1774         for (stack=glob_mgr->stack_list;
1775              stack;
1776              stack=stack->next) {
1777                 
1778                 if (stack->port == port) {
1779
1780                         if (stack->blocked) {
1781                                 cb_log(0,port, "Port Blocked:%d L2:%d L1:%d\n", stack->blocked, stack->l2link, stack->l1link);
1782                                 return -1;
1783                         }
1784
1785                         if (stack->ptp ) {
1786
1787                                 if (stack->l1link && stack->l2link) {
1788                                         return 1;
1789                                 } else {
1790                                         cb_log(1,port, "Port Down L2:%d L1:%d\n",
1791                                                 stack->l2link, stack->l1link);
1792                                         return 0;
1793                                 }
1794                         } else {
1795                                 if ( !check || stack->l1link )
1796                                         return 1;
1797                                 else {
1798                                         cb_log(1,port, "Port down PMP\n");
1799                                         return 0;
1800                                 }
1801                         }
1802                 }
1803         }
1804   
1805         return -1;
1806 }
1807
1808
1809 int release_cr(struct misdn_stack *stack, mISDNuser_head_t *hh)
1810 {
1811         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1812         struct misdn_bchannel dummybc;
1813         iframe_t frm; /* fake te frm to remove callref from global callreflist */
1814         frm.dinfo = hh->dinfo;
1815
1816         frm.addr=stack->upper_id | FLG_MSG_DOWN;
1817
1818         frm.prim = CC_RELEASE_CR|INDICATION;
1819         cb_log(4, stack->port, " --> CC_RELEASE_CR: Faking Release_cr for %x l3id:%x\n",frm.addr, frm.dinfo);
1820         /** removing procid **/
1821         if (!bc) {
1822                 cb_log(4, stack->port, " --> Didn't find BC so temporarily creating dummy BC (l3id:%x) on this port.\n", hh->dinfo);
1823                 misdn_make_dummy(&dummybc, stack->port, hh->dinfo, stack->nt, 0);
1824                 bc=&dummybc; 
1825         }
1826
1827         if (bc) {
1828                 if ( (bc->l3_id & 0xff00) == 0xff00) {
1829                         cb_log(4, stack->port, " --> Removing Process Id:%x on this port.\n", bc->l3_id&0xff);
1830                         stack->procids[bc->l3_id&0xff] = 0 ;
1831                 }
1832         }
1833         else cb_log(0, stack->port, "Couldn't find BC so I couldn't remove the Process!!!! this is a bad port.\n");
1834
1835         if (handle_cr(stack, &frm)<0) {
1836         }
1837
1838         return 0 ;
1839 }
1840
1841 int
1842 handle_event_nt(void *dat, void *arg)
1843 {
1844         manager_t *mgr = (manager_t *)dat;
1845         msg_t *msg = (msg_t *)arg;
1846         mISDNuser_head_t *hh;
1847         int reject=0;
1848
1849         struct misdn_stack *stack=find_stack_by_mgr(mgr);
1850         int port;
1851
1852         if (!msg || !mgr)
1853                 return(-EINVAL);
1854
1855         hh=(mISDNuser_head_t*)msg->data;
1856         port=stack->port;
1857         
1858         cb_log(5, stack->port, " --> lib: prim %x dinfo %x\n",hh->prim, hh->dinfo);
1859         {
1860                 switch(hh->prim){
1861                 case CC_RETRIEVE|INDICATION:
1862                 {
1863                         struct misdn_bchannel *bc;
1864                         struct misdn_bchannel *hold_bc;
1865
1866                         iframe_t frm; /* fake te frm to add callref to global callreflist */
1867                         frm.dinfo = hh->dinfo;
1868
1869                         frm.addr=stack->upper_id | FLG_MSG_DOWN;
1870
1871                         frm.prim = CC_NEW_CR|INDICATION;
1872                         
1873                         if (handle_cr( stack, &frm)< 0) {
1874                                 msg_t *dmsg;
1875                                 cb_log(4, stack->port, "Patch from MEIDANIS:Sending RELEASE_COMPLETE %x (No free Chan for you..)\n", hh->dinfo);
1876                                 dmsg = create_l3msg(CC_RELEASE_COMPLETE | REQUEST,MT_RELEASE_COMPLETE, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1877                                 stack->nst.manager_l3(&stack->nst, dmsg);
1878                                 free_msg(msg);
1879                                 return 0;
1880                         }
1881                         
1882                         bc = find_bc_by_l3id(stack, hh->dinfo);
1883                         hold_bc = stack_holder_find(stack, bc->l3_id);
1884                         cb_log(4, stack->port, "bc_l3id:%x holded_bc_l3id:%x\n",bc->l3_id, hold_bc->l3_id);
1885
1886                         if (hold_bc) {
1887                                 cb_log(4, stack->port, "REMOVING Holder\n");
1888
1889                                 /*swap the backup to our new channel back*/
1890                                 stack_holder_remove(stack, hold_bc);
1891                                 memcpy(bc, hold_bc, sizeof(*bc));
1892                                 free(hold_bc);
1893
1894                                 bc->holded=0;
1895                                 bc->b_stid=0;
1896                         }
1897                         
1898                 }
1899                         
1900                         break;
1901                         
1902                 case CC_SETUP|CONFIRM:
1903                 {
1904                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1905                         int l3id = *((int *)(((u_char *)msg->data)+ mISDNUSER_HEAD_SIZE));
1906                         cb_log(4, stack->port, " --> lib: Event_ind:SETUP CONFIRM [NT] : new L3ID  is %x\n",l3id );
1907         
1908                         if (!bc) { cb_log(4, stack->port, "Bc Not found (after SETUP CONFIRM)\n"); return 0; }
1909                         cb_log (2,bc->port,"I IND :CC_SETUP|CONFIRM: old l3id:%x new l3id:%x\n", bc->l3_id, l3id);
1910                         bc->l3_id=l3id;
1911                         cb_event(EVENT_NEW_L3ID, bc, glob_mgr->user_data);
1912                 }
1913                 free_msg(msg);
1914                 return 0;
1915       
1916                 case CC_SETUP|INDICATION:
1917                 {
1918                         struct misdn_bchannel* bc=misdn_lib_get_free_bc(stack->port, 0, 1, 0);
1919                         if (!bc) 
1920                         ERR_NO_CHANNEL:
1921                         {
1922                                 msg_t *dmsg;
1923                                 cb_log(4, stack->port, "Patch from MEIDANIS:Sending RELEASE_COMPLETE %x (No free Chan for you..)\n", hh->dinfo);
1924                                 dmsg = create_l3msg(CC_RELEASE_COMPLETE | REQUEST,MT_RELEASE_COMPLETE, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1925                                 stack->nst.manager_l3(&stack->nst, dmsg);
1926                                 free_msg(msg);
1927                                 return 0;
1928                         }
1929   
1930                         cb_log(4, stack->port, " --> new_process: New L3Id: %x\n",hh->dinfo);
1931                         bc->l3_id=hh->dinfo;
1932                 }
1933                 break;
1934
1935                 case CC_CONNECT_ACKNOWLEDGE|INDICATION:
1936                 break;
1937                 
1938                 case CC_ALERTING|INDICATION:
1939                 case CC_PROCEEDING|INDICATION:
1940                 case CC_SETUP_ACKNOWLEDGE|INDICATION:
1941                         if(!stack->ptp) break;  
1942                 case CC_CONNECT|INDICATION:
1943                 break;
1944                 case CC_DISCONNECT|INDICATION:
1945                 {
1946                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1947                         if (!bc) {
1948                                 bc=find_bc_by_masked_l3id(stack, hh->dinfo, 0xffff0000);
1949                                 if (bc) { 
1950                                         int myprocid=bc->l3_id&0x0000ffff;
1951                                         hh->dinfo=(hh->dinfo&0xffff0000)|myprocid;
1952                                         cb_log(3,stack->port,"Reject dinfo: %x cause:%d\n",hh->dinfo,bc->cause);
1953                                         reject=1;               
1954                                 }
1955                         }
1956                 }
1957                 break;
1958                 
1959                 case CC_FACILITY|INDICATION:
1960                 {
1961                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1962                         if (!bc) {
1963                                 bc=find_bc_by_masked_l3id(stack, hh->dinfo, 0xffff0000);
1964                                 if (bc) { 
1965                                         int myprocid=bc->l3_id&0x0000ffff;
1966                                         hh->dinfo=(hh->dinfo&0xffff0000)|myprocid;
1967                                         cb_log(4,bc->port,"Repaired reject Bug, new dinfo: %x\n",hh->dinfo);
1968                                 }
1969                         }
1970                 }
1971                 break;
1972                 
1973                 case CC_RELEASE_COMPLETE|INDICATION:
1974                         break;
1975
1976                 case CC_SUSPEND|INDICATION:
1977                 {
1978                         msg_t *dmsg;
1979                         cb_log(4, stack->port, " --> Got Suspend, sending Reject for now\n");
1980                         dmsg = create_l3msg(CC_SUSPEND_REJECT | REQUEST,MT_SUSPEND_REJECT, hh->dinfo,sizeof(RELEASE_COMPLETE_t), 1);
1981                         stack->nst.manager_l3(&stack->nst, dmsg);
1982                         free_msg(msg);
1983                         return 0;
1984                 }
1985                 break;
1986                 case CC_RESUME|INDICATION:
1987                         break;
1988
1989                 case CC_RELEASE|CONFIRM:
1990                         {
1991                                 struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
1992
1993                                 if (bc) { 
1994                                         cb_log(1, stack->port, "CC_RELEASE|CONFIRM (l3id:%x), sending RELEASE_COMPLETE\n", hh->dinfo);
1995                                         misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE);
1996                                 }
1997                         }
1998                         break;
1999                         
2000                 case CC_RELEASE|INDICATION:
2001                         break;
2002
2003                 case CC_RELEASE_CR|INDICATION:
2004                         release_cr(stack, hh);
2005                         free_msg(msg);
2006                         return 0 ;
2007                 break;
2008       
2009                 case CC_NEW_CR|INDICATION:
2010                         /*  Got New CR for bchan, for now I handle this one in */
2011                         /*  connect_ack, Need to be changed */
2012                 {
2013                         struct misdn_bchannel *bc=find_bc_by_l3id(stack, hh->dinfo);
2014                         int l3id = *((int *)(((u_char *)msg->data)+ mISDNUSER_HEAD_SIZE));
2015                         if (!bc) { cb_log(0, stack->port, " --> In NEW_CR: didn't found bc ??\n"); return -1;};
2016                         if (((l3id&0xff00)!=0xff00) && ((bc->l3_id&0xff00)==0xff00)) {
2017                                 cb_log(4, stack->port, " --> Removing Process Id:%x on this port.\n", 0xff&bc->l3_id);
2018                                 stack->procids[bc->l3_id&0xff] = 0 ;
2019                         }
2020                         cb_log(4, stack->port, "lib: Event_ind:CC_NEW_CR : very new L3ID  is %x\n",l3id );
2021         
2022                         bc->l3_id =l3id;
2023                         cb_event(EVENT_NEW_L3ID, bc, glob_mgr->user_data);
2024         
2025                         free_msg(msg);
2026                         return 0;
2027                 }
2028       
2029                 case DL_ESTABLISH | INDICATION:
2030                 case DL_ESTABLISH | CONFIRM:
2031                 {
2032                         cb_log(3, stack->port, "%% GOT L2 Activate Info.\n");
2033                         
2034                         if (stack->ptp && stack->l2link) {
2035                                 cb_log(0, stack->port, "%% GOT L2 Activate Info. but we're activated already.. this l2 is faulty, blocking port\n");
2036                                 cb_event(EVENT_PORT_ALARM, &stack->bc[0], glob_mgr->user_data);
2037                         }
2038
2039                         if (stack->ptp && !stack->restart_sent) {
2040                                 /* make sure we restart the interface of the 
2041                                  * other side */
2042                                 stack->restart_sent=1;
2043                                 misdn_lib_send_restart(stack->port, -1);
2044
2045                         }
2046                 
2047                         /* when we get the L2 UP, the L1 is UP definitely too*/
2048                         stack->l2link = 1;
2049                         stack->l2upcnt=0;
2050                         
2051                         free_msg(msg);
2052                         return 0;
2053                 }
2054                 break;
2055
2056
2057                 case DL_RELEASE | INDICATION:
2058                 case DL_RELEASE | CONFIRM:
2059                 {
2060                         if (stack->ptp) {
2061                                 cb_log(3 , stack->port, "%% GOT L2 DeActivate Info.\n");
2062
2063                                 if (stack->l2upcnt>3) {
2064                                         cb_log(0 , stack->port, "!!! Could not Get the L2 up after 3 Attempts!!!\n");
2065                                 }  else {
2066 #if 0
2067                                         if (stack->nt) misdn_lib_reinit_nt_stack(stack->port);
2068 #endif
2069                                         if (stack->l1link) {
2070                                                 misdn_lib_get_l2_up(stack);
2071                                                 stack->l2upcnt++;
2072                                         }
2073                                 }
2074                                 
2075                         } else 
2076                                 cb_log(3, stack->port, "%% GOT L2 DeActivate Info.\n");
2077                         
2078                         stack->l2link = 0;
2079                         free_msg(msg);
2080                         return 0;
2081                 }
2082                 break;
2083                 }
2084         }
2085         
2086         {
2087                 /*  Parse Events and fire_up to App. */
2088                 struct misdn_bchannel *bc;
2089                 struct misdn_bchannel dummybc;
2090                 
2091                 enum event_e event = isdn_msg_get_event(msgs_g, msg, 1);
2092     
2093                 bc=find_bc_by_l3id(stack, hh->dinfo);
2094     
2095                 if (!bc) {
2096                         cb_log(4, stack->port, " --> Didn't find BC so temporarily creating dummy BC (l3id:%x).\n", hh->dinfo);
2097                         misdn_make_dummy(&dummybc, stack->port,  hh->dinfo, stack->nt, 0);
2098                         bc=&dummybc; 
2099                 }
2100                 if (bc ) {
2101                         isdn_msg_parse_event(msgs_g,msg,bc, 1);
2102
2103                         switch (event) {
2104                                 case EVENT_SETUP:
2105                                         if (bc->channel<=0 || bc->channel==0xff) 
2106                                                 bc->channel=0;
2107                                 
2108                                         if (find_free_chan_in_stack(stack,bc, bc->channel,0)<0) 
2109                                                 goto ERR_NO_CHANNEL;
2110                                         break;
2111                                 case EVENT_RELEASE:
2112                                 case EVENT_RELEASE_COMPLETE:
2113                                         {
2114                                         int channel=bc->channel;
2115                                         int tmpcause=bc->cause; 
2116                                         empty_bc(bc);
2117                                         bc->cause=tmpcause;
2118                                         clean_up_bc(bc);
2119
2120                                         if (channel>0)
2121                                                 empty_chan_in_stack(stack,channel);
2122                                         bc->in_use=0;
2123                                         }
2124                                         break;
2125
2126                                 default:
2127                                 break;
2128                         }
2129                         
2130                         if(!isdn_get_info(msgs_g,event,1)) {
2131                                 cb_log(4, stack->port, "Unknown Event Ind: prim %x dinfo %x\n",hh->prim, hh->dinfo);
2132                         } else {
2133                                 if (reject) {
2134                                         switch(bc->cause){
2135                                                 case AST_CAUSE_USER_BUSY:
2136                                                         cb_log(1, stack->port, "Siemens Busy reject..\n");
2137
2138                                                         break;
2139                                                 default:
2140                                                         break;
2141                                         }
2142                                 }
2143                                 cb_event(event, bc, glob_mgr->user_data);
2144                         }
2145                 } else {
2146                         cb_log(4, stack->port, "No BC found with l3id: prim %x dinfo %x\n",hh->prim, hh->dinfo);
2147                 }
2148
2149                 free_msg(msg);
2150         }
2151
2152
2153         return 0;
2154 }
2155
2156
2157 static int handle_timers(msg_t* msg)
2158 {
2159         iframe_t *frm= (iframe_t*)msg->data;
2160         struct misdn_stack *stack; 
2161   
2162         /* Timer Stuff */
2163         switch (frm->prim) {
2164         case MGR_INITTIMER | CONFIRM:
2165         case MGR_ADDTIMER | CONFIRM:
2166         case MGR_DELTIMER | CONFIRM:
2167         case MGR_REMOVETIMER | CONFIRM:
2168                 free_msg(msg);
2169                 return(1);
2170         }
2171   
2172   
2173   
2174         if (frm->prim==(MGR_TIMER | INDICATION) ) {
2175                 for (stack = glob_mgr->stack_list;
2176                      stack;
2177                      stack = stack->next) {
2178                         itimer_t *it;
2179       
2180                         if (!stack->nt) continue;
2181       
2182                         it = stack->nst.tlist;
2183                         /* find timer */
2184                         for(it=stack->nst.tlist;
2185                             it;
2186                             it=it->next) {
2187                                 if (it->id == (int)frm->addr)
2188                                         break;
2189                         }
2190                         if (it) {
2191                                 int ret;
2192                                 ret = mISDN_write_frame(stack->midev, msg->data, frm->addr,
2193                                                         MGR_TIMER | RESPONSE, 0, 0, NULL, TIMEOUT_1SEC);
2194                                 test_and_clear_bit(FLG_TIMER_RUNING, (long unsigned int *)&it->Flags);
2195                                 ret = it->function(it->data);
2196                                 free_msg(msg);
2197                                 return 1;
2198                         }
2199                 }
2200     
2201                 cb_log(0, 0, "Timer Msg without Timer ??\n");
2202                 free_msg(msg);
2203                 return 1;
2204         }
2205   
2206         return 0;
2207 }
2208
2209
2210
2211 void misdn_lib_tone_generator_start(struct misdn_bchannel *bc)
2212 {
2213         bc->generate_tone=1;
2214 }
2215
2216 void misdn_lib_tone_generator_stop(struct misdn_bchannel *bc)
2217 {
2218         bc->generate_tone=0;
2219 }
2220
2221
2222 static int do_tone(struct misdn_bchannel *bc, int len)
2223 {
2224         bc->tone_cnt=len;
2225         
2226         if (bc->generate_tone) {
2227                 cb_event(EVENT_TONE_GENERATE, bc, glob_mgr->user_data);
2228                 
2229                 if ( !bc->nojitter ) {
2230                         misdn_tx_jitter(bc,len);
2231                 }
2232                 
2233                 return 1;
2234         }
2235         
2236         return 0;
2237 }
2238
2239
2240 #ifdef MISDN_SAVE_DATA
2241 static void misdn_save_data(int id, char *p1, int l1, char *p2, int l2) 
2242 {
2243         char n1[32],n2[32];
2244         FILE *rx, *tx;
2245
2246         sprintf(n1,"/tmp/misdn-rx-%d.raw",id);
2247         sprintf(n2,"/tmp/misdn-tx-%d.raw",id);
2248
2249         rx = fopen(n1,"a+"); 
2250         tx = fopen(n2,"a+");
2251
2252         if (!rx || !tx) {
2253                 cb_log(0,0,"Couldn't open files: %s\n",strerror(errno));
2254                 return ;
2255         }
2256         
2257         fwrite(p1,1,l1,rx);
2258         fwrite(p2,1,l2,tx);
2259         
2260         fclose(rx);
2261         fclose(tx);
2262
2263 }
2264 #endif
2265
2266 void misdn_tx_jitter(struct misdn_bchannel *bc, int len)
2267 {
2268         char buf[4096 + mISDN_HEADER_LEN];
2269         char *data=&buf[mISDN_HEADER_LEN];
2270         iframe_t *txfrm= (iframe_t*)buf;
2271         int jlen, r;
2272         
2273         jlen=cb_jb_empty(bc,data,len);
2274         
2275         if (jlen) {
2276 #ifdef MISDN_SAVE_DATA
2277                 misdn_save_data((bc->port*100+bc->channel), data, jlen, bc->bframe, bc->bframe_len);
2278 #endif
2279                 flip_buf_bits( data, jlen);
2280                 
2281                 if (jlen < len) {
2282                         cb_log(7,bc->port,"Jitterbuffer Underrun.\n");
2283                 }
2284                 
2285                 txfrm->prim = DL_DATA|REQUEST;
2286                 
2287                 txfrm->dinfo = 0;
2288                 
2289                 txfrm->addr = bc->addr|FLG_MSG_DOWN; /*  | IF_DOWN; */
2290                 
2291                 txfrm->len =jlen;
2292                 cb_log(9, bc->port, "Transmitting %d samples 2 misdn\n", txfrm->len);
2293
2294                 r=mISDN_write( glob_mgr->midev, buf, txfrm->len + mISDN_HEADER_LEN, 8000 );
2295         } else {
2296 #define MISDN_GEN_SILENCE
2297 #ifdef MISDN_GEN_SILENCE
2298                 int cnt=len/TONE_SILENCE_SIZE;
2299                 int rest=len%TONE_SILENCE_SIZE;
2300                 int i;
2301
2302                 for (i=0; i<cnt; i++) {
2303                         memcpy(data, tone_silence_flip, TONE_SILENCE_SIZE );
2304                         data +=TONE_SILENCE_SIZE;
2305                 }
2306
2307                 if (rest) {
2308                         memcpy(data, tone_silence_flip, rest);
2309                 }
2310
2311                 txfrm->prim = DL_DATA|REQUEST;
2312
2313                 txfrm->dinfo = 0;
2314
2315                 txfrm->addr = bc->addr|FLG_MSG_DOWN; /*  | IF_DOWN; */
2316
2317                 txfrm->len =len;
2318                 cb_log(9, bc->port, "Transmitting %d samples 2 misdn\n", txfrm->len);
2319
2320                 r=mISDN_write( glob_mgr->midev, buf, txfrm->len + mISDN_HEADER_LEN, 8000 );
2321 #endif
2322
2323         }
2324 }
2325
2326 static int handle_bchan(msg_t *msg)
2327 {
2328         iframe_t *frm= (iframe_t*)msg->data;
2329         struct misdn_bchannel *bc=find_bc_by_addr(frm->addr);
2330         struct misdn_stack *stack;
2331         
2332         if (!bc) {
2333                 cb_log(1,0,"handle_bchan: BC not found for prim:%x with addr:%x dinfo:%x\n", frm->prim, frm->addr, frm->dinfo);
2334                 return 0 ;
2335         }
2336         
2337         stack = get_stack_by_bc(bc);
2338         
2339         if (!stack) {
2340                 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);
2341                 return 0;
2342         }
2343         
2344         switch (frm->prim) {
2345
2346         case MGR_SETSTACK| CONFIRM:
2347                 cb_log(3, stack->port, "BCHAN: MGR_SETSTACK|CONFIRM pid:%d\n",bc->pid);
2348                 break;
2349                 
2350         case MGR_SETSTACK| INDICATION:
2351                 cb_log(3, stack->port, "BCHAN: MGR_SETSTACK|IND pid:%d\n",bc->pid);
2352         break;
2353 #if 0
2354         AGAIN:
2355                 bc->addr = mISDN_get_layerid(stack->midev, bc->b_stid, bc->layer);
2356                 if (!bc->addr) {
2357
2358                         if (errno == EAGAIN) {
2359                                 usleep(1000);
2360                                 goto AGAIN;
2361                         }
2362                         
2363                         cb_log(0,stack->port,"$$$ Get Layer (%d) Id Error: %s\n",bc->layer,strerror(errno));
2364                         
2365                         /* we kill the channel later, when we received some
2366                            data. */
2367                         bc->addr= frm->addr;
2368                 } else if ( bc->addr < 0) {
2369                         cb_log(0, stack->port,"$$$ bc->addr <0 Error:%s\n",strerror(errno));
2370                         bc->addr=0;
2371                 }
2372                 
2373                 cb_log(4, stack->port," --> Got Adr %x\n", bc->addr);
2374
2375                 free_msg(msg);
2376         
2377                 
2378                 switch(bc->bc_state) {
2379                 case BCHAN_SETUP:
2380                         bc_state_change(bc,BCHAN_SETUPED);
2381                 break;
2382
2383                 case BCHAN_CLEAN_REQUEST:
2384                 default:
2385                         cb_log(0, stack->port," --> STATE WASN'T SETUP (but %s) in SETSTACK|IND pid:%d\n",bc_state2str(bc->bc_state), bc->pid);
2386                         clean_up_bc(bc);
2387                 }
2388                 return 1;
2389 #endif
2390
2391         case MGR_DELLAYER| INDICATION:
2392                 cb_log(3, stack->port, "BCHAN: MGR_DELLAYER|IND pid:%d\n",bc->pid);
2393                 break;
2394                 
2395         case MGR_DELLAYER| CONFIRM:
2396                 cb_log(3, stack->port, "BCHAN: MGR_DELLAYER|CNF pid:%d\n",bc->pid);
2397                 
2398                 bc->pid=0;
2399                 bc->addr=0;
2400                 
2401                 free_msg(msg);
2402                 return 1;
2403                 
2404         case PH_ACTIVATE | INDICATION:
2405         case DL_ESTABLISH | INDICATION:
2406                 cb_log(3, stack->port, "BCHAN: ACT Ind pid:%d\n", bc->pid);
2407
2408                 free_msg(msg);
2409                 return 1;    
2410
2411         case PH_ACTIVATE | CONFIRM:
2412         case DL_ESTABLISH | CONFIRM:
2413                 
2414                 cb_log(3, stack->port, "BCHAN: bchan ACT Confirm pid:%d\n",bc->pid);
2415                 free_msg(msg);
2416                 
2417                 return 1;    
2418
2419         case DL_ESTABLISH | REQUEST:
2420                 {
2421                         char buf[128];
2422                         mISDN_write_frame(stack->midev, buf, bc->addr | FLG_MSG_TARGET | FLG_MSG_DOWN,  DL_ESTABLISH | CONFIRM, 0,0, NULL, TIMEOUT_1SEC);
2423                 }
2424                 free_msg(msg);
2425                 return 1;
2426
2427         case DL_RELEASE|REQUEST:
2428                 {
2429                         char buf[128];
2430                         mISDN_write_frame(stack->midev, buf, bc->addr | FLG_MSG_TARGET | FLG_MSG_DOWN,  DL_RELEASE| CONFIRM, 0,0, NULL, TIMEOUT_1SEC);
2431                 }
2432                 free_msg(msg);
2433                 return 1;
2434                 
2435         case PH_DEACTIVATE | INDICATION:
2436         case DL_RELEASE | INDICATION:
2437                 cb_log (3, stack->port, "BCHAN: DeACT Ind pid:%d\n",bc->pid);
2438                 
2439                 free_msg(msg);
2440                 return 1;
2441     
2442         case PH_DEACTIVATE | CONFIRM:
2443         case DL_RELEASE | CONFIRM:
2444                 cb_log(3, stack->port, "BCHAN: DeACT Conf pid:%d\n",bc->pid);
2445                 
2446                 free_msg(msg);
2447                 return 1;
2448     
2449         case PH_CONTROL|INDICATION:
2450         {
2451                 unsigned int *cont = (unsigned int *) &frm->data.p;
2452                 
2453                 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);
2454
2455                 if ((*cont & ~DTMF_TONE_MASK) == DTMF_TONE_VAL) {
2456                         int dtmf = *cont & DTMF_TONE_MASK;
2457                         cb_log(4, stack->port, " --> DTMF TONE: %c\n",dtmf);
2458                         bc->dtmf=dtmf;
2459                         cb_event(EVENT_DTMF_TONE, bc, glob_mgr->user_data);
2460         
2461                         free_msg(msg);
2462                         return 1;
2463                 }
2464                 if (*cont == BF_REJECT) {
2465                         cb_log(4, stack->port, " --> BF REJECT\n");
2466                         free_msg(msg);
2467                         return 1;
2468                 }
2469                 if (*cont == BF_ACCEPT) {
2470                         cb_log(4, stack->port, " --> BF ACCEPT\n");
2471                         free_msg(msg);
2472                         return 1;
2473                 }
2474         }
2475         break;
2476
2477         case PH_DATA|REQUEST:
2478         case DL_DATA|REQUEST:
2479                 cb_log(0, stack->port, "DL_DATA REQUEST \n");
2480                 do_tone(bc, 64);
2481                 
2482                 free_msg(msg);
2483                 return 1;
2484         
2485         
2486         case PH_DATA|INDICATION:
2487         case DL_DATA|INDICATION:
2488         {
2489                 bc->bframe = (void*)&frm->data.i;
2490                 bc->bframe_len = frm->len;
2491
2492                 /** Anyway flip the bufbits **/
2493                 if ( misdn_cap_is_speech(bc->capability) ) 
2494                         flip_buf_bits(bc->bframe, bc->bframe_len);
2495         
2496
2497                 if (!bc->bframe_len) {
2498                         cb_log(2, stack->port, "DL_DATA INDICATION bc->addr:%x frm->addr:%x\n", bc->addr, frm->addr);
2499                         free_msg(msg);
2500                         return 1;
2501                 }
2502
2503                 if ( (bc->addr&STACK_ID_MASK) != (frm->addr&STACK_ID_MASK) ) {
2504                         cb_log(2, stack->port, "DL_DATA INDICATION bc->addr:%x frm->addr:%x\n", bc->addr, frm->addr);
2505                         free_msg(msg);
2506                         return 1;
2507                 }
2508                 
2509 #if MISDN_DEBUG
2510                 cb_log(0, stack->port, "DL_DATA INDICATION Len %d\n", frm->len);
2511
2512 #endif
2513                 
2514                 if ( (bc->bc_state == BCHAN_ACTIVATED) && frm->len > 0) {
2515                         int t;
2516
2517 #ifdef MISDN_B_DEBUG
2518                         cb_log(0,bc->port,"do_tone START\n");
2519 #endif
2520                         t=do_tone(bc,frm->len);
2521
2522 #ifdef MISDN_B_DEBUG
2523                         cb_log(0,bc->port,"do_tone STOP (%d)\n",t);
2524 #endif
2525                         if (  !t ) {
2526                                 int i;
2527                                 
2528                                 if ( misdn_cap_is_speech(bc->capability)) {
2529                                         if ( !bc->nojitter ) {
2530 #ifdef MISDN_B_DEBUG
2531                                                 cb_log(0,bc->port,"tx_jitter START\n");
2532 #endif
2533                                                 misdn_tx_jitter(bc,frm->len);
2534 #ifdef MISDN_B_DEBUG
2535                                                 cb_log(0,bc->port,"tx_jitter STOP\n");
2536 #endif
2537                                         }
2538                                 }
2539
2540 #ifdef MISDN_B_DEBUG    
2541                                 cb_log(0,bc->port,"EVENT_B_DATA START\n");
2542 #endif
2543                                 
2544                                 i = cb_event(EVENT_BCHAN_DATA, bc, glob_mgr->user_data);
2545 #ifdef MISDN_B_DEBUG    
2546                                 cb_log(0,bc->port,"EVENT_B_DATA STOP\n");
2547 #endif
2548                                 
2549                                 if (i<0) {
2550                                         cb_log(10,stack->port,"cb_event returned <0\n");
2551                                         /*clean_up_bc(bc);*/
2552                                 }
2553                         }
2554                 }
2555                 free_msg(msg);
2556                 return 1;
2557         }
2558
2559
2560         case PH_CONTROL | CONFIRM:
2561                 cb_log(4, stack->port, "PH_CONTROL|CNF bc->addr:%x\n", frm->addr);
2562                 free_msg(msg);
2563                 return 1;
2564
2565         case PH_DATA | CONFIRM:
2566         case DL_DATA|CONFIRM:
2567 #if MISDN_DEBUG
2568
2569                 cb_log(0, stack->port, "Data confirmed\n");
2570
2571 #endif
2572                 free_msg(msg);
2573                 return 1;
2574         case DL_DATA|RESPONSE:
2575 #if MISDN_DEBUG
2576                 cb_log(0, stack->port, "Data response\n");
2577
2578 #endif
2579                 break;
2580         }
2581   
2582         return 0;
2583 }
2584
2585
2586
2587 static int handle_frm_nt(msg_t *msg)
2588 {
2589         iframe_t *frm= (iframe_t*)msg->data;
2590         struct misdn_stack *stack;
2591         int err=0;
2592
2593         stack=find_stack_by_addr( frm->addr );
2594
2595         
2596   
2597         if (!stack || !stack->nt) {
2598                 return 0;
2599         }
2600
2601         
2602         if ((err=stack->nst.l1_l2(&stack->nst,msg))) {
2603     
2604                 if (nt_err_cnt > 0 ) {
2605                         if (nt_err_cnt < 100) {
2606                                 nt_err_cnt++; 
2607                                 cb_log(0, stack->port, "NT Stack sends us error: %d \n", err);
2608                         } else if (nt_err_cnt < 105){
2609                                 cb_log(0, stack->port, "NT Stack sends us error: %d over 100 times, so I'll stop this message\n", err);
2610                                 nt_err_cnt = - 1; 
2611                         }
2612                 }
2613                 free_msg(msg);
2614                 return 1;
2615                 
2616         }
2617         
2618         return 1;
2619 }
2620
2621
2622 static int handle_frm(msg_t *msg)
2623 {
2624         iframe_t *frm = (iframe_t*) msg->data;
2625         
2626         struct misdn_stack *stack=find_stack_by_addr(frm->addr);
2627
2628         if (!stack || stack->nt) {
2629                 return 0;
2630         }
2631         
2632         cb_log(4,stack?stack->port:0,"handle_frm: frm->addr:%x frm->prim:%x\n",frm->addr,frm->prim);
2633
2634         {
2635                 struct misdn_bchannel dummybc;
2636                 struct misdn_bchannel *bc;
2637                 int ret=handle_cr(stack, frm);
2638
2639                 if (ret<0) {
2640                         cb_log(3,stack?stack->port:0,"handle_frm: handle_cr <0 prim:%x addr:%x\n", frm->prim, frm->addr);
2641
2642
2643                 }
2644
2645                 if(ret) {
2646                         free_msg(msg);
2647                         return 1;
2648                 }
2649     
2650                 bc=find_bc_by_l3id(stack, frm->dinfo);
2651
2652                 if (!bc && (frm->prim==(CC_RESTART|CONFIRM)) ) {
2653                         misdn_make_dummy(&dummybc, stack->port, MISDN_ID_GLOBAL, stack->nt, 0);
2654                         bc=&dummybc;
2655                 }
2656
2657                 if (!bc && (frm->prim==(CC_SETUP|INDICATION)) ) {
2658                         misdn_make_dummy(&dummybc, stack->port, MISDN_ID_GLOBAL, stack->nt, 0);
2659                         dummybc.port=stack->port;
2660                         dummybc.l3_id=frm->dinfo;
2661                         bc=&dummybc;
2662
2663                         misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
2664
2665                         free_msg(msg);
2666                         return 1;
2667                 }
2668
2669     
2670 handle_frm_bc:
2671                 if (bc ) {
2672                         enum event_e event = isdn_msg_get_event(msgs_g, msg, 0);
2673                         enum event_response_e response=RESPONSE_OK;
2674                         int ret;
2675       
2676                         isdn_msg_parse_event(msgs_g,msg,bc, 0);
2677                         
2678                         /** Preprocess some Events **/
2679                         ret = handle_event(bc, event, frm);
2680                         if (ret<0) {
2681                                 cb_log(0,stack->port,"couldn't handle event\n");
2682                                 free_msg(msg);
2683                                 return 1;
2684                         }
2685                         /*  shoot up event to App: */
2686                         cb_log(5, stack->port, "lib Got Prim: Addr %x prim %x dinfo %x\n",frm->addr, frm->prim, frm->dinfo);
2687       
2688                         if(!isdn_get_info(msgs_g,event,0)) 
2689                                 cb_log(0, stack->port, "Unknown Event Ind: Addr:%x prim %x dinfo %x\n",frm->addr, frm->prim, frm->dinfo);
2690                         else
2691                                 response=cb_event(event, bc, glob_mgr->user_data);
2692 #if 1
2693                         if (event == EVENT_SETUP) {
2694                                 switch (response) {
2695                                 case RESPONSE_IGNORE_SETUP_WITHOUT_CLOSE:
2696
2697                                         cb_log(0, stack->port, "TOTALLY IGNORING SETUP\n");                                     
2698                                         
2699                                         break;
2700                                 case RESPONSE_IGNORE_SETUP:
2701                                         /* I think we should send CC_RELEASE_CR, but am not sure*/
2702                                         bc->out_cause = AST_CAUSE_NORMAL_CLEARING;
2703                                 
2704                                 case RESPONSE_RELEASE_SETUP:
2705                                         misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
2706                                         if (bc->channel>0)
2707                                                 empty_chan_in_stack(stack, bc->channel);
2708                                         empty_bc(bc);
2709                                         bc_state_change(bc,BCHAN_CLEANED);
2710                                         bc->in_use=0;
2711
2712                                         cb_log(0, stack->port, "GOT IGNORE SETUP\n");
2713                                         break;
2714                                 case RESPONSE_OK:
2715                                         cb_log(4, stack->port, "GOT SETUP OK\n");
2716
2717                                         
2718                                         break;
2719                                 default:
2720                                         break;
2721                                 }
2722                         }
2723
2724                         if (event == EVENT_RELEASE_COMPLETE) {
2725                                 /* release bchannel only after we've announced the RELEASE_COMPLETE */
2726                                 int channel=bc->channel;
2727                                 int tmpcause=bc->cause; 
2728                                 int tmp_out_cause=bc->out_cause;        
2729                                 empty_bc(bc);
2730                                 bc->cause=tmpcause;
2731                                 bc->out_cause=tmp_out_cause;
2732                                 clean_up_bc(bc);
2733                                 
2734                                 if (tmpcause == AST_CAUSE_REQUESTED_CHAN_UNAVAIL) {
2735                                         cb_log(0,stack->port,"**** Received CAUSE:%d, so not cleaning up channel %d\n", AST_CAUSE_REQUESTED_CHAN_UNAVAIL, channel);
2736                                         cb_log(0,stack->port,"**** This channel is now no longer available,\nplease try to restart it with 'misdn send restart <port> <channel>'\n");
2737                                         set_chan_in_stack(stack, channel);
2738                                         bc->channel=channel;
2739                                         misdn_lib_send_restart(stack->port, channel);
2740                                 } else {
2741                                         if (channel>0)
2742                                                 empty_chan_in_stack(stack, channel);
2743                                 }
2744                                 bc->in_use=0;
2745                         }
2746
2747                         if (event == EVENT_RESTART) {
2748                                 cb_log(0, stack->port, "**** Received RESTART_ACK channel:%d\n", bc->restart_channel);
2749                                 empty_chan_in_stack(stack, bc->restart_channel);
2750                         }
2751
2752                         cb_log(5, stack->port, "Freeing Msg on prim:%x \n",frm->prim);
2753
2754                         
2755                         free_msg(msg);
2756                         return 1;
2757 #endif
2758       
2759                 } else {
2760                         struct misdn_bchannel dummybc;
2761                         if (frm->prim!=(CC_FACILITY|INDICATION))
2762                                 cb_log(0, stack->port, " --> Didn't find BC so temporarily creating dummy BC (l3id:%x) on this port.\n", frm->dinfo);
2763                         else
2764                                 cb_log(5, stack->port, " --> Using Dummy BC for FACILITY\n");
2765
2766                         memset (&dummybc,0,sizeof(dummybc));
2767                         dummybc.port=stack->port;
2768                         dummybc.l3_id=frm->dinfo;
2769                         bc=&dummybc; 
2770                         goto handle_frm_bc;
2771                 }
2772         }
2773
2774         cb_log(4, stack->port, "TE_FRM_HANDLER: Returning 0 on prim:%x \n",frm->prim);
2775         return 0;
2776 }
2777
2778
2779 static int handle_l1(msg_t *msg)
2780 {
2781         iframe_t *frm = (iframe_t*) msg->data;
2782         struct misdn_stack *stack = find_stack_by_addr(frm->addr);
2783         int i ;
2784         
2785         if (!stack) return 0 ;
2786
2787         switch (frm->prim) {
2788         case PH_ACTIVATE | CONFIRM:
2789         case PH_ACTIVATE | INDICATION:
2790                 cb_log (3, stack->port, "L1: PH L1Link Up!\n");
2791                 stack->l1link=1;
2792                 
2793                 if (stack->nt) {
2794                         
2795                         if (stack->nst.l1_l2(&stack->nst, msg))
2796                                 free_msg(msg);
2797
2798                         if (stack->ptp)
2799                                 misdn_lib_get_l2_up(stack);
2800                 } else {
2801                         free_msg(msg);
2802                 }
2803                 
2804                 for (i=0;i<=stack->b_num; i++) {
2805                         if (stack->bc[i].evq != EVENT_NOTHING) {
2806                                 cb_log(4, stack->port, "Firing Queued Event %s because L1 got up\n", isdn_get_info(msgs_g, stack->bc[i].evq, 0));
2807                                 misdn_lib_send_event(&stack->bc[i],stack->bc[i].evq);
2808                                 stack->bc[i].evq=EVENT_NOTHING;
2809                         }
2810                         
2811                 }
2812                 return 1;
2813
2814         case PH_ACTIVATE | REQUEST:
2815                 free_msg(msg);
2816                 cb_log(3,stack->port,"L1: PH_ACTIVATE|REQUEST \n");
2817                 return 1;
2818                 
2819         case PH_DEACTIVATE | REQUEST:
2820                 free_msg(msg);
2821                 cb_log(3,stack->port,"L1: PH_DEACTIVATE|REQUEST \n");
2822                 return 1;
2823                 
2824         case PH_DEACTIVATE | CONFIRM:
2825         case PH_DEACTIVATE | INDICATION:
2826                 cb_log (3, stack->port, "L1: PH L1Link Down! \n");
2827         
2828 #if 0
2829                 for (i=0; i<=stack->b_num; i++) {
2830                         if (global_state == MISDN_INITIALIZED)  {
2831                                 cb_event(EVENT_CLEANUP, &stack->bc[i], glob_mgr->user_data);
2832                         }
2833                 }
2834 #endif
2835                 
2836                 if (stack->nt) {
2837                         if (stack->nst.l1_l2(&stack->nst, msg))
2838                                 free_msg(msg);
2839                 } else {
2840                         free_msg(msg);
2841                 }
2842                 
2843                 stack->l1link=0;
2844                 stack->l2link=0;
2845                 return 1;
2846         }
2847   
2848         return 0;
2849 }
2850
2851 static int handle_l2(msg_t *msg)
2852 {
2853         iframe_t *frm = (iframe_t*) msg->data;
2854
2855         struct misdn_stack *stack = find_stack_by_addr(frm->addr);
2856         
2857         if (!stack) {
2858                 return 0 ;
2859         }
2860         
2861         switch(frm->prim) {
2862
2863         case DL_ESTABLISH | REQUEST:
2864                 cb_log(1,stack->port,"DL_ESTABLISH|REQUEST \n");
2865                 return 1;
2866         case DL_RELEASE | REQUEST:
2867                 cb_log(1,stack->port,"DL_RELEASE|REQUEST \n");
2868                 return 1;
2869                 
2870         case DL_ESTABLISH | INDICATION:
2871         case DL_ESTABLISH | CONFIRM:
2872         {
2873                 cb_log (3, stack->port, "L2: L2Link Up! \n");
2874                 if (stack->ptp && stack->l2link) {
2875                         cb_log (-1, stack->port, "L2: L2Link Up! but it's already UP.. must be faulty, blocking port\n"); 
2876                         cb_event(EVENT_PORT_ALARM, &stack->bc[0], glob_mgr->user_data);
2877                 }
2878                 stack->l2link=1;
2879                 free_msg(msg);
2880                 return 1;
2881         }
2882         break;
2883     
2884         case DL_RELEASE | INDICATION:
2885         case DL_RELEASE | CONFIRM:
2886         {
2887                 cb_log (3, stack->port, "L2: L2Link Down! \n");
2888                 stack->l2link=0;
2889                 
2890                 free_msg(msg);
2891                 return 1;
2892         }
2893         break;
2894         }
2895         return 0;
2896 }
2897
2898 static int handle_mgmt(msg_t *msg)
2899 {
2900         iframe_t *frm = (iframe_t*) msg->data;
2901         struct misdn_stack *stack;
2902
2903         if ( (frm->addr == 0) && (frm->prim == (MGR_DELLAYER|CONFIRM)) ) {
2904                 cb_log(2, 0, "MGMT: DELLAYER|CONFIRM Addr: 0 !\n") ;
2905                 free_msg(msg);
2906                 return 1;
2907         }
2908         
2909         stack = find_stack_by_addr(frm->addr);
2910         
2911         if (!stack) {
2912                 if (frm->prim == (MGR_DELLAYER|CONFIRM)) {
2913                         cb_log(2, 0, "MGMT: DELLAYER|CONFIRM Addr: %x !\n",
2914                                         frm->addr) ;
2915                         free_msg(msg);
2916                         return 1;
2917                 }
2918                 
2919                 return 0;
2920         }
2921         
2922         switch(frm->prim) {
2923         case MGR_SHORTSTATUS | INDICATION:
2924         case MGR_SHORTSTATUS | CONFIRM:
2925                 cb_log(5, 0, "MGMT: Short status dinfo %x\n",frm->dinfo);
2926                 
2927                 switch (frm->dinfo) {
2928                 case SSTATUS_L1_ACTIVATED:
2929                         cb_log(3, 0, "MGMT: SSTATUS: L1_ACTIVATED \n");
2930                         stack->l1link=1;
2931                 
2932                         break;
2933                 case SSTATUS_L1_DEACTIVATED:
2934                         cb_log(3, 0, "MGMT: SSTATUS: L1_DEACTIVATED \n");
2935                         stack->l1link=0;
2936 #if 0
2937                         clear_l3(stack);
2938 #endif
2939                         break;
2940
2941                 case SSTATUS_L2_ESTABLISHED:
2942                         cb_log(3, stack->port, "MGMT: SSTATUS: L2_ESTABLISH \n");
2943                         stack->l2link=1;
2944                         break;
2945                         
2946                 case SSTATUS_L2_RELEASED:
2947                         cb_log(3, stack->port, "MGMT: SSTATUS: L2_RELEASED \n");
2948                         stack->l2link=0;
2949                         break;
2950                 }
2951                 
2952                 free_msg(msg);
2953                 return 1;
2954                 
2955         case MGR_SETSTACK | INDICATION:
2956                 cb_log(4, stack->port, "MGMT: SETSTACK|IND dinfo %x\n",frm->dinfo);
2957                 free_msg(msg);
2958                 return 1;
2959         case MGR_DELLAYER | CONFIRM:
2960                 cb_log(4, stack->port, "MGMT: DELLAYER|CNF dinfo %x\n",frm->dinfo) ;
2961                 free_msg(msg);
2962                 return 1;
2963                 
2964         }
2965         
2966         /*
2967         if ( (frm->prim & 0x0f0000) ==  0x0f0000) {
2968         cb_log(5, 0, "$$$ MGMT FRAME: prim %x addr %x dinfo %x\n",frm->prim, frm->addr, frm->dinfo) ;
2969         free_msg(msg);
2970         return 1;
2971         } */
2972     
2973         return 0;
2974 }
2975
2976
2977 static msg_t *fetch_msg(int midev) 
2978 {
2979         msg_t *msg=alloc_msg(MAX_MSG_SIZE);
2980         int r;
2981
2982         if (!msg) {
2983                 cb_log(0, 0, "fetch_msg: alloc msg failed !!");
2984                 return NULL;
2985         }
2986
2987         AGAIN:
2988                 r=mISDN_read(midev,msg->data,MAX_MSG_SIZE, TIMEOUT_10SEC);
2989                 msg->len=r;
2990     
2991                 if (r==0) {
2992                         free_msg(msg); /* danger, cause usually freeing in main_loop */
2993                         cb_log(6,0,"Got empty Msg..\n");
2994                         return NULL;
2995                 }
2996
2997                 if (r<0) {
2998                         if (errno == EAGAIN) {
2999                                 /*we wait for mISDN here*/
3000                                 cb_log(4,0,"mISDN_read wants us to wait\n");
3001                                 usleep(5000);
3002                                 goto AGAIN;
3003                         }
3004                         
3005                         cb_log(0,0,"mISDN_read returned :%d error:%s (%d)\n",r,strerror(errno),errno); 
3006                 }
3007
3008 #if 0
3009                if  (!(frm->prim == (DL_DATA|INDICATION) )|| (frm->prim == (PH_DATA|INDICATION)))
3010                        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 );
3011 #endif
3012                 return msg;
3013 }
3014
3015 void misdn_lib_isdn_l1watcher(int port)
3016 {
3017         struct misdn_stack *stack;
3018
3019         for (stack = glob_mgr->stack_list; stack && (stack->port != port); stack = stack->next)
3020                 ;
3021
3022         if (stack) {
3023                 cb_log(4, port, "Checking L1 State\n"); 
3024                 if (!stack->l1link) {
3025                         cb_log(4, port, "L1 State Down, trying to get it up again\n");  
3026                         misdn_lib_get_short_status(stack);
3027                         misdn_lib_get_l1_up(stack); 
3028                         misdn_lib_get_l2_up(stack); 
3029                 }
3030         }
3031 }
3032
3033 /* This is a thread */
3034 static void misdn_lib_isdn_event_catcher(void *arg)
3035 {
3036         struct misdn_lib *mgr = arg;
3037         int zero_frm=0 , fff_frm=0 ;
3038         int midev= mgr->midev;
3039         int port=0;
3040         
3041         while (1) {
3042                 msg_t *msg = fetch_msg(midev); 
3043                 iframe_t *frm;
3044                 
3045                 
3046                 if (!msg) continue;
3047                 
3048                 frm = (iframe_t*) msg->data;
3049                 
3050                 /** When we make a call from NT2Ast we get these frames **/
3051                 if (frm->len == 0 && frm->addr == 0 && frm->dinfo == 0 && frm->prim == 0 ) {
3052                         zero_frm++; 
3053                         free_msg(msg);
3054                         continue;
3055                 } else {
3056                         if (zero_frm) {
3057                                 cb_log(0, port, "*** Alert: %d zero_frms caught\n", zero_frm);
3058                                 zero_frm = 0 ;
3059                         }
3060                 }
3061                 
3062                 /** I get this sometimes after setup_bc **/
3063                 if (frm->len == 0 &&  frm->dinfo == 0 && frm->prim == 0xffffffff ) {
3064                         fff_frm++; 
3065                         free_msg(msg);
3066                         continue;
3067                 } else {
3068                         if (fff_frm) {
3069                                 cb_log(0, port, "*** Alert: %d fff_frms caught\n", fff_frm);
3070                                 fff_frm = 0 ;
3071                         }
3072                 }
3073                 
3074                 manager_isdn_handler(frm, msg);
3075         }
3076
3077 }
3078
3079
3080 /** App Interface **/
3081
3082 int te_lib_init() {
3083         char buff[1025] = "";
3084         iframe_t *frm=(iframe_t*)buff;
3085         int midev=mISDN_open();
3086         int ret;
3087
3088         if  (midev<=0) return midev;
3089   
3090 /* create entity for layer 3 TE-mode */
3091         mISDN_write_frame(midev, buff, 0, MGR_NEWENTITY | REQUEST, 0, 0, NULL, TIMEOUT_1SEC);
3092         ret = mISDN_read_frame(midev, frm, sizeof(iframe_t), 0, MGR_NEWENTITY | CONFIRM, TIMEOUT_1SEC);
3093   
3094         if (ret < mISDN_HEADER_LEN) {
3095         noentity:
3096                 fprintf(stderr, "cannot request MGR_NEWENTITY from mISDN: %s\n",strerror(errno));
3097                 exit(-1);
3098         }
3099   
3100         entity = frm->dinfo & 0xffff ;
3101   
3102         if (!entity)
3103                 goto noentity;
3104
3105         return midev;
3106   
3107 }
3108
3109 void te_lib_destroy(int midev)
3110 {
3111         char buf[1024];
3112         mISDN_write_frame(midev, buf, 0, MGR_DELENTITY | REQUEST, entity, 0, NULL, TIMEOUT_1SEC);
3113
3114         cb_log(4, 0, "Entity deleted\n");
3115         mISDN_close(midev);
3116         cb_log(4, 0, "midev closed\n");
3117 }
3118
3119
3120
3121 void misdn_lib_transfer(struct misdn_bchannel* holded_bc)