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