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