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