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